├── .DS_Store ├── README.md ├── V3_demo ├── api_demo │ ├── asset │ │ ├── Encryption_HMAC.go │ │ ├── Encryption_HMAC.java │ │ ├── Encryption_HMAC.js │ │ ├── Encryption_HMAC.php │ │ ├── Encryption_HMAC.py │ │ ├── Encryption_HMAC.rb │ │ ├── Encryption_RSA.java │ │ └── Encryption_RSA.py │ ├── contract │ │ ├── Encryption_HMAC.go │ │ ├── Encryption_HMAC.java │ │ ├── Encryption_HMAC.js │ │ ├── Encryption_HMAC.php │ │ ├── Encryption_HMAC.py │ │ ├── Encryption_HMAC.rb │ │ ├── Encryption_HMAC.sh │ │ ├── Encryption_RSA.java │ │ └── Encryption_RSA.py │ ├── spot │ │ ├── Encryption_HMAC.go │ │ ├── Encryption_HMAC.java │ │ ├── Encryption_HMAC.js │ │ ├── Encryption_HMAC.php │ │ ├── Encryption_HMAC.py │ │ ├── Encryption_HMAC.rb │ │ ├── Encryption_RSA.java │ │ └── Encryption_RSA.py │ └── unified_margin │ │ ├── Encryption_HMAC.go │ │ ├── Encryption_HMAC.java │ │ ├── Encryption_HMAC.js │ │ ├── Encryption_HMAC.php │ │ ├── Encryption_HMAC.py │ │ ├── Encryption_HMAC.rb │ │ ├── Encryption_RSA.java │ │ └── Encryption_RSA.py └── wss_demo │ ├── js │ ├── ws_private_demo.js │ └── ws_public_demo.js │ └── python │ ├── ws_private_hmac_demo.py │ ├── ws_private_rsa_demo.py │ └── ws_public_demo.py ├── V5_demo ├── api_demo │ ├── Encryption_HMAC.cpp │ ├── Encryption_HMAC.cs │ ├── Encryption_HMAC.go │ ├── Encryption_HMAC.java │ ├── Encryption_HMAC.js │ ├── Encryption_HMAC.php │ ├── Encryption_HMAC.py │ ├── Encryption_HMAC.rb │ ├── Encryption_HMAC.rs │ ├── Encryption_HMAC.rs.bak │ ├── Encryption_HMAC.scala │ ├── Encryption_HMAC.sh │ ├── Encryption_HMAC.ts │ ├── Encryption_HMAC_async.py │ ├── Encryption_RSA.cs │ ├── Encryption_RSA.java │ ├── Encryption_RSA.py │ └── comparePubPrvTrd.py └── wss_demo │ ├── c# │ ├── ws_execution_fast_demo.cs │ ├── ws_private_demo.cs │ ├── ws_public_demo.cs │ └── ws_trade_api_demo.cs │ ├── c++ │ ├── ws_execution.fast_demo.cpp │ ├── ws_private_demo.cpp │ ├── ws_public_demo.cpp │ └── ws_trade_api_demo.cpp │ ├── go │ ├── ws_execution_fast_demo.go │ ├── ws_private_demo.go │ ├── ws_public_demo.go │ └── ws_trade_api_demo.go │ ├── java │ ├── ws_execution_fast_demo.java │ ├── ws_private_demo.java │ ├── ws_public_demo.java │ └── ws_trade_api_demo.java │ ├── javascript │ ├── ws_execution_fast_demo.js │ ├── ws_private_demo.js │ ├── ws_public_demo.js │ └── ws_trade_api_demo.js │ ├── python │ ├── ws_private_hmac_demo.py │ ├── ws_private_rsa_demo.py │ ├── ws_public_demo.py │ ├── ws_trade_api_demo.py │ └── wss_fast_execution_demo.py │ └── typescript │ ├── ws_fast_execution_demo.ts │ ├── ws_private_demo.ts │ ├── ws_public_demo.ts │ └── ws_trade_api_demo.ts ├── data_transfer_demo └── http_request │ ├── google_sheet_api.md │ ├── import_data_to_csv.cs │ ├── import_data_to_csv.java │ ├── import_data_to_csv.js │ ├── import_data_to_csv.ts │ ├── import_data_to_excel.cs │ ├── import_data_to_excel.java │ ├── import_data_to_excel.js │ ├── import_data_to_excel.py │ ├── import_data_to_excel.ts │ ├── import_data_to_google_sheet.java │ ├── import_data_to_google_sheet.py │ ├── impot_data_to_csv.go │ └── impot_data_to_csv.py ├── function_test_demo ├── .DS_Store ├── convert_coin_test.go ├── create_sub_user_test.java ├── open_order_test.java ├── twap_order_test.py ├── universal_transfer_test.go └── uta_margin_data_test.py ├── legacy_demo ├── api_demo │ ├── Encryption.cpp │ ├── Encryption.cs │ ├── Encryption.go │ ├── Encryption.java │ ├── Encryption.rb │ ├── asset │ │ ├── Encryption.java │ │ ├── Encryption.js │ │ ├── Encryption.php │ │ ├── Encryption.py │ │ └── Encryption.sh │ ├── encryption.sh │ ├── futures │ │ ├── Encryption.java │ │ ├── Encryption.js │ │ ├── Encryption.php │ │ ├── Encryption.py │ │ └── Encryption.sh │ ├── http2.py │ ├── spot │ │ ├── Encryption.java │ │ ├── Encryption.js │ │ ├── Encryption.php │ │ ├── Encryption.py │ │ └── Encryption.sh │ └── usdc │ │ ├── Encryption.java │ │ ├── Encryption.js │ │ ├── Encryption_Javascript.html │ │ ├── encryption.php │ │ └── encryption.py └── wss_demo │ ├── js │ ├── ws_private_demo.js │ └── ws_public_demo.js │ └── python │ ├── logfile_wrapper.log │ ├── ws_private_demo.py │ ├── ws_private_usdc.py │ └── ws_public_demo.py └── perfTest_demo ├── basicPerfLinearV3.py ├── basicPerfLinearV3IOC.py ├── basicPerfLinearV5.py ├── basicPerfLinearV5IOC.py ├── basicPerfOptionV5IOC.py ├── basicPerfSpotV3IOC.py └── basicPerfSpotV5IOC.py /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bybit-exchange/api-usage-examples/b3e23e9ccb50ec3928fa7e8f67455d0a0f069a0e/.DS_Store -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This repository maintains example API wrappers for using the bybit REST API and Websocket. 2 | -------------------------------------------------------------------------------- /V3_demo/api_demo/asset/Encryption_HMAC.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "crypto/hmac" 6 | "crypto/sha256" 7 | "encoding/hex" 8 | "encoding/json" 9 | "fmt" 10 | "io/ioutil" 11 | "log" 12 | "net/http" 13 | "net/http/httputil" 14 | "strconv" 15 | "time" 16 | ) 17 | 18 | func httpClient() *http.Client { 19 | client := &http.Client{Timeout: 10 * time.Second} 20 | return client 21 | } 22 | 23 | var url string = "https://api-testnet.bybit.com" 24 | var api_key = "XXXXXXXXX" 25 | var apiSecret = "XXXXXXXXX" 26 | var recv_window = "5000" 27 | var signature = "" 28 | 29 | func main() { 30 | c := httpClient() 31 | 32 | //POST Method 33 | postParams := map[string]interface{}{"transferId": "7DC9A628-D1B4-4CFD-8CE8-7D4218C2F237", "coin": "USDT", "amount": "1", "from_account_type": "SPOT", "to_account_type": "CONTRACT"} 34 | postEndPoint := "/asset/v3/private/transfer/inter-transfer" 35 | postRequest(c, http.MethodPost, postParams, postEndPoint) 36 | 37 | //GET Method 38 | getEndPoint := "/asset/v3/private/transfer/inter-transfer/list/query" 39 | getParams := "coin=USDT" 40 | getRequest(c, http.MethodGet, getParams, getEndPoint) 41 | } 42 | 43 | func getRequest(client *http.Client, method string, params string, endPoint string) []byte { 44 | now := time.Now() 45 | unixNano := now.UnixNano() 46 | time_stamp := unixNano / 1000000 47 | hmac256 := hmac.New(sha256.New, []byte(apiSecret)) 48 | hmac256.Write([]byte(strconv.FormatInt(time_stamp, 10) + api_key + recv_window + params)) 49 | signature = hex.EncodeToString(hmac256.Sum(nil)) 50 | request, error := http.NewRequest("GET", url+endPoint+"?"+params, nil) 51 | request.Header.Set("Content-Type", "application/json") 52 | request.Header.Set("X-BAPI-API-KEY", api_key) 53 | request.Header.Set("X-BAPI-SIGN", signature) 54 | request.Header.Set("X-BAPI-TIMESTAMP", strconv.FormatInt(time_stamp, 10)) 55 | request.Header.Set("X-BAPI-SIGN-TYPE", "2") 56 | request.Header.Set("X-BAPI-RECV-WINDOW", recv_window) 57 | reqDump, err := httputil.DumpRequestOut(request, true) 58 | if err != nil { 59 | log.Fatal(err) 60 | } 61 | fmt.Printf("Request Dump:\n%s", string(reqDump)) 62 | response, error := client.Do(request) 63 | if error != nil { 64 | panic(error) 65 | } 66 | defer response.Body.Close() 67 | elapsed := time.Since(now).Seconds() 68 | fmt.Printf("\n%s took %v seconds \n", endPoint, elapsed) 69 | fmt.Println("response Status:", response.Status) 70 | fmt.Println("response Headers:", response.Header) 71 | body, _ := ioutil.ReadAll(response.Body) 72 | fmt.Println("response Body:", string(body)) 73 | return body 74 | } 75 | 76 | func postRequest(client *http.Client, method string, params interface{}, endPoint string) []byte { 77 | now := time.Now() 78 | unixNano := now.UnixNano() 79 | time_stamp := unixNano / 1000000 80 | jsonData, err := json.Marshal(params) 81 | if err != nil { 82 | log.Fatal(err) 83 | } 84 | hmac256 := hmac.New(sha256.New, []byte(apiSecret)) 85 | hmac256.Write([]byte(strconv.FormatInt(time_stamp, 10) + api_key + recv_window + string(jsonData[:]))) 86 | signature = hex.EncodeToString(hmac256.Sum(nil)) 87 | request, error := http.NewRequest("POST", url+endPoint, bytes.NewBuffer(jsonData)) 88 | request.Header.Set("Content-Type", "application/json") 89 | request.Header.Set("X-BAPI-API-KEY", api_key) 90 | request.Header.Set("X-BAPI-SIGN", signature) 91 | request.Header.Set("X-BAPI-TIMESTAMP", strconv.FormatInt(time_stamp, 10)) 92 | request.Header.Set("X-BAPI-SIGN-TYPE", "2") 93 | request.Header.Set("X-BAPI-RECV-WINDOW", recv_window) 94 | reqDump, err := httputil.DumpRequestOut(request, true) 95 | if err != nil { 96 | log.Fatal(err) 97 | } 98 | fmt.Printf("Request Dump:\n%s", string(reqDump)) 99 | response, error := client.Do(request) 100 | if error != nil { 101 | panic(error) 102 | } 103 | defer response.Body.Close() 104 | elapsed := time.Since(now).Seconds() 105 | fmt.Printf("\n%s took %v seconds \n", endPoint, elapsed) 106 | fmt.Println("response Status:", response.Status) 107 | fmt.Println("response Headers:", response.Header) 108 | body, _ := ioutil.ReadAll(response.Body) 109 | fmt.Println("response Body:", string(body)) 110 | return body 111 | } 112 | -------------------------------------------------------------------------------- /V3_demo/api_demo/asset/Encryption_HMAC.js: -------------------------------------------------------------------------------- 1 | const crypto = require('crypto'); 2 | const axios = require('axios'); 3 | const { v4: uuidv4 } = require('uuid'); 4 | 5 | url='https://api-testnet.bybit.com'; 6 | 7 | var apiKey = "XXXXXXXXXXXX"; 8 | var secret = "XXXXXXXXXXXX"; 9 | var recvWindow = 5000; 10 | var timestamp = Date.now().toString(); 11 | 12 | function getSignature(parameters, secret) { 13 | return crypto.createHmac('sha256', secret).update(timestamp + apiKey + recvWindow + parameters).digest('hex'); 14 | } 15 | 16 | async function http_request(endpoint,method,data,Info) { 17 | var sign=getSignature(data,secret); 18 | if(method=="POST") 19 | { 20 | fullendpoint=url+endpoint; 21 | } 22 | else{ 23 | fullendpoint=url+endpoint+"?"+data; 24 | data=""; 25 | } 26 | //endpoint=url+endpoint 27 | var config = { 28 | method: method, 29 | url: fullendpoint, 30 | headers: { 31 | 'X-BAPI-SIGN-TYPE': '2', 32 | 'X-BAPI-SIGN': sign, 33 | 'X-BAPI-API-KEY': apiKey, 34 | 'X-BAPI-TIMESTAMP': timestamp, 35 | 'X-BAPI-RECV-WINDOW': '5000', 36 | 'Content-Type': 'application/json; charset=utf-8' 37 | }, 38 | data : data 39 | }; 40 | console.log(Info + " Calling...."); 41 | await axios(config) 42 | .then(function (response) { 43 | console.log(JSON.stringify(response.data)); 44 | }) 45 | .catch(function (error) { 46 | console.log(error); 47 | }); 48 | } 49 | 50 | //Create Order 51 | async function TestCase() 52 | { 53 | //Create Internal Transfer ( SPOT to UNIFIED ) 54 | endpoint="/asset/v3/private/transfer/inter-transfer" 55 | method="POST" 56 | transferId=uuidv4(); 57 | var params='{"transferId": "' + transferId + '","coin": "USDT","amount": "1","from_account_type": "SPOT","to_account_type": "UNIFIED"}' 58 | await http_request(endpoint,method,params,"InternalTransfer") 59 | 60 | //Query Internal Transfer List 61 | endpoint="/asset/v3/private/transfer/inter-transfer/list/query" 62 | method="GET" 63 | params='coin=USDT' 64 | await http_request(endpoint,method,params,"InternalTransferList") 65 | } 66 | 67 | //Internal Transfer and List 68 | TestCase() 69 | 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /V3_demo/api_demo/asset/Encryption_HMAC.php: -------------------------------------------------------------------------------- 1 | $url . $endpoint, 27 | CURLOPT_RETURNTRANSFER => true, 28 | CURLOPT_ENCODING => '', 29 | CURLOPT_MAXREDIRS => 10, 30 | CURLOPT_TIMEOUT => 0, 31 | CURLOPT_FOLLOWLOCATION => true, 32 | CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, 33 | CURLOPT_CUSTOMREQUEST => $method, 34 | CURLOPT_POSTFIELDS => $params, 35 | CURLOPT_HTTPHEADER => array( 36 | "X-BAPI-API-KEY: $api_key", 37 | "X-BAPI-SIGN: $signature", 38 | "X-BAPI-SIGN-TYPE: 2", 39 | "X-BAPI-TIMESTAMP: $timestamp", 40 | "X-BAPI-RECV-WINDOW: 5000", 41 | "Content-Type: application/json" 42 | ), 43 | )); 44 | if($method=="GET") 45 | { 46 | curl_setopt($curl, CURLOPT_HTTPGET, true); 47 | } 48 | echo $Info . "\n"; 49 | $response = curl_exec($curl); 50 | echo $response . "\n"; 51 | } 52 | 53 | #Create Internal Transfer ( SPOT to UNIFIED ) 54 | $endpoint="/asset/v3/private/transfer/inter-transfer"; 55 | $method="POST"; 56 | $transferId=guidv4(openssl_random_pseudo_bytes(16)); 57 | $params='{"transferId": "' . $transferId . '","coin": "USDT","amount": "1","from_account_type": "SPOT","to_account_type": "UNIFIED"}'; 58 | http_req("$endpoint","$method","$params","InternalTransfer"); 59 | 60 | 61 | #Query Internal Transfer List 62 | $endpoint="/asset/v3/private/transfer/inter-transfer/list/query"; 63 | $method="GET"; 64 | $params='coin=USDT'; 65 | http_req($endpoint,$method,$params,"InternalTransferList"); 66 | 67 | curl_close($curl); 68 | 69 | 70 | -------------------------------------------------------------------------------- /V3_demo/api_demo/asset/Encryption_HMAC.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import time 3 | import hashlib 4 | import hmac 5 | import uuid 6 | 7 | api_key='XXXXXXXXXXXX' 8 | secret_key='XXXXXXXXXXXX' 9 | httpClient=requests.Session() 10 | recv_window=str(5000) 11 | url="https://api-testnet.bybit.com" # Testnet endpoint 12 | 13 | def HTTP_Request(endPoint,method,payload,Info): 14 | global time_stamp 15 | time_stamp=str(int(time.time() * 10 ** 3)) 16 | signature=genSignature(payload) 17 | headers = { 18 | 'X-BAPI-API-KEY': api_key, 19 | 'X-BAPI-SIGN': signature, 20 | 'X-BAPI-SIGN-TYPE': '2', 21 | 'X-BAPI-TIMESTAMP': time_stamp, 22 | 'X-BAPI-RECV-WINDOW': recv_window, 23 | 'Content-Type': 'application/json' 24 | } 25 | if(method=="POST"): 26 | response = httpClient.request(method, url+endPoint, headers=headers, data=payload) 27 | else: 28 | response = httpClient.request(method, url+endPoint+"?"+payload, headers=headers) 29 | print(response.text) 30 | print(Info + " Elapsed Time : " + str(response.elapsed)) 31 | 32 | def genSignature(payload): 33 | param_str= str(time_stamp) + api_key + recv_window + payload 34 | hash = hmac.new(bytes(secret_key, "utf-8"), param_str.encode("utf-8"),hashlib.sha256) 35 | signature = hash.hexdigest() 36 | return signature 37 | 38 | #Create Internal Transfer ( SPOT to UNIFIED ) 39 | endpoint="/asset/v3/private/transfer/inter-transfer" 40 | method="POST" 41 | transferId=uuid.uuid4() 42 | params='{"transferId": "' + str(transferId) + '","coin": "USDT","amount": "1","from_account_type": "SPOT","to_account_type": "UNIFIED"}' 43 | HTTP_Request(endpoint,method,params,"InternalTransfer") 44 | 45 | #Query Internal Transfer List 46 | endpoint="/asset/v3/private/transfer/inter-transfer/list/query" 47 | method="GET" 48 | params='coin=USDT' 49 | HTTP_Request(endpoint,method,params,"InternalTransferList") 50 | -------------------------------------------------------------------------------- /V3_demo/api_demo/asset/Encryption_HMAC.rb: -------------------------------------------------------------------------------- 1 | require 'digest' 2 | require "uri" 3 | require "net/http" 4 | require "date" 5 | require 'open-uri' 6 | require 'openssl' 7 | require 'securerandom' 8 | 9 | 10 | $api_key='XXXXXXXXX' 11 | $secret_key='XXXXXXXXX' 12 | $recv_window = '5000' 13 | $url = URI("https://api-testnet.bybit.com") # Testnet endpoint 14 | $time_stamp = "" 15 | 16 | def HTTP_Request(endPoint,method,payload) 17 | $time_stamp = DateTime.now.strftime('%Q') 18 | signature = genSignature(payload) 19 | fullUrl = $url + endPoint 20 | if method == "POST" 21 | request = Net::HTTP::Post.new(fullUrl,'Content-Type' => 'application/json') 22 | elsif method == "GET" 23 | payload="?"+payload 24 | fullUrl = $url + endPoint + payload 25 | request = Net::HTTP::Get.new(fullUrl) 26 | else 27 | puts "Check the method. It should be either GET or POST" 28 | exit 29 | end 30 | https = Net::HTTP.new(fullUrl.host, fullUrl.port) 31 | https.set_debug_output($stdout) 32 | https.use_ssl = true 33 | request["X-BAPI-API-KEY"] = $api_key 34 | request["X-BAPI-TIMESTAMP"] = $time_stamp 35 | request["X-BAPI-RECV-WINDOW"] = $recv_window 36 | request["X-BAPI-SIGN"] = signature 37 | request.body = payload 38 | puts payload 39 | response = https.request(request) 40 | puts response.read_body 41 | end 42 | 43 | def genSignature(payload) 44 | param_str= $time_stamp + $api_key + $recv_window + payload 45 | OpenSSL::HMAC.hexdigest('sha256', $secret_key, param_str) 46 | end 47 | 48 | #Create Internal Transfer ( SPOT to UNIFIED ) 49 | endPoint = "/asset/v3/private/transfer/inter-transfer" 50 | method = "POST" 51 | transferId = SecureRandom.uuid 52 | payload='{"transferId": "' + transferId + '","coin": "USDT","amount": "1","from_account_type": "SPOT","to_account_type": "UNIFIED"}' 53 | HTTP_Request(endPoint,method,payload) 54 | 55 | #Query Internal Transfer List 56 | endPoint = "/asset/v3/private/transfer/inter-transfer/list/query" 57 | method = "GET" 58 | payload="coin=USDT" 59 | HTTP_Request(endPoint,method,payload) 60 | -------------------------------------------------------------------------------- /V3_demo/api_demo/asset/Encryption_RSA.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import time 3 | import hashlib 4 | import uuid 5 | from Crypto.Hash import SHA256 # install pycryptodome libaray 6 | from Crypto.Signature import PKCS1_v1_5 7 | from Crypto.PublicKey import RSA 8 | 9 | api_key='XXXXXXXXX' 10 | rsa_private_key_path = '/user/private.pem' # use absolute path 11 | 12 | httpClient=requests.Session() 13 | recv_window=str(5000) 14 | url="https://api-testnet.bybit.com" # Testnet endpoint 15 | 16 | def HTTP_Request(endPoint,method,payload,Info): 17 | global time_stamp 18 | time_stamp=str(int(time.time() * 10 ** 3)) 19 | signature=genSignature(payload, rsa_private_key_path) 20 | headers = { 21 | 'X-BAPI-API-KEY': api_key, 22 | 'X-BAPI-SIGN': signature, 23 | 'X-BAPI-SIGN-TYPE': '2', 24 | 'X-BAPI-TIMESTAMP': time_stamp, 25 | 'X-BAPI-RECV-WINDOW': recv_window, 26 | 'Content-Type': 'application/json' 27 | } 28 | if(method=="POST"): 29 | response = httpClient.request(method, url+endPoint, headers=headers, data=payload) 30 | else: 31 | response = httpClient.request(method, url+endPoint+"?"+payload, headers=headers) 32 | print(response.text) 33 | print(Info + " Elapsed Time : " + str(response.elapsed)) 34 | 35 | 36 | """ 37 | Load private_key.pem, then generate base64 signature 38 | """ 39 | def genSignature(payload, rsa_private_key_path): 40 | param_str= str(time_stamp) + api_key + recv_window + payload 41 | 42 | with open(rsa_private_key_path, "r") as private_key_obj: 43 | private_key_str = private_key_obj.read() 44 | private_key = RSA.importKey(private_key_str) 45 | encoded_param = SHA256.new(param_str.encode("utf-8")) 46 | signature = PKCS1_v1_5.new(private_key).sign(encoded_param) 47 | 48 | return base64.b64encode(signature).decode() 49 | 50 | #Create Internal Transfer ( SPOT to UNIFIED ) 51 | endpoint="/asset/v3/private/transfer/inter-transfer" 52 | method="POST" 53 | transferId=uuid.uuid4() 54 | params='{"transferId": "' + str(transferId) + '","coin": "USDT","amount": "1","from_account_type": "SPOT","to_account_type": "UNIFIED"}' 55 | HTTP_Request(endpoint,method,params,"InternalTransfer") 56 | 57 | #Query Internal Transfer List 58 | endpoint="/asset/v3/private/transfer/inter-transfer/list/query" 59 | method="GET" 60 | params='coin=USDT' 61 | HTTP_Request(endpoint,method,params,"InternalTransferList") 62 | -------------------------------------------------------------------------------- /V3_demo/api_demo/contract/Encryption_HMAC.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "crypto/hmac" 6 | "crypto/sha256" 7 | "encoding/hex" 8 | "encoding/json" 9 | "fmt" 10 | "io/ioutil" 11 | "log" 12 | "net/http" 13 | "net/http/httputil" 14 | "strconv" 15 | "time" 16 | ) 17 | 18 | func httpClient() *http.Client { 19 | client := &http.Client{Timeout: 10 * time.Second} 20 | return client 21 | } 22 | 23 | var url string = "https://api-testnet.bybit.com" 24 | var api_key = "XXXXXXXXXX" 25 | var apiSecret = "XXXXXXXXXX" 26 | var recv_window = "5000" 27 | var signature = "" 28 | 29 | func main() { 30 | c := httpClient() 31 | 32 | //POST Method 33 | postParams := map[string]interface{}{"symbol": "BTCUSDT", "side": "Buy", "positionIdx": 1, "orderType": "Limit", "qty": "0.001", "price": "10000", "timeInForce": "GoodTillCancel"} 34 | postEndPoint := "/contract/v3/private/order/create" 35 | postRequest(c, http.MethodPost, postParams, postEndPoint) 36 | 37 | //GET Method 38 | getEndPoint := "/contract/v3/private/order/unfilled-orders" 39 | getParams := "settleCoin=USDT" 40 | getRequest(c, http.MethodGet, getParams, getEndPoint) 41 | } 42 | 43 | func getRequest(client *http.Client, method string, params string, endPoint string) []byte { 44 | now := time.Now() 45 | unixNano := now.UnixNano() 46 | time_stamp := unixNano / 1000000 47 | hmac256 := hmac.New(sha256.New, []byte(apiSecret)) 48 | hmac256.Write([]byte(strconv.FormatInt(time_stamp, 10) + api_key + recv_window + params)) 49 | signature = hex.EncodeToString(hmac256.Sum(nil)) 50 | request, error := http.NewRequest("GET", url+endPoint+"?"+params, nil) 51 | request.Header.Set("Content-Type", "application/json") 52 | request.Header.Set("X-BAPI-API-KEY", api_key) 53 | request.Header.Set("X-BAPI-SIGN", signature) 54 | request.Header.Set("X-BAPI-TIMESTAMP", strconv.FormatInt(time_stamp, 10)) 55 | request.Header.Set("X-BAPI-SIGN-TYPE", "2") 56 | request.Header.Set("X-BAPI-RECV-WINDOW", recv_window) 57 | reqDump, err := httputil.DumpRequestOut(request, true) 58 | if err != nil { 59 | log.Fatal(err) 60 | } 61 | fmt.Printf("Request Dump:\n%s", string(reqDump)) 62 | response, error := client.Do(request) 63 | if error != nil { 64 | panic(error) 65 | } 66 | defer response.Body.Close() 67 | elapsed := time.Since(now).Seconds() 68 | fmt.Printf("\n%s took %v seconds \n", endPoint, elapsed) 69 | fmt.Println("response Status:", response.Status) 70 | fmt.Println("response Headers:", response.Header) 71 | body, _ := ioutil.ReadAll(response.Body) 72 | fmt.Println("response Body:", string(body)) 73 | return body 74 | } 75 | 76 | func postRequest(client *http.Client, method string, params interface{}, endPoint string) []byte { 77 | now := time.Now() 78 | unixNano := now.UnixNano() 79 | time_stamp := unixNano / 1000000 80 | jsonData, err := json.Marshal(params) 81 | if err != nil { 82 | log.Fatal(err) 83 | } 84 | hmac256 := hmac.New(sha256.New, []byte(apiSecret)) 85 | hmac256.Write([]byte(strconv.FormatInt(time_stamp, 10) + api_key + recv_window + string(jsonData[:]))) 86 | signature = hex.EncodeToString(hmac256.Sum(nil)) 87 | request, error := http.NewRequest("POST", url+endPoint, bytes.NewBuffer(jsonData)) 88 | request.Header.Set("Content-Type", "application/json") 89 | request.Header.Set("X-BAPI-API-KEY", api_key) 90 | request.Header.Set("X-BAPI-SIGN", signature) 91 | request.Header.Set("X-BAPI-TIMESTAMP", strconv.FormatInt(time_stamp, 10)) 92 | request.Header.Set("X-BAPI-SIGN-TYPE", "2") 93 | request.Header.Set("X-BAPI-RECV-WINDOW", recv_window) 94 | reqDump, err := httputil.DumpRequestOut(request, true) 95 | if err != nil { 96 | log.Fatal(err) 97 | } 98 | fmt.Printf("Request Dump:\n%s", string(reqDump)) 99 | response, error := client.Do(request) 100 | if error != nil { 101 | panic(error) 102 | } 103 | defer response.Body.Close() 104 | elapsed := time.Since(now).Seconds() 105 | fmt.Printf("\n%s took %v seconds \n", endPoint, elapsed) 106 | fmt.Println("response Status:", response.Status) 107 | fmt.Println("response Headers:", response.Header) 108 | body, _ := ioutil.ReadAll(response.Body) 109 | fmt.Println("response Body:", string(body)) 110 | return body 111 | } 112 | -------------------------------------------------------------------------------- /V3_demo/api_demo/contract/Encryption_HMAC.js: -------------------------------------------------------------------------------- 1 | const crypto = require('crypto'); 2 | const axios = require('axios'); 3 | 4 | url='https://api-testnet.bybit.com'; 5 | 6 | var apiKey = "XXXXXXXXXXXXX"; 7 | var secret = "XXXXXXXXXXXXX"; 8 | var recvWindow = 5000; 9 | var timestamp = Date.now().toString(); 10 | 11 | function getSignature(parameters, secret) { 12 | return crypto.createHmac('sha256', secret).update(timestamp + apiKey + recvWindow + parameters).digest('hex'); 13 | } 14 | 15 | async function http_request(endpoint,method,data,Info) { 16 | var sign=getSignature(data,secret); 17 | if(method=="POST") 18 | { 19 | fullendpoint=url+endpoint; 20 | } 21 | else{ 22 | fullendpoint=url+endpoint+"?"+data; 23 | data=""; 24 | } 25 | //endpoint=url+endpoint 26 | var config = { 27 | method: method, 28 | url: fullendpoint, 29 | headers: { 30 | 'X-BAPI-SIGN-TYPE': '2', 31 | 'X-BAPI-SIGN': sign, 32 | 'X-BAPI-API-KEY': apiKey, 33 | 'X-BAPI-TIMESTAMP': timestamp, 34 | 'X-BAPI-RECV-WINDOW': '5000', 35 | 'Content-Type': 'application/json; charset=utf-8' 36 | }, 37 | data : data 38 | }; 39 | console.log(Info + " Calling...."); 40 | await axios(config) 41 | .then(function (response) { 42 | console.log(JSON.stringify(response.data)); 43 | }) 44 | .catch(function (error) { 45 | console.log(error); 46 | }); 47 | } 48 | 49 | //Create Order 50 | async function TestCase() 51 | { 52 | endpoint="/contract/v3/private/order/create" 53 | const orderLinkId = crypto.randomBytes(16).toString("hex"); 54 | var data = '{"symbol":"BTCUSDT","orderType":"Limit","side":"Buy","orderLinkId":"' + orderLinkId + '","qty":"0.001","price":"10000","timeInForce":"GoodTillCancel","position_idx":"1"}'; 55 | await http_request(endpoint,"POST",data,"Create"); 56 | 57 | //Get unfilled Order List 58 | endpoint="/contract/v3/private/order/unfilled-orders" 59 | var data = 'symbol=BTCUSDT&orderStatus=New&orderLinkId=' + orderLinkId; 60 | await http_request(endpoint,"GET",data,"Unfilled Order List"); 61 | 62 | //Cancel order 63 | endpoint="/contract/v3/private/order/cancel" 64 | var data = '{"symbol": "BTCUSDT","orderLinkId":"' + orderLinkId +'"}'; 65 | await http_request(endpoint,"POST",data,"Cancel"); 66 | } 67 | 68 | //Create, List and Cancel Orders 69 | TestCase() 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /V3_demo/api_demo/contract/Encryption_HMAC.php: -------------------------------------------------------------------------------- 1 | $url . $endpoint, 19 | CURLOPT_RETURNTRANSFER => true, 20 | CURLOPT_ENCODING => '', 21 | CURLOPT_MAXREDIRS => 10, 22 | CURLOPT_TIMEOUT => 0, 23 | CURLOPT_FOLLOWLOCATION => true, 24 | CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, 25 | CURLOPT_CUSTOMREQUEST => $method, 26 | CURLOPT_POSTFIELDS => $params, 27 | CURLOPT_HTTPHEADER => array( 28 | "X-BAPI-API-KEY: $api_key", 29 | "X-BAPI-SIGN: $signature", 30 | "X-BAPI-SIGN-TYPE: 2", 31 | "X-BAPI-TIMESTAMP: $timestamp", 32 | "X-BAPI-RECV-WINDOW: 5000", 33 | "Content-Type: application/json" 34 | ), 35 | )); 36 | if($method=="GET") 37 | { 38 | curl_setopt($curl, CURLOPT_HTTPGET, true); 39 | } 40 | echo $Info . "\n"; 41 | $response = curl_exec($curl); 42 | echo $response . "\n"; 43 | } 44 | 45 | #Create Order 46 | $endpoint="/contract/v3/private/order/create"; 47 | $method="POST"; 48 | $orderLinkId=uniqid(); 49 | $params='{"symbol": "BTCUSDT","side": "Buy","positionIdx": 1,"orderType": "Limit","qty": "0.001","price": "10000","timeInForce": "GoodTillCancel","orderLinkId": "' . $orderLinkId . '"}'; 50 | http_req("$endpoint","$method","$params","Create Order"); 51 | 52 | #Get Order List 53 | $endpoint="/contract/v3/private/order/list"; 54 | $method="GET"; 55 | $params="symbol=BTCUSDT&orderLinkId=" . $orderLinkId; 56 | http_req($endpoint,$method,$params,"List Order"); 57 | 58 | #Cancel Order 59 | $endpoint="/contract/v3/private/order/cancel"; 60 | $method="POST"; 61 | $params='{"symbol": "BTCUSDT","orderLinkId": "' . $orderLinkId . '"}'; 62 | http_req($endpoint,$method,$params,"Cancel Order"); 63 | 64 | curl_close($curl); 65 | 66 | 67 | -------------------------------------------------------------------------------- /V3_demo/api_demo/contract/Encryption_HMAC.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import time 3 | import hashlib 4 | import hmac 5 | import uuid 6 | 7 | api_key='XXXXXXXXX' 8 | secret_key='XXXXXXXXX' 9 | httpClient=requests.Session() 10 | recv_window=str(5000) 11 | url="https://api-testnet.bybit.com" # Testnet endpoint 12 | 13 | def HTTP_Request(endPoint,method,payload,Info): 14 | global time_stamp 15 | time_stamp=str(int(time.time() * 10 ** 3)) 16 | signature=genSignature(payload) 17 | headers = { 18 | 'X-BAPI-API-KEY': api_key, 19 | 'X-BAPI-SIGN': signature, 20 | 'X-BAPI-SIGN-TYPE': '2', 21 | 'X-BAPI-TIMESTAMP': time_stamp, 22 | 'X-BAPI-RECV-WINDOW': recv_window, 23 | 'Content-Type': 'application/json' 24 | } 25 | if(method=="POST"): 26 | response = httpClient.request(method, url+endPoint, headers=headers, data=payload) 27 | else: 28 | response = httpClient.request(method, url+endPoint+"?"+payload, headers=headers) 29 | print(response.text) 30 | print(Info + " Elapsed Time : " + str(response.elapsed)) 31 | 32 | def genSignature(payload): 33 | param_str= str(time_stamp) + api_key + recv_window + payload 34 | hash = hmac.new(bytes(secret_key, "utf-8"), param_str.encode("utf-8"),hashlib.sha256) 35 | signature = hash.hexdigest() 36 | return signature 37 | 38 | #Create Order 39 | endpoint="/contract/v3/private/order/create" 40 | method="POST" 41 | orderLinkId=uuid.uuid4().hex 42 | params='{"symbol": "BTCUSDT","side": "Buy","positionIdx": 1,"orderType": "Limit","qty": "0.001","price": "10000","timeInForce": "GoodTillCancel","orderLinkId": "' + orderLinkId + '"}' 43 | HTTP_Request(endpoint,method,params,"Create") 44 | 45 | #Get unfilled Orders 46 | endpoint="/contract/v3/private/order/unfilled-orders" 47 | method="GET" 48 | params='settleCoin=USDT' 49 | HTTP_Request(endpoint,method,params,"UnFilled") 50 | 51 | #Get Order List 52 | endpoint="/contract/v3/private/order/list" 53 | method="GET" 54 | params="symbol=BTCUSDT&orderStatus=New&orderLinkId="+orderLinkId 55 | HTTP_Request(endpoint,method,params,"List") 56 | 57 | #Cancel Order 58 | endpoint="/contract/v3/private/order/cancel" 59 | method="POST" 60 | params='{"symbol": "BTCUSDT","orderLinkId": "'+orderLinkId+'"}' 61 | HTTP_Request(endpoint,method,params,"Cancel") 62 | -------------------------------------------------------------------------------- /V3_demo/api_demo/contract/Encryption_HMAC.rb: -------------------------------------------------------------------------------- 1 | require 'digest' 2 | require "uri" 3 | require "net/http" 4 | require "date" 5 | require 'open-uri' 6 | require 'openssl' 7 | require 'securerandom' 8 | 9 | 10 | $api_key='XXXXXXXX' 11 | $secret_key='XXXXXXXX' 12 | $recv_window = '5000' 13 | $url = URI("https://api-testnet.bybit.com") # Testnet endpoint 14 | $time_stamp = "" 15 | 16 | def HTTP_Request(endPoint,method,payload) 17 | $time_stamp = DateTime.now.strftime('%Q') 18 | signature = genSignature(payload) 19 | fullUrl = $url + endPoint 20 | if method == "POST" 21 | request = Net::HTTP::Post.new(fullUrl,'Content-Type' => 'application/json') 22 | elsif method == "GET" 23 | payload="?"+payload 24 | fullUrl = $url + endPoint + payload 25 | request = Net::HTTP::Get.new(fullUrl) 26 | else 27 | puts "Check the method. It should be either GET or POST" 28 | exit 29 | end 30 | https = Net::HTTP.new(fullUrl.host, fullUrl.port) 31 | https.set_debug_output($stdout) 32 | https.use_ssl = true 33 | request["X-BAPI-API-KEY"] = $api_key 34 | request["X-BAPI-TIMESTAMP"] = $time_stamp 35 | request["X-BAPI-RECV-WINDOW"] = $recv_window 36 | request["X-BAPI-SIGN"] = signature 37 | request.body = payload 38 | puts payload 39 | response = https.request(request) 40 | puts response.read_body 41 | end 42 | 43 | def genSignature(payload) 44 | param_str= $time_stamp + $api_key + $recv_window + payload 45 | OpenSSL::HMAC.hexdigest('sha256', $secret_key, param_str) 46 | end 47 | 48 | #Create Order ( POST Method ) 49 | endPoint = "/contract/v3/private/order/create" 50 | method = "POST" 51 | orderLinkId = SecureRandom.uuid 52 | payload='{"symbol": "BTCUSDT","side": "Buy","positionIdx": 1,"orderType": "Limit","qty": "0.001","price": "10000","timeInForce": "GoodTillCancel","orderLinkId": "' + orderLinkId + '"}' 53 | HTTP_Request(endPoint,method,payload) 54 | 55 | #Retrieve Unfilled Orders ( GET Method ) 56 | endPoint = "/contract/v3/private/order/unfilled-orders" 57 | method = "GET" 58 | payload='settleCoin=USDT' 59 | HTTP_Request(endPoint,method,payload) 60 | -------------------------------------------------------------------------------- /V3_demo/api_demo/contract/Encryption_HMAC.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | 4 | api_key='XXXXXXXXXX' 5 | secret_key='XXXXXXXXXX' 6 | time_in_seconds=$(date +%s) 7 | timestamp=$((time_in_seconds * 1000)) 8 | sign=$(echo -n "${timestamp}${api_key}"5000'{"symbol": "BTCUSDT","side": "Buy","positionIdx": 1,"orderType": "Limit","qty": "0.001","price": "8000","timeInForce": "GoodTillCancel","reduce_only": false,"closeOnTrigger": false,"position_idx":1,"orderLinkId": "TESTING123"}' | openssl dgst -sha256 -hmac "${secret_key}") 9 | 10 | response=$(curl --location --request POST 'https://api-testnet.bybit.com/contract/v3/private/order/create' \ 11 | --header 'X-BAPI-SIGN-TYPE: 2' \ 12 | --header 'X-BAPI-SIGN: '${sign} \ 13 | --header 'X-BAPI-API-KEY: '${api_key} \ 14 | --header 'X-BAPI-TIMESTAMP: '${timestamp} \ 15 | --header 'X-BAPI-RECV-WINDOW: 5000' \ 16 | --header 'Content-Type: application/json' \ 17 | --data-raw '{"symbol": "BTCUSDT","side": "Buy","positionIdx": 1,"orderType": "Limit","qty": "0.001","price": "8000","timeInForce": "GoodTillCancel","reduce_only": false,"closeOnTrigger": false,"position_idx":1,"orderLinkId": "TESTING123"}') 18 | 19 | echo "Curl Response : $?" 20 | echo "${response}" 21 | order_id=$(jq '.result.orderId' <<< ${response}) 22 | if [ "${order_id}" == "null" ] 23 | then 24 | echo "${response}" 25 | else 26 | echo "Order ID # ${order_id}" 27 | fi 28 | -------------------------------------------------------------------------------- /V3_demo/api_demo/contract/Encryption_RSA.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import time 3 | import hashlib 4 | import uuid 5 | from Crypto.Hash import SHA256 # install pycryptodome libaray 6 | from Crypto.Signature import PKCS1_v1_5 7 | from Crypto.PublicKey import RSA 8 | 9 | api_key='XXXXXXXXX' 10 | rsa_private_key_path = '/user/private.pem' # use absolute path 11 | 12 | httpClient=requests.Session() 13 | recv_window=str(5000) 14 | url="https://api-testnet.bybit.com" # Testnet endpoint 15 | 16 | def HTTP_Request(endPoint,method,payload,Info): 17 | global time_stamp 18 | time_stamp=str(int(time.time() * 10 ** 3)) 19 | signature=genSignature(payload, rsa_private_key_path) 20 | headers = { 21 | 'X-BAPI-API-KEY': api_key, 22 | 'X-BAPI-SIGN': signature, 23 | 'X-BAPI-SIGN-TYPE': '2', 24 | 'X-BAPI-TIMESTAMP': time_stamp, 25 | 'X-BAPI-RECV-WINDOW': recv_window, 26 | 'Content-Type': 'application/json' 27 | } 28 | if(method=="POST"): 29 | response = httpClient.request(method, url+endPoint, headers=headers, data=payload) 30 | else: 31 | response = httpClient.request(method, url+endPoint+"?"+payload, headers=headers) 32 | print(response.text) 33 | print(Info + " Elapsed Time : " + str(response.elapsed)) 34 | 35 | 36 | """ 37 | Load private_key.pem, then generate base64 signature 38 | """ 39 | def genSignature(payload, rsa_private_key_path): 40 | param_str= str(time_stamp) + api_key + recv_window + payload 41 | 42 | with open(rsa_private_key_path, "r") as private_key_obj: 43 | private_key_str = private_key_obj.read() 44 | private_key = RSA.importKey(private_key_str) 45 | encoded_param = SHA256.new(param_str.encode("utf-8")) 46 | signature = PKCS1_v1_5.new(private_key).sign(encoded_param) 47 | 48 | return base64.b64encode(signature).decode() 49 | 50 | #Create Order 51 | endpoint="/contract/v3/private/order/create" 52 | method="POST" 53 | orderLinkId=uuid.uuid4().hex 54 | params='{"symbol": "BTCUSDT","side": "Buy","positionIdx": 1,"orderType": "Limit","qty": "0.001","price": "10000","timeInForce": "GoodTillCancel","orderLinkId": "' + orderLinkId + '"}' 55 | HTTP_Request(endpoint,method,params,"Create") 56 | 57 | #Get unfilled Orders 58 | endpoint="/contract/v3/private/order/unfilled-orders" 59 | method="GET" 60 | params='settleCoin=USDT' 61 | HTTP_Request(endpoint,method,params,"UnFilled") 62 | 63 | #Get Order List 64 | endpoint="/contract/v3/private/order/list" 65 | method="GET" 66 | params="symbol=BTCUSDT&orderStatus=New&orderLinkId="+orderLinkId 67 | HTTP_Request(endpoint,method,params,"List") 68 | 69 | #Cancel Order 70 | endpoint="/contract/v3/private/order/cancel" 71 | method="POST" 72 | params='{"symbol": "BTCUSDT","orderLinkId": "'+orderLinkId+'"}' 73 | HTTP_Request(endpoint,method,params,"Cancel") 74 | -------------------------------------------------------------------------------- /V3_demo/api_demo/spot/Encryption_HMAC.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "crypto/hmac" 6 | "crypto/sha256" 7 | "encoding/hex" 8 | "encoding/json" 9 | "fmt" 10 | "io/ioutil" 11 | "log" 12 | "net/http" 13 | "net/http/httputil" 14 | "strconv" 15 | "time" 16 | ) 17 | 18 | func httpClient() *http.Client { 19 | client := &http.Client{Timeout: 10 * time.Second} 20 | return client 21 | } 22 | 23 | var url string = "https://api-testnet.bybit.com" 24 | var api_key = "XXXXXX" 25 | var apiSecret = "XXXXXX" 26 | var recv_window = "5000" 27 | var signature = "" 28 | 29 | func main() { 30 | c := httpClient() 31 | 32 | //POST Method 33 | postParams := map[string]interface{}{"symbol": "BTCUSDT", "orderType": "Limit", "side": "Buy", "orderLinkId": "TEST1234", "orderQty": "0.001", "orderPrice": "10000", "timeInForce": "GTC"} 34 | postEndPoint := "/spot/v3/private/order" 35 | postRequest(c, http.MethodPost, postParams, postEndPoint) 36 | 37 | //GET Method 38 | getEndPoint := "/spot/v3/private/order" 39 | getParams := "orderLinkId=TEST1234" 40 | getRequest(c, http.MethodGet, getParams, getEndPoint) 41 | } 42 | 43 | func getRequest(client *http.Client, method string, params string, endPoint string) []byte { 44 | now := time.Now() 45 | unixNano := now.UnixNano() 46 | time_stamp := unixNano / 1000000 47 | hmac256 := hmac.New(sha256.New, []byte(apiSecret)) 48 | hmac256.Write([]byte(strconv.FormatInt(time_stamp, 10) + api_key + recv_window + params)) 49 | signature = hex.EncodeToString(hmac256.Sum(nil)) 50 | request, error := http.NewRequest("GET", url+endPoint+"?"+params, nil) 51 | request.Header.Set("Content-Type", "application/json") 52 | request.Header.Set("X-BAPI-API-KEY", api_key) 53 | request.Header.Set("X-BAPI-SIGN", signature) 54 | request.Header.Set("X-BAPI-TIMESTAMP", strconv.FormatInt(time_stamp, 10)) 55 | request.Header.Set("X-BAPI-SIGN-TYPE", "2") 56 | request.Header.Set("X-BAPI-RECV-WINDOW", recv_window) 57 | reqDump, err := httputil.DumpRequestOut(request, true) 58 | if err != nil { 59 | log.Fatal(err) 60 | } 61 | fmt.Printf("Request Dump:\n%s", string(reqDump)) 62 | response, error := client.Do(request) 63 | if error != nil { 64 | panic(error) 65 | } 66 | defer response.Body.Close() 67 | elapsed := time.Since(now).Seconds() 68 | fmt.Printf("\n%s took %v seconds \n", endPoint, elapsed) 69 | fmt.Println("response Status:", response.Status) 70 | fmt.Println("response Headers:", response.Header) 71 | body, _ := ioutil.ReadAll(response.Body) 72 | fmt.Println("response Body:", string(body)) 73 | return body 74 | } 75 | 76 | func postRequest(client *http.Client, method string, params interface{}, endPoint string) []byte { 77 | now := time.Now() 78 | unixNano := now.UnixNano() 79 | time_stamp := unixNano / 1000000 80 | jsonData, err := json.Marshal(params) 81 | if err != nil { 82 | log.Fatal(err) 83 | } 84 | hmac256 := hmac.New(sha256.New, []byte(apiSecret)) 85 | hmac256.Write([]byte(strconv.FormatInt(time_stamp, 10) + api_key + recv_window + string(jsonData[:]))) 86 | signature = hex.EncodeToString(hmac256.Sum(nil)) 87 | request, error := http.NewRequest("POST", url+endPoint, bytes.NewBuffer(jsonData)) 88 | request.Header.Set("Content-Type", "application/json") 89 | request.Header.Set("X-BAPI-API-KEY", api_key) 90 | request.Header.Set("X-BAPI-SIGN", signature) 91 | request.Header.Set("X-BAPI-TIMESTAMP", strconv.FormatInt(time_stamp, 10)) 92 | request.Header.Set("X-BAPI-SIGN-TYPE", "2") 93 | request.Header.Set("X-BAPI-RECV-WINDOW", recv_window) 94 | reqDump, err := httputil.DumpRequestOut(request, true) 95 | if err != nil { 96 | log.Fatal(err) 97 | } 98 | fmt.Printf("Request Dump:\n%s", string(reqDump)) 99 | response, error := client.Do(request) 100 | if error != nil { 101 | panic(error) 102 | } 103 | defer response.Body.Close() 104 | elapsed := time.Since(now).Seconds() 105 | fmt.Printf("\n%s took %v seconds \n", endPoint, elapsed) 106 | fmt.Println("response Status:", response.Status) 107 | fmt.Println("response Headers:", response.Header) 108 | body, _ := ioutil.ReadAll(response.Body) 109 | fmt.Println("response Body:", string(body)) 110 | return body 111 | } 112 | -------------------------------------------------------------------------------- /V3_demo/api_demo/spot/Encryption_HMAC.js: -------------------------------------------------------------------------------- 1 | const crypto = require('crypto'); 2 | const axios = require('axios'); 3 | 4 | url='https://api-testnet.bybit.com'; 5 | 6 | var apiKey = "XXXXXXXXXXXXX"; 7 | var secret = "XXXXXXXXXXXXX"; 8 | var recvWindow = 5000; 9 | var timestamp = Date.now().toString(); 10 | 11 | function getSignature(parameters, secret) { 12 | return crypto.createHmac('sha256', secret).update(timestamp + apiKey + recvWindow + parameters).digest('hex'); 13 | } 14 | 15 | async function http_request(endpoint,method,data,Info) { 16 | var sign=getSignature(data,secret); 17 | if(method=="POST") 18 | { 19 | fullendpoint=url+endpoint; 20 | } 21 | else{ 22 | fullendpoint=url+endpoint+"?"+data; 23 | data=""; 24 | } 25 | //endpoint=url+endpoint 26 | var config = { 27 | method: method, 28 | url: fullendpoint, 29 | headers: { 30 | 'X-BAPI-SIGN-TYPE': '2', 31 | 'X-BAPI-SIGN': sign, 32 | 'X-BAPI-API-KEY': apiKey, 33 | 'X-BAPI-TIMESTAMP': timestamp, 34 | 'X-BAPI-RECV-WINDOW': '5000', 35 | 'Content-Type': 'application/json; charset=utf-8' 36 | }, 37 | data : data 38 | }; 39 | console.log(Info + " Calling...."); 40 | await axios(config) 41 | .then(function (response) { 42 | console.log(JSON.stringify(response.data)); 43 | }) 44 | .catch(function (error) { 45 | console.log(error); 46 | }); 47 | } 48 | 49 | //Create Order 50 | async function TestCase() 51 | { 52 | endpoint="/spot/v3/private/order" 53 | const orderLinkId = crypto.randomBytes(16).toString("hex"); 54 | var data = '{"symbol":"BTCUSDT","orderType":"Limit","side":"Buy","orderLinkId":"' + orderLinkId + '","orderQty":"0.001","orderPrice":"10000","timeInForce":"GTC"}'; 55 | await http_request(endpoint,"POST",data,"Create"); 56 | 57 | //Get Order List 58 | endpoint="/spot/v3/private/order" 59 | var data = 'orderLinkId=' + orderLinkId ; 60 | await http_request(endpoint,"GET",data,"Order List"); 61 | 62 | //Cancel order 63 | endpoint="/spot/v3/private/cancel-order" 64 | var data = '{"orderLinkId":"' + orderLinkId +'"}'; 65 | await http_request(endpoint,"POST",data,"Cancel"); 66 | } 67 | 68 | //Create, List and Cancel Orders 69 | TestCase() 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /V3_demo/api_demo/spot/Encryption_HMAC.php: -------------------------------------------------------------------------------- 1 | $url . $endpoint, 15 | CURLOPT_RETURNTRANSFER => true, 16 | CURLOPT_ENCODING => '', 17 | CURLOPT_MAXREDIRS => 10, 18 | CURLOPT_TIMEOUT => 0, 19 | CURLOPT_FOLLOWLOCATION => true, 20 | CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, 21 | CURLOPT_CUSTOMREQUEST => $method, 22 | CURLOPT_POSTFIELDS => $params, 23 | CURLOPT_HTTPHEADER => array( 24 | "X-BAPI-API-KEY: $api_key", 25 | "X-BAPI-SIGN: $signature", 26 | "X-BAPI-SIGN-TYPE: 2", 27 | "X-BAPI-TIMESTAMP: $timestamp", 28 | "X-BAPI-RECV-WINDOW: 5000", 29 | "Content-Type: application/json" 30 | ), 31 | )); 32 | if($method=="GET") 33 | { 34 | curl_setopt($curl, CURLOPT_HTTPGET, true); 35 | } 36 | echo $Info . "\n"; 37 | $response = curl_exec($curl); 38 | echo $response . "\n"; 39 | } 40 | 41 | #Create Order 42 | $endpoint="/spot/v3/private/order"; 43 | $method="POST"; 44 | $orderLinkId=uniqid(); 45 | $params='{"symbol":"BTCUSDT","orderType":"Limit","side":"Buy","orderLinkId":"' . $orderLinkId . '","orderQty":"0.001","orderPrice":"10000","timeInForce":"GTC"}'; 46 | http_req("$endpoint","$method","$params","Create Order"); 47 | 48 | #Get Order List 49 | $endpoint="/spot/v3/private/order"; 50 | $method="GET"; 51 | $params='orderLinkId=' . $orderLinkId; 52 | http_req($endpoint,$method,$params,"List Order"); 53 | 54 | #Cancel Order 55 | $endpoint="/spot/v3/private/cancel-order"; 56 | $method="POST"; 57 | $params='{"orderLinkId":"' . $orderLinkId .'"}'; 58 | http_req($endpoint,$method,$params,"Cancel Order"); 59 | 60 | curl_close($curl); 61 | 62 | 63 | -------------------------------------------------------------------------------- /V3_demo/api_demo/spot/Encryption_HMAC.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import time 3 | import hashlib 4 | import hmac 5 | import uuid 6 | 7 | api_key='XXXXXXXX' 8 | secret_key='XXXXXXXX' 9 | httpClient=requests.Session() 10 | recv_window=str(5000) 11 | url="https://api-testnet.bybit.com" # Testnet endpoint 12 | 13 | def HTTP_Request(endPoint,method,payload,Info): 14 | global time_stamp 15 | time_stamp=str(int(time.time() * 10 ** 3)) 16 | signature=genSignature(payload) 17 | headers = { 18 | 'X-BAPI-API-KEY': api_key, 19 | 'X-BAPI-SIGN': signature, 20 | 'X-BAPI-SIGN-TYPE': '2', 21 | 'X-BAPI-TIMESTAMP': time_stamp, 22 | 'X-BAPI-RECV-WINDOW': recv_window, 23 | 'Content-Type': 'application/json' 24 | } 25 | if(method=="POST"): 26 | response = httpClient.request(method, url+endPoint, headers=headers, data=payload) 27 | else: 28 | response = httpClient.request(method, url+endPoint+"?"+payload, headers=headers) 29 | print(response.text) 30 | print(Info + " Response Time : " + str(response.elapsed)) 31 | 32 | def genSignature(payload): 33 | param_str= str(time_stamp) + api_key + recv_window + payload 34 | hash = hmac.new(bytes(secret_key, "utf-8"), param_str.encode("utf-8"),hashlib.sha256) 35 | signature = hash.hexdigest() 36 | return signature 37 | 38 | #Create Order 39 | endpoint="/spot/v3/private/order" 40 | method="POST" 41 | orderLinkId=uuid.uuid4().hex 42 | params='{"symbol":"BTCUSDT","orderType":"Limit","side":"Buy","orderLinkId":"' + orderLinkId + '","orderQty":"0.001","orderPrice":"10000","timeInForce":"GTC"}'; 43 | HTTP_Request(endpoint,method,params,"Create") 44 | 45 | #Get Order List 46 | endpoint="/spot/v3/private/order" 47 | method="GET" 48 | params='orderLinkId=' + orderLinkId 49 | HTTP_Request(endpoint,method,params,"List") 50 | 51 | #Cancel Order 52 | endpoint="/spot/v3/private/cancel-order" 53 | method="POST" 54 | params='{"orderLinkId":"' + orderLinkId +'"}' 55 | HTTP_Request(endpoint,method,params,"Cancel") 56 | -------------------------------------------------------------------------------- /V3_demo/api_demo/spot/Encryption_HMAC.rb: -------------------------------------------------------------------------------- 1 | require 'digest' 2 | require "uri" 3 | require "net/http" 4 | require "date" 5 | require 'open-uri' 6 | require 'openssl' 7 | require 'securerandom' 8 | 9 | 10 | $api_key='XXXXXXXX' 11 | $secret_key='XXXXXXXX' 12 | $recv_window = '5000' 13 | $url = URI("https://api-testnet.bybit.com") # Testnet endpoint 14 | $time_stamp = "" 15 | 16 | def HTTP_Request(endPoint,method,payload) 17 | $time_stamp = DateTime.now.strftime('%Q') 18 | signature = genSignature(payload) 19 | fullUrl = $url + endPoint 20 | if method == "POST" 21 | request = Net::HTTP::Post.new(fullUrl,'Content-Type' => 'application/json') 22 | elsif method == "GET" 23 | payload="?"+payload 24 | fullUrl = $url + endPoint + payload 25 | request = Net::HTTP::Get.new(fullUrl) 26 | else 27 | puts "Check the method. It should be either GET or POST" 28 | exit 29 | end 30 | https = Net::HTTP.new(fullUrl.host, fullUrl.port) 31 | https.set_debug_output($stdout) 32 | https.use_ssl = true 33 | request["X-BAPI-API-KEY"] = $api_key 34 | request["X-BAPI-TIMESTAMP"] = $time_stamp 35 | request["X-BAPI-RECV-WINDOW"] = $recv_window 36 | request["X-BAPI-SIGN"] = signature 37 | request.body = payload 38 | puts payload 39 | response = https.request(request) 40 | puts response.read_body 41 | end 42 | 43 | def genSignature(payload) 44 | param_str= $time_stamp + $api_key + $recv_window + payload 45 | OpenSSL::HMAC.hexdigest('sha256', $secret_key, param_str) 46 | end 47 | 48 | #Create Order ( POST Method ) 49 | endPoint = "/spot/v3/private/order" 50 | method = "POST" 51 | orderLinkId = SecureRandom.uuid 52 | payload='{"symbol":"BTCUSDT","orderType":"Limit","side":"Buy","orderLinkId":"' + orderLinkId + '","orderQty":"0.001","orderPrice":"10000","timeInForce":"GTC"}'; 53 | HTTP_Request(endPoint,method,payload) 54 | 55 | #Retrieve Orders ( GET Method ) 56 | endPoint = "/spot/v3/private/order" 57 | method = "GET" 58 | payload="orderLinkId=" + orderLinkId 59 | HTTP_Request(endPoint,method,payload) 60 | -------------------------------------------------------------------------------- /V3_demo/api_demo/spot/Encryption_RSA.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import time 3 | import hashlib 4 | import uuid 5 | from Crypto.Hash import SHA256 # install pycryptodome libaray 6 | from Crypto.Signature import PKCS1_v1_5 7 | from Crypto.PublicKey import RSA 8 | 9 | api_key='XXXXXXXXX' 10 | rsa_private_key_path = '/user/private.pem' # use absolute path 11 | 12 | httpClient=requests.Session() 13 | recv_window=str(5000) 14 | url="https://api-testnet.bybit.com" # Testnet endpoint 15 | 16 | def HTTP_Request(endPoint,method,payload,Info): 17 | global time_stamp 18 | time_stamp=str(int(time.time() * 10 ** 3)) 19 | signature=genSignature(payload, rsa_private_key_path) 20 | headers = { 21 | 'X-BAPI-API-KEY': api_key, 22 | 'X-BAPI-SIGN': signature, 23 | 'X-BAPI-SIGN-TYPE': '2', 24 | 'X-BAPI-TIMESTAMP': time_stamp, 25 | 'X-BAPI-RECV-WINDOW': recv_window, 26 | 'Content-Type': 'application/json' 27 | } 28 | if(method=="POST"): 29 | response = httpClient.request(method, url+endPoint, headers=headers, data=payload) 30 | else: 31 | response = httpClient.request(method, url+endPoint+"?"+payload, headers=headers) 32 | print(response.text) 33 | print(Info + " Elapsed Time : " + str(response.elapsed)) 34 | 35 | 36 | """ 37 | Load private_key.pem, then generate base64 signature 38 | """ 39 | def genSignature(payload, rsa_private_key_path): 40 | param_str= str(time_stamp) + api_key + recv_window + payload 41 | 42 | with open(rsa_private_key_path, "r") as private_key_obj: 43 | private_key_str = private_key_obj.read() 44 | private_key = RSA.importKey(private_key_str) 45 | encoded_param = SHA256.new(param_str.encode("utf-8")) 46 | signature = PKCS1_v1_5.new(private_key).sign(encoded_param) 47 | 48 | return base64.b64encode(signature).decode() 49 | 50 | #Create Order 51 | endpoint="/spot/v3/private/order" 52 | method="POST" 53 | orderLinkId=uuid.uuid4().hex 54 | params='{"symbol":"BTCUSDT","orderType":"Limit","side":"Buy","orderLinkId":"' + orderLinkId + '","orderQty":"0.001","orderPrice":"10000","timeInForce":"GTC"}'; 55 | HTTP_Request(endpoint,method,params,"Create") 56 | 57 | #Get Order List 58 | endpoint="/spot/v3/private/order" 59 | method="GET" 60 | params='orderLinkId=' + orderLinkId 61 | HTTP_Request(endpoint,method,params,"List") 62 | 63 | #Cancel Order 64 | endpoint="/spot/v3/private/cancel-order" 65 | method="POST" 66 | params='{"orderLinkId":"' + orderLinkId +'"}' 67 | HTTP_Request(endpoint,method,params,"Cancel") 68 | -------------------------------------------------------------------------------- /V3_demo/api_demo/unified_margin/Encryption_HMAC.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "crypto/hmac" 6 | "crypto/sha256" 7 | "encoding/hex" 8 | "encoding/json" 9 | "fmt" 10 | "io/ioutil" 11 | "log" 12 | "net/http" 13 | "net/http/httputil" 14 | "strconv" 15 | "time" 16 | ) 17 | 18 | func httpClient() *http.Client { 19 | client := &http.Client{Timeout: 10 * time.Second} 20 | return client 21 | } 22 | 23 | var url string = "https://api-testnet.bybit.com" 24 | var api_key = "XXXXXXXX" 25 | var apiSecret = "XXXXXXXX" 26 | var recv_window = "5000" 27 | var signature = "" 28 | 29 | func main() { 30 | c := httpClient() 31 | 32 | //POST Method 33 | postParams := map[string]interface{}{"symbol": "BTCUSDT", "orderType": "Limit", "side": "Buy", "qty": "0.001", "price": "10000", "timeInForce": "GoodTillCancel", "category": "linear", "orderLinkId": "TEST1234"} 34 | postEndPoint := "/unified/v3/private/order/create" 35 | postRequest(c, http.MethodPost, postParams, postEndPoint) 36 | 37 | //GET Method 38 | getEndPoint := "/unified/v3/private/order/unfilled-orders" 39 | getParams := "category=linear&symbol=BTCUSDT" 40 | getRequest(c, http.MethodGet, getParams, getEndPoint) 41 | } 42 | 43 | func getRequest(client *http.Client, method string, params string, endPoint string) []byte { 44 | now := time.Now() 45 | unixNano := now.UnixNano() 46 | time_stamp := unixNano / 1000000 47 | hmac256 := hmac.New(sha256.New, []byte(apiSecret)) 48 | hmac256.Write([]byte(strconv.FormatInt(time_stamp, 10) + api_key + recv_window + params)) 49 | signature = hex.EncodeToString(hmac256.Sum(nil)) 50 | request, error := http.NewRequest("GET", url+endPoint+"?"+params, nil) 51 | request.Header.Set("Content-Type", "application/json") 52 | request.Header.Set("X-BAPI-API-KEY", api_key) 53 | request.Header.Set("X-BAPI-SIGN", signature) 54 | request.Header.Set("X-BAPI-TIMESTAMP", strconv.FormatInt(time_stamp, 10)) 55 | request.Header.Set("X-BAPI-SIGN-TYPE", "2") 56 | request.Header.Set("X-BAPI-RECV-WINDOW", recv_window) 57 | reqDump, err := httputil.DumpRequestOut(request, true) 58 | if err != nil { 59 | log.Fatal(err) 60 | } 61 | fmt.Printf("Request Dump:\n%s", string(reqDump)) 62 | response, error := client.Do(request) 63 | if error != nil { 64 | panic(error) 65 | } 66 | defer response.Body.Close() 67 | elapsed := time.Since(now).Seconds() 68 | fmt.Printf("\n%s took %v seconds \n", endPoint, elapsed) 69 | fmt.Println("response Status:", response.Status) 70 | fmt.Println("response Headers:", response.Header) 71 | body, _ := ioutil.ReadAll(response.Body) 72 | fmt.Println("response Body:", string(body)) 73 | return body 74 | } 75 | 76 | func postRequest(client *http.Client, method string, params interface{}, endPoint string) []byte { 77 | now := time.Now() 78 | unixNano := now.UnixNano() 79 | time_stamp := unixNano / 1000000 80 | jsonData, err := json.Marshal(params) 81 | if err != nil { 82 | log.Fatal(err) 83 | } 84 | hmac256 := hmac.New(sha256.New, []byte(apiSecret)) 85 | hmac256.Write([]byte(strconv.FormatInt(time_stamp, 10) + api_key + recv_window + string(jsonData[:]))) 86 | signature = hex.EncodeToString(hmac256.Sum(nil)) 87 | request, error := http.NewRequest("POST", url+endPoint, bytes.NewBuffer(jsonData)) 88 | request.Header.Set("Content-Type", "application/json") 89 | request.Header.Set("X-BAPI-API-KEY", api_key) 90 | request.Header.Set("X-BAPI-SIGN", signature) 91 | request.Header.Set("X-BAPI-TIMESTAMP", strconv.FormatInt(time_stamp, 10)) 92 | request.Header.Set("X-BAPI-SIGN-TYPE", "2") 93 | request.Header.Set("X-BAPI-RECV-WINDOW", recv_window) 94 | reqDump, err := httputil.DumpRequestOut(request, true) 95 | if err != nil { 96 | log.Fatal(err) 97 | } 98 | fmt.Printf("Request Dump:\n%s", string(reqDump)) 99 | response, error := client.Do(request) 100 | if error != nil { 101 | panic(error) 102 | } 103 | defer response.Body.Close() 104 | elapsed := time.Since(now).Seconds() 105 | fmt.Printf("\n%s took %v seconds \n", endPoint, elapsed) 106 | fmt.Println("response Status:", response.Status) 107 | fmt.Println("response Headers:", response.Header) 108 | body, _ := ioutil.ReadAll(response.Body) 109 | fmt.Println("response Body:", string(body)) 110 | return body 111 | } 112 | -------------------------------------------------------------------------------- /V3_demo/api_demo/unified_margin/Encryption_HMAC.js: -------------------------------------------------------------------------------- 1 | const crypto = require('crypto'); 2 | const axios = require('axios'); 3 | 4 | url='https://api-testnet.bybit.com'; 5 | 6 | var apiKey = "XXXXXXXXXX"; 7 | var secret = "XXXXXXXXXX"; 8 | var recvWindow = 5000; 9 | var timestamp = Date.now().toString(); 10 | 11 | function getSignature(parameters, secret) { 12 | return crypto.createHmac('sha256', secret).update(timestamp + apiKey + recvWindow + parameters).digest('hex'); 13 | } 14 | 15 | async function http_request(endpoint,method,data,Info) { 16 | var sign=getSignature(data,secret); 17 | if(method=="POST") 18 | { 19 | fullendpoint=url+endpoint; 20 | } 21 | else{ 22 | fullendpoint=url+endpoint+"?"+data; 23 | data=""; 24 | } 25 | //endpoint=url+endpoint 26 | var config = { 27 | method: method, 28 | url: fullendpoint, 29 | headers: { 30 | 'X-BAPI-SIGN-TYPE': '2', 31 | 'X-BAPI-SIGN': sign, 32 | 'X-BAPI-API-KEY': apiKey, 33 | 'X-BAPI-TIMESTAMP': timestamp, 34 | 'X-BAPI-RECV-WINDOW': '5000', 35 | 'Content-Type': 'application/json; charset=utf-8' 36 | }, 37 | data : data 38 | }; 39 | console.log(Info + " Calling...."); 40 | await axios(config) 41 | .then(function (response) { 42 | console.log(JSON.stringify(response.data)); 43 | }) 44 | .catch(function (error) { 45 | console.log(error); 46 | }); 47 | } 48 | 49 | //Create Order 50 | async function TestCase() 51 | { 52 | endpoint="/unified/v3/private/order/create" 53 | const orderLinkId = crypto.randomBytes(16).toString("hex"); 54 | var data = '{"symbol":"BTCUSDT","orderType":"Limit","side":"Buy","orderLinkId":"' + orderLinkId + '","qty":"0.001","price":"10000","timeInForce":"GoodTillCancel","category":"linear"}'; 55 | await http_request(endpoint,"POST",data,"Create"); 56 | 57 | //Get unfilled Order List 58 | endpoint="/unified/v3/private/order/unfilled-orders" 59 | var data = 'symbol=BTCUSDT&category=linear&orderStatus=New&orderLinkId=' + orderLinkId; 60 | await http_request(endpoint,"GET",data,"Unfilled Order List"); 61 | 62 | //Get Order List 63 | endpoint="/unified/v3/private/order/list" 64 | var data = 'symbol=BTCUSDT&category=linear&orderStatus=New&orderLinkId=' + orderLinkId ; 65 | await http_request(endpoint,"GET",data,"Order List"); 66 | 67 | //Cancel order 68 | endpoint="/unified/v3/private/order/cancel" 69 | var data = '{"symbol": "BTCUSDT","category":"linear","orderLinkId":"' + orderLinkId +'"}'; 70 | await http_request(endpoint,"POST",data,"Cancel"); 71 | } 72 | 73 | //Create, List and Cancel Orders 74 | TestCase() 75 | 76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /V3_demo/api_demo/unified_margin/Encryption_HMAC.php: -------------------------------------------------------------------------------- 1 | $url . $endpoint, 19 | CURLOPT_RETURNTRANSFER => true, 20 | CURLOPT_ENCODING => '', 21 | CURLOPT_MAXREDIRS => 10, 22 | CURLOPT_TIMEOUT => 0, 23 | CURLOPT_FOLLOWLOCATION => true, 24 | CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, 25 | CURLOPT_CUSTOMREQUEST => $method, 26 | CURLOPT_POSTFIELDS => $params, 27 | CURLOPT_HTTPHEADER => array( 28 | "X-BAPI-API-KEY: $api_key", 29 | "X-BAPI-SIGN: $signature", 30 | "X-BAPI-SIGN-TYPE: 2", 31 | "X-BAPI-TIMESTAMP: $timestamp", 32 | "X-BAPI-RECV-WINDOW: 5000", 33 | "Content-Type: application/json" 34 | ), 35 | )); 36 | if($method=="GET") 37 | { 38 | curl_setopt($curl, CURLOPT_HTTPGET, true); 39 | } 40 | echo $Info . "\n"; 41 | $response = curl_exec($curl); 42 | echo $response . "\n"; 43 | } 44 | 45 | #Create Order 46 | $endpoint="/unified/v3/private/order/create"; 47 | $method="POST"; 48 | $orderLinkId=uniqid(); 49 | $params='{"symbol":"BTCUSDT","orderType":"Limit","side":"Buy","qty":"0.001","price":"10000","timeInForce":"GoodTillCancel","category":"linear","orderLinkId": "' . $orderLinkId . '"}'; 50 | http_req("$endpoint","$method","$params","Create Order"); 51 | 52 | #Get unfilled Order List 53 | $endpoint="/unified/v3/private/order/unfilled-orders"; 54 | $method="GET"; 55 | $params='category=linear&symbol=BTCUSDT'; 56 | http_req($endpoint,$method,$params,"Unfilled Order"); 57 | 58 | #Cancel Order 59 | $endpoint="/unified/v3/private/order/cancel"; 60 | $method="POST"; 61 | $params='{"symbol": "ETHUSDT","category":"linear","orderLinkId": "' . $orderLinkId . '"}'; 62 | http_req($endpoint,$method,$params,"Cancel Order"); 63 | 64 | curl_close($curl); 65 | 66 | 67 | -------------------------------------------------------------------------------- /V3_demo/api_demo/unified_margin/Encryption_HMAC.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import time 3 | import hashlib 4 | import hmac 5 | import uuid 6 | 7 | api_key='XXXXXXXXXX' 8 | secret_key='XXXXXXXXXX' 9 | httpClient=requests.Session() 10 | recv_window=str(5000) 11 | url="https://api-testnet.bybit.com" # Testnet endpoint 12 | 13 | def HTTP_Request(endPoint,method,payload,Info): 14 | global time_stamp 15 | time_stamp=str(int(time.time() * 10 ** 3)) 16 | signature=genSignature(payload) 17 | headers = { 18 | 'X-BAPI-API-KEY': api_key, 19 | 'X-BAPI-SIGN': signature, 20 | 'X-BAPI-SIGN-TYPE': '2', 21 | 'X-BAPI-TIMESTAMP': time_stamp, 22 | 'X-BAPI-RECV-WINDOW': recv_window, 23 | 'Content-Type': 'application/json' 24 | } 25 | if(method=="POST"): 26 | response = httpClient.request(method, url+endPoint, headers=headers, data=payload) 27 | else: 28 | response = httpClient.request(method, url+endPoint+"?"+payload, headers=headers) 29 | print(response.text) 30 | print(Info + " Elapsed Time : " + str(response.elapsed)) 31 | 32 | def genSignature(payload): 33 | param_str= str(time_stamp) + api_key + recv_window + payload 34 | hash = hmac.new(bytes(secret_key, "utf-8"), param_str.encode("utf-8"),hashlib.sha256) 35 | signature = hash.hexdigest() 36 | return signature 37 | 38 | #Create Order 39 | endpoint="/unified/v3/private/order/create" 40 | method="POST" 41 | orderLinkId=uuid.uuid4().hex 42 | params='{"symbol":"BTCUSDT","orderType":"Limit","side":"Buy","qty":"0.001","price":"10000","timeInForce":"GoodTillCancel","category":"linear","orderLinkId": "' + orderLinkId + '"}' 43 | HTTP_Request(endpoint,method,params,"Create") 44 | 45 | #Get unfilled Orders 46 | endpoint="/unified/v3/private/order/unfilled-orders" 47 | method="GET" 48 | params='category=linear&symbol=BTCUSDT' 49 | HTTP_Request(endpoint,method,params,"UnFilled") 50 | 51 | #Get Order List 52 | endpoint="/unified/v3/private/order/list" 53 | method="GET" 54 | params="symbol=BTCUSDT&category=linear&orderLinkId="+orderLinkId 55 | HTTP_Request(endpoint,method,params,"List") 56 | 57 | #Cancel Order 58 | endpoint="/unified/v3/private/order/cancel" 59 | method="POST" 60 | params='{"symbol": "BTCUSDT","category":"linear","orderLinkId": "'+orderLinkId+'"}' 61 | HTTP_Request(endpoint,method,params,"Cancel") 62 | -------------------------------------------------------------------------------- /V3_demo/api_demo/unified_margin/Encryption_HMAC.rb: -------------------------------------------------------------------------------- 1 | require 'digest' 2 | require "uri" 3 | require "net/http" 4 | require "date" 5 | require 'open-uri' 6 | require 'openssl' 7 | require 'securerandom' 8 | 9 | 10 | $api_key='XXXXXXXXX' 11 | $secret_key='XXXXXXXXX' 12 | $recv_window = '5000' 13 | $url = URI("https://api-testnet.bybit.com") # Testnet endpoint 14 | $time_stamp = "" 15 | 16 | def HTTP_Request(endPoint,method,payload) 17 | $time_stamp = DateTime.now.strftime('%Q') 18 | signature = genSignature(payload) 19 | fullUrl = $url + endPoint 20 | if method == "POST" 21 | request = Net::HTTP::Post.new(fullUrl,'Content-Type' => 'application/json') 22 | elsif method == "GET" 23 | payload="?"+payload 24 | fullUrl = $url + endPoint + payload 25 | request = Net::HTTP::Get.new(fullUrl) 26 | else 27 | puts "Check the method. It should be either GET or POST" 28 | exit 29 | end 30 | https = Net::HTTP.new(fullUrl.host, fullUrl.port) 31 | https.set_debug_output($stdout) 32 | https.use_ssl = true 33 | request["X-BAPI-API-KEY"] = $api_key 34 | request["X-BAPI-TIMESTAMP"] = $time_stamp 35 | request["X-BAPI-RECV-WINDOW"] = $recv_window 36 | request["X-BAPI-SIGN"] = signature 37 | request.body = payload 38 | puts payload 39 | response = https.request(request) 40 | puts response.read_body 41 | end 42 | 43 | def genSignature(payload) 44 | param_str= $time_stamp + $api_key + $recv_window + payload 45 | OpenSSL::HMAC.hexdigest('sha256', $secret_key, param_str) 46 | end 47 | 48 | #Create Order ( POST Method ) 49 | endPoint = "/unified/v3/private/order/create" 50 | method = "POST" 51 | orderLinkId = SecureRandom.uuid 52 | payload='{"symbol":"BTCUSDT","orderType":"Limit","side":"Buy","qty":"0.001","price":"10000","timeInForce":"GoodTillCancel","category":"linear","orderLinkId": "' + orderLinkId + '"}' 53 | HTTP_Request(endPoint,method,payload) 54 | 55 | #Retrieve Unfilled Orders ( GET Method ) 56 | endPoint = "/unified/v3/private/order/unfilled-orders" 57 | method = "GET" 58 | payload='category=linear&symbol=BTCUSDT' 59 | HTTP_Request(endPoint,method,payload) 60 | -------------------------------------------------------------------------------- /V3_demo/api_demo/unified_margin/Encryption_RSA.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import time 3 | import hashlib 4 | import uuid 5 | from Crypto.Hash import SHA256 # install pycryptodome libaray 6 | from Crypto.Signature import PKCS1_v1_5 7 | from Crypto.PublicKey import RSA 8 | 9 | api_key='XXXXXXXXX' 10 | rsa_private_key_path = '/user/private.pem' # use absolute path 11 | 12 | httpClient=requests.Session() 13 | recv_window=str(5000) 14 | url="https://api-testnet.bybit.com" # Testnet endpoint 15 | 16 | def HTTP_Request(endPoint,method,payload,Info): 17 | global time_stamp 18 | time_stamp=str(int(time.time() * 10 ** 3)) 19 | signature=genSignature(payload, rsa_private_key_path) 20 | headers = { 21 | 'X-BAPI-API-KEY': api_key, 22 | 'X-BAPI-SIGN': signature, 23 | 'X-BAPI-SIGN-TYPE': '2', 24 | 'X-BAPI-TIMESTAMP': time_stamp, 25 | 'X-BAPI-RECV-WINDOW': recv_window, 26 | 'Content-Type': 'application/json' 27 | } 28 | if(method=="POST"): 29 | response = httpClient.request(method, url+endPoint, headers=headers, data=payload) 30 | else: 31 | response = httpClient.request(method, url+endPoint+"?"+payload, headers=headers) 32 | print(response.text) 33 | print(Info + " Elapsed Time : " + str(response.elapsed)) 34 | 35 | 36 | """ 37 | Load private_key.pem, then generate base64 signature 38 | """ 39 | def genSignature(payload, rsa_private_key_path): 40 | param_str= str(time_stamp) + api_key + recv_window + payload 41 | 42 | with open(rsa_private_key_path, "r") as private_key_obj: 43 | private_key_str = private_key_obj.read() 44 | private_key = RSA.importKey(private_key_str) 45 | encoded_param = SHA256.new(param_str.encode("utf-8")) 46 | signature = PKCS1_v1_5.new(private_key).sign(encoded_param) 47 | 48 | return base64.b64encode(signature).decode() 49 | 50 | #Create Order 51 | endpoint="/unified/v3/private/order/create" 52 | method="POST" 53 | orderLinkId=uuid.uuid4().hex 54 | params='{"symbol":"BTCUSDT","orderType":"Limit","side":"Buy","qty":"0.001","price":"10000","timeInForce":"GoodTillCancel","category":"linear","orderLinkId": "' + orderLinkId + '"}' 55 | HTTP_Request(endpoint,method,params,"Create") 56 | 57 | #Get unfilled Orders 58 | endpoint="/unified/v3/private/order/unfilled-orders" 59 | method="GET" 60 | params='category=linear&symbol=BTCUSDT' 61 | HTTP_Request(endpoint,method,params,"UnFilled") 62 | 63 | #Get Order List 64 | endpoint="/unified/v3/private/order/list" 65 | method="GET" 66 | params="symbol=BTCUSDT&category=linear&orderLinkId="+orderLinkId 67 | HTTP_Request(endpoint,method,params,"List") 68 | 69 | #Cancel Order 70 | endpoint="/unified/v3/private/order/cancel" 71 | method="POST" 72 | params='{"symbol": "BTCUSDT","category":"linear","orderLinkId": "'+orderLinkId+'"}' 73 | HTTP_Request(endpoint,method,params,"Cancel") 74 | -------------------------------------------------------------------------------- /V3_demo/wss_demo/js/ws_private_demo.js: -------------------------------------------------------------------------------- 1 | var url = require('url'); 2 | var WebSocket = require('ws'); 3 | var crypto = require('crypto'); 4 | var endpoint = "wss://stream-testnet.bybit.com/contract/private/v3" 5 | console.log('attempting to connect to WebSocket %j', endpoint); 6 | var client = new WebSocket(endpoint); 7 | const apiKey="XXXXXXXXX"; 8 | const apiSecret="XXXXXXXXX"; 9 | client.on('open', function () { 10 | console.log('"open" event!'); 11 | console.log('WebSocket Client Connected'); 12 | const expires = new Date().getTime() + 10000; 13 | const signature = crypto.createHmac("sha256", apiSecret).update("GET/realtime" + expires).digest("hex"); 14 | const payload={ 15 | op: "auth", 16 | args: [apiKey, expires.toFixed(0), signature], 17 | } 18 | client.send(JSON.stringify(payload)); 19 | setInterval(()=>{client.ping()}, 30000); 20 | client.ping(); 21 | client.send(JSON.stringify({"op": "subscribe", "args": ['order']})); 22 | }); 23 | 24 | client.on('message', function (data) { 25 | console.log('"message" event! %j', JSON.parse(Buffer.from(data).toString())); 26 | }); 27 | client.on('ping', function (data, flags) { 28 | console.log("ping received"); 29 | }); 30 | client.on('pong', function (data, flags) { 31 | console.log("pong received"); 32 | }); 33 | -------------------------------------------------------------------------------- /V3_demo/wss_demo/js/ws_public_demo.js: -------------------------------------------------------------------------------- 1 | var url = require('url'); 2 | var WebSocket = require('ws'); 3 | var crypto = require('crypto'); 4 | var endpoint = "wss://stream-testnet.bybit.com/contract/usdt/public/v3" 5 | console.log('attempting to connect to WebSocket %j', endpoint); 6 | var client = new WebSocket(endpoint); 7 | client.on('open', function () { 8 | console.log('"open" event!'); 9 | console.log('WebSocket Client Connected'); 10 | setInterval(()=>{client.ping()}, 30000); 11 | client.ping(); 12 | client.send(JSON.stringify({"op": "subscribe", "args": ["orderbook.25.BTCUSDT"]})); 13 | }); 14 | 15 | client.on('message', function (data) { 16 | console.log('"message" event! %j', JSON.parse(Buffer.from(data).toString())); 17 | }); 18 | client.on('ping', function (data, flags) { 19 | console.log("ping received"); 20 | }); 21 | client.on('pong', function (data, flags) { 22 | console.log("pong received"); 23 | }); 24 | -------------------------------------------------------------------------------- /V3_demo/wss_demo/python/ws_private_hmac_demo.py: -------------------------------------------------------------------------------- 1 | import hmac 2 | import json 3 | import logging 4 | import time 5 | 6 | import websocket 7 | 8 | logging.basicConfig(filename='logfile_wrapper.log', level=logging.DEBUG, 9 | format='%(asctime)s %(levelname)s %(message)s') 10 | topic = "user.order.contractAccount" 11 | 12 | def on_message(ws, message): 13 | data = json.loads(message) 14 | print(data) 15 | 16 | def on_error(ws, error): 17 | print('we got error') 18 | print(error) 19 | 20 | def on_close(ws): 21 | print("### about to close please don't close ###") 22 | 23 | def send_auth(ws): 24 | key = 'XXXXXXXXXX' 25 | secret = 'XXXXXXXXXX' 26 | expires = int((time.time() + 10) * 1000) 27 | _val = f'GET/realtime{expires}' 28 | print(_val) 29 | signature = str(hmac.new( 30 | bytes(secret, 'utf-8'), 31 | bytes(_val, 'utf-8'), digestmod='sha256' 32 | ).hexdigest()) 33 | ws.send(json.dumps({"op": "auth", "args": [key, expires, signature]})) 34 | 35 | def on_pong(ws, *data): 36 | print('pong received') 37 | 38 | def on_ping(ws, *data): 39 | print('ping received') 40 | 41 | def on_open(ws): 42 | print('opened') 43 | send_auth(ws) 44 | print('send subscription ' + topic) 45 | ws.send(json.dumps({"op": "subscribe", "args": [topic]})) 46 | 47 | def connWS(): 48 | ws = websocket.WebSocketApp("wss://stream-testnet.bybit.com/contract/private/v3", 49 | on_message=on_message, 50 | on_error=on_error, 51 | on_close=on_close, 52 | on_ping=on_ping, 53 | on_pong=on_pong, 54 | on_open=on_open 55 | ) 56 | ws.run_forever( 57 | #http_proxy_host='127.0.0.1', 58 | #http_proxy_port=1087, 59 | ping_interval=20, 60 | ping_timeout=10 61 | ) 62 | 63 | if __name__ == "__main__": 64 | #websocket.enableTrace(True) 65 | connWS() 66 | -------------------------------------------------------------------------------- /V3_demo/wss_demo/python/ws_private_rsa_demo.py: -------------------------------------------------------------------------------- 1 | import hmac 2 | import websocket 3 | import threading 4 | import time 5 | from Crypto.PublicKey import RSA 6 | import json 7 | import base64 8 | from Crypto.Hash import SHA256 9 | from Crypto.Signature import PKCS1_v1_5 10 | 11 | 12 | class StreamManager(object): 13 | def __init__(self, ws_url: str, topic_list: list, rsa_api_key: str, private_key: str = None): 14 | self.ws = None 15 | self.ws_url = ws_url 16 | self.topic_list = topic_list 17 | self.rsa_api_key = rsa_api_key 18 | self.private_key = private_key 19 | 20 | @staticmethod 21 | def on_message(ws, message): 22 | print(message) 23 | 24 | @staticmethod 25 | def on_error(ws, error): 26 | print(f"we got error:{error}") 27 | 28 | @staticmethod 29 | def on_close(ws): 30 | print("### about to close please don't close ###") 31 | 32 | def on_open(self, ws): 33 | def send_auth(ws): 34 | expires = int((time.time() + 1000000000) * 1000) 35 | _val = f'GET/realtime{expires}' 36 | private_key = RSA.importKey(self.private_key) 37 | h = SHA256.new(_val.encode('utf-8')) 38 | signature_temp = PKCS1_v1_5.new(private_key).sign(h) 39 | result = base64.b64encode(signature_temp).decode() 40 | 41 | auth_data = json.dumps({ 42 | "op": "auth", 43 | "args": [self.rsa_api_key, expires, result] 44 | }) 45 | print(auth_data) 46 | ws.send(auth_data) 47 | 48 | t0 = threading.Thread(target=send_auth, args=(ws,)) 49 | t0.start() 50 | 51 | def pingPer(ws): 52 | while True: 53 | ping_data = json.dumps({ 54 | "op": "ping", 55 | "args": [[int((time.time() + 1) * 1000)]] 56 | }) 57 | 58 | ws.send(ping_data) 59 | print(ping_data) 60 | time.sleep(20) 61 | 62 | t1 = threading.Thread(target=pingPer, args=(ws,)) 63 | t1.start() 64 | subscribe_data = json.dumps({ 65 | "op": "subscribe", 66 | "args": self.topic_list 67 | }) 68 | print(subscribe_data) 69 | time.sleep(1) 70 | ws.send(subscribe_data) 71 | 72 | def start(self): 73 | self.ws = websocket.WebSocketApp( 74 | url=self.ws_url, 75 | on_message=lambda ws, message: self.on_message(ws, message), 76 | on_error=lambda ws, error: self.on_error(ws, error), 77 | on_close=lambda ws: self.on_close(ws), 78 | on_open=lambda ws: self.on_open(ws) 79 | ) 80 | self.ws.run_forever() 81 | 82 | 83 | if __name__ == "__main__": 84 | private_key_file = "xxxx_private.pem" # private pem file name 85 | with open(f"/Users/xxxxx/{private_key_file}", "r") as pk: 86 | private_key_str = pk.read() # 获取private_key 87 | 88 | testnet_domain = "stream-testnet.bybit.com" # wss testnet 89 | mainnet_domain = "stream.bybit.com" # wss mainnet 90 | 91 | contract_path = "/contract/private/v3" # contract v3 92 | unified_path = "/unified/private/v3" # unified v3 93 | uta_path = "/v5/private" # v5 94 | 95 | url_wss = f"wss://{testnet_domain}{contract_path}" 96 | 97 | rsa_apiKey = "XXXXXXXX" # the one that provided by Bybit after you input rsa public key 98 | privateKey = private_key_str 99 | 100 | v3_contract_topics = ["user.order.contractAccount", "user.position.contractAccount", "user.wallet.contractAccount", 101 | "user.execution.contractAccount"] 102 | 103 | v3_unified_topic = ["user.order.unifiedAccount", "user.position.unifiedAccount", "user.execution.unifiedAccount", 104 | "user.wallet.unifiedAccount"] 105 | 106 | v5_topics = ["order", "position", "wallet", "execution"] 107 | 108 | sm = StreamManager(ws_url=url_wss, topic_list=v5_uta_topics, rsa_api_key=rsa_apiKey, private_key=privateKey) 109 | sm.start() 110 | -------------------------------------------------------------------------------- /V3_demo/wss_demo/python/ws_public_demo.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | import time 4 | from datetime import datetime 5 | import websocket 6 | 7 | logging.basicConfig(filename='logfile_wrapper.log', level=logging.DEBUG, 8 | format='%(asctime)s %(levelname)s %(message)s') 9 | 10 | topic = "orderbook.25.BTCUSDT" 11 | 12 | def on_message(ws, message): 13 | data = json.loads(message) 14 | print(data) 15 | 16 | def on_error(ws, error): 17 | print('we got error') 18 | print(error) 19 | print('print error complete') 20 | 21 | def on_close(ws): 22 | print("### about to close please don't close ###") 23 | 24 | def on_open(ws): 25 | print('opened') 26 | ws.send(json.dumps({"op": "subscribe", "args": [topic]})) 27 | 28 | def on_pong(ws, *data): 29 | print('pong received') 30 | 31 | def on_ping(ws, *data): 32 | now = datetime.now() 33 | dt_string = now.strftime("%d/%m/%Y %H:%M:%S") 34 | print("date and time =", dt_string) 35 | print('ping received') 36 | 37 | def connWS(): 38 | ws = websocket.WebSocketApp( 39 | "wss://stream-testnet.bybit.com/contract/usdt/public/v3", 40 | on_message=on_message, 41 | on_error=on_error, 42 | on_close=on_close, 43 | on_ping=on_ping, 44 | on_pong=on_pong, 45 | on_open=on_open 46 | ) 47 | ws.run_forever( 48 | #http_proxy_host='127.0.0.1', 49 | #http_proxy_port=1087, 50 | ping_interval=20, 51 | ping_timeout=10 52 | ) 53 | 54 | 55 | if __name__ == "__main__": 56 | #websocket.enableTrace(True) 57 | connWS() 58 | -------------------------------------------------------------------------------- /V5_demo/api_demo/Encryption_HMAC.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "crypto/hmac" 6 | "crypto/sha256" 7 | "encoding/hex" 8 | "encoding/json" 9 | "fmt" 10 | "io/ioutil" 11 | "log" 12 | "net/http" 13 | "net/http/httputil" 14 | "strconv" 15 | "time" 16 | ) 17 | 18 | func httpClient() *http.Client { 19 | client := &http.Client{Timeout: 10 * time.Second} 20 | return client 21 | } 22 | 23 | var url string = "https://api-testnet.bybit.com" 24 | var api_key = "XXXXXXXXXX" 25 | var apiSecret = "XXXXXXXXXX" 26 | var recv_window = "5000" 27 | var signature = "" 28 | 29 | func main() { 30 | c := httpClient() 31 | 32 | //POST Method 33 | postParams := map[string]interface{}{"category": "linear", "symbol": "BTCUSDT", "side": "Buy", "positionIdx": 0, "orderType": "Limit", "qty": "0.001", "price": "10000", "timeInForce": "GTC"} 34 | postEndPoint := "/v5/order/create" 35 | postRequest(c, http.MethodPost, postParams, postEndPoint) 36 | 37 | //GET Method 38 | getEndPoint := "/v5/order/realtime" 39 | getParams := "category=linear&settleCoin=USDT" 40 | getRequest(c, http.MethodGet, getParams, getEndPoint) 41 | } 42 | 43 | func getRequest(client *http.Client, method string, params string, endPoint string) []byte { 44 | now := time.Now() 45 | unixNano := now.UnixNano() 46 | time_stamp := unixNano / 1000000 47 | hmac256 := hmac.New(sha256.New, []byte(apiSecret)) 48 | hmac256.Write([]byte(strconv.FormatInt(time_stamp, 10) + api_key + recv_window + params)) 49 | signature = hex.EncodeToString(hmac256.Sum(nil)) 50 | request, error := http.NewRequest("GET", url+endPoint+"?"+params, nil) 51 | request.Header.Set("Content-Type", "application/json") 52 | request.Header.Set("X-BAPI-API-KEY", api_key) 53 | request.Header.Set("X-BAPI-SIGN", signature) 54 | request.Header.Set("X-BAPI-TIMESTAMP", strconv.FormatInt(time_stamp, 10)) 55 | request.Header.Set("X-BAPI-SIGN-TYPE", "2") 56 | request.Header.Set("X-BAPI-RECV-WINDOW", recv_window) 57 | reqDump, err := httputil.DumpRequestOut(request, true) 58 | if err != nil { 59 | log.Fatal(err) 60 | } 61 | fmt.Printf("Request Dump:\n%s", string(reqDump)) 62 | response, error := client.Do(request) 63 | if error != nil { 64 | panic(error) 65 | } 66 | defer response.Body.Close() 67 | elapsed := time.Since(now).Seconds() 68 | fmt.Printf("\n%s took %v seconds \n", endPoint, elapsed) 69 | fmt.Println("response Status:", response.Status) 70 | fmt.Println("response Headers:", response.Header) 71 | body, _ := ioutil.ReadAll(response.Body) 72 | fmt.Println("response Body:", string(body)) 73 | return body 74 | } 75 | 76 | func postRequest(client *http.Client, method string, params interface{}, endPoint string) []byte { 77 | now := time.Now() 78 | unixNano := now.UnixNano() 79 | time_stamp := unixNano / 1000000 80 | jsonData, err := json.Marshal(params) 81 | if err != nil { 82 | log.Fatal(err) 83 | } 84 | hmac256 := hmac.New(sha256.New, []byte(apiSecret)) 85 | hmac256.Write([]byte(strconv.FormatInt(time_stamp, 10) + api_key + recv_window + string(jsonData[:]))) 86 | signature = hex.EncodeToString(hmac256.Sum(nil)) 87 | request, error := http.NewRequest("POST", url+endPoint, bytes.NewBuffer(jsonData)) 88 | request.Header.Set("Content-Type", "application/json") 89 | request.Header.Set("X-BAPI-API-KEY", api_key) 90 | request.Header.Set("X-BAPI-SIGN", signature) 91 | request.Header.Set("X-BAPI-TIMESTAMP", strconv.FormatInt(time_stamp, 10)) 92 | request.Header.Set("X-BAPI-SIGN-TYPE", "2") 93 | request.Header.Set("X-BAPI-RECV-WINDOW", recv_window) 94 | reqDump, err := httputil.DumpRequestOut(request, true) 95 | if err != nil { 96 | log.Fatal(err) 97 | } 98 | fmt.Printf("Request Dump:\n%s", string(reqDump)) 99 | response, error := client.Do(request) 100 | if error != nil { 101 | panic(error) 102 | } 103 | defer response.Body.Close() 104 | elapsed := time.Since(now).Seconds() 105 | fmt.Printf("\n%s took %v seconds \n", endPoint, elapsed) 106 | fmt.Println("response Status:", response.Status) 107 | fmt.Println("response Headers:", response.Header) 108 | body, _ := ioutil.ReadAll(response.Body) 109 | fmt.Println("response Body:", string(body)) 110 | return body 111 | } 112 | -------------------------------------------------------------------------------- /V5_demo/api_demo/Encryption_HMAC.js: -------------------------------------------------------------------------------- 1 | const crypto = require('crypto'); 2 | const axios = require('axios'); 3 | 4 | url='https://api-testnet.bybit.com'; 5 | 6 | var apiKey = "xxxxxxxxxx"; 7 | var secret = "xxxxxxxxxxxxxxxxxxx"; 8 | var recvWindow = 5000; 9 | var timestamp = Date.now().toString(); 10 | 11 | function getSignature(parameters, secret) { 12 | return crypto.createHmac('sha256', secret).update(timestamp + apiKey + recvWindow + parameters).digest('hex'); 13 | } 14 | 15 | async function http_request(endpoint,method,data,Info) { 16 | var sign=getSignature(data,secret); 17 | var fullendpoint; 18 | 19 | // Build the request URL based on the method 20 | if (method === "POST") { 21 | fullendpoint = url + endpoint; 22 | } else { 23 | fullendpoint = url + endpoint + "?" + data; 24 | data = ""; 25 | } 26 | 27 | var headers = { 28 | 'X-BAPI-SIGN-TYPE': '2', 29 | 'X-BAPI-SIGN': sign, 30 | 'X-BAPI-API-KEY': apiKey, 31 | 'X-BAPI-TIMESTAMP': timestamp, 32 | 'X-BAPI-RECV-WINDOW': recvWindow.toString() 33 | }; 34 | 35 | if (method === "POST") { 36 | headers['Content-Type'] = 'application/json; charset=utf-8'; 37 | } 38 | 39 | var config = { 40 | method: method, 41 | url: fullendpoint, 42 | headers: headers, 43 | data: data 44 | }; 45 | 46 | console.log(Info + " Calling...."); 47 | await axios(config) 48 | .then(function (response) { 49 | console.log(JSON.stringify(response.data)); 50 | }) 51 | .catch(function (error) { 52 | console.log(error.response.data); 53 | }); 54 | } 55 | 56 | //Create Order 57 | async function TestCase() 58 | { 59 | endpoint="/v5/order/create" 60 | const orderLinkId = crypto.randomBytes(16).toString("hex"); 61 | var data = '{"category":"linear","symbol": "BTCUSDT","side": "Buy","positionIdx": 0,"orderType": "Limit","qty": "0.001","price": "10000","timeInForce": "GTC","orderLinkId": "' + orderLinkId + '"}'; 62 | await http_request(endpoint,"POST",data,"Create"); 63 | 64 | //Get unfilled Order List 65 | endpoint="/v5/order/realtime" 66 | var data = 'category=linear&settleCoin=USDT'; 67 | await http_request(endpoint,"GET",data,"Order List"); 68 | 69 | //Cancel order 70 | endpoint="/v5/order/cancel" 71 | var data = '{"category":"linear","symbol": "BTCUSDT","orderLinkId": "'+orderLinkId+'"}'; 72 | await http_request(endpoint,"POST",data,"Cancel"); 73 | } 74 | 75 | //Create, List and Cancel Orders 76 | TestCase() -------------------------------------------------------------------------------- /V5_demo/api_demo/Encryption_HMAC.php: -------------------------------------------------------------------------------- 1 | $url . $endpoint, 19 | CURLOPT_RETURNTRANSFER => true, 20 | CURLOPT_ENCODING => '', 21 | CURLOPT_MAXREDIRS => 10, 22 | CURLOPT_TIMEOUT => 0, 23 | CURLOPT_FOLLOWLOCATION => true, 24 | CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, 25 | CURLOPT_CUSTOMREQUEST => $method, 26 | CURLOPT_POSTFIELDS => $params, 27 | CURLOPT_HTTPHEADER => array( 28 | "X-BAPI-API-KEY: $api_key", 29 | "X-BAPI-SIGN: $signature", 30 | "X-BAPI-SIGN-TYPE: 2", 31 | "X-BAPI-TIMESTAMP: $timestamp", 32 | "X-BAPI-RECV-WINDOW: 5000", 33 | "Content-Type: application/json" 34 | ), 35 | )); 36 | if($method=="GET") 37 | { 38 | curl_setopt($curl, CURLOPT_HTTPGET, true); 39 | } 40 | echo $Info . "\n"; 41 | $response = curl_exec($curl); 42 | echo $response . "\n"; 43 | } 44 | 45 | #Create Order 46 | $endpoint="/v5/order/create"; 47 | $method="POST"; 48 | $orderLinkId=uniqid(); 49 | $params='{"category":"linear","symbol": "BTCUSDT","side": "Buy","positionIdx": 0,"orderType": "Limit","qty": "0.001","price": "10000","timeInForce": "GTC","orderLinkId": "' . $orderLinkId . '"}'; 50 | http_req("$endpoint","$method","$params","Create Order"); 51 | 52 | #Get Order List 53 | $endpoint="/v5/order/realtime"; 54 | $method="GET"; 55 | $params="category=linear&settleCoin=USDT"; 56 | http_req($endpoint,$method,$params,"List Order"); 57 | 58 | #Cancel Order 59 | $endpoint="/v5/order/cancel"; 60 | $method="POST"; 61 | $params='{"category":"linear","symbol": "BTCUSDT","orderLinkId": "' . $orderLinkId . '"}'; 62 | http_req($endpoint,$method,$params,"Cancel Order"); 63 | 64 | curl_close($curl); 65 | -------------------------------------------------------------------------------- /V5_demo/api_demo/Encryption_HMAC.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import time 3 | import hashlib 4 | import hmac 5 | import uuid 6 | 7 | api_key='XXXXXXXXXX' 8 | secret_key='XXXXXXXXXX' 9 | httpClient=requests.Session() 10 | recv_window=str(5000) 11 | url="https://api-testnet.bybit.com" # Testnet endpoint 12 | 13 | def HTTP_Request(endPoint,method,payload,Info): 14 | global time_stamp 15 | time_stamp=str(int(time.time() * 10 ** 3)) 16 | signature=genSignature(payload) 17 | headers = { 18 | 'X-BAPI-API-KEY': api_key, 19 | 'X-BAPI-SIGN': signature, 20 | 'X-BAPI-SIGN-TYPE': '2', 21 | 'X-BAPI-TIMESTAMP': time_stamp, 22 | 'X-BAPI-RECV-WINDOW': recv_window, 23 | 'Content-Type': 'application/json' 24 | } 25 | if(method=="POST"): 26 | response = httpClient.request(method, url+endPoint, headers=headers, data=payload) 27 | else: 28 | response = httpClient.request(method, url+endPoint+"?"+payload, headers=headers) 29 | print(response.text) 30 | print(response.headers) 31 | print(Info + " Elapsed Time : " + str(response.elapsed)) 32 | 33 | def genSignature(payload): 34 | param_str= str(time_stamp) + api_key + recv_window + payload 35 | hash = hmac.new(bytes(secret_key, "utf-8"), param_str.encode("utf-8"),hashlib.sha256) 36 | signature = hash.hexdigest() 37 | return signature 38 | 39 | #Create Order 40 | endpoint="/v5/order/create" 41 | method="POST" 42 | orderLinkId=uuid.uuid4().hex 43 | params='{"category":"linear","symbol": "BTCUSDT","side": "Buy","positionIdx": 0,"orderType": "Limit","qty": "0.001","price": "10000","timeInForce": "GTC","orderLinkId": "' + orderLinkId + '"}' 44 | HTTP_Request(endpoint,method,params,"Create") 45 | 46 | #Get unfilled Orders 47 | endpoint="/v5/order/realtime" 48 | method="GET" 49 | params='category=linear&settleCoin=USDT' 50 | HTTP_Request(endpoint,method,params,"UnFilled") 51 | 52 | #Cancel Order 53 | endpoint="/v5/order/cancel" 54 | method="POST" 55 | params='{"category":"linear","symbol": "BTCUSDT","orderLinkId": "'+orderLinkId+'"}' 56 | HTTP_Request(endpoint,method,params,"Cancel") 57 | -------------------------------------------------------------------------------- /V5_demo/api_demo/Encryption_HMAC.rb: -------------------------------------------------------------------------------- 1 | require 'digest' 2 | require "uri" 3 | require "net/http" 4 | require "date" 5 | require 'open-uri' 6 | require 'openssl' 7 | require 'securerandom' 8 | 9 | 10 | $api_key='XXXXXXXXXX' 11 | $secret_key='XXXXXXXXXX' 12 | $recv_window = '5000' 13 | $url = URI("https://api-testnet.bybit.com") # Testnet endpoint 14 | $time_stamp = "" 15 | 16 | def HTTP_Request(endPoint,method,payload) 17 | $time_stamp = DateTime.now.strftime('%Q') 18 | signature = genSignature(payload) 19 | fullUrl = $url + endPoint 20 | if method == "POST" 21 | request = Net::HTTP::Post.new(fullUrl,'Content-Type' => 'application/json') 22 | request.body = payload 23 | elsif method == "GET" 24 | payload="?"+payload 25 | fullUrl = $url + endPoint + payload 26 | request = Net::HTTP::Get.new(fullUrl) 27 | else 28 | puts "Check the method. It should be either GET or POST" 29 | exit 30 | end 31 | https = Net::HTTP.new(fullUrl.host, fullUrl.port) 32 | #https.set_debug_output($stdout) 33 | https.use_ssl = true 34 | request["X-BAPI-API-KEY"] = $api_key 35 | request["X-BAPI-TIMESTAMP"] = $time_stamp 36 | request["X-BAPI-RECV-WINDOW"] = $recv_window 37 | request["X-BAPI-SIGN"] = signature 38 | response = https.request(request) 39 | puts response.read_body 40 | end 41 | 42 | def genSignature(payload) 43 | param_str= $time_stamp + $api_key + $recv_window + payload 44 | OpenSSL::HMAC.hexdigest('sha256', $secret_key, param_str) 45 | end 46 | 47 | #Create Order ( POST Method ) 48 | endPoint = "/v5/order/create" 49 | method = "POST" 50 | orderLinkId = SecureRandom.uuid 51 | payload='{"category":"linear","symbol": "BTCUSDT","side": "Buy","positionIdx": 0,"orderType": "Limit","qty": "0.001","price": "10000","timeInForce": "GTC","orderLinkId": "' + orderLinkId + '"}' 52 | HTTP_Request(endPoint,method,payload) 53 | 54 | #Retrieve Unfilled Orders ( GET Method ) 55 | endPoint = "/v5/order/realtime" 56 | method = "GET" 57 | payload='category=linear&settleCoin=USDT' 58 | HTTP_Request(endPoint,method,payload) 59 | 60 | #Cancel Order 61 | endPoint="/v5/order/cancel" 62 | method="POST" 63 | payload='{"category":"linear","symbol": "BTCUSDT","orderLinkId": "'+orderLinkId+'"}' 64 | HTTP_Request(endPoint,method,payload) 65 | -------------------------------------------------------------------------------- /V5_demo/api_demo/Encryption_HMAC.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | 4 | api_key='XXXXXXXXXX' 5 | secret_key='XXXXXXXXXX' 6 | time_in_seconds=$(date +%s) 7 | timestamp=$((time_in_seconds * 1000)) 8 | sign=$(echo -n "${timestamp}${api_key}"5000'{"category":"linear","symbol": "BTCUSDT","side": "Buy","positionIdx": 0,"orderType": "Limit","qty": "0.001","price": "10000","timeInForce": "GTC","orderLinkId": "TEST1234"}' | openssl dgst -sha256 -hmac "${secret_key}") 9 | 10 | response=$(curl --location --request POST 'https://api-testnet.bybit.com/v5/order/create' \ 11 | --header 'X-BAPI-SIGN-TYPE: 2' \ 12 | --header 'X-BAPI-SIGN: '${sign} \ 13 | --header 'X-BAPI-API-KEY: '${api_key} \ 14 | --header 'X-BAPI-TIMESTAMP: '${timestamp} \ 15 | --header 'X-BAPI-RECV-WINDOW: 5000' \ 16 | --header 'Content-Type: application/json' \ 17 | --data-raw '{"category":"linear","symbol": "BTCUSDT","side": "Buy","positionIdx": 0,"orderType": "Limit","qty": "0.001","price": "10000","timeInForce": "GTC","orderLinkId": "TEST1234"}') 18 | 19 | echo "Curl Response : $?" 20 | echo "${response}" 21 | order_id=$(jq '.result.orderId' <<< ${response}) 22 | if [ "${order_id}" == "null" ] 23 | then 24 | echo "${response}" 25 | else 26 | echo "Order ID # ${order_id}" 27 | fi 28 | -------------------------------------------------------------------------------- /V5_demo/api_demo/Encryption_HMAC.ts: -------------------------------------------------------------------------------- 1 | import * as crypto from 'crypto'; 2 | import axios, { AxiosRequestConfig } from 'axios'; 3 | 4 | const url = 'https://api-testnet.bybit.com'; 5 | 6 | const apiKey = "xxxxxxxxxxxx"; 7 | const secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxx"; 8 | const recvWindow = 5000; 9 | const timestamp = Date.now().toString(); 10 | 11 | function generateSignature(parameters: string, secret: string): string { 12 | return crypto.createHmac('sha256', secret).update(timestamp + apiKey + recvWindow + parameters).digest('hex'); 13 | } 14 | 15 | async function http_request(endpoint, method, data, Info) { 16 | var sign = generateSignature(data, secret); 17 | var fullendpoint: string; 18 | 19 | if (method === "POST") { 20 | fullendpoint = url + endpoint; 21 | } else { 22 | fullendpoint = url + endpoint + "?" + data; 23 | data = ""; 24 | } 25 | 26 | var headers = { 27 | 'X-BAPI-SIGN-TYPE': '2', 28 | 'X-BAPI-SIGN': sign, 29 | 'X-BAPI-API-KEY': apiKey, 30 | 'X-BAPI-TIMESTAMP': timestamp, 31 | 'X-BAPI-RECV-WINDOW': recvWindow.toString() 32 | }; 33 | 34 | if (method === "POST") { 35 | headers['Content-Type'] = 'application/json; charset=utf-8'; 36 | } 37 | 38 | var config = { 39 | method: method, 40 | url: fullendpoint, 41 | headers: headers, 42 | data: data 43 | }; 44 | 45 | console.log(Info + " Calling...."); 46 | await axios(config) 47 | .then(function (response) { 48 | console.log(JSON.stringify(response.data)); 49 | }) 50 | .catch(function (error) { 51 | console.log(error.response.data); 52 | }); 53 | } 54 | 55 | async function TestCase(): Promise { 56 | const orderLinkId = crypto.randomBytes(16).toString("hex"); 57 | 58 | // Create Order 59 | let endpoint = "/v5/order/create"; 60 | let data = `{"category":"linear","symbol": "BTCUSDT","side": "Buy","positionIdx": 0,"orderType": "Limit","qty": "0.001","price": "10000","timeInForce": "GTC","orderLinkId": "${orderLinkId}"}`; 61 | await http_request(endpoint, "POST", data, "Create"); 62 | 63 | // Get unfilled Order List 64 | endpoint = "/v5/order/realtime"; 65 | data = 'category=linear&symbol=BTCUSDT'; 66 | await http_request(endpoint, "GET", data, "Realtime"); 67 | 68 | // Cancel order 69 | endpoint = "/v5/order/cancel"; 70 | data = `{"category":"linear","symbol": "BTCUSDT","orderLinkId": "${orderLinkId}"}`; 71 | await http_request(endpoint, "POST", data, "Cancel"); 72 | } 73 | 74 | // Create, List and Cancel Orders 75 | TestCase(); -------------------------------------------------------------------------------- /V5_demo/api_demo/Encryption_HMAC_async.py: -------------------------------------------------------------------------------- 1 | import aiohttp 2 | import asyncio 3 | import time 4 | import hmac 5 | import hashlib 6 | import uuid 7 | 8 | api_key = 'XXXXXXXXXX' 9 | secret_key = 'XXXXXXXXXX' 10 | recv_window = str(5000) 11 | url = "https://api-testnet.bybit.com" # Testnet endpoint 12 | 13 | async def HTTP_Request(endPoint, method, payload, Info): 14 | global time_stamp 15 | time_stamp = str(int(time.time() * 10 ** 3)) 16 | signature = genSignature(payload) 17 | headers = { 18 | 'X-BAPI-API-KEY': api_key, 19 | 'X-BAPI-SIGN': signature, 20 | 'X-BAPI-SIGN-TYPE': '2', 21 | 'X-BAPI-TIMESTAMP': time_stamp, 22 | 'X-BAPI-RECV-WINDOW': recv_window, 23 | 'Content-Type': 'application/json' 24 | } 25 | 26 | async with aiohttp.ClientSession() as session: 27 | if method == "POST": 28 | async with session.post(url + endPoint, headers=headers, data=payload) as response: 29 | response_text = await response.text() 30 | else: 31 | async with session.get(url + endPoint + "?" + payload, headers=headers) as response: 32 | response_text = await response.text() 33 | 34 | print(response_text) 35 | print(Info + " Elapsed Time : " + str(response.elapsed)) 36 | 37 | def genSignature(payload): 38 | param_str = time_stamp + api_key + recv_window + payload 39 | hash = hmac.new(bytes(secret_key, "utf-8"), param_str.encode("utf-8"), hashlib.sha256) 40 | signature = hash.hexdigest() 41 | return signature 42 | 43 | async def main(): 44 | # Create Order 45 | endpoint = "/v5/order/create" 46 | method = "POST" 47 | orderLinkId = uuid.uuid4().hex 48 | params = '{"category":"linear","symbol": "BTCUSDT","side": "Buy","positionIdx": 0,"orderType": "Limit","qty": "0.001","price": "10000","timeInForce": "GTC","orderLinkId": "' + orderLinkId + '"}' 49 | await HTTP_Request(endpoint, method, params, "Create") 50 | 51 | # Run the main function using asyncio 52 | asyncio.run(main()) 53 | -------------------------------------------------------------------------------- /V5_demo/api_demo/Encryption_RSA.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import time 3 | import hashlib 4 | import uuid 5 | from Crypto.Hash import SHA256 # install pycryptodome libaray 6 | from Crypto.Signature import PKCS1_v1_5 7 | from Crypto.PublicKey import RSA 8 | import base64 9 | 10 | api_key='XXXXXXXXXX' 11 | rsa_private_key_path = '/Users/XXXXXXXXXX/private.pem' # use absolute path 12 | 13 | httpClient=requests.Session() 14 | recv_window=str(5000) 15 | url="https://api-testnet.bybit.com" # Testnet endpoint 16 | 17 | def HTTP_Request(endPoint,method,payload,Info): 18 | global time_stamp 19 | time_stamp=str(int(time.time() * 10 ** 3)) 20 | signature=genSignature(payload, rsa_private_key_path) 21 | headers = { 22 | 'X-BAPI-API-KEY': api_key, 23 | 'X-BAPI-SIGN': signature, 24 | 'X-BAPI-SIGN-TYPE': '2', 25 | 'X-BAPI-TIMESTAMP': time_stamp, 26 | 'X-BAPI-RECV-WINDOW': recv_window, 27 | 'Content-Type': 'application/json' 28 | } 29 | if(method=="POST"): 30 | response = httpClient.request(method, url+endPoint, headers=headers, data=payload) 31 | else: 32 | response = httpClient.request(method, url+endPoint+"?"+payload, headers=headers) 33 | print(response.text) 34 | print(response.status_code) 35 | print(Info + " Elapsed Time : " + str(response.elapsed)) 36 | 37 | 38 | """ 39 | Load private_key.pem, then generate base64 signature 40 | """ 41 | def genSignature(payload, rsa_private_key_path): 42 | param_str= str(time_stamp) + api_key + recv_window + payload 43 | 44 | with open(rsa_private_key_path, "r") as private_key_obj: 45 | private_key_str = private_key_obj.read() 46 | private_key = RSA.importKey(private_key_str) 47 | encoded_param = SHA256.new(param_str.encode("utf-8")) 48 | signature = PKCS1_v1_5.new(private_key).sign(encoded_param) 49 | 50 | return base64.b64encode(signature).decode() 51 | 52 | #Create Order 53 | endpoint="/v5/order/create" 54 | method="POST" 55 | orderLinkId=uuid.uuid4().hex 56 | params='{"category":"linear","symbol": "BTCUSDT","side": "Buy","positionIdx": 0,"orderType": "Limit","qty": "0.001","price": "10000","timeInForce": "GTC","orderLinkId": "' + orderLinkId + '"}' 57 | HTTP_Request(endpoint,method,params,"Create") 58 | 59 | #Get unfilled Orders 60 | endpoint="/v5/order/realtime" 61 | method="GET" 62 | params='category=linear&settleCoin=USDT' 63 | HTTP_Request(endpoint,method,params,"UnFilled") 64 | 65 | #Cancel Order 66 | endpoint="/v5/order/cancel" 67 | method="POST" 68 | params='{"category":"linear","symbol": "BTCUSDT","orderLinkId": "'+orderLinkId+'"}' 69 | HTTP_Request(endpoint,method,params,"Cancel") 70 | -------------------------------------------------------------------------------- /V5_demo/wss_demo/c#/ws_execution_fast_demo.cs: -------------------------------------------------------------------------------- 1 | using System.Net.WebSockets; 2 | using System.Text; 3 | using Newtonsoft.Json.Linq; 4 | using System.Security.Cryptography; 5 | using Newtonsoft.Json; 6 | 7 | Connect().Wait(); 8 | 9 | async Task Connect() 10 | { 11 | using var ws = new ClientWebSocket(); 12 | await ws.ConnectAsync(new Uri("wss://stream-testnet.bybit.com/v5/private"), CancellationToken.None); 13 | 14 | Console.WriteLine("Connected."); 15 | 16 | var cts = new CancellationTokenSource(); 17 | 18 | _ = Task.Run(() => Receive(ws)); 19 | _ = Task.Run(() => Ping(ws, cts.Token)); 20 | 21 | await OnOpen(ws); 22 | 23 | await Task.Delay(Timeout.Infinite, cts.Token); 24 | } 25 | 26 | async Task OnOpen(ClientWebSocket ws) 27 | { 28 | Console.WriteLine("opened"); 29 | await SendAuth(ws); 30 | await SendSubscription(ws); 31 | } 32 | 33 | async Task SendAuth(ClientWebSocket ws) 34 | { 35 | string key = "xxxxxxxxxx"; 36 | string secret = "xxxxxxxxxxxxxxxx"; 37 | long expires = DateTimeOffset.Now.ToUnixTimeMilliseconds() + 10000; 38 | string _val = $"GET/realtime{expires}"; 39 | 40 | var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secret)); 41 | var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(_val)); 42 | string signature = BitConverter.ToString(hash).Replace("-", "").ToLower(); 43 | 44 | var authMessage = new { op = "auth", args = new object[] { key, expires, signature } }; 45 | string authMessageJson = JsonConvert.SerializeObject(authMessage); 46 | Console.WriteLine(authMessageJson); 47 | await ws.SendAsync(new ArraySegment(Encoding.UTF8.GetBytes(authMessageJson)), WebSocketMessageType.Text, true, CancellationToken.None); 48 | } 49 | 50 | async Task SendSubscription(ClientWebSocket ws) 51 | { 52 | string channel = "execution.fast"; 53 | var subMessage = new { op = "subscribe", args = new string[] { topic } }; 54 | string subMessageJson = JsonConvert.SerializeObject(subMessage); 55 | Console.WriteLine("send subscription " + channel); 56 | await ws.SendAsync(new ArraySegment(Encoding.UTF8.GetBytes(subMessageJson)), WebSocketMessageType.Text, true, CancellationToken.None); 57 | } 58 | 59 | async Task Receive(ClientWebSocket ws) 60 | { 61 | var buffer = new ArraySegment(new byte[8192]); 62 | while (true) 63 | { 64 | var result = await ws.ReceiveAsync(buffer, CancellationToken.None); 65 | if (result.MessageType == WebSocketMessageType.Close) 66 | { 67 | Console.WriteLine("### about to close ###"); 68 | break; 69 | } 70 | else if (result.MessageType == WebSocketMessageType.Text) 71 | { 72 | if (buffer.Array != null) 73 | { 74 | var message = Encoding.UTF8.GetString(buffer.Array, 0, result.Count); 75 | var data = JsonConvert.DeserializeObject(message); 76 | if (data != null) 77 | { 78 | Console.WriteLine(data.ToString()); 79 | } 80 | } 81 | } 82 | } 83 | } 84 | 85 | async Task Ping(ClientWebSocket ws, CancellationToken token) 86 | { 87 | while (!token.IsCancellationRequested) 88 | { 89 | await Task.Delay(TimeSpan.FromSeconds(20), token); 90 | if (ws.State == WebSocketState.Open) 91 | { 92 | await ws.SendAsync(new ArraySegment(Encoding.UTF8.GetBytes("ping")), WebSocketMessageType.Text, true, CancellationToken.None); 93 | Console.WriteLine("ping sent"); 94 | } 95 | } 96 | } 97 | 98 | -------------------------------------------------------------------------------- /V5_demo/wss_demo/c#/ws_private_demo.cs: -------------------------------------------------------------------------------- 1 | using System.Net.WebSockets; 2 | using System.Text; 3 | using Newtonsoft.Json.Linq; 4 | using System.Security.Cryptography; 5 | using Newtonsoft.Json; 6 | 7 | Connect().Wait(); 8 | 9 | async Task Connect() 10 | { 11 | using var ws = new ClientWebSocket(); 12 | await ws.ConnectAsync(new Uri("wss://stream-testnet.bybit.com/v5/private"), CancellationToken.None); 13 | 14 | Console.WriteLine("Connected."); 15 | 16 | var cts = new CancellationTokenSource(); 17 | 18 | _ = Task.Run(() => Receive(ws)); 19 | _ = Task.Run(() => Ping(ws, cts.Token)); 20 | 21 | await OnOpen(ws); 22 | 23 | await Task.Delay(Timeout.Infinite, cts.Token); 24 | } 25 | 26 | async Task OnOpen(ClientWebSocket ws) 27 | { 28 | Console.WriteLine("opened"); 29 | await SendAuth(ws); 30 | await SendSubscription(ws); 31 | } 32 | 33 | async Task SendAuth(ClientWebSocket ws) 34 | { 35 | string key = "xxxxxxxxxx"; 36 | string secret = "xxxxxxxxxxxxxxxx"; 37 | long expires = DateTimeOffset.Now.ToUnixTimeMilliseconds() + 10000; 38 | string _val = $"GET/realtime{expires}"; 39 | 40 | var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secret)); 41 | var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(_val)); 42 | string signature = BitConverter.ToString(hash).Replace("-", "").ToLower(); 43 | 44 | var authMessage = new { op = "auth", args = new object[] { key, expires, signature } }; 45 | string authMessageJson = JsonConvert.SerializeObject(authMessage); 46 | Console.WriteLine(authMessageJson); 47 | await ws.SendAsync(new ArraySegment(Encoding.UTF8.GetBytes(authMessageJson)), WebSocketMessageType.Text, true, CancellationToken.None); 48 | } 49 | 50 | async Task SendSubscription(ClientWebSocket ws) 51 | { 52 | string topic = "order"; 53 | var subMessage = new { op = "subscribe", args = new string[] { topic } }; 54 | string subMessageJson = JsonConvert.SerializeObject(subMessage); 55 | Console.WriteLine("send subscription " + topic); 56 | await ws.SendAsync(new ArraySegment(Encoding.UTF8.GetBytes(subMessageJson)), WebSocketMessageType.Text, true, CancellationToken.None); 57 | } 58 | 59 | async Task Receive(ClientWebSocket ws) 60 | { 61 | var buffer = new ArraySegment(new byte[8192]); 62 | while (true) 63 | { 64 | var result = await ws.ReceiveAsync(buffer, CancellationToken.None); 65 | if (result.MessageType == WebSocketMessageType.Close) 66 | { 67 | Console.WriteLine("### about to close ###"); 68 | break; 69 | } 70 | else if (result.MessageType == WebSocketMessageType.Text) 71 | { 72 | if (buffer.Array != null) 73 | { 74 | var message = Encoding.UTF8.GetString(buffer.Array, 0, result.Count); 75 | var data = JsonConvert.DeserializeObject(message); 76 | if (data != null) 77 | { 78 | Console.WriteLine(data.ToString()); 79 | } 80 | } 81 | } 82 | } 83 | } 84 | 85 | async Task Ping(ClientWebSocket ws, CancellationToken token) 86 | { 87 | while (!token.IsCancellationRequested) 88 | { 89 | await Task.Delay(TimeSpan.FromSeconds(20), token); 90 | if (ws.State == WebSocketState.Open) 91 | { 92 | await ws.SendAsync(new ArraySegment(Encoding.UTF8.GetBytes("ping")), WebSocketMessageType.Text, true, CancellationToken.None); 93 | Console.WriteLine("ping sent"); 94 | } 95 | } 96 | } 97 | 98 | -------------------------------------------------------------------------------- /V5_demo/wss_demo/c#/ws_public_demo.cs: -------------------------------------------------------------------------------- 1 | using System.Net.WebSockets; 2 | using System.Text; 3 | using Newtonsoft.Json; 4 | using Newtonsoft.Json.Linq; 5 | 6 | 7 | string topic = "orderbook.50.BTCUSDT"; 8 | 9 | await ConnectWS(); 10 | 11 | async Task ConnectWS() 12 | { 13 | using (var ws = new ClientWebSocket()) 14 | { 15 | await ws.ConnectAsync(new Uri("wss://stream-testnet.bybit.com/v5/public/linear"), CancellationToken.None); 16 | await OnOpen(ws); 17 | await Receive(ws); 18 | } 19 | } 20 | 21 | async Task OnOpen(ClientWebSocket ws) 22 | { 23 | Console.WriteLine("opened"); 24 | var subscribeRequest = JsonConvert.SerializeObject(new 25 | { 26 | op = "subscribe", 27 | args = new string[] { topic } 28 | }); 29 | await ws.SendAsync(Encoding.UTF8.GetBytes(subscribeRequest), WebSocketMessageType.Text, true, CancellationToken.None); 30 | } 31 | 32 | async Task Receive(ClientWebSocket ws) 33 | { 34 | var buffer = new ArraySegment(new byte[8192]); 35 | while (true) 36 | { 37 | var result = await ws.ReceiveAsync(buffer, CancellationToken.None); 38 | if (result.MessageType == WebSocketMessageType.Close) 39 | { 40 | Console.WriteLine("### about to close ###"); 41 | break; 42 | } 43 | else if (result.MessageType == WebSocketMessageType.Text) 44 | { 45 | if (buffer.Array != null) 46 | { 47 | var message = Encoding.UTF8.GetString(buffer.Array, 0, result.Count); 48 | var data = JsonConvert.DeserializeObject(message); 49 | if (data != null) 50 | { 51 | Console.WriteLine(data.ToString()); 52 | } 53 | } 54 | } 55 | } 56 | } 57 | 58 | 59 | -------------------------------------------------------------------------------- /V5_demo/wss_demo/c++/ws_trade_api_demo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | typedef websocketpp::client client; 9 | 10 | std::string generateSignature(const std::string &message, const std::string &secret) { 11 | unsigned char* digest; 12 | digest = HMAC(EVP_sha256(), secret.c_str(), secret.length(), (unsigned char*)message.c_str(), message.length(), NULL, NULL); 13 | char mdString[SHA256_DIGEST_LENGTH*2+1]; 14 | for(int i = 0; i < SHA256_DIGEST_LENGTH; ++i) 15 | sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]); 16 | return std::string(mdString); 17 | } 18 | 19 | void on_message(websocketpp::connection_hdl, client::message_ptr msg) { 20 | std::cout << "Received message: " << msg->get_payload() << std::endl; 21 | } 22 | 23 | int main() { 24 | client c; 25 | std::string uri = "wss://stream-testnet.bybit.com/v5/trade"; 26 | 27 | try { 28 | c.set_access_channels(websocketpp::log::alevel::all); 29 | c.clear_access_channels(websocketpp::log::alevel::frame_payload); 30 | c.init_asio(); 31 | c.set_message_handler(&on_message); 32 | 33 | websocketpp::lib::error_code ec; 34 | client::connection_ptr con = c.get_connection(uri, ec); 35 | if (ec) { 36 | std::cout << "Could not create connection because: " << ec.message() << std::endl; 37 | return 0; 38 | } 39 | 40 | c.connect(con); 41 | c.run(); 42 | 43 | std::string apiKey = "your_api_key"; 44 | std::string apiSecret = "your_api_secret"; 45 | long expires = std::time(nullptr) * 1000 + 10000; // Unix timestamp in milliseconds 46 | std::string signature = generateSignature("GET/realtime" + std::to_string(expires), apiSecret); 47 | 48 | std::stringstream ss; 49 | ss << "{\"op\":\"auth\",\"args\":[\"" << apiKey << "\"," << expires << ",\"" << signature << "\"]}"; 50 | con->send(ss.str()); 51 | 52 | json order = { 53 | {"reqId", generate_uuid()}, 54 | {"op", "order.create"}, 55 | {"args", json::array({ 56 | { 57 | {"category", "spot"}, 58 | {"symbol", "XRPUSDT"}, 59 | {"side", "Buy"}, 60 | {"orderType", "Market"}, 61 | {"qty", "10"}, 62 | {"timeInForce", "IOC"} 63 | } 64 | })} 65 | }; 66 | std::string placeOrderMessage = placeOrderSS.str(); 67 | con->send(placeOrderMessage); 68 | 69 | } catch (websocketpp::exception const & e) { 70 | std::cout << e.what() << std::endl; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /V5_demo/wss_demo/go/ws_execution_fast_demo.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/hmac" 5 | "crypto/sha256" 6 | "encoding/hex" 7 | "encoding/json" 8 | "fmt" 9 | "github.com/gorilla/websocket" 10 | "log" 11 | "time" 12 | ) 13 | 14 | func main() { 15 | connect() 16 | } 17 | 18 | func connect() { 19 | address := "wss://stream-testnet.bybit.com/v5/private" 20 | c, _, err := websocket.DefaultDialer.Dial(address, nil) 21 | if err != nil { 22 | log.Fatal("Failed to connect:", err) 23 | } 24 | defer c.Close() 25 | 26 | fmt.Println("Connected.") 27 | onOpen(c) 28 | 29 | ticker := time.NewTicker(20 * time.Second) 30 | go func() { 31 | for range ticker.C { 32 | err := c.WriteMessage(websocket.TextMessage, []byte("ping")) 33 | if err != nil { 34 | log.Println("Failed to send ping:", err) 35 | } 36 | fmt.Println("Ping sent.") 37 | } 38 | }() 39 | 40 | for { 41 | _, message, err := c.ReadMessage() 42 | if err != nil { 43 | log.Println("Failed to read message:", err) 44 | return 45 | } 46 | receive(string(message)) 47 | } 48 | } 49 | 50 | func onOpen(c *websocket.Conn) { 51 | fmt.Println("Opened.") 52 | sendAuth(c) 53 | sendSubscription(c, "execution.fast") 54 | } 55 | 56 | func sendAuth(c *websocket.Conn) { 57 | key := "xxxxxxxxxxxxxx" 58 | secret := "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" 59 | expires := time.Now().UnixNano()/1e6 + 10000 60 | val := fmt.Sprintf("GET/realtime%d", expires) 61 | 62 | mac := hmac.New(sha256.New, []byte(secret)) 63 | mac.Write([]byte(val)) 64 | signature := hex.EncodeToString(mac.Sum(nil)) 65 | 66 | authMessage := map[string]interface{}{ 67 | "op": "auth", 68 | "args": []interface{}{key, expires, signature}, 69 | } 70 | 71 | message, err := json.Marshal(authMessage) 72 | if err != nil { 73 | log.Println("Failed to marshal auth message:", err) 74 | return 75 | } 76 | err = c.WriteMessage(websocket.TextMessage, message) 77 | if err != nil { 78 | log.Println("Failed to send auth message:", err) 79 | return 80 | } 81 | } 82 | 83 | func sendSubscription(c *websocket.Conn, topic string) { 84 | subMessage := map[string]interface{}{ 85 | "op": "subscribe", 86 | "args": []string{topic}, 87 | } 88 | 89 | message, err := json.Marshal(subMessage) 90 | if err != nil { 91 | log.Println("Failed to marshal subscription message:", err) 92 | return 93 | } 94 | err = c.WriteMessage(websocket.TextMessage, message) 95 | if err != nil { 96 | log.Println("Failed to send subscription message:", err) 97 | return 98 | } 99 | fmt.Println("Subscription sent for topic:", topic) 100 | } 101 | 102 | func receive(message string) { 103 | var data map[string]interface{} 104 | err := json.Unmarshal([]byte(message), &data) 105 | if err != nil { 106 | log.Println("Failed to unmarshal message:", err) 107 | return 108 | } 109 | fmt.Println(data) 110 | } 111 | -------------------------------------------------------------------------------- /V5_demo/wss_demo/go/ws_private_demo.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/hmac" 5 | "crypto/sha256" 6 | "encoding/hex" 7 | "encoding/json" 8 | "fmt" 9 | "github.com/gorilla/websocket" 10 | "log" 11 | "time" 12 | ) 13 | 14 | func main() { 15 | connect() 16 | } 17 | 18 | func connect() { 19 | address := "wss://stream-testnet.bybit.com/v5/private" 20 | c, _, err := websocket.DefaultDialer.Dial(address, nil) 21 | if err != nil { 22 | log.Fatal("Failed to connect:", err) 23 | } 24 | defer c.Close() 25 | 26 | fmt.Println("Connected.") 27 | onOpen(c) 28 | 29 | ticker := time.NewTicker(20 * time.Second) 30 | go func() { 31 | for range ticker.C { 32 | err := c.WriteMessage(websocket.TextMessage, []byte("ping")) 33 | if err != nil { 34 | log.Println("Failed to send ping:", err) 35 | } 36 | fmt.Println("Ping sent.") 37 | } 38 | }() 39 | 40 | for { 41 | _, message, err := c.ReadMessage() 42 | if err != nil { 43 | log.Println("Failed to read message:", err) 44 | return 45 | } 46 | receive(string(message)) 47 | } 48 | } 49 | 50 | func onOpen(c *websocket.Conn) { 51 | fmt.Println("Opened.") 52 | sendAuth(c) 53 | sendSubscription(c, "order") 54 | } 55 | 56 | func sendAuth(c *websocket.Conn) { 57 | key := "xxxxxxxxxxxxxx" 58 | secret := "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" 59 | expires := time.Now().UnixNano()/1e6 + 10000 60 | val := fmt.Sprintf("GET/realtime%d", expires) 61 | 62 | mac := hmac.New(sha256.New, []byte(secret)) 63 | mac.Write([]byte(val)) 64 | signature := hex.EncodeToString(mac.Sum(nil)) 65 | 66 | authMessage := map[string]interface{}{ 67 | "op": "auth", 68 | "args": []interface{}{key, expires, signature}, 69 | } 70 | 71 | message, err := json.Marshal(authMessage) 72 | if err != nil { 73 | log.Println("Failed to marshal auth message:", err) 74 | return 75 | } 76 | err = c.WriteMessage(websocket.TextMessage, message) 77 | if err != nil { 78 | log.Println("Failed to send auth message:", err) 79 | return 80 | } 81 | } 82 | 83 | func sendSubscription(c *websocket.Conn, topic string) { 84 | subMessage := map[string]interface{}{ 85 | "op": "subscribe", 86 | "args": []string{topic}, 87 | } 88 | 89 | message, err := json.Marshal(subMessage) 90 | if err != nil { 91 | log.Println("Failed to marshal subscription message:", err) 92 | return 93 | } 94 | err = c.WriteMessage(websocket.TextMessage, message) 95 | if err != nil { 96 | log.Println("Failed to send subscription message:", err) 97 | return 98 | } 99 | fmt.Println("Subscription sent for topic:", topic) 100 | } 101 | 102 | func receive(message string) { 103 | var data map[string]interface{} 104 | err := json.Unmarshal([]byte(message), &data) 105 | if err != nil { 106 | log.Println("Failed to unmarshal message:", err) 107 | return 108 | } 109 | fmt.Println(data) 110 | } 111 | -------------------------------------------------------------------------------- /V5_demo/wss_demo/go/ws_public_demo.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/gorilla/websocket" 7 | "log" 8 | "time" 9 | ) 10 | 11 | func main() { 12 | topic := "orderbook.50.BTCUSDT" 13 | connectWS(topic) 14 | } 15 | 16 | func connectWS(topic string) { 17 | address := "wss://stream-testnet.bybit.com/v5/public/linear" 18 | c, _, err := websocket.DefaultDialer.Dial(address, nil) 19 | if err != nil { 20 | log.Fatal("Failed to connect:", err) 21 | } 22 | defer c.Close() 23 | 24 | fmt.Println("Connected.") 25 | 26 | subscribe(c, topic) 27 | 28 | for { 29 | _, message, err := c.ReadMessage() 30 | if err != nil { 31 | log.Println("Failed to read message:", err) 32 | return 33 | } 34 | receive(string(message)) 35 | } 36 | } 37 | 38 | func subscribe(c *websocket.Conn, topic string) { 39 | subscribeRequest := map[string]interface{}{ 40 | "op": "subscribe", 41 | "args": []string{topic}, 42 | } 43 | message, err := json.Marshal(subscribeRequest) 44 | if err != nil { 45 | log.Println("Failed to marshal JSON:", err) 46 | return 47 | } 48 | err = c.WriteMessage(websocket.TextMessage, message) 49 | if err != nil { 50 | log.Println("Failed to send subscribe message:", err) 51 | return 52 | } 53 | } 54 | 55 | func receive(message string) { 56 | var data map[string]interface{} 57 | err := json.Unmarshal([]byte(message), &data) 58 | if err != nil { 59 | log.Println("Failed to unmarshal JSON:", err) 60 | return 61 | } 62 | fmt.Println(data) 63 | } 64 | 65 | func keepAlive(c *websocket.Conn) { 66 | for { 67 | err := c.WriteMessage(websocket.PingMessage, nil) 68 | if err != nil { 69 | log.Println("Ping failed:", err) 70 | return 71 | } 72 | time.Sleep(time.Second * 10) 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /V5_demo/wss_demo/go/ws_trade_api_demo.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/hmac" 5 | "crypto/sha256" 6 | "encoding/hex" 7 | "fmt" 8 | "log" 9 | "net/url" 10 | "strconv" 11 | "time" 12 | 13 | "github.com/gorilla/websocket" 14 | ) 15 | 16 | const apiKey = "your_api_key" 17 | const apiSecret = "your_api_secret" 18 | const wsURL = "wss://stream-testnet.bybit.com/v5/trade" 19 | 20 | func main() { 21 | u := url.URL{Scheme: "wss", Host: "stream-testnet.bybit.com", Path: "/v5/trade"} 22 | log.Printf("connecting to %s", u.String()) 23 | 24 | c, _, err := websocket.DefaultDialer.Dial(u.String(), nil) 25 | if err != nil { 26 | log.Fatal("dial:", err) 27 | } 28 | defer c.Close() 29 | 30 | go func() { 31 | defer c.Close() 32 | for { 33 | _, message, err := c.ReadMessage() 34 | if err != nil { 35 | log.Println("read:", err) 36 | return 37 | } 38 | log.Printf("recv: %s", message) 39 | } 40 | }() 41 | 42 | // Authentication 43 | expires := time.Now().Unix()*1000 + 10000 44 | signature := signMessage(fmt.Sprintf("GET/realtime%d", expires), apiSecret) 45 | 46 | authMessage := fmt.Sprintf(`{"op":"auth","args":["%s",%d,"%s"]}`, apiKey, expires, signature) 47 | c.WriteMessage(websocket.TextMessage, []byte(authMessage)) 48 | 49 | time.Sleep(time.Second * 1) 50 | 51 | // Subscription 52 | subscriptionMessage := `{ 53 | "reqId": "sub-001", 54 | "header": { 55 | "X-BAPI-TIMESTAMP": "` + strconv.FormatInt(time.Now().Unix()*1000, 10) + `", 56 | "X-BAPI-RECV-WINDOW": "8000" 57 | }, 58 | "op": "order.create", 59 | "args": [{ 60 | "symbol": "XRPUSDT", 61 | "side": "Buy", 62 | "orderType": "Market", 63 | "qty": "10", 64 | "category": "spot" 65 | }] 66 | }` 67 | c.WriteMessage(websocket.TextMessage, []byte(subscriptionMessage)) 68 | 69 | time.Sleep(time.Second * 10) // Keep the connection open to receive messages. 70 | } 71 | 72 | func signMessage(message, secret string) string { 73 | mac := hmac.New(sha256.New, []byte(secret)) 74 | mac.Write([]byte(message)) 75 | return hex.EncodeToString(mac.Sum(nil)) 76 | } 77 | -------------------------------------------------------------------------------- /V5_demo/wss_demo/java/ws_public_demo.java: -------------------------------------------------------------------------------- 1 | package org.example; 2 | import com.fasterxml.jackson.databind.JsonNode; 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import org.java_websocket.client.WebSocketClient; 5 | import org.java_websocket.enums.ReadyState; 6 | import org.java_websocket.handshake.ServerHandshake; 7 | 8 | import java.net.URI; 9 | import java.net.URISyntaxException; 10 | import java.util.HashMap; 11 | import java.util.Map; 12 | import java.util.concurrent.CountDownLatch; 13 | 14 | public class ws_public_demo { 15 | public static void main(String[] args) { 16 | String topic = "orderbook.50.BTCUSDT"; 17 | try { 18 | connectWS(topic); 19 | } catch (Exception e) { 20 | e.printStackTrace(); 21 | } 22 | } 23 | 24 | static void connectWS(String topic) throws URISyntaxException, InterruptedException { 25 | URI uri = new URI("wss://stream-testnet.bybit.com/v5/public/linear"); 26 | CountDownLatch connected = new CountDownLatch(1); 27 | 28 | WebSocketClient ws = new WebSocketClient(uri) { 29 | @Override 30 | public void onOpen(ServerHandshake handshakedata) { 31 | System.out.println("opened"); 32 | ws_public_demo.onOpen(this, topic); 33 | connected.countDown(); 34 | } 35 | 36 | @Override 37 | public void onMessage(String message) { 38 | receive(message); 39 | } 40 | 41 | @Override 42 | public void onClose(int code, String reason, boolean remote) { 43 | System.out.println("### about to close ###"); 44 | } 45 | 46 | @Override 47 | public void onError(Exception ex) { 48 | ex.printStackTrace(); 49 | } 50 | }; 51 | 52 | ws.connect(); 53 | connected.await(); 54 | while (ws.getReadyState() == ReadyState.OPEN) { 55 | Thread.sleep(1000); 56 | } 57 | } 58 | 59 | static void onOpen(WebSocketClient ws, String topic) { 60 | Map subscribeRequest = new HashMap<>(); 61 | subscribeRequest.put("op", "subscribe"); 62 | subscribeRequest.put("args", new String[]{topic}); 63 | 64 | ObjectMapper objectMapper = new ObjectMapper(); 65 | try { 66 | String subscribeMessage = objectMapper.writeValueAsString(subscribeRequest); 67 | ws.send(subscribeMessage); 68 | } catch (Exception e) { 69 | e.printStackTrace(); 70 | } 71 | } 72 | 73 | static void receive(String message) { 74 | ObjectMapper objectMapper = new ObjectMapper(); 75 | try { 76 | JsonNode data = objectMapper.readTree(message); 77 | System.out.println(data.toString()); 78 | } catch (Exception e) { 79 | e.printStackTrace(); 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /V5_demo/wss_demo/javascript/ws_execution_fast_demo.js: -------------------------------------------------------------------------------- 1 | var url = require('url'); 2 | var WebSocket = require('ws'); 3 | var crypto = require('crypto'); 4 | var endpoint = "wss://stream-testnet.bybit.com/v5/private" 5 | console.log('attempting to connect to WebSocket %j', endpoint); 6 | var client = new WebSocket(endpoint); 7 | const apiKey="XXXXXXXXX"; 8 | const apiSecret="XXXXXXXXX"; 9 | client.on('open', function () { 10 | console.log('"open" event!'); 11 | console.log('WebSocket Client Connected'); 12 | const expires = new Date().getTime() + 10000; 13 | const signature = crypto.createHmac("sha256", apiSecret).update("GET/realtime" + expires).digest("hex"); 14 | const payload={ 15 | op: "auth", 16 | args: [apiKey, expires.toFixed(0), signature], 17 | } 18 | client.send(JSON.stringify(payload)); 19 | setInterval(()=>{client.ping()}, 30000); 20 | client.ping(); 21 | client.send(JSON.stringify({"op": "subscribe", "args": ['execution.fast']})); 22 | }); 23 | 24 | client.on('message', function (data) { 25 | console.log('"message" event! %j', JSON.parse(Buffer.from(data).toString())); 26 | }); 27 | client.on('ping', function (data, flags) { 28 | console.log("ping received"); 29 | }); 30 | client.on('pong', function (data, flags) { 31 | console.log("pong received"); 32 | }); 33 | -------------------------------------------------------------------------------- /V5_demo/wss_demo/javascript/ws_private_demo.js: -------------------------------------------------------------------------------- 1 | var url = require('url'); 2 | var WebSocket = require('ws'); 3 | var crypto = require('crypto'); 4 | var endpoint = "wss://stream-testnet.bybit.com/v5/private" 5 | console.log('attempting to connect to WebSocket %j', endpoint); 6 | var client = new WebSocket(endpoint); 7 | const apiKey="XXXXXXXXX"; 8 | const apiSecret="XXXXXXXXX"; 9 | client.on('open', function () { 10 | console.log('"open" event!'); 11 | console.log('WebSocket Client Connected'); 12 | const expires = new Date().getTime() + 10000; 13 | const signature = crypto.createHmac("sha256", apiSecret).update("GET/realtime" + expires).digest("hex"); 14 | const payload={ 15 | op: "auth", 16 | args: [apiKey, expires.toFixed(0), signature], 17 | } 18 | client.send(JSON.stringify(payload)); 19 | setInterval(()=>{client.ping()}, 30000); 20 | client.ping(); 21 | client.send(JSON.stringify({"op": "subscribe", "args": ['order']})); 22 | }); 23 | 24 | client.on('message', function (data) { 25 | console.log('"message" event! %j', JSON.parse(Buffer.from(data).toString())); 26 | }); 27 | client.on('ping', function (data, flags) { 28 | console.log("ping received"); 29 | }); 30 | client.on('pong', function (data, flags) { 31 | console.log("pong received"); 32 | }); 33 | -------------------------------------------------------------------------------- /V5_demo/wss_demo/javascript/ws_public_demo.js: -------------------------------------------------------------------------------- 1 | var url = require('url'); 2 | var WebSocket = require('ws'); 3 | var crypto = require('crypto'); 4 | var endpoint = "wss://stream-testnet.bybit.com/v5/public/linear" 5 | console.log('attempting to connect to WebSocket %j', endpoint); 6 | var client = new WebSocket(endpoint); 7 | client.on('open', function () { 8 | console.log('"open" event!'); 9 | console.log('WebSocket Client Connected'); 10 | setInterval(()=>{client.ping()}, 30000); 11 | client.ping(); 12 | client.send(JSON.stringify({"op": "subscribe", "args": ["orderbook.50.BTCUSDT"]})); 13 | }); 14 | 15 | client.on('message', function (data) { 16 | console.log('"message" event! %j', JSON.parse(Buffer.from(data).toString())); 17 | }); 18 | client.on('ping', function (data, flags) { 19 | console.log("ping received"); 20 | }); 21 | client.on('pong', function (data, flags) { 22 | console.log("pong received"); 23 | }); 24 | -------------------------------------------------------------------------------- /V5_demo/wss_demo/javascript/ws_trade_api_demo.js: -------------------------------------------------------------------------------- 1 | const WebSocket = require('ws'); 2 | const crypto = require('crypto'); 3 | 4 | const apiKey = 'your_api_key'; 5 | const apiSecret = 'your_api_secret'; 6 | const wsUrl = 'wss://stream-testnet.bybit.com/v5/trade'; 7 | 8 | const ws = new WebSocket(wsUrl); 9 | 10 | ws.on('open', function open() { 11 | authenticate(ws); 12 | setTimeout(() => { 13 | sendSubscription(ws); 14 | }, 2000); // Wait for authentication to complete 15 | }); 16 | 17 | ws.on('message', function incoming(data) { 18 | console.log(data); 19 | }); 20 | 21 | function authenticate(ws) { 22 | const expires = Date.now() + 10000; // 10 seconds from now 23 | const signature = crypto.createHmac('sha256', apiSecret).update(`GET/realtime${expires}`).digest('hex'); 24 | 25 | const authMessage = { 26 | reqId: 'auth', 27 | op: 'auth', 28 | args: [apiKey, expires, signature], 29 | }; 30 | 31 | ws.send(JSON.stringify(authMessage)); 32 | } 33 | 34 | function sendSubscription(ws) { 35 | const subscriptionMessage = { 36 | reqId: 'sub-001', 37 | header: { 38 | "X-BAPI-TIMESTAMP": String(Date.now()), 39 | "X-BAPI-RECV-WINDOW": "8000", 40 | }, 41 | op: "order.create", 42 | args: [ 43 | { 44 | "symbol": "XRPUSDT", 45 | "side": "Buy", 46 | "orderType": "Market", 47 | "qty": "10", 48 | "category": "spot" 49 | } 50 | ] 51 | }; 52 | 53 | ws.send(JSON.stringify(subscriptionMessage)); 54 | } 55 | -------------------------------------------------------------------------------- /V5_demo/wss_demo/python/ws_private_hmac_demo.py: -------------------------------------------------------------------------------- 1 | import hmac 2 | import json 3 | import logging 4 | import time 5 | import threading 6 | import websocket 7 | 8 | logging.basicConfig(filename='logfile_wrapper.log', level=logging.DEBUG, 9 | format='%(asctime)s %(levelname)s %(message)s') 10 | topic = "order" 11 | 12 | def on_message(ws, message): 13 | data = json.loads(message) 14 | print(data) 15 | 16 | def on_error(ws, error): 17 | print('we got error') 18 | print(error) 19 | 20 | def on_close(ws): 21 | print("### about to close please don't close ###") 22 | 23 | def send_auth(ws): 24 | key = 'XXXXXXXXXX' 25 | secret = 'XXXXXXXXXX' 26 | expires = int((time.time() + 10) * 1000) 27 | _val = f'GET/realtime{expires}' 28 | print(_val) 29 | signature = str(hmac.new( 30 | bytes(secret, 'utf-8'), 31 | bytes(_val, 'utf-8'), digestmod='sha256' 32 | ).hexdigest()) 33 | ws.send(json.dumps({"op": "auth", "args": [key, expires, signature]})) 34 | 35 | def on_pong(ws, *data): 36 | print('pong received') 37 | 38 | def on_ping(ws, *data): 39 | print('ping received') 40 | 41 | def on_open(ws): 42 | print('opened') 43 | send_auth(ws) 44 | print('send subscription ' + topic) 45 | ws.send(json.dumps({"op": "subscribe", "args": [topic]})) 46 | def pingPer(ws): 47 | while True: 48 | ws.send(json.dumps({'op': 'ping'})) 49 | time.sleep(15) 50 | t1 = threading.Thread(target=pingPer, args=(ws,)) 51 | t1.start() 52 | 53 | def connWS(): 54 | ws = websocket.WebSocketApp("wss://stream-testnet.bybit.com/v5/private", 55 | on_message=on_message, 56 | on_error=on_error, 57 | on_close=on_close, 58 | on_ping=on_ping, 59 | on_pong=on_pong, 60 | on_open=on_open 61 | ) 62 | ws.run_forever( 63 | #http_proxy_host='127.0.0.1', 64 | #http_proxy_port=1087, 65 | ping_interval=20, 66 | ping_timeout=10 67 | ) 68 | 69 | if __name__ == "__main__": 70 | websocket.enableTrace(True) 71 | connWS() 72 | -------------------------------------------------------------------------------- /V5_demo/wss_demo/python/ws_private_rsa_demo.py: -------------------------------------------------------------------------------- 1 | import hmac 2 | import websocket 3 | import threading 4 | import time 5 | from Crypto.PublicKey import RSA 6 | import json 7 | import base64 8 | from Crypto.Hash import SHA256 9 | from Crypto.Signature import PKCS1_v1_5 10 | 11 | 12 | class StreamManager(object): 13 | def __init__(self, ws_url: str, topic_list: list, rsa_api_key: str, private_key: str = None): 14 | self.ws = None 15 | self.ws_url = ws_url 16 | self.topic_list = topic_list 17 | self.rsa_api_key = rsa_api_key 18 | self.private_key = private_key 19 | 20 | @staticmethod 21 | def on_message(ws, message): 22 | print(message) 23 | 24 | @staticmethod 25 | def on_error(ws, error): 26 | print(f"we got error:{error}") 27 | 28 | @staticmethod 29 | def on_close(ws): 30 | print("### about to close please don't close ###") 31 | 32 | def on_open(self, ws): 33 | def send_auth(ws): 34 | expires = int((time.time() + 1000000000) * 1000) 35 | _val = f'GET/realtime{expires}' 36 | private_key = RSA.importKey(self.private_key) 37 | h = SHA256.new(_val.encode('utf-8')) 38 | signature_temp = PKCS1_v1_5.new(private_key).sign(h) 39 | result = base64.b64encode(signature_temp).decode() 40 | 41 | auth_data = json.dumps({ 42 | "op": "auth", 43 | "args": [self.rsa_api_key, expires, result] 44 | }) 45 | print(auth_data) 46 | ws.send(auth_data) 47 | 48 | t0 = threading.Thread(target=send_auth, args=(ws,)) 49 | t0.start() 50 | 51 | def pingPer(ws): 52 | while True: 53 | ping_data = json.dumps({ 54 | "op": "ping", 55 | "args": [[int((time.time() + 1) * 1000)]] 56 | }) 57 | 58 | ws.send(ping_data) 59 | print(ping_data) 60 | time.sleep(20) 61 | 62 | t1 = threading.Thread(target=pingPer, args=(ws,)) 63 | t1.start() 64 | subscribe_data = json.dumps({ 65 | "op": "subscribe", 66 | "args": self.topic_list 67 | }) 68 | print(subscribe_data) 69 | time.sleep(1) 70 | ws.send(subscribe_data) 71 | 72 | def start(self): 73 | self.ws = websocket.WebSocketApp( 74 | url=self.ws_url, 75 | on_message=lambda ws, message: self.on_message(ws, message), 76 | on_error=lambda ws, error: self.on_error(ws, error), 77 | on_close=lambda ws: self.on_close(ws), 78 | on_open=lambda ws: self.on_open(ws) 79 | ) 80 | self.ws.run_forever() 81 | 82 | 83 | if __name__ == "__main__": 84 | private_key_file = "xxxx_private.pem" # private pem file name 85 | with open(f"/Users/xxxxx/{private_key_file}", "r") as pk: 86 | private_key_str = pk.read() # Read private_key 87 | 88 | testnet_domain = "stream-testnet.bybit.com" # wss testnet 89 | mainnet_domain = "stream.bybit.com" # wss mainnet 90 | uta_path = "/v5/private" # v5 91 | url_wss = f"wss://{testnet_domain}{uta_path}" 92 | 93 | rsa_apiKey = "XXXXXXXXXX" # the one that provided by Bybit after you input rsa public key 94 | privateKey = private_key_str 95 | v5_topics = ["order", "position", "wallet", "execution"] 96 | 97 | sm = StreamManager(ws_url=url_wss, topic_list=v5_topics, rsa_api_key=rsa_apiKey, private_key=privateKey) 98 | sm.start() 99 | -------------------------------------------------------------------------------- /V5_demo/wss_demo/python/ws_public_demo.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | import time 4 | from datetime import datetime 5 | import websocket 6 | import threading 7 | 8 | logging.basicConfig(filename='logfile_wrapper.log', level=logging.DEBUG, 9 | format='%(asctime)s %(levelname)s %(message)s') 10 | 11 | topic = "orderbook.50.BTCUSDT" 12 | 13 | def on_message(ws, message): 14 | data = json.loads(message) 15 | print(data) 16 | 17 | def on_error(ws, error): 18 | print('we got error') 19 | print(error) 20 | print('print error complete') 21 | 22 | def on_close(ws): 23 | print("### about to close please don't close ###") 24 | 25 | def on_open(ws): 26 | print('opened') 27 | ws.send(json.dumps({"op": "subscribe", "args": [topic]})) 28 | def pingPer(ws): 29 | while True: 30 | ws.send(json.dumps({'op': 'ping'})) 31 | time.sleep(10) 32 | t1 = threading.Thread(target=pingPer, args=(ws,)) 33 | t1.start() 34 | 35 | def on_pong(ws, *data): 36 | print('pong received') 37 | 38 | def on_ping(ws, *data): 39 | now = datetime.now() 40 | dt_string = now.strftime("%d/%m/%Y %H:%M:%S") 41 | print("date and time =", dt_string) 42 | print('ping received') 43 | 44 | def connWS(): 45 | ws = websocket.WebSocketApp( 46 | "wss://stream-testnet.bybit.com/v5/public/linear", 47 | on_message=on_message, 48 | on_error=on_error, 49 | on_close=on_close, 50 | on_ping=on_ping, 51 | on_pong=on_pong, 52 | on_open=on_open 53 | ) 54 | ws.run_forever( 55 | #http_proxy_host='127.0.0.1', 56 | #http_proxy_port=1087, 57 | ping_interval=20, 58 | ping_timeout=10 59 | ) 60 | 61 | 62 | if __name__ == "__main__": 63 | websocket.enableTrace(True) 64 | connWS() 65 | -------------------------------------------------------------------------------- /V5_demo/wss_demo/python/ws_trade_api_demo.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import websockets 3 | import json 4 | import hmac 5 | import hashlib 6 | from datetime import datetime 7 | 8 | 9 | async def authenticate(ws): 10 | api_key = "xxxxxxxxxx" 11 | api_secret = "xxxxxxxxxx" 12 | expires = int((datetime.now().timestamp() + 10) * 1000) # Expires in 10 seconds 13 | signature = hmac.new(api_secret.encode(), f'GET/realtime{expires}'.encode(), hashlib.sha256).hexdigest() 14 | 15 | auth_msg = { 16 | "reqId": "auth", 17 | "op": "auth", 18 | "args": [api_key, expires, signature] 19 | } 20 | 21 | await ws.send(json.dumps(auth_msg)) 22 | response = await ws.recv() 23 | print(f"Auth response: {response}") 24 | 25 | 26 | async def send_subscription(ws): 27 | sub_msg = { 28 | "reqId": "sub-003", 29 | "header": { 30 | "X-BAPI-TIMESTAMP": str(int(datetime.now().timestamp() * 1000)), 31 | "X-BAPI-RECV-WINDOW": "8000", 32 | }, 33 | "op": "order.create", 34 | "args": [ 35 | { 36 | "category": "linear", 37 | "orderLinkId": "crzyO2.0-1716303565222835550", 38 | "orderType": "Market", 39 | "positionIdx": 1, 40 | "price": "0.5496", 41 | "qty": "11", 42 | "side": "Buy", 43 | "symbol": "XRPUSDT", 44 | "reduceOnly": False, 45 | "closeOnTrigger": False 46 | } 47 | ] 48 | } 49 | 50 | await ws.send(json.dumps(sub_msg)) 51 | print("Subscription message sent.") 52 | 53 | 54 | async def on_ping(ws): 55 | while True: 56 | try: 57 | print('Sending ping') 58 | await ws.send(json.dumps({'op': 'ping'})) 59 | await asyncio.sleep(10) # Sleep for 10 seconds 60 | except websockets.exceptions.ConnectionClosed: 61 | print("WebSocket connection closed.") 62 | break 63 | 64 | 65 | async def listen_messages(ws): 66 | try: 67 | while True: 68 | message = await ws.recv() 69 | print(f"Message received: {message}") 70 | except websockets.exceptions.ConnectionClosed: 71 | print("WebSocket connection closed.") 72 | 73 | 74 | async def main(): 75 | uri = "wss://stream-testnet.bybit.com/v5/trade" 76 | async with websockets.connect(uri) as ws: 77 | await authenticate(ws) 78 | await send_subscription(ws) 79 | listen_task = asyncio.create_task(listen_messages(ws)) 80 | ping_task = asyncio.create_task(on_ping(ws)) 81 | await asyncio.gather(listen_task, ping_task) 82 | 83 | 84 | # Run the main function in an asyncio event loop 85 | if __name__ == "__main__": 86 | asyncio.run(main()) 87 | -------------------------------------------------------------------------------- /V5_demo/wss_demo/python/wss_fast_execution_demo.py: -------------------------------------------------------------------------------- 1 | import hmac 2 | import json 3 | import logging 4 | import time 5 | import websocket 6 | import threading 7 | 8 | logging.basicConfig(filename='logfile_wrapper.log', level=logging.DEBUG, 9 | format='%(asctime)s %(levelname)s %(message)s') 10 | topic = "execution.fast" 11 | 12 | def on_message(ws, message): 13 | data = json.loads(message) 14 | print(data) 15 | 16 | def on_error(ws, error): 17 | print('we got error') 18 | print(error) 19 | 20 | def on_close(ws): 21 | print("### about to close please don't close ###") 22 | 23 | def send_auth(ws): 24 | key = 'xxxxxxxxxxxxxxxxx' 25 | secret = 'xxxxxxxxxxxxxxxxx' 26 | expires = int((time.time() + 10) * 1000) 27 | _val = f'GET/realtime{expires}' 28 | print(_val) 29 | signature = str(hmac.new( 30 | bytes(secret, 'utf-8'), 31 | bytes(_val, 'utf-8'), digestmod='sha256' 32 | ).hexdigest()) 33 | ws.send(json.dumps({"op": "auth", "args": [key, expires, signature]})) 34 | 35 | def on_pong(ws, *data): 36 | print('pong received') 37 | 38 | def on_ping(ws, *data): 39 | print('ping received') 40 | 41 | def on_open(ws): 42 | print('opened') 43 | send_auth(ws) 44 | print('send subscription ' + topic) 45 | ws.send(json.dumps({"op": "subscribe", "args": [topic]})) 46 | def pingPer(ws): 47 | while True: 48 | ws.send(json.dumps({'op': 'ping'})) 49 | time.sleep(10) 50 | t1 = threading.Thread(target=pingPer, args=(ws,)) 51 | t1.start() 52 | 53 | def connWS(): 54 | ws = websocket.WebSocketApp("wss://stream-testnet.bybit.com/v5/private", 55 | on_message=on_message, 56 | on_error=on_error, 57 | on_close=on_close, 58 | on_ping=on_ping, 59 | on_pong=on_pong, 60 | on_open=on_open 61 | ) 62 | ws.run_forever( 63 | #http_proxy_host='127.0.0.1', 64 | #http_proxy_port=1087, 65 | ping_interval=20, 66 | ping_timeout=10 67 | ) 68 | 69 | if __name__ == "__main__": 70 | websocket.enableTrace(True) 71 | connWS() 72 | -------------------------------------------------------------------------------- /V5_demo/wss_demo/typescript/ws_fast_execution_demo.ts: -------------------------------------------------------------------------------- 1 | import WebSocket from 'ws'; 2 | import * as crypto from 'crypto'; 3 | 4 | const endpoint: string = "wss://stream-testnet.bybit.com/v5/private"; 5 | console.log('attempting to connect to WebSocket %j', endpoint); 6 | 7 | const client: WebSocket = new WebSocket(endpoint); 8 | const apiKey: string = "xxxxxxxxxxxxxxxx"; 9 | const apiSecret: string = "xxxxxxxxxxxxxxxxxxxxxxxx"; 10 | 11 | client.on('open', () => { 12 | console.log('"open" event!'); 13 | console.log('WebSocket Client Connected'); 14 | 15 | const expires: number = new Date().getTime() + 10000; 16 | const signature: string = crypto.createHmac("sha256", apiSecret).update("GET/realtime" + expires).digest("hex"); 17 | 18 | const payload = { 19 | op: "auth", 20 | args: [apiKey, expires.toFixed(0), signature] 21 | }; 22 | 23 | client.send(JSON.stringify(payload)); 24 | setInterval(() => { client.ping(); }, 30000); 25 | client.ping(); 26 | client.send(JSON.stringify({"op": "subscribe", "args": ['execution.fast']})); 27 | }); 28 | 29 | client.on('message', (data: WebSocket.Data) => { 30 | console.log('"message" event! %j', JSON.parse(data.toString())); 31 | }); 32 | 33 | client.on('ping', (data: Buffer) => { 34 | console.log("ping received"); 35 | }); 36 | 37 | client.on('pong', (data: Buffer) => { 38 | console.log("pong received"); 39 | }); 40 | -------------------------------------------------------------------------------- /V5_demo/wss_demo/typescript/ws_private_demo.ts: -------------------------------------------------------------------------------- 1 | import WebSocket from 'ws'; 2 | import * as crypto from 'crypto'; 3 | 4 | const endpoint: string = "wss://stream-testnet.bybit.com/v5/private"; 5 | console.log('attempting to connect to WebSocket %j', endpoint); 6 | 7 | const client: WebSocket = new WebSocket(endpoint); 8 | const apiKey: string = "xxxxxxxxxxxxxxxx"; 9 | const apiSecret: string = "xxxxxxxxxxxxxxxxxxxxxxxx"; 10 | 11 | client.on('open', () => { 12 | console.log('"open" event!'); 13 | console.log('WebSocket Client Connected'); 14 | 15 | const expires: number = new Date().getTime() + 10000; 16 | const signature: string = crypto.createHmac("sha256", apiSecret).update("GET/realtime" + expires).digest("hex"); 17 | 18 | const payload = { 19 | op: "auth", 20 | args: [apiKey, expires.toFixed(0), signature] 21 | }; 22 | 23 | client.send(JSON.stringify(payload)); 24 | setInterval(() => { client.ping(); }, 30000); 25 | client.ping(); 26 | client.send(JSON.stringify({"op": "subscribe", "args": ['order']})); 27 | }); 28 | 29 | client.on('message', (data: WebSocket.Data) => { 30 | console.log('"message" event! %j', JSON.parse(data.toString())); 31 | }); 32 | 33 | client.on('ping', (data: Buffer) => { 34 | console.log("ping received"); 35 | }); 36 | 37 | client.on('pong', (data: Buffer) => { 38 | console.log("pong received"); 39 | }); 40 | -------------------------------------------------------------------------------- /V5_demo/wss_demo/typescript/ws_public_demo.ts: -------------------------------------------------------------------------------- 1 | import WebSocket from 'ws'; 2 | 3 | const endpoint: string = "wss://stream-testnet.bybit.com/v5/public/linear"; 4 | console.log('attempting to connect to WebSocket %j', endpoint); 5 | const client = new WebSocket(endpoint); 6 | 7 | client.on('open', () => { 8 | console.log('"open" event!'); 9 | console.log('WebSocket Client Connected'); 10 | setInterval(() => { client.ping(); }, 30000); 11 | client.ping(); 12 | client.send(JSON.stringify({ "op": "subscribe", "args": ["orderbook.50.BTCUSDT"] })); 13 | }); 14 | 15 | client.on('message', (data: WebSocket.Data) => { 16 | console.log('"message" event! %j', JSON.parse(data.toString())); 17 | }); 18 | 19 | client.on('ping', (data: Buffer) => { 20 | console.log("ping received"); 21 | }); 22 | 23 | client.on('pong', (data: Buffer) => { 24 | console.log("pong received"); 25 | }); 26 | -------------------------------------------------------------------------------- /V5_demo/wss_demo/typescript/ws_trade_api_demo.ts: -------------------------------------------------------------------------------- 1 | import WebSocket from 'ws'; 2 | import crypto from 'crypto'; 3 | 4 | const apiKey: string = 'your_api_key'; 5 | const apiSecret: string = 'your_api_secret'; 6 | const wsUrl: string = 'wss://stream-testnet.bybit.com/v5/trade'; 7 | 8 | const ws: WebSocket = new WebSocket(wsUrl); 9 | 10 | ws.on('open', () => { 11 | authenticate(ws); 12 | setTimeout(() => { 13 | sendSubscription(ws); 14 | }, 2000); // Wait for authentication to complete 15 | }); 16 | 17 | ws.on('message', (data: string) => { 18 | console.log(data); 19 | }); 20 | 21 | function authenticate(ws: WebSocket): void { 22 | const expires: number = Date.now() + 10000; // 10 seconds from now 23 | const signature: string = crypto.createHmac('sha256', apiSecret).update(`GET/realtime${expires}`).digest('hex'); 24 | 25 | const authMessage: any = { 26 | reqId: 'auth', 27 | op: 'auth', 28 | args: [apiKey, expires, signature], 29 | }; 30 | 31 | ws.send(JSON.stringify(authMessage)); 32 | } 33 | 34 | function sendSubscription(ws: WebSocket): void { 35 | const subscriptionMessage: any = { 36 | reqId: 'sub-001', 37 | header: { 38 | "X-BAPI-TIMESTAMP": String(Date.now()), 39 | "X-BAPI-RECV-WINDOW": "8000", 40 | }, 41 | op: "order.create", 42 | args: [ 43 | { 44 | "symbol": "XRPUSDT", 45 | "side": "Buy", 46 | "orderType": "Market", 47 | "qty": "10", 48 | "category": "spot" 49 | } 50 | ] 51 | }; 52 | 53 | ws.send(JSON.stringify(subscriptionMessage)); 54 | } 55 | -------------------------------------------------------------------------------- /data_transfer_demo/http_request/google_sheet_api.md: -------------------------------------------------------------------------------- 1 | ## Using Google Sheets API 2 | 3 | ### Steps 4 | #### Step 1 Create a Project in Google Cloud Platform 5 | - Go to the Google Cloud Console. [https://console.cloud.google.com/welcome] 6 | - Click the project drop-down and select New Project. 7 | - Enter a name for the project, and optionally, edit the provided project ID. Click Create. 8 | 9 | #### Step 2 Enable the Google Sheets API 10 | - In the Cloud Console, navigate to the menu item API & Services > Library. 11 | - Search for "Google Sheets API" and select the matching result. 12 | - Click Enable. 13 | #### Step 3 Create Credentials 14 | - Navigate to API & Services > Credentials. 15 | - Click Create Credentials and select OAuth 2.0 Client ID. 16 | - Choose Desktop App as the application type. 17 | - Click Create. You will see a dialog with your client ID and client secret. 18 | - Click OK to close the dialog. 19 | - Click on the download icon (down arrow) on the right of the credentials you just created to download the credentials.json file. 20 | #### Step 4 Integrate with Your Java Application 21 | - Move the credentials.json to the root directory of your Java project or to a location you can easily reference. 22 | - Use the Google Sheets API client libraries to authenticate and interact with the API using the provided credentials.json. 23 | 24 | **Notes** 25 | Always keep your credentials.json private. Never expose it in public repositories or public locations. 26 | Follow best practices for storing and handling API keys and credentials. 27 | 28 | ### List of dependencies 29 | #### Java Google Sheet API Example 30 | ```java 31 | // Maven 32 | 33 | com.fasterxml.jackson.core 34 | jackson-databind 35 | 2.13.1 36 | 37 | 38 | com.squareup.okhttp3 39 | okhttp 40 | 4.9.2 41 | 42 | 43 | org.apache.poi 44 | poi 45 | 5.1.0 46 | 47 | 48 | org.apache.poi 49 | poi-ooxml 50 | 5.1.0 51 | 52 | 53 | com.google.oauth-client 54 | google-oauth-client 55 | 1.30.6 56 | 57 | 58 | com.google.oauth-client 59 | google-oauth-client-java6 60 | 1.30.6 61 | 62 | 63 | com.google.apis 64 | google-api-services-sheets 65 | v4-rev612-1.25.0 66 | 67 | 68 | com.google.http-client 69 | google-http-client-gson 70 | 1.39.2 71 | 72 | 73 | com.google.oauth-client 74 | google-oauth-client-jetty 75 | 1.30.6 76 | 77 | ``` 78 | #### Python Google Sheet API Example 79 | ```python 80 | # pip list 81 | google-auth==2.23.3 82 | google-auth-oauthlib==1.1.0 83 | gspread==5.11.3 84 | requests==2.30.0 85 | pandas==2.0.1 86 | ``` -------------------------------------------------------------------------------- /data_transfer_demo/http_request/import_data_to_csv.js: -------------------------------------------------------------------------------- 1 | const axios = require('axios'); 2 | const csvWriter = require('csv-writer').createObjectCsvWriter; 3 | const crypto = require('crypto'); 4 | 5 | const api_key = 'xxxxxxxxxxxxxxx'; 6 | const secret_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; 7 | const recv_window = '5000'; 8 | const url = 'https://api-testnet.bybit.com'; 9 | 10 | function genSignature(payload) { 11 | const timeStamp = Date.now().toString(); 12 | const param_str = timeStamp + api_key + recv_window + payload; 13 | const hash = crypto.createHmac('sha256', secret_key).update(param_str).digest('hex'); 14 | return hash; 15 | } 16 | 17 | async function HTTP_Request(endPoint, method, payload, info) { 18 | const timeStamp = Date.now().toString(); 19 | const signature = genSignature(payload); 20 | 21 | const headers = { 22 | 'X-BAPI-API-KEY': api_key, 23 | 'X-BAPI-SIGN': signature, 24 | 'X-BAPI-SIGN-TYPE': '2', 25 | 'X-BAPI-TIMESTAMP': timeStamp, 26 | 'X-BAPI-RECV-WINDOW': recv_window, 27 | 'Content-Type': 'application/json' 28 | }; 29 | 30 | let response; 31 | if (method === "POST") { 32 | response = await axios.post(url + endPoint, payload, { headers }); 33 | } else { 34 | response = await axios.get(url + endPoint + '?' + payload, { headers }); 35 | } 36 | 37 | console.log(response.data); 38 | console.log(`${info} Elapsed Time: ${response.elapsedTime}`); 39 | 40 | const listData = response.data.result.list; 41 | if (listData && listData.length > 0) { 42 | const csv = csvWriter({ 43 | path: 'BybitMarketDataTicker.csv', 44 | header: Object.keys(listData[0]).map(key => ({ id: key, title: key })) 45 | }); 46 | 47 | await csv.writeRecords(listData); 48 | } 49 | } 50 | 51 | const endpoint = '/v5/market/tickers'; 52 | const method = 'GET'; 53 | const params = 'category=linear'; 54 | 55 | HTTP_Request(endpoint, method, params, 'Market Ticker Data') 56 | .then(() => console.log('Done!')) 57 | .catch(error => console.error(error)); 58 | -------------------------------------------------------------------------------- /data_transfer_demo/http_request/import_data_to_csv.ts: -------------------------------------------------------------------------------- 1 | import axios from 'axios'; 2 | import { createObjectCsvWriter } from 'csv-writer'; 3 | import * as crypto from 'crypto'; 4 | 5 | 6 | const api_key = 'xxxxxxxxxxx'; 7 | const secret_key = 'xxxxxxxxxxxxxxxx'; 8 | const recv_window = '5000'; 9 | const url = 'https://api-testnet.bybit.com'; 10 | 11 | function genSignature(payload: string): string { 12 | const timeStamp = (Date.now()).toString(); 13 | const param_str = timeStamp + api_key + recv_window + payload; 14 | const hash = crypto.createHmac('sha256', secret_key).update(param_str).digest('hex'); 15 | return hash; 16 | } 17 | 18 | async function HTTP_Request(endPoint: string, method: 'GET' | 'POST', payload: string, info: string) { 19 | const timeStamp = (Date.now()).toString(); 20 | const signature = genSignature(payload); 21 | 22 | const headers = { 23 | 'X-BAPI-API-KEY': api_key, 24 | 'X-BAPI-SIGN': signature, 25 | 'X-BAPI-SIGN-TYPE': '2', 26 | 'X-BAPI-TIMESTAMP': timeStamp, 27 | 'X-BAPI-RECV-WINDOW': recv_window, 28 | 'Content-Type': 'application/json' 29 | }; 30 | 31 | let response; 32 | if (method === "POST") { 33 | response = await axios.post(url + endPoint, payload, { headers }); 34 | } else { 35 | response = await axios.get(url + endPoint + '?' + payload, { headers }); 36 | } 37 | 38 | console.log(response.data); 39 | console.log(`${info} Elapsed Time: ${response.elapsedTime}`); 40 | 41 | const listData = response.data.result.list; 42 | if (listData && listData.length > 0) { 43 | const csvWriter = createObjectCsvWriter({ 44 | path: 'BybitMarketDataTicker.csv', 45 | header: Object.keys(listData[0]).map(key => ({ id: key, title: key })) 46 | }); 47 | 48 | await csvWriter.writeRecords(listData); 49 | } 50 | } 51 | 52 | const endpoint = '/v5/market/tickers'; 53 | const method: 'GET' | 'POST' = 'GET'; 54 | const params = 'category=linear'; 55 | HTTP_Request(endpoint, method, params, 'Market Ticker Data') 56 | .then(() => console.log('Done!')) 57 | .catch(error => console.error(error)); -------------------------------------------------------------------------------- /data_transfer_demo/http_request/import_data_to_excel.js: -------------------------------------------------------------------------------- 1 | const axios = require('axios'); 2 | const crypto = require('crypto'); 3 | const ExcelJS = require('exceljs'); 4 | 5 | const api_key = 'xxxxxxxxxxxxxxxxx'; 6 | const secret_key = 'xxxxxxxxxxxxxxxxx'; 7 | const recv_window = '5000'; 8 | const url = 'https://api-testnet.bybit.com'; 9 | 10 | function genSignature(payload) { 11 | const timeStamp = Date.now().toString(); 12 | const param_str = timeStamp + api_key + recv_window + payload; 13 | const hash = crypto.createHmac('sha256', secret_key).update(param_str).digest('hex'); 14 | return hash; 15 | } 16 | 17 | async function HTTP_Request(endPoint, method, payload, info) { 18 | const timeStamp = Date.now().toString(); 19 | const signature = genSignature(payload); 20 | 21 | const headers = { 22 | 'X-BAPI-API-KEY': api_key, 23 | 'X-BAPI-SIGN': signature, 24 | 'X-BAPI-SIGN-TYPE': '2', 25 | 'X-BAPI-TIMESTAMP': timeStamp, 26 | 'X-BAPI-RECV-WINDOW': recv_window, 27 | 'Content-Type': 'application/json' 28 | }; 29 | 30 | let response; 31 | if (method === "POST") { 32 | response = await axios.post(url + endPoint, payload, { headers }); 33 | } else { 34 | response = await axios.get(url + endPoint + '?' + payload, { headers }); 35 | } 36 | 37 | console.log(response.data); 38 | console.log(`${info} Elapsed Time: ${response.elapsedTime}`); 39 | 40 | const listData = response.data.result.list; 41 | if (listData && listData.length > 0) { 42 | const workbook = new ExcelJS.Workbook(); 43 | const worksheet = workbook.addWorksheet('Data'); 44 | 45 | // Create header row 46 | const headers = Object.keys(listData[0]); 47 | worksheet.addRow(headers); 48 | 49 | // Populate data 50 | listData.forEach((item) => { 51 | const row = []; 52 | headers.forEach((header) => { 53 | row.push(item[header]); 54 | }); 55 | worksheet.addRow(row); 56 | }); 57 | 58 | // Save the workbook to a file 59 | await workbook.xlsx.writeFile('BybitMarketDataTicker.xlsx'); 60 | } 61 | } 62 | 63 | const endpoint = '/v5/market/tickers'; 64 | const method = 'GET'; 65 | const params = 'category=linear'; 66 | HTTP_Request(endpoint, method, params, 'Market Ticker Data') 67 | .then(() => console.log('Done!')) 68 | .catch(error => console.error(error)); 69 | -------------------------------------------------------------------------------- /data_transfer_demo/http_request/import_data_to_excel.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import time 3 | import hashlib 4 | import hmac 5 | import pandas as pd 6 | 7 | api_key = 'xxxxxxx' 8 | secret_key = 'xxxxxxxxxxxxx' 9 | httpClient = requests.Session() 10 | recv_window = str(5000) 11 | url = "https://api-testnet.bybit.com" # Testnet endpoint 12 | 13 | 14 | def HTTP_Request(endPoint, method, payload, Info): 15 | global time_stamp 16 | time_stamp = str(int(time.time() * 10 ** 3)) 17 | signature = genSignature(payload) 18 | headers = { 19 | 'X-BAPI-API-KEY': api_key, 20 | 'X-BAPI-SIGN': signature, 21 | 'X-BAPI-SIGN-TYPE': '2', 22 | 'X-BAPI-TIMESTAMP': time_stamp, 23 | 'X-BAPI-RECV-WINDOW': recv_window, 24 | 'Content-Type': 'application/json' 25 | } 26 | if (method == "POST"): 27 | response = httpClient.request(method, url + endPoint, headers=headers, data=payload) 28 | else: 29 | response = httpClient.request(method, url + endPoint + "?" + payload, headers=headers) 30 | print(response.text) 31 | print(Info + " Elapsed Time : " + str(response.elapsed)) 32 | 33 | response_json = response.json() 34 | list_data = response_json['result']['list'] 35 | export_to_excel(list_data) 36 | 37 | 38 | def genSignature(payload): 39 | param_str = str(time_stamp) + api_key + recv_window + payload 40 | hash = hmac.new(bytes(secret_key, "utf-8"), param_str.encode("utf-8"), hashlib.sha256) 41 | signature = hash.hexdigest() 42 | return signature 43 | 44 | 45 | def export_to_excel(list_data): 46 | df = pd.DataFrame(list_data) 47 | df.to_excel("BybitMarketDataTicker.xlsx", index=False) 48 | 49 | 50 | # Get unfilled wallet balance 51 | endpoint = "/v5/market/tickers" 52 | method = "GET" 53 | params = 'category=linear' 54 | HTTP_Request(endpoint, method, params, "Market Ticker Data") 55 | -------------------------------------------------------------------------------- /data_transfer_demo/http_request/import_data_to_excel.ts: -------------------------------------------------------------------------------- 1 | import axios, { AxiosResponse } from 'axios'; 2 | import * as ExcelJS from 'exceljs'; 3 | import * as crypto from 'crypto'; 4 | 5 | 6 | const api_key = 'xxxxxxxxxx'; 7 | const secret_key = 'xxxxxxxxxxxxx'; 8 | const recv_window = '5000'; 9 | const url = 'https://api-testnet.bybit.com'; 10 | 11 | function genSignature(payload: string): string { 12 | const timeStamp = (Date.now()).toString(); 13 | const param_str = timeStamp + api_key + recv_window + payload; 14 | const hash = crypto.createHmac('sha256', secret_key).update(param_str).digest('hex'); 15 | return hash; 16 | } 17 | 18 | async function HTTP_Request(endPoint: string, method: 'GET' | 'POST', payload: string, info: string) { 19 | const timeStamp = (Date.now()).toString(); 20 | const signature = genSignature(payload); 21 | 22 | const headers = { 23 | 'X-BAPI-API-KEY': api_key, 24 | 'X-BAPI-SIGN': signature, 25 | 'X-BAPI-SIGN-TYPE': '2', 26 | 'X-BAPI-TIMESTAMP': timeStamp, 27 | 'X-BAPI-RECV-WINDOW': recv_window, 28 | 'Content-Type': 'application/json' 29 | }; 30 | 31 | let response: AxiosResponse; 32 | if (method === "POST") { 33 | response = await axios.post(url + endPoint, payload, { headers }); 34 | } else { 35 | response = await axios.get(url + endPoint + '?' + payload, { headers }); 36 | } 37 | 38 | console.log(response.data); 39 | 40 | const listData = response.data.result.list; 41 | if (listData && listData.length > 0) { 42 | // Create a new Excel workbook and worksheet 43 | const workbook = new ExcelJS.Workbook(); 44 | const worksheet = workbook.addWorksheet('LinearData'); 45 | 46 | // Define headers based on your data structure 47 | const headers = Object.keys(listData[0]); 48 | worksheet.addRow(headers); 49 | 50 | // Populate data rows 51 | listData.forEach((item: { [x: string]: any; }) => { 52 | const row = []; 53 | headers.forEach((header) => { 54 | row.push(item[header]); 55 | }); 56 | worksheet.addRow(row); 57 | }); 58 | 59 | // Save the workbook to a file 60 | const excelFileName = 'BybitMarketDataTicker.xlsx'; 61 | await workbook.xlsx.writeFile(excelFileName); 62 | console.log(`Data exported to ${excelFileName}`); 63 | } 64 | } 65 | 66 | const endpoint = '/v5/market/tickers'; 67 | const method: 'GET' | 'POST' = 'GET'; 68 | const params = 'category=linear'; 69 | HTTP_Request(endpoint, method, params, 'Market Ticker Data') 70 | .then(() => console.log('Done!')) 71 | .catch(error => console.error(error)); -------------------------------------------------------------------------------- /data_transfer_demo/http_request/import_data_to_google_sheet.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import time 3 | import hashlib 4 | import hmac 5 | import json 6 | import pandas as pd 7 | import os 8 | import pickle 9 | from google_auth_oauthlib.flow import InstalledAppFlow 10 | from google.auth.transport.requests import Request 11 | 12 | api_key = 'xxxxxxxxxxxxxxx' 13 | secret_key = 'xxxxxxxxxxxxxxxxxxxxxx' 14 | httpClient = requests.Session() 15 | recv_window = str(5000) 16 | url = "https://api-testnet.bybit.com" # Testnet endpoint 17 | SCOPES = ['https://www.googleapis.com/auth/spreadsheets'] 18 | 19 | def get_google_auth_token(): 20 | creds = None 21 | 22 | # The file token.pickle stores the user's access and refresh tokens, and is 23 | # created automatically when the authorization flow completes for the first time. 24 | if os.path.exists('token.pickle'): 25 | with open('token.pickle', 'rb') as token: 26 | creds = pickle.load(token) 27 | 28 | # If there are no (valid) credentials available, prompt the user to log in. 29 | if not creds or not creds.valid: 30 | if creds and creds.expired and creds.refresh_token: 31 | creds.refresh(Request()) 32 | else: 33 | flow = InstalledAppFlow.from_client_secrets_file( 34 | 'credentials.json', SCOPES) 35 | creds = flow.run_local_server(port=0) 36 | # Save the credentials for the next run 37 | with open('token.pickle', 'wb') as token: 38 | pickle.dump(creds, token) 39 | 40 | return creds.token 41 | def HTTP_Request(endPoint, method, payload, Info): 42 | global time_stamp 43 | time_stamp = str(int(time.time() * 10 ** 3)) 44 | signature = genSignature(payload) 45 | headers = { 46 | 'X-BAPI-API-KEY': api_key, 47 | 'X-BAPI-SIGN': signature, 48 | 'X-BAPI-SIGN-TYPE': '2', 49 | 'X-BAPI-TIMESTAMP': time_stamp, 50 | 'X-BAPI-RECV-WINDOW': recv_window, 51 | 'Content-Type': 'application/json' 52 | } 53 | if (method == "POST"): 54 | response = httpClient.request(method, url + endPoint, headers=headers, data=payload) 55 | else: 56 | response = httpClient.request(method, url + endPoint + "?" + payload, headers=headers) 57 | print(response.text) 58 | print(Info + " Elapsed Time : " + str(response.elapsed)) 59 | 60 | response_json = response.json() 61 | list_data = response_json['result']['list'] 62 | df = pd.DataFrame(list_data) 63 | values_to_append = df.values.tolist() 64 | spreadSheetId = "xxxxxxxxxxxx" # replace by your sheet id 65 | append_to_google_sheet(spreadSheetId, "A1", values_to_append) 66 | 67 | def genSignature(payload): 68 | param_str = str(time_stamp) + api_key + recv_window + payload 69 | hash = hmac.new(bytes(secret_key, "utf-8"), param_str.encode("utf-8"), hashlib.sha256) 70 | signature = hash.hexdigest() 71 | return signature 72 | 73 | 74 | def append_to_google_sheet(spreadsheet_id, range_, values): 75 | # Define the endpoint URL (replace YOUR_SPREADSHEET_ID and YOUR_RANGE with appropriate values) 76 | endpoint = f"https://sheets.googleapis.com/v4/spreadsheets/{spreadsheet_id}/values/{range_}:append" 77 | 78 | # The access token you got after OAuth2.0 authorization 79 | access_token = get_google_auth_token() 80 | headers = { 81 | "Authorization": f"Bearer {access_token}", 82 | "Content-Type": "application/json" 83 | } 84 | # Prepare the request data 85 | body = { 86 | "values": values # This should be a list of lists representing rows of your data 87 | } 88 | params = { 89 | "valueInputOption": "RAW", 90 | "insertDataOption": "INSERT_ROWS" 91 | } 92 | response = requests.post(endpoint, headers=headers, params=params, data=json.dumps(body)) 93 | if response.status_code == 200: 94 | print("Data appended successfully") 95 | else: 96 | print("Failed to append data:", response.text) 97 | 98 | 99 | # Get unfilled wallet balance 100 | endpoint = "/v5/market/tickers" 101 | method = "GET" 102 | params = 'category=linear' 103 | HTTP_Request(endpoint, method, params, "Market Ticker Data") 104 | -------------------------------------------------------------------------------- /data_transfer_demo/http_request/impot_data_to_csv.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import time 3 | import hashlib 4 | import hmac 5 | import csv 6 | 7 | api_key='xxxxxxxxxxxxxxxxx' 8 | secret_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' 9 | httpClient=requests.Session() 10 | recv_window=str(5000) 11 | url="https://api-testnet.bybit.com" # Testnet endpoint 12 | 13 | def HTTP_Request(endPoint,method,payload,Info): 14 | global time_stamp 15 | time_stamp=str(int(time.time() * 10 ** 3)) 16 | signature=genSignature(payload) 17 | headers = { 18 | 'X-BAPI-API-KEY': api_key, 19 | 'X-BAPI-SIGN': signature, 20 | 'X-BAPI-SIGN-TYPE': '2', 21 | 'X-BAPI-TIMESTAMP': time_stamp, 22 | 'X-BAPI-RECV-WINDOW': recv_window, 23 | 'Content-Type': 'application/json' 24 | } 25 | if(method=="POST"): 26 | response = httpClient.request(method, url+endPoint, headers=headers, data=payload) 27 | else: 28 | response = httpClient.request(method, url+endPoint+"?"+payload, headers=headers) 29 | print(response.text) 30 | print(Info + " Elapsed Time : " + str(response.elapsed)) 31 | 32 | response_json = response.json() 33 | list_data = response_json['result']['list'] 34 | with open('BybitMarketDataTicker.csv', 'w', newline='') as csv_file: 35 | writer = csv.DictWriter(csv_file, fieldnames=list_data[0].keys()) 36 | writer.writeheader() 37 | for item in list_data: 38 | writer.writerow(item) 39 | 40 | def genSignature(payload): 41 | param_str= str(time_stamp) + api_key + recv_window + payload 42 | hash = hmac.new(bytes(secret_key, "utf-8"), param_str.encode("utf-8"),hashlib.sha256) 43 | signature = hash.hexdigest() 44 | return signature 45 | 46 | endpoint="/v5/market/tickers" 47 | method="GET" 48 | params='category=linear' 49 | HTTP_Request(endpoint,method,params,"Market Ticker Data") -------------------------------------------------------------------------------- /function_test_demo/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bybit-exchange/api-usage-examples/b3e23e9ccb50ec3928fa7e8f67455d0a0f069a0e/function_test_demo/.DS_Store -------------------------------------------------------------------------------- /function_test_demo/convert_coin_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "fmt" 7 | bybit "github.com/bybit-exchange/bybit.go.api" 8 | ) 9 | 10 | func main() { 11 | client := bybit.NewBybitHttpClient("xxx", "xxx", bybit.WithBaseURL(bybit.TESTNET)) 12 | GetConvertCoinList(client) 13 | response, err := RequestConvertQuote(client) 14 | if err != nil { 15 | fmt.Println("Error requesting convert quote:", err) 16 | return 17 | } 18 | quoteTxId, err := GetQuoteTxId(response) 19 | if err != nil { 20 | fmt.Println("Error getting quote Tx ID:", err) 21 | return 22 | } 23 | ConfirmConvertQuote(client, quoteTxId) 24 | GetConvertStatus(client, quoteTxId) 25 | GetConvertHistory(client) 26 | } 27 | 28 | func GetQuoteTxId(response *bybit.ServerResponse) (quoteTxId string, err error) { 29 | result, ok := response.Result.(map[string]interface{}) 30 | if !ok { 31 | errMsg := "Conversion of response.Result to map[string]interface{} failed" 32 | fmt.Println(errMsg) 33 | return "", errors.New(errMsg) 34 | } 35 | 36 | // Now you can safely retrieve the quoteTxId 37 | quoteTxId, ok = result["quoteTxId"].(string) 38 | if !ok { 39 | errMsg := "Retrieval of quoteTxId failed" 40 | fmt.Println(errMsg) 41 | return "", errors.New(errMsg) 42 | } 43 | 44 | fmt.Println("quoteTxId: ", quoteTxId) 45 | return quoteTxId, nil 46 | } 47 | 48 | func GetConvertCoinList(client *bybit.Client) { 49 | params := map[string]interface{}{"coin": "USDT", "accountType": "eb_convert_uta"} 50 | response, err := client.NewUtaBybitServiceWithParams(params).GetConvertCoinList(context.Background()) 51 | if err != nil { 52 | fmt.Println(err) 53 | return 54 | } 55 | fmt.Println(bybit.PrettyPrint(response)) 56 | } 57 | 58 | func GetConvertStatus(client *bybit.Client, quoteTxId string) { 59 | params := map[string]interface{}{"quoteTxId": quoteTxId, "accountType": "eb_convert_uta"} 60 | response, err := client.NewUtaBybitServiceWithParams(params).GetConvertStatus(context.Background()) 61 | if err != nil { 62 | fmt.Println(err) 63 | return 64 | } 65 | fmt.Println(bybit.PrettyPrint(response)) 66 | } 67 | 68 | func GetConvertHistory(client *bybit.Client) { 69 | params := map[string]interface{}{"accountType": "eb_convert_uta"} 70 | response, err := client.NewUtaBybitServiceWithParams(params).GetConvertHistory(context.Background()) 71 | if err != nil { 72 | fmt.Println(err) 73 | return 74 | } 75 | fmt.Println(bybit.PrettyPrint(response)) 76 | } 77 | 78 | func RequestConvertQuote(client *bybit.Client) (response *bybit.ServerResponse, err error) { 79 | params := map[string]interface{}{"fromCoin": "BTC", "toCoin": "ETH", "requestCoin": "BTC", "requestAmount": "1", "accountType": "eb_convert_uta"} 80 | return client.NewUtaBybitServiceWithParams(params).RequestConvertQuote(context.Background()) 81 | } 82 | 83 | func ConfirmConvertQuote(client *bybit.Client, quoteTxId string) { 84 | params := map[string]interface{}{"quoteTxId": quoteTxId} 85 | response, err := client.NewUtaBybitServiceWithParams(params).ConfirmConvertQuote(context.Background()) 86 | if err != nil { 87 | fmt.Println(err) 88 | return 89 | } 90 | fmt.Println(bybit.PrettyPrint(response)) 91 | } 92 | -------------------------------------------------------------------------------- /function_test_demo/create_sub_user_test.java: -------------------------------------------------------------------------------- 1 | package com.bybit.api.functionalTest; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import okhttp3.*; 5 | 6 | import javax.crypto.Mac; 7 | import javax.crypto.spec.SecretKeySpec; 8 | import java.security.InvalidKeyException; 9 | import java.security.NoSuchAlgorithmException; 10 | import java.util.HashMap; 11 | import java.util.Map; 12 | import java.io.IOException; 13 | import java.time.ZonedDateTime; 14 | 15 | public class create_subuser_example { 16 | private static final String API_KEY = "xxxx"; 17 | private static final String API_SECRET = "xxxxx"; 18 | private final static String TIMESTAMP = Long.toString(ZonedDateTime.now().toInstant().toEpochMilli()); 19 | private final static String RECV_WINDOW = "5000"; 20 | private final static String URL_PATH = "https://api-testnet.bybit.com/v5/user/create-sub-member"; 21 | 22 | public static void createSubAccount() throws IOException, NoSuchAlgorithmException, InvalidKeyException { 23 | // Build JSON payload 24 | Map map = new HashMap<>(); 25 | map.put("username", "tesx2t01"); 26 | map.put("isUta", true); 27 | map.put("memberType", 1); 28 | map.put("switch", 1); 29 | map.put("note", "testnet sub UM acct"); 30 | 31 | String signature = genPostSign(map); 32 | String jsonMap = JSON.toJSONString(map); 33 | 34 | OkHttpClient client = new OkHttpClient().newBuilder().build(); 35 | MediaType mediaType = MediaType.parse("application/json"); 36 | Request request = new Request.Builder() 37 | .url(URL_PATH) 38 | .post(RequestBody.create(mediaType, jsonMap)) 39 | .addHeader("X-BAPI-API-KEY", API_KEY) 40 | .addHeader("X-BAPI-SIGN", signature) 41 | .addHeader("X-BAPI-SIGN-TYPE", "2") 42 | .addHeader("X-BAPI-TIMESTAMP", TIMESTAMP) 43 | .addHeader("X-BAPI-RECV-WINDOW", RECV_WINDOW) 44 | .addHeader("Content-Type", "application/json") 45 | .build(); 46 | Call call = client.newCall(request); 47 | try { 48 | Response response = call.execute(); 49 | assert response.body() != null; 50 | System.out.println(response.body().string()); 51 | }catch (IOException e){ 52 | e.printStackTrace(); 53 | } 54 | } 55 | 56 | private static String genPostSign(Map params) throws NoSuchAlgorithmException, InvalidKeyException { 57 | Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); 58 | SecretKeySpec secret_key = new SecretKeySpec(API_SECRET.getBytes(), "HmacSHA256"); 59 | sha256_HMAC.init(secret_key); 60 | 61 | // Assuming JSON.toJSONString(params) correctly converts map to JSON string 62 | String paramJson = JSON.toJSONString(params); 63 | String sb = TIMESTAMP + API_KEY + RECV_WINDOW + paramJson; 64 | return bytesToHex(sha256_HMAC.doFinal(sb.getBytes())); 65 | } 66 | 67 | private static String bytesToHex(byte[] bytes) { 68 | StringBuilder hexString = new StringBuilder(); 69 | for (byte b : bytes) { 70 | String hex = Integer.toHexString(0xff & b); 71 | if (hex.length() == 1) hexString.append('0'); 72 | hexString.append(hex); 73 | } 74 | return hexString.toString(); 75 | } 76 | 77 | public static void main(String[] args) { 78 | try { 79 | createSubAccount(); 80 | } catch (IOException e) { 81 | e.printStackTrace(); 82 | } catch (NoSuchAlgorithmException | InvalidKeyException e) { 83 | throw new RuntimeException(e); 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /function_test_demo/twap_order_test.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import time 3 | import hmac 4 | import hashlib 5 | import json 6 | 7 | api_key = 'xxxx' 8 | api_secret = 'xxxx' 9 | base_url = 'https://api-testnet.bybit.com' 10 | recv_window = '5000' 11 | httpClient = requests.Session() 12 | 13 | 14 | def create_order(category, symbol, qty, side, order_type): 15 | global time_stamp 16 | """ Function to create an order on Bybit """ 17 | endpoint = "/v5/order/create" 18 | url = base_url + endpoint 19 | 20 | time_stamp = str(int(time.time() * 1000)) 21 | params = { 22 | "symbol": symbol, 23 | "category": category, 24 | "qty": str(qty), 25 | "side": side, 26 | "orderType": order_type, 27 | } 28 | signature = genSignature(params) 29 | 30 | headers = { 31 | 'X-BAPI-API-KEY': api_key, 32 | 'X-BAPI-SIGN': signature, 33 | 'X-BAPI-SIGN-TYPE': '2', 34 | 'X-BAPI-TIMESTAMP': time_stamp, 35 | 'X-BAPI-RECV-WINDOW': recv_window, 36 | 'Content-Type': 'application/json' 37 | } 38 | response = httpClient.request("POST", url, headers=headers, json=params) 39 | print("Response Text:", response.text) 40 | print("Response Headers:", response.headers) 41 | 42 | 43 | def genSignature(payload): 44 | param_str = str(time_stamp) + api_key + recv_window + json.dumps(payload) 45 | hash = hmac.new(bytes(api_secret, "utf-8"), param_str.encode("utf-8"), hashlib.sha256) 46 | signature = hash.hexdigest() 47 | return signature 48 | 49 | 50 | def twap_order(category, symbol, total_qty, side, duration, interval): 51 | """ Function to execute a TWAP strategy """ 52 | chunks = duration // interval 53 | qty_per_chunk = total_qty / chunks 54 | 55 | for _ in range(chunks): 56 | create_order(category, symbol, qty_per_chunk, side, 'Market') # set order params as you need 57 | time.sleep(interval * 60) # sleep for 'interval' minutes 58 | 59 | 60 | # Example usage 61 | twap_order('linear', 'BTCUSDT', 1, 'Buy', 100, 10) # TWAP over 100 mins, order every 10 minutes 62 | -------------------------------------------------------------------------------- /function_test_demo/universal_transfer_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "crypto/hmac" 6 | "crypto/sha256" 7 | "encoding/hex" 8 | "encoding/json" 9 | "fmt" 10 | "github.com/google/uuid" 11 | "io/ioutil" 12 | "log" 13 | "net/http" 14 | "net/http/httputil" 15 | "strconv" 16 | "time" 17 | ) 18 | 19 | func httpClient() *http.Client { 20 | client := &http.Client{Timeout: 10 * time.Second} 21 | return client 22 | } 23 | 24 | var url string = "https://api-testnet.bybit.com" 25 | var api_key = "xxxx" 26 | var apiSecret = "xxxxx" 27 | var recv_window = "5000" 28 | var signature = "" 29 | 30 | func main() { 31 | c := httpClient() 32 | transferId, _ := uuid.NewUUID() 33 | //POST Method 34 | postParams := map[string]interface{}{"fromAccountType": "FUND", "toAccountType": "FUND", "amount": "500", "coin": "USDT", "from_member_id": "1637192", "to_member_id": "1558347", "transfer_id": transferId.String()} 35 | postEndPoint := "/v5/asset/transfer/universal-transfer" 36 | universalTransferRequest(c, http.MethodPost, postParams, postEndPoint) 37 | } 38 | 39 | func universalTransferRequest(client *http.Client, method string, params interface{}, endPoint string) []byte { 40 | now := time.Now() 41 | unixNano := now.UnixNano() 42 | time_stamp := unixNano / 1000000 43 | jsonData, err := json.Marshal(params) 44 | if err != nil { 45 | log.Fatal(err) 46 | } 47 | hmac256 := hmac.New(sha256.New, []byte(apiSecret)) 48 | hmac256.Write([]byte(strconv.FormatInt(time_stamp, 10) + api_key + recv_window + string(jsonData[:]))) 49 | signature = hex.EncodeToString(hmac256.Sum(nil)) 50 | request, error := http.NewRequest("POST", url+endPoint, bytes.NewBuffer(jsonData)) 51 | request.Header.Set("Content-Type", "application/json") 52 | request.Header.Set("X-BAPI-API-KEY", api_key) 53 | request.Header.Set("X-BAPI-SIGN", signature) 54 | request.Header.Set("X-BAPI-TIMESTAMP", strconv.FormatInt(time_stamp, 10)) 55 | request.Header.Set("X-BAPI-SIGN-TYPE", "2") 56 | request.Header.Set("X-BAPI-RECV-WINDOW", recv_window) 57 | reqDump, err := httputil.DumpRequestOut(request, true) 58 | if err != nil { 59 | log.Fatal(err) 60 | } 61 | fmt.Printf("Request Dump:\n%s", string(reqDump)) 62 | response, error := client.Do(request) 63 | if error != nil { 64 | panic(error) 65 | } 66 | defer response.Body.Close() 67 | elapsed := time.Since(now).Seconds() 68 | fmt.Printf("\n%s took %v seconds \n", endPoint, elapsed) 69 | fmt.Println("response Status:", response.Status) 70 | fmt.Println("response Headers:", response.Header) 71 | body, _ := ioutil.ReadAll(response.Body) 72 | fmt.Println("response Body:", string(body)) 73 | return body 74 | } 75 | -------------------------------------------------------------------------------- /function_test_demo/uta_margin_data_test.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import time 3 | import hashlib 4 | import hmac 5 | 6 | api_key = 'xxxx' 7 | secret_key = 'xxxxx' 8 | httpClient = requests.Session() 9 | recv_window = str(5000) 10 | url = "https://api.bybit.com" 11 | 12 | 13 | def HTTP_Request(endPoint, method, payload, Info): 14 | global time_stamp 15 | time_stamp = str(int(time.time() * 10 ** 3)) 16 | signature = genSignature(payload) 17 | headers = { 18 | 'X-BAPI-API-KEY': api_key, 19 | 'X-BAPI-SIGN': signature, 20 | 'X-BAPI-SIGN-TYPE': '2', 21 | 'X-BAPI-TIMESTAMP': time_stamp, 22 | 'X-BAPI-RECV-WINDOW': recv_window, 23 | 'Content-Type': 'application/json' 24 | } 25 | if (method == "POST"): 26 | response = httpClient.request(method, url + endPoint, headers=headers, data=payload) 27 | else: 28 | response = httpClient.request(method, url + endPoint + "?" + payload, headers=headers) 29 | print(response.text) 30 | print(response.headers) 31 | print(Info + " Elapsed Time : " + str(response.elapsed)) 32 | 33 | 34 | def genSignature(payload): 35 | param_str = str(time_stamp) + api_key + recv_window + payload 36 | hash = hmac.new(bytes(secret_key, "utf-8"), param_str.encode("utf-8"), hashlib.sha256) 37 | signature = hash.hexdigest() 38 | return signature 39 | 40 | 41 | # Get VIP Margin Data 42 | endpoint = "/v5/spot-margin-trade/data" 43 | method = "GET" 44 | params = 'currency=USDT' 45 | HTTP_Request(endpoint, method, params, "Get usdt margin data") 46 | 47 | # Get Historical Interest Rate 48 | endpoint = "/v5/spot-margin-trade/interest-rate-history" 49 | method = "GET" 50 | params = 'currency=USDT&vipLevel=No%20VIP' 51 | HTTP_Request(endpoint, method, params, "Get usdt interest borrow rate") 52 | -------------------------------------------------------------------------------- /legacy_demo/api_demo/Encryption.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | 7 | typedef std::map Params; 8 | 9 | std::string HmacEncode( const char * key, const char * input) { 10 | const EVP_MD * engine = NULL; 11 | engine = EVP_sha256(); 12 | 13 | unsigned char *p = (unsigned char*)malloc(1024); 14 | char buf[1024] = {0}; 15 | char tmp[3] = {0}; 16 | unsigned int output_length = 0; 17 | p = (unsigned char*)malloc(EVP_MAX_MD_SIZE); 18 | 19 | HMAC_CTX ctx; 20 | HMAC_CTX_init(&ctx); 21 | HMAC_Init_ex(&ctx, key, strlen(key), engine, NULL); 22 | HMAC_Update(&ctx, (unsigned char*)input, strlen(input)); 23 | 24 | HMAC_Final(&ctx, p, &output_length); 25 | HMAC_CTX_cleanup(&ctx); 26 | for (int i = 0; i<32; i++) 27 | { 28 | sprintf(tmp, "%02x", p[i]); 29 | strcat(buf, tmp); 30 | } 31 | return std::string(buf); 32 | } 33 | 34 | std::string GetSignature(Params param, std::string secret){ 35 | std::string input = ""; 36 | for(Params::iterator it=param.begin();it!=param.end();++it){ 37 | input += it->first+"="+it->second+"&"; 38 | } 39 | return HmacEncode(secret.c_str(), input.substr(0, input.length()-1).c_str()); 40 | } -------------------------------------------------------------------------------- /legacy_demo/api_demo/Encryption.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using System.Security.Cryptography; 4 | 5 | public class Test 6 | { 7 | 8 | public static string CreateSignature(string secret, string message) 9 | { 10 | var signatureBytes = Hmacsha256(Encoding.UTF8.GetBytes(secret), Encoding.UTF8.GetBytes(message)); 11 | 12 | return ByteArrayToString(signatureBytes); 13 | } 14 | 15 | private static byte[] Hmacsha256(byte[] keyByte, byte[] messageBytes) 16 | { 17 | using (var hash = new HMACSHA256(keyByte)) 18 | { 19 | return hash.ComputeHash(messageBytes); 20 | } 21 | } 22 | 23 | 24 | public static string ByteArrayToString(byte[] ba) 25 | { 26 | var hex = new StringBuilder(ba.Length * 2); 27 | 28 | foreach (var b in ba) 29 | { 30 | hex.AppendFormat("{0:x2}", b); 31 | } 32 | return hex.ToString(); 33 | } 34 | 35 | public static void Main() 36 | { 37 | string secret = "t7T0YlFnYXk0Fx3JswQsDrViLg1Gh3DUU5Mr"; 38 | // Note bool should be lowercase while generating sign string 39 | string paramstr = "api_key=B2Rou0PLPpGqcU0Vu2&side=Buy&symbol=BTCUSD&qty=100&price=3001.5&time_in_force=GoodTillCancel&order_type=Limit&reduce_only=true×tamp=1542434791000"; 40 | Console.WriteLine(CreateSignature(secret, paramstr));// 52a6a6fc4da6d395baa8daccd21eb903eb47c19c03112cc2c80b005f2d181aef 41 | } 42 | 43 | } -------------------------------------------------------------------------------- /legacy_demo/api_demo/Encryption.go: -------------------------------------------------------------------------------- 1 | package example 2 | 3 | import ( 4 | "crypto/hmac" 5 | "crypto/sha256" 6 | "fmt" 7 | "io" 8 | "sort" 9 | ) 10 | 11 | func GetSignature(params map[string]string, key string) string { 12 | keys := make([]string, len(params)) 13 | i := 0 14 | _val := "" 15 | for k, _ := range params { 16 | keys[i] = k 17 | i++ 18 | } 19 | sort.Strings(keys) 20 | for _, k := range keys { 21 | _val += k + "=" + params[k] + "&" 22 | } 23 | _val = _val[0 : len(_val)-1] 24 | h := hmac.New(sha256.New, []byte(key)) 25 | io.WriteString(h, _val) 26 | return fmt.Sprintf("%x", h.Sum(nil)) 27 | } 28 | -------------------------------------------------------------------------------- /legacy_demo/api_demo/Encryption.java: -------------------------------------------------------------------------------- 1 | import okhttp3.*; 2 | 3 | import javax.crypto.Mac; 4 | import javax.crypto.spec.SecretKeySpec; 5 | import java.io.BufferedReader; 6 | import java.io.IOException; 7 | import java.io.InputStreamReader; 8 | import java.net.HttpURLConnection; 9 | import java.net.URL; 10 | import java.security.InvalidKeyException; 11 | import java.security.NoSuchAlgorithmException; 12 | import java.time.ZonedDateTime; 13 | import java.util.Comparator; 14 | import java.util.Iterator; 15 | import java.util.Set; 16 | import java.util.TreeMap; 17 | 18 | public class Encryption { 19 | public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, IOException { 20 | TreeMap map = new TreeMap( 21 | new Comparator() { 22 | public int compare(String obj1, String obj2) { 23 | //sort in alphabet order 24 | return obj1.compareTo(obj2); 25 | } 26 | }); 27 | map.put("symbol", "BTCUSD"); 28 | map.put("order_type", "Market"); 29 | map.put("qty", "1"); 30 | map.put("side", "Buy"); 31 | map.put("time_in_force", "GoodTillCancel"); 32 | map.put("timestamp", ZonedDateTime.now().toInstant().toEpochMilli()+""); 33 | 34 | String apiKey = "Your API Key"; 35 | String secret = "Your API Secret"; 36 | map.put("api_key", apiKey); 37 | 38 | String queryString = genQueryString(map, secret); 39 | OkHttpClient client = new OkHttpClient(); 40 | RequestBody body=RequestBody.create(null,new byte[0]); 41 | Request request = new Request.Builder() 42 | .post(body) 43 | .url("https://api-testnet.bybit.com/v2/private/order/create?"+queryString) 44 | .build(); 45 | Call call = client.newCall(request); 46 | try { 47 | Response response = call.execute(); 48 | System.out.println(response.body().string()); 49 | }catch (IOException e){ 50 | e.printStackTrace(); 51 | } 52 | } 53 | 54 | /** 55 | * 56 | * @param params 57 | * Map params = new TreeMap( 58 | * new Comparator() { 59 | * public int compare(String obj1, String obj2) { 60 | * //sort in alphabet order 61 | * return obj1.compareTo(obj2); 62 | * } 63 | * }); 64 | * @param secret 65 | * @return 66 | */ 67 | private static String genQueryString(TreeMap params, String secret) throws NoSuchAlgorithmException, InvalidKeyException { 68 | Set keySet = params.keySet(); 69 | Iterator iter = keySet.iterator(); 70 | StringBuilder sb = new StringBuilder(); 71 | while (iter.hasNext()) { 72 | String key = iter.next(); 73 | sb.append(key + "=" + params.get(key)); 74 | sb.append("&"); 75 | } 76 | sb.deleteCharAt(sb.length() - 1); 77 | Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); 78 | SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256"); 79 | sha256_HMAC.init(secret_key); 80 | 81 | return sb+"&sign="+bytesToHex(sha256_HMAC.doFinal(sb.toString().getBytes())); 82 | } 83 | 84 | private static String bytesToHex(byte[] hash) { 85 | StringBuffer hexString = new StringBuffer(); 86 | for (int i = 0; i < hash.length; i++) { 87 | String hex = Integer.toHexString(0xff & hash[i]); 88 | if(hex.length() == 1) hexString.append('0'); 89 | hexString.append(hex); 90 | } 91 | return hexString.toString(); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /legacy_demo/api_demo/Encryption.rb: -------------------------------------------------------------------------------- 1 | require 'uri' 2 | 3 | require "openssl" 4 | 5 | def get_signature(param_str, secret) 6 | OpenSSL::HMAC.hexdigest('sha256', secret, param_str) 7 | end 8 | 9 | api_key = "XXXXXXXX" 10 | secret = "XXXXXXXX" 11 | 12 | params = { 13 | symbol: "BTCUSD", 14 | timestamp: Time.now.to_i * 1000, 15 | leverage: 100, 16 | }.merge(api_key: api_key) 17 | 18 | signature = get_signature(URI.encode_www_form(params.sort), secret) 19 | puts signature -------------------------------------------------------------------------------- /legacy_demo/api_demo/asset/Encryption.js: -------------------------------------------------------------------------------- 1 | var axios = require('axios'); 2 | querystring = require('querystring'); 3 | const crypto = require('crypto'); 4 | const uuid = require('uuid'); 5 | 6 | 7 | var apiKey = "XXXXXXXXXXXXXXX"; 8 | var secret = "XXXXXXXXXXXXXXX"; 9 | var transferId = uuid.v4(); 10 | var qs=""; 11 | var amount="5"; 12 | var coin="USDT"; 13 | var timestamp = Date.now(); 14 | var unordered = { "transferId": transferId, "amount": amount, "coin": coin, "from_account_type":"SPOT", "to_account_type":"CONTRACT", "timestamp": timestamp, "api_key": apiKey, "recv_window": "50000"}; 15 | 16 | console.log(unordered); 17 | //sort the unordered object and generate signature value 18 | var keys = [],k, i, len; 19 | for (k in unordered) { 20 | if (unordered.hasOwnProperty(k)) { 21 | keys.push(k); 22 | } 23 | } 24 | keys.sort(); 25 | len = keys.length; 26 | for (i = 0; i < len; i++) { 27 | k = keys[i]; 28 | qs=qs + k +'='+unordered[k] + '&'; //Generate QueryString 29 | } 30 | sign = crypto.createHmac('sha256', secret).update(qs.slice(0, -1)).digest('hex'); 31 | unordered["sign"] =sign; 32 | 33 | var config = { 34 | method: 'post', 35 | url: 'https://api-testnet.bybit.com/asset/v1/private/transfer', 36 | data : unordered 37 | }; 38 | 39 | axios(config) 40 | .then(function (response) { 41 | console.log(JSON.stringify(response.data)); 42 | }) 43 | .catch(function (error) { 44 | console.log(error); 45 | }); 46 | -------------------------------------------------------------------------------- /legacy_demo/api_demo/asset/Encryption.php: -------------------------------------------------------------------------------- 1 | guidv4(openssl_random_pseudo_bytes(16)), 23 | "amount" => "10", 24 | "coin" => "USDT", 25 | "from_account_type" => "CONTRACT", 26 | "to_account_type" => "SPOT", 27 | "timestamp" => time() * 1000, 28 | "api_key" => $public_key, 29 | "recv_window" => "50000" 30 | ]; 31 | 32 | $sign=get_signed_params($public_key, $secret_key, $params); 33 | $params = array_merge(['sign' => $sign], $params); 34 | $json_value=json_encode($params); 35 | 36 | curl_setopt_array($curl, array( 37 | CURLOPT_URL => 'https://api-testnet.bybit.com/asset/v1/private/transfer', 38 | CURLOPT_RETURNTRANSFER => true, 39 | CURLOPT_ENCODING => '', 40 | CURLOPT_MAXREDIRS => 10, 41 | CURLOPT_TIMEOUT => 0, 42 | CURLOPT_FOLLOWLOCATION => true, 43 | CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, 44 | CURLOPT_CUSTOMREQUEST => 'POST', 45 | CURLOPT_POSTFIELDS => $json_value 46 | )); 47 | 48 | $response = curl_exec($curl); 49 | 50 | curl_close($curl); 51 | echo $response; 52 | -------------------------------------------------------------------------------- /legacy_demo/api_demo/asset/Encryption.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import hmac 3 | import json 4 | import requests 5 | import urllib3 6 | from random import randrange 7 | import time 8 | def transfer(apiKey,secretKey,coin,fromAccountType,toAccountType,amount,transferId): 9 | params = { 10 | "fromAccountType": fromAccountType, 11 | "toAccountType": toAccountType, 12 | "coin": coin, 13 | "amount": amount, 14 | "transferId": transferId, 15 | "api_key": apiKey, 16 | "timestamp": str(int(time.time()*1000)) 17 | } 18 | sign = '' 19 | for key in sorted(params.keys()): 20 | v = params[key] 21 | if isinstance(params[key], bool): 22 | if params[key]: 23 | v = 'true' 24 | else : 25 | v = 'false' 26 | sign += key + '=' + v + '&' 27 | sign = sign[:-1] 28 | print(sign) 29 | hash = hmac.new(secretKey, sign.encode("utf-8"), hashlib.sha256) 30 | signature = hash.hexdigest() 31 | print(signature) 32 | sign_real = { 33 | "sign": signature 34 | } 35 | url = 'https://api.bybit.com/asset/v1/private/transfer' 36 | headers = {"Content-Type": "application/json"} 37 | body = dict(params,**sign_real) 38 | urllib3.disable_warnings() 39 | response = requests.post(url, data=json.dumps(body), headers=headers,verify=False) 40 | print(response.text) 41 | def main(): 42 | apiKey = "xxxx" 43 | secret = b"xxxx" 44 | transfer(apiKey, secret,'USDT','CONTRACT','SPOT','0.001','21ff1b44-2d5d-4293-913d-4545c5ad'+str(randrange(1000,9999))) 45 | if __name__ == '__main__': 46 | main() 47 | -------------------------------------------------------------------------------- /legacy_demo/api_demo/asset/Encryption.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | api_key="XXXXXXXXXXX" 4 | secret_key="XXXXXXXXXXX" 5 | time_in_seconds=$(date +%s) 6 | timestamp=$((time_in_seconds * 1000)) 7 | coin="USDT" 8 | amount="5" 9 | transfer_id=$(uuidgen) 10 | sign=$(echo -n "amount=${amount}&api_key=${api_key}&coin=${coin}&from_account_type=SPOT&recv_window=50000×tamp=${timestamp}&to_account_type=CONTRACT&transferId=${transfer_id}" | openssl dgst -sha256 -hmac "${secret_key}") 11 | response=$(curl --request POST --silent 'https://api-testnet.bybit.com/asset/v1/private/transfer' \ 12 | --data-raw '{ 13 | "transferId": "'"${transfer_id}"'", 14 | "amount": "'"${amount}"'", 15 | "coin": "'"${coin}"'", 16 | "from_account_type":"SPOT", 17 | "to_account_type":"CONTRACT", 18 | "sign": "'"${sign}"'", 19 | "timestamp": "'"${timestamp}"'", 20 | "api_key": "'"${api_key}"'", 21 | "recv_window": "50000" 22 | }' 23 | ) 24 | echo "${response}" 25 | -------------------------------------------------------------------------------- /legacy_demo/api_demo/encryption.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | api_key="XXXXXXXXXXXXXXX" 4 | secret_key="XXXXXXXXXXXXXXX" 5 | time_in_seconds=$(date +%s) 6 | timestamp=$((time_in_seconds * 1000)) 7 | sign=$(echo -n "api_key=${api_key}&close_on_trigger=false&order_type=Market&qty=0.001&reduce_only=false&side=Buy&symbol=BTCUSDT&time_in_force=GoodTillCancel×tamp=${timestamp}" | openssl dgst -sha256 -hmac "${secret_key}") 8 | 9 | response=$(curl --silent https://api-testnet.bybit.com/private/linear/order/create \ 10 | -H "Content-Type: application/json" \ 11 | -d '{"api_key":"'"${api_key}"'","side":"Buy","symbol":"BTCUSDT","order_type":"Market","qty":"0.001","time_in_force":"GoodTillCancel","close_on_trigger":false,"reduce_only":false,"timestamp":"'"${timestamp}"'","sign":"'"${sign}"'"}') 12 | 13 | echo "Curl Response : $?" 14 | #echo "${response}" 15 | order_id=$(jq '.result.order_id' <<< ${response}) 16 | if [ "${order_id}" == "null" ] 17 | then 18 | echo "${response}" 19 | else 20 | echo "Order ID # ${order_id}" 21 | fi 22 | -------------------------------------------------------------------------------- /legacy_demo/api_demo/futures/Encryption.js: -------------------------------------------------------------------------------- 1 | const crypto = require('crypto'); 2 | const axios = require('axios') 3 | url='https://api-testnet.bybit.com/v2/private/order/create'; 4 | 5 | var apiKey = "xxxx"; 6 | var secret = "xxxx"; 7 | var timestamp = Date.now().toString(); 8 | var params = { 9 | "symbol":"BTCUSD", 10 | "side":"Buy", 11 | "qty":"1", 12 | "price":"10000", 13 | "order_type":"Limit", 14 | "timestamp":timestamp, 15 | "api_key" : apiKey, 16 | "time_in_force":"GoodTillCancel" 17 | }; 18 | 19 | params["sign"]=getSignature(params,secret); 20 | 21 | axios.post(url,params).then(res => console.log(res.data)).catch(err=>console.log(err)); 22 | 23 | function getSignature(parameters, secret) { 24 | var orderedParams = ""; 25 | Object.keys(parameters).sort().forEach(function(key) { 26 | orderedParams += key + "=" + parameters[key] + "&"; 27 | }); 28 | orderedParams = orderedParams.substring(0, orderedParams.length - 1); 29 | 30 | return crypto.createHmac('sha256', secret).update(orderedParams).digest('hex'); 31 | } 32 | 33 | -------------------------------------------------------------------------------- /legacy_demo/api_demo/futures/Encryption.php: -------------------------------------------------------------------------------- 1 | $public_key], $params); 5 | ksort($params); 6 | //decode return value of http_build_query to make sure signing by plain parameter string 7 | $signature = hash_hmac('sha256', urldecode(http_build_query($params)), $secret_key); 8 | return http_build_query($params) . "&sign=$signature"; 9 | } 10 | 11 | $params = [ 12 | 'symbol' => 'BTCUSDT', 13 | 'side' => 'Buy', 14 | 'order_type' => 'Limit', 15 | 'qty' => '0.01', 16 | 'price' => '30000', 17 | 'time_in_force' => 'GoodTillCancel', 18 | 'reduce_only' => false, 19 | 'close_on_trigger' => false, 20 | 'timestamp' => time() * 1000, 21 | 'position_idx' => 0 22 | ]; 23 | 24 | $url = 'https://api-testnet.bybit.com/private/linear/order/create'; 25 | 26 | $public_key = 'XXXXXXXXXXXXXXXXX'; 27 | $secret_key = 'XXXXXXXXXXXXXXXXX'; 28 | $qs=get_signed_params($public_key, $secret_key, $params); 29 | $curl_url=$url."?".$qs; 30 | $curl=curl_init($curl_url); 31 | echo $curl_url; 32 | curl_setopt($curl, CURLOPT_URL, $curl_url); 33 | #curl_setopt($curl, CURLOPT_POSTFIELDS, $qs); 34 | curl_setopt($curl, CURLOPT_POST, true); 35 | curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 36 | curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); 37 | curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); 38 | curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); 39 | #curl_setopt($curl, CURLOPT_PROXY,"127.0.0.1:1087"); 40 | $response=curl_exec($curl); 41 | echo $response; 42 | -------------------------------------------------------------------------------- /legacy_demo/api_demo/futures/Encryption.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import hmac 3 | import json 4 | import requests 5 | import urllib3 6 | import time 7 | def create_order(apiKey,secretKey,symbol,side,order_type,qty,price): 8 | timestamp = int(time.time() * 10 ** 3) 9 | params = { 10 | "side": side, 11 | "symbol": symbol, 12 | "order_type": order_type, 13 | "qty": qty, 14 | "price": price, 15 | "time_in_force": "PostOnly", 16 | "api_key": apiKey, 17 | "timestamp": str(timestamp), 18 | "recv_window": "5000", 19 | "reduce_only": False, 20 | "close_on_trigger": False, 21 | } 22 | sign = '' 23 | for key in sorted(params.keys()): 24 | v = params[key] 25 | if isinstance(params[key], bool): 26 | if params[key]: 27 | v = 'true' 28 | else : 29 | v = 'false' 30 | sign += key + '=' + v + '&' 31 | sign = sign[:-1] 32 | hash = hmac.new(secretKey, sign.encode("utf-8"), hashlib.sha256) 33 | signature = hash.hexdigest() 34 | sign_real = { 35 | "sign": signature 36 | } 37 | url = 'https://api-testnet.bybit.com/private/linear/order/create' 38 | headers = {"Content-Type": "application/json"} 39 | body = dict(params,**sign_real) 40 | urllib3.disable_warnings() 41 | s = requests.session() 42 | s.keep_alive = False 43 | response = requests.post(url, data=json.dumps(body), headers=headers,verify=False) 44 | print(response.text) 45 | def main(): 46 | apiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX" 47 | secret = b"XXXXXXXXXXXXXXXXXXXXXXXXXXXXX" 48 | create_order(apiKey, secret,'UNIUSDT','Buy','Limit','1','10') 49 | create_order(apiKey, secret,'BTCUSDT','Buy','Market','0.001','0') #for market order, we are just passing the price as 0 50 | if __name__ == '__main__': 51 | main() 52 | -------------------------------------------------------------------------------- /legacy_demo/api_demo/futures/Encryption.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | api_key="XXXXXXXXXXXXXXXXXXXXXXXXX" 4 | secret_key="XXXXXXXXXXXXXXXXXXXXXXXXX" 5 | time_in_seconds=$(date +%s) 6 | timestamp=$((time_in_seconds * 1000)) 7 | sign=$(echo -n "api_key=${api_key}&close_on_trigger=false&order_type=Market&qty=0.001&reduce_only=false&side=Buy&symbol=BTCUSDT&time_in_force=GoodTillCancel×tamp=${timestamp}" | openssl dgst -sha256 -hmac "${secret_key}") 8 | 9 | response=$(curl --silent https://api-testnet.bybit.com/private/linear/order/create \ 10 | -H "Content-Type: application/json" \ 11 | -d '{"api_key":"'"${api_key}"'","side":"Buy","symbol":"BTCUSDT","order_type":"Market","qty":"0.001","time_in_force":"GoodTillCancel","close_on_trigger":false,"reduce_only":false,"timestamp":"'"${timestamp}"'","sign":"'"${sign}"'"}') 12 | 13 | echo "Curl Response : $?" 14 | #echo "${response}" 15 | order_id=$(jq '.result.order_id' <<< ${response}) 16 | if [ "${order_id}" == "null" ] 17 | then 18 | echo "${response}" 19 | else 20 | echo "Order ID 21 | -------------------------------------------------------------------------------- /legacy_demo/api_demo/http2.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import httpx # `requests` does not allow us to send HTTP/2 requests 3 | import hmac 4 | import urllib3 5 | import time 6 | from urllib.parse import quote_plus 7 | 8 | 9 | # This file demonstrates an HTTP/2 request to cancel a spot order. However, 10 | # it can be adapted for the other APIs (derivatives, etc) 11 | 12 | 13 | api_key = "" 14 | api_secret = "" 15 | 16 | 17 | # Note that while api.bybit.com does support HTTP/2 E2E, 18 | # api.bytick.com does not 19 | url = "https://api.bybit.com/spot/v1/order" 20 | 21 | 22 | def auth(): 23 | timestamp = int(time.time() * 10 ** 3) 24 | headers = {} 25 | params = { # delete order request 26 | "orderId": "1084090149712726016", 27 | "api_key": api_key, 28 | "timestamp": str(timestamp), 29 | "recv_window": "5000" 30 | } 31 | param_str = '' 32 | for key in sorted(params.keys()): 33 | v = params[key] 34 | if isinstance(params[key], bool): 35 | if params[key]: 36 | v = "true" 37 | else: 38 | v = "false" 39 | param_str += key + "=" + v + "&" 40 | param_str = param_str[:-1] 41 | signature = str(hmac.new( 42 | bytes(api_secret, "utf-8"), 43 | bytes(param_str, "utf-8"), digestmod="sha256" 44 | ).hexdigest()) 45 | sign_real = { 46 | "sign": signature 47 | } 48 | param_str = quote_plus(param_str, safe="=&") 49 | full_param_str = f"{param_str}&sign={sign_real['sign']}" 50 | urllib3.disable_warnings() 51 | return f"{url}?{full_param_str}" 52 | 53 | 54 | async def main(): 55 | client = httpx.AsyncClient(http2=True) 56 | url_with_params = auth() 57 | response = await client.delete(url_with_params) 58 | await client.aclose() 59 | print(response.http_version) # "HTTP/1.0", "HTTP/1.1", or "HTTP/2". 60 | print(response) 61 | print(response.text) 62 | 63 | 64 | asyncio.run(main()) 65 | -------------------------------------------------------------------------------- /legacy_demo/api_demo/spot/Encryption.js: -------------------------------------------------------------------------------- 1 | const crypto = require('crypto'); 2 | const axios = require('axios') 3 | url='https://api-testnet.bybit.com/spot/v1/order'; 4 | 5 | var apiKey = "xxxx"; 6 | var secret = "xxxx"; 7 | var timestamp = Date.now().toString(); 8 | var params = { 9 | "symbol":"BTCUSDT", 10 | "side":"Buy", 11 | "qty":"0.001", 12 | "price":"10000", 13 | "type":"Limit", 14 | "timestamp":timestamp, 15 | "api_key" : apiKey, 16 | "timeInForce":"GTC" 17 | }; 18 | 19 | paramsQueryString=getSignature(params, secret); 20 | axios.post(url,paramsQueryString).then(res => console.log(res.data)).catch(err=>console.log(err)); 21 | 22 | function getSignature(parameters, secret) { 23 | var orderedParams = ""; 24 | Object.keys(parameters).sort().forEach(function(key) { 25 | orderedParams += key + "=" + parameters[key] + "&"; 26 | }); 27 | orderedParams = orderedParams.substring(0, orderedParams.length - 1); 28 | 29 | return orderedParams+'&sign='+crypto.createHmac('sha256', secret).update(orderedParams).digest('hex'); 30 | } 31 | 32 | -------------------------------------------------------------------------------- /legacy_demo/api_demo/spot/Encryption.php: -------------------------------------------------------------------------------- 1 | $public_key], $params); 5 | ksort($params); 6 | //decode return value of http_build_query to make sure signing by plain parameter string 7 | $signature = hash_hmac('sha256', urldecode(http_build_query($params)), $secret_key); 8 | return http_build_query($params) . "&sign=$signature"; 9 | } 10 | 11 | $params = [ 12 | 'symbol' => 'BITUSDT', 13 | 'side' => 'Buy', 14 | 'type' => 'Limit', 15 | 'qty' => '10', 16 | 'price' => '1', 17 | 'time_in_force' => 'GoodTillCancel', 18 | 'reduce_only' => false, 19 | 'close_on_trigger' => false, 20 | 'timestamp' => time() * 1000 21 | ]; 22 | 23 | $url = 'https://api-testnet.bybit.com/spot/v1/order'; 24 | 25 | $public_key = 'XXXXXXXXXXXXXXXXXXXXXXX'; 26 | $secret_key = 'XXXXXXXXXXXXXXXXXXXXXXX'; 27 | $qs=get_signed_params($public_key, $secret_key, $params); 28 | $curl_url=$url."?".$qs; 29 | $curl=curl_init($curl_url); 30 | echo $curl_url . "\n"; 31 | curl_setopt($curl, CURLOPT_URL, $curl_url); 32 | #curl_setopt($curl, CURLOPT_POSTFIELDS, $qs); 33 | curl_setopt($curl, CURLOPT_POST, true); 34 | curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 35 | curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); 36 | curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); 37 | curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); 38 | #curl_setopt($curl, CURLOPT_PROXY,"127.0.0.1:1087"); 39 | $response=curl_exec($curl); 40 | echo $response . "\n"; 41 | -------------------------------------------------------------------------------- /legacy_demo/api_demo/spot/Encryption.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import hmac 3 | import json 4 | import requests 5 | import urllib3 6 | import time 7 | from urllib.parse import quote_plus 8 | 9 | def create_order(apiKey,secretKey,symbol,side,order_type,qty,price): 10 | timestamp = int(time.time() * 10 ** 3) 11 | url = 'https://api-testnet.bybit.com/spot/v1/order' 12 | headers = {} 13 | method="POST" 14 | params = { 15 | "side": side, 16 | "symbol": symbol, 17 | "type": order_type, 18 | "qty": qty, 19 | "price": price, 20 | "time_in_force": "GoodTillCancel", 21 | "api_key": apiKey, 22 | "timestamp": str(timestamp), 23 | "recv_window": "5000" 24 | } 25 | param_str = '' 26 | for key in sorted(params.keys()): 27 | v = params[key] 28 | if isinstance(params[key], bool): 29 | if params[key]: 30 | v = 'true' 31 | else : 32 | v = 'false' 33 | param_str += key + '=' + v + '&' 34 | param_str = param_str[:-1] 35 | hash = hmac.new(secretKey, param_str.encode("utf-8"), hashlib.sha256) 36 | signature = hash.hexdigest() 37 | sign_real = { 38 | "sign": signature 39 | } 40 | param_str = quote_plus(param_str, safe="=&") 41 | full_param_str = f"{param_str}&sign={sign_real['sign']}" 42 | urllib3.disable_warnings() 43 | s = requests.session() 44 | s.keep_alive = False 45 | response = requests.request(method, f"{url}?{full_param_str}",headers=headers, verify=False) 46 | print(response.text) 47 | def main(): 48 | apiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" 49 | secret = b"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" 50 | create_order(apiKey, secret,'BITUSDT','Buy','Limit','10','1') 51 | create_order(apiKey, secret,'BITUSDT','Buy','Market','10','0') #for market order, we are just passing the price as 0 52 | if __name__ == '__main__': 53 | main() 54 | -------------------------------------------------------------------------------- /legacy_demo/api_demo/spot/Encryption.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | api_key="XXXXXXXXXXXXXXXXXXXXX" 4 | secret_key="XXXXXXXXXXXXXXXXXXXXX" 5 | time_in_seconds=$(date +%s) 6 | timestamp=$((time_in_seconds * 1000)) 7 | #Sort your paramters in Alphabetical order - https://bybit-exchange.github.io/docs/spot/#t-constructingtherequest 8 | params="api_key=${api_key}&price=30000&qty=0.001&side=Buy&symbol=BTCUSDT&timeInForce=GTC×tamp=${timestamp}&type=Limit" 9 | sign=$(echo -n "${params}" | openssl dgst -sha256 -hmac "${secret_key}") 10 | 11 | response=$(curl -d "${params}&sign=${sign}" -X POST "https://api-testnet.bybit.com/spot/v1/order") 12 | 13 | echo "Curl Response : $?" 14 | orderId=$(jq '.result.orderId' <<< ${response}) 15 | if [ "${orderId}" == "null" ] 16 | then 17 | echo "${response}" 18 | else 19 | echo "Order ID # ${orderId}" 20 | fi 21 | -------------------------------------------------------------------------------- /legacy_demo/api_demo/usdc/Encryption.js: -------------------------------------------------------------------------------- 1 | const crypto = require('crypto'); 2 | const axios = require('axios') 3 | url='https://api-testnet.bybit.com/option/usdc/openapi/private/v1/place-order'; 4 | 5 | var apiKey = "xxxx"; 6 | var secret = "xxxx"; 7 | var headers={ 8 | 'X-BAPI-API-KEY':apiKey, 9 | 'X-BAPI-TIMESTAMP':Date.now() 10 | } 11 | var timestamp = Date.now().toString(); 12 | var params = { 13 | "outRequestId":Date.now().toString(), 14 | "symbol":"BTC-28JAN22-140000-C", 15 | "orderType":"Limit", 16 | "side":"Sell", 17 | "timeInForce":"GoodTillCancel", 18 | "orderQty":"0.01", 19 | "orderPrice":"40" 20 | }; 21 | 22 | headers["X-BAPI-SIGN"]=getSignature(headers,params, secret); 23 | 24 | axios.post(url,params, 25 | { 26 | headers:headers, 27 | }).then(res => console.log(res.data)).catch(err=>console.log(err)); 28 | 29 | function getSignature(headers, params, secret) { 30 | var queryString = headers['X-BAPI-TIMESTAMP'].toString()+headers['X-BAPI-API-KEY']+JSON.stringify(params); 31 | return crypto.createHmac('sha256', secret).update(queryString).digest('hex'); 32 | } 33 | 34 | -------------------------------------------------------------------------------- /legacy_demo/api_demo/usdc/Encryption_Javascript.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 33 | 34 | 35 | Hello World 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /legacy_demo/api_demo/usdc/encryption.php: -------------------------------------------------------------------------------- 1 | 'https://api-testnet.bybit.com/option/usdc/openapi/private/v1/place-order', 14 | CURLOPT_RETURNTRANSFER => true, 15 | CURLOPT_ENCODING => '', 16 | CURLOPT_MAXREDIRS => 10, 17 | CURLOPT_TIMEOUT => 0, 18 | CURLOPT_FOLLOWLOCATION => true, 19 | CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, 20 | CURLOPT_CUSTOMREQUEST => 'POST', 21 | CURLOPT_POSTFIELDS => $params, 22 | CURLOPT_HTTPHEADER => array( 23 | "X-BAPI-API-KEY: $api_key", 24 | "X-BAPI-SIGN: $signature", 25 | "X-BAPI-SIGN-TYPE: 2", 26 | "X-BAPI-TIMESTAMP: $timestamp", 27 | "X-BAPI-RECV-WINDOW: 5000", 28 | "Content-Type: application/json" 29 | ), 30 | )); 31 | 32 | $response = curl_exec($curl); 33 | curl_close($curl); 34 | echo $response; 35 | -------------------------------------------------------------------------------- /legacy_demo/api_demo/usdc/encryption.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | import time 4 | import hashlib 5 | import hmac 6 | 7 | api_key='API-KEY' 8 | secret_key='SECRET-KEY' 9 | time_stamp=str(int(time.time() * 10 ** 3)) 10 | recv_window=str(5000) 11 | url = "https://api-testnet.bybit.com/option/usdc/openapi/private/v1/place-order" 12 | 13 | payload = json.dumps({"outRequestId":"8c7af60012","symbol":"BTC-17DEC21-40000-C","orderType":"Limit","side":"Buy", 14 | "orderQty":"0.01","orderPrice":"308","iv":"72","timeInForce":"GoodTillCancel","orderLinkId":"c3d5cb801a", 15 | "reduceOnly":True,"placeMode":1,"placeType":1}) 16 | 17 | payload = json.dumps({"outRequestId":"8c7f60012","symbol":"BTC-28JAN22-140000-C","side":"Sell","orderType":"Limit","orderQty":"0.01","orderPrice":"258","timeInForce":"GoodTillCancel","reduceOnly":True,"placeMode":1,"placeType":1}) 18 | param_str= str(time_stamp) + api_key + recv_window + payload 19 | hash = hmac.new(bytes(secret_key, "utf-8"), param_str.encode("utf-8"),hashlib.sha256) 20 | signature = hash.hexdigest() 21 | 22 | headers = { 23 | 'X-BAPI-API-KEY': api_key, 24 | 'X-BAPI-SIGN': signature, 25 | 'X-BAPI-SIGN-TYPE': '2', 26 | 'X-BAPI-TIMESTAMP': time_stamp, 27 | 'X-BAPI-RECV-WINDOW': recv_window, 28 | 'Content-Type': 'application/json' 29 | } 30 | response = requests.request("POST", url, headers=headers, data=payload) 31 | print(response.text) 32 | -------------------------------------------------------------------------------- /legacy_demo/wss_demo/js/ws_private_demo.js: -------------------------------------------------------------------------------- 1 | var url = require('url'); 2 | var WebSocket = require('ws'); 3 | var crypto = require('crypto'); 4 | var endpoint = "wss://stream-testnet.bybit.com/realtime" 5 | console.log('attempting to connect to WebSocket %j', endpoint); 6 | var client = new WebSocket(endpoint); 7 | const apiKey="XXXXXXXX"; 8 | const apiSecret="XXXXXXXX"; 9 | client.on('open', function () { 10 | console.log('"open" event!'); 11 | console.log('WebSocket Client Connected'); 12 | const expires = new Date().getTime() + 10000; 13 | const signature = crypto.createHmac("sha256", apiSecret).update("GET/realtime" + expires).digest("hex"); 14 | const payload={ 15 | op: "auth", 16 | args: [apiKey, expires.toFixed(0), signature], 17 | } 18 | client.send(JSON.stringify(payload)); 19 | setInterval(()=>{client.ping()}, 30000); 20 | client.ping(); 21 | client.send(JSON.stringify({"op": "subscribe", "args": ['order']})); 22 | }); 23 | 24 | client.on('message', function (data) { 25 | console.log('"message" event! %j', data); 26 | }); 27 | client.on('ping', function (data, flags) { 28 | console.log("ping received"); 29 | }); 30 | client.on('pong', function (data, flags) { 31 | console.log("pong received"); 32 | }); 33 | -------------------------------------------------------------------------------- /legacy_demo/wss_demo/js/ws_public_demo.js: -------------------------------------------------------------------------------- 1 | var url = require('url'); 2 | var WebSocket = require('ws'); 3 | var crypto = require('crypto'); 4 | var endpoint = "wss://stream-testnet.bybit.com/realtime" 5 | console.log('attempting to connect to WebSocket %j', endpoint); 6 | var client = new WebSocket(endpoint); 7 | client.on('open', function () { 8 | console.log('"open" event!'); 9 | console.log('WebSocket Client Connected'); 10 | setInterval(()=>{client.ping()}, 30000); 11 | client.ping(); 12 | client.send(JSON.stringify({"op": "subscribe", "args": ["orderBookL2_25.BTCUSD"]})); 13 | }); 14 | 15 | client.on('message', function (data) { 16 | console.log('"message" event! %j', data); 17 | }); 18 | client.on('ping', function (data, flags) { 19 | console.log("ping received"); 20 | }); 21 | client.on('pong', function (data, flags) { 22 | console.log("pong received"); 23 | }); 24 | -------------------------------------------------------------------------------- /legacy_demo/wss_demo/python/logfile_wrapper.log: -------------------------------------------------------------------------------- 1 | 2021-10-28 16:38:04,354 DEBUG --- request header --- 2 | 2021-10-28 16:38:04,354 DEBUG GET /realtime HTTP/1.1 3 | Upgrade: websocket 4 | Connection: Upgrade 5 | Host: stream.bybit.com 6 | Origin: http://stream.bybit.com 7 | Sec-WebSocket-Key: iMfB9uHihIjt/49uhCCk/g== 8 | Sec-WebSocket-Version: 13 9 | 10 | 11 | 2021-10-28 16:38:04,355 DEBUG ----------------------- 12 | 2021-10-28 16:38:04,355 DEBUG --- response header --- 13 | 2021-10-28 16:38:04,837 DEBUG HTTP/1.1 101 Switching Protocols 14 | 2021-10-28 16:38:04,837 DEBUG Connection: upgrade 15 | 2021-10-28 16:38:04,838 DEBUG Date: Thu, 28 Oct 2021 08:38:04 GMT 16 | 2021-10-28 16:38:04,838 DEBUG Upgrade: websocket 17 | 2021-10-28 16:38:04,838 DEBUG Sec-WebSocket-Accept: xPBX9SPDUm8H9hYixgsuY0qnL2U= 18 | 2021-10-28 16:38:04,839 DEBUG X-Cache: Miss from cloudfront 19 | 2021-10-28 16:38:04,839 DEBUG Via: 1.1 573b4e1c3f2f4bebe43f934c516f0052.cloudfront.net (CloudFront) 20 | 2021-10-28 16:38:04,839 DEBUG X-Amz-Cf-Pop: SIN2-P1 21 | 2021-10-28 16:38:04,840 DEBUG X-Amz-Cf-Id: LUV5KuXjPcEqBa8EWyZjjqlxK3zkBFrR4qCNR5ZMQkrwgcOC3sEVOw== 22 | 2021-10-28 16:38:04,840 DEBUG ----------------------- 23 | 2021-10-28 16:38:04,842 DEBUG send: b'\x81\xb6\xf5\x1b\xa9>\x8e9\xc6N\xd7!\x89\x1c\x86n\xcbM\x96i\xc0\\\x909\x85\x1e\xd7z\xdbY\x869\x93\x1e\xae9\xc6L\x91~\xdb|\x9at\xc2r\xc7D\x9b\x0b\xdbY\xfd}\xa0H\xed\x1c\xa8f' 24 | 2021-10-28 16:38:06,835 DEBUG send: b'\x88\x82uK\xbcDv\xa3' 25 | -------------------------------------------------------------------------------- /legacy_demo/wss_demo/python/ws_private_demo.py: -------------------------------------------------------------------------------- 1 | import hmac 2 | import json 3 | import logging 4 | import time 5 | 6 | import websocket 7 | 8 | logging.basicConfig(filename='logfile_wrapper.log', level=logging.DEBUG, 9 | format='%(asctime)s %(levelname)s %(message)s') 10 | topic = "order" 11 | 12 | trade_results = {} 13 | size = {} 14 | size_usdt = {} 15 | 16 | 17 | def on_message(ws, message): 18 | data = json.loads(message) 19 | print(data) 20 | 21 | 22 | def on_error(ws, error): 23 | print('we got error') 24 | print(error) 25 | 26 | 27 | def on_close(ws): 28 | print("### about to close please don't close ###") 29 | 30 | 31 | def send_auth(ws): 32 | key = 'xxxx' 33 | secret = 'xxxx' 34 | expires = int((time.time() + 10) * 1000) 35 | _val = f'GET/realtime{expires}' 36 | print(_val) 37 | signature = str(hmac.new( 38 | bytes(secret, 'utf-8'), 39 | bytes(_val, 'utf-8'), digestmod='sha256' 40 | ).hexdigest()) 41 | ws.send(json.dumps({"op": "auth", "args": [key, expires, signature]})) 42 | 43 | 44 | def on_pong(ws, *data): 45 | print('pong received') 46 | 47 | 48 | def on_ping(ws, *data): 49 | #now = datetime.now() 50 | #dt_string = now.strftime("%d/%m/%Y %H:%M:%S") 51 | #print("date and time =", dt_string) 52 | print('ping received') 53 | 54 | 55 | def on_open(ws): 56 | print('opened') 57 | send_auth(ws) 58 | print('send subscription ' + topic) 59 | ws.send(json.dumps({"op": "subscribe", "args": [topic]})) 60 | 61 | 62 | def connWS(): 63 | ws = websocket.WebSocketApp("wss://stream.bybit.com/realtime_private", 64 | on_message=on_message, 65 | on_error=on_error, 66 | on_close=on_close, 67 | on_ping=on_ping, 68 | on_pong=on_pong, 69 | on_open=on_open 70 | ) 71 | ws.run_forever( 72 | #http_proxy_host='127.0.0.1', 73 | #http_proxy_port=1087, 74 | ping_interval=30, 75 | ping_timeout=10 76 | ) 77 | 78 | 79 | if __name__ == "__main__": 80 | websocket.enableTrace(True) 81 | connWS() 82 | -------------------------------------------------------------------------------- /legacy_demo/wss_demo/python/ws_private_usdc.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import hmac 3 | import websocket 4 | from websocket import create_connection 5 | import threading 6 | import time 7 | import json 8 | import argparse 9 | import logging 10 | logging.basicConfig(filename='logfile_wrapper.log', level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s') 11 | from datetime import datetime 12 | 13 | def on_message(ws, message): 14 | print(json.loads(message)) 15 | 16 | def on_error(ws, error): 17 | print('we got error') 18 | print(error) 19 | 20 | def on_close(ws): 21 | print("### about to close please don't close ###") 22 | 23 | def send_auth(ws): 24 | key='xxxx' 25 | secret='xxxx' 26 | expires=int((time.time() +10) * 1000) 27 | _val = f'GET/realtime{expires}' 28 | print(_val) 29 | signature = str(hmac.new( 30 | bytes(secret, 'utf-8'), 31 | bytes(_val, 'utf-8'), digestmod='sha256' 32 | ).hexdigest()) 33 | ws.send(json.dumps({"op": "auth","args": [key, expires, signature]})) 34 | 35 | def on_pong(ws, *data): 36 | print('pong received') 37 | 38 | def on_ping(ws, *data): 39 | print('ping received') 40 | 41 | def on_open(ws): 42 | print('opened') 43 | send_auth(ws) 44 | ws.send(json.dumps({"op": "subscribe", "args": ["user.openapi.perp.position","user.openapi.perp.order","user.openapi.perp.trade","user.openapi.option.position","user.openapi.option.order","user.openapi.option.trade"]})) 45 | 46 | def connWS(): 47 | ws = websocket.WebSocketApp("wss://stream-testnet.bybit.com/trade/option/usdc/private/v1", 48 | on_message = on_message, 49 | on_error = on_error, 50 | on_close = on_close, 51 | on_ping = on_ping, 52 | on_pong = on_pong, 53 | on_open=on_open 54 | ) 55 | ws.run_forever( 56 | #http_proxy_host='127.0.0.1', 57 | #http_proxy_port=1087, 58 | ping_interval=15, 59 | ping_timeout=10 60 | ) 61 | 62 | if __name__ == "__main__": 63 | websocket.enableTrace(True) 64 | connWS() 65 | -------------------------------------------------------------------------------- /legacy_demo/wss_demo/python/ws_public_demo.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | import time 4 | from datetime import datetime 5 | 6 | import websocket 7 | 8 | logging.basicConfig(filename='logfile_wrapper.log', level=logging.DEBUG, 9 | format='%(asctime)s %(levelname)s %(message)s') 10 | 11 | #now = datetime.now() #dt_string = now.strftime("%d/%m/%Y %H:%M:%S") 12 | #print("date and time =", dt_string) 13 | prev_send_time = int(time.time() * 1000) 14 | topic = "orderBookL2_25.BTCUSD" 15 | 16 | trade_results = {} 17 | size = {} 18 | size_usdt = {} 19 | 20 | 21 | def on_message(ws, message): 22 | data = json.loads(message) 23 | print(data) 24 | 25 | 26 | def on_error(ws, error): 27 | print('we got error') 28 | print(error) 29 | print('print error complete') 30 | 31 | 32 | def on_close(ws): 33 | print("### about to close please don't close ###") 34 | 35 | 36 | def on_open(ws): 37 | print('opened') 38 | ws.send(json.dumps({"op": "subscribe", "args": [topic]})) 39 | 40 | 41 | def on_pong(ws, *data): 42 | print('pong received') 43 | 44 | 45 | def on_ping(ws, *data): 46 | now = datetime.now() 47 | dt_string = now.strftime("%d/%m/%Y %H:%M:%S") 48 | print("date and time =", dt_string) 49 | print('ping received') 50 | 51 | 52 | def connWS(): 53 | ws = websocket.WebSocketApp( 54 | "wss://stream.bybit.com/realtime", 55 | on_message=on_message, 56 | on_error=on_error, 57 | on_close=on_close, 58 | on_ping=on_ping, 59 | on_pong=on_pong, 60 | on_open=on_open 61 | ) 62 | ws.run_forever( 63 | #http_proxy_host='127.0.0.1', 64 | #http_proxy_port=1087, 65 | ping_interval=20, 66 | ping_timeout=10 67 | ) 68 | 69 | 70 | if __name__ == "__main__": 71 | websocket.enableTrace(True) 72 | connWS() 73 | --------------------------------------------------------------------------------