### Get Strategy Recommendations (Shell) Source: https://www.gate.com/docs/developers/apiv4/en/bot Fetches strategy recommendations using `curl` and shell commands. This example demonstrates how to construct the signature and make the authenticated GET request. ```Shell key="YOUR_API_KEY" secret="YOUR_API_SECRET" host="https://api.gateio.ws" prefix="/api/v4" method="GET" url="/bot/strategy/recommend" query_param="" body_param='' timestamp=$(date +%s) body_hash=$(printf "$body_param" | openssl sha512 | awk '{print $NF}') sign_string="$method\n$prefix$url\n$query_param\n$body_hash\n$timestamp" sign=$(printf "$sign_string" | openssl sha512 -hmac "$secret" | awk '{print $NF}') full_url="$host$prefix$url" curl -X $method $full_url \ -H "Timestamp: $timestamp" -H "KEY: $key" -H "SIGN: $sign" ``` -------------------------------- ### Python Quick Repayment Example Source: https://www.gate.com/docs/developers/apiv4/en/unified Demonstrates how to perform a quick repayment using Python. Ensure you have the `requests` library installed and implement the `gen_sign` function for authentication. ```Python # coding: utf-8 import requests import time import hashlib import hmac host = "https://api.gateio.ws" prefix = "/api/v4" headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} url = '/unified/quick_repayment' query_param = '' body='{"debt_currencies":["ETH"],"available_currencies":["USDT","BTC"]}' # for `gen_sign` implementation, refer to section `Authentication` above sign_headers = gen_sign('POST', prefix + url, query_param, body) headers.update(sign_headers) r = requests.request('POST', host + prefix + url, headers=headers, data=body) print(r.json()) ``` -------------------------------- ### Python Example for GET Order Source: https://www.gate.com/docs/developers/apiv4/en/crossex Demonstrates how to fetch order details using the Gate.io API with Python. This requires the `requests` library and a `gen_sign` function for authentication. ```Python # coding: utf-8 import requests import time import hashlib import hmac host = "https://api.gateio.ws" prefix = "/api/v4" headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} url = '/crossex/orders/2048522992198912' query_param = '' # for `gen_sign` implementation, refer to section `Authentication` above sign_headers = gen_sign('GET', prefix + url, query_param) headers.update(sign_headers) r = requests.request('GET', host + prefix + url, headers=headers) print(r.json()) ``` -------------------------------- ### Get Lending Information (cURL) Source: https://www.gate.com/docs/developers/apiv4/en/earnuni Demonstrates how to fetch lending information using cURL. This example requires you to replace placeholders with your actual API key, secret, and host. ```Shell key="YOUR_API_KEY" secret="YOUR_API_SECRET" host="https://api.gateio.ws" prefix="/api/v4" method="GET" url="/earn/uni/lends" query_param="" body_param='' timestamp=$(date +%s) body_hash=$(printf "$body_param" | openssl sha512 | awk '{print $NF}') sign_string="$method\n$prefix$url\n$query_param\n$body_hash\n$timestamp" sign=$(printf "$sign_string" | openssl sha512 -hmac "$secret" | awk '{print $NF}') full_url="$host$prefix$url" curl -X $method $full_url \ -H "Timestamp: $timestamp" -H "KEY: $key" -H "SIGN: $sign" ``` -------------------------------- ### Python Example for TradFi Transactions Source: https://www.gate.com/docs/developers/apiv4/en/tradfi This Python snippet shows how to make a GET request to retrieve tradfi transactions. Ensure you have the 'requests' library installed and your API credentials configured. ```python # coding: utf-8 import requests import time import hashlib import hmac host = "https://api.gateio.ws" prefix = "/api/v4" headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} url = '/tradfi/transactions' query_param = '' # for `gen_sign` implementation, refer to section `Authentication` above sign_headers = gen_sign('GET', prefix + url, query_param) headers.update(sign_headers) r = requests.request('GET', host + prefix + url, headers=headers) print(r.json()) ``` -------------------------------- ### Create a Spot Order using Go WebSocket Source: https://www.gate.com/docs/developers/apiv4/ws/en This Go example shows how to connect to the WebSocket, log in (implicitly required before placing orders), and then place a limit order. It includes the necessary struct definitions for API requests and order parameters. ```go package main import ( "crypto/hmac" "crypto/sha512" "crypto/tls" "encoding/hex" "encoding/json" "fmt" "github.com/gorilla/websocket" "net/url" "strconv" "time" ) // example WebSocket create order in go func main() { u := url.URL{Scheme: "ws", Host: "xxxx", Path: "xxx"} websocket.DefaultDialer.TLSClientConfig = &tls.Config{RootCAs: nil, InsecureSkipVerify: true} c, _, err := websocket.DefaultDialer.Dial(u.String(), nil) if err != nil { panic(err) } c.SetPingHandler(nil) // read msg go func() { for { _, message, err := c.ReadMessage() if err != nil { c.Close() panic(err) } fmt.Printf("recv: %s\n", message) } }() // warn: before order, you should login first, pls refer to the channel `spot.login`; // order_place orderParam := OrderParam{ Text: "t-123456", CurrencyPair: "ETH_BTC", Type: "limit", Account: "spot", Side: "buy", Iceberg: "0", Amount: "1", Price: "5.00032", TimeInForce: "gtc", AutoBorrow: false, StpAct: "cn", } paramBytes, _ := json.Marshal(orderParam) requestId := fmt.Sprintf("%d-%d", time.Now().UnixMilli(), 1) order_place := ApiRequest{ Time: time.Now().Unix(), Channel: "spot.order_place", Event: "api", Payload: ApiPayload{ RequestId: requestId, RequestParam: []byte(paramBytes), }, } orderPlaceReqByte, _ := json.Marshal(order_place) err = c.WriteMessage(websocket.TextMessage, orderPlaceReqByte) if err != nil { panic(err) } select {} } type ApiRequest struct { App string `json:"app,omitempty"` Time int64 `json:"time"` Id *int64 `json:"id,omitempty"` Channel string `json:"channel"` Event string `json:"event"` Payload ApiPayload `json:"payload"` } type ApiPayload struct { ApiKey string `json:"api_key,omitempty"` Signature string `json:"signature,omitempty"` Timestamp string `json:"timestamp,omitempty"` RequestId string `json:"req_id,omitempty"` RequestParam json.RawMessage `json:"req_param,omitempty"` } type OrderParam struct { Text string `json:"text,omitempty"` CurrencyPair string `json:"currency_pair,omitempty"` Type string `json:"type,omitempty"` Account string `json:"account,omitempty"` Side string `json:"side,omitempty"` Iceberg string `json:"iceberg,omitempty"` Amount string `json:"amount,omitempty"` Price string `json:"price,omitempty"` TimeInForce string `json:"time_in_force,omitempty"` AutoBorrow bool `json:"auto_borrow,omitempty"` StpAct string `json:"stp_act,omitempty"` } ``` -------------------------------- ### Subscribe to Spot Orders via WebSocket Source: https://www.gate.com/docs/developers/apiv4/ws/en This Go example demonstrates how to establish a WebSocket connection, subscribe to spot order updates, and receive messages. It includes authentication logic by referencing a `genSign` function. ```go package main import ( "encoding/json" "fmt" "log" "time" "github.com/gorilla/websocket" ) func main() { url := "wss://api.gateio.ws/ws/v4/" conn, _, err := websocket.DefaultDialer.Dial(url, nil) if err != nil { log.Fatal("dial error:", err) } defer conn.Close() timestamp := time.Now().Unix() request := map[string]interface{}{ "time": timestamp, "channel": "spot.orders_v2", "event": "subscribe", "payload": []string{"BTC_USDT"}, } // refer to Authentication section for gen_sign implementation request["auth"] = genSign(request["channel"].(string), request["event"].(string), timestamp) msg, err := json.Marshal(request) if err != nil { log.Fatal("json marshal error:", err) } err = conn.WriteMessage(websocket.TextMessage, msg) if err != nil { log.Fatal("write message error:", err) } _, message, err := conn.ReadMessage() if err != nil { log.Fatal("read message error:", err) } fmt.Println(string(message)) } ``` -------------------------------- ### Python Example for Futures API Request Source: https://www.gate.com/docs/developers/apiv4/en/futures This Python snippet demonstrates how to make a GET request to the Gate.io Futures API, including authentication headers generated by `gen_sign`. Ensure you have the `requests` library installed. ```python import requests import time import hashlib import hmac host = "https://api.gateio.ws" prefix = "/api/v4" headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} url = '/futures/usdt/price_orders/0' query_param = '' # for `gen_sign` implementation, refer to section `Authentication` above sign_headers = gen_sign('GET', prefix + url, query_param) headers.update(sign_headers) r = requests.request('GET', host + prefix + url, headers=headers) print(r.json()) ``` -------------------------------- ### Go WebSocket API Client Example Source: https://www.gate.com/docs/developers/apiv4/ws/en This Go program demonstrates how to generate an API signature for WebSocket authentication and construct a login request. It also shows how to establish a WebSocket connection and includes placeholders for API keys, secrets, and server details. The example focuses on the initial connection and authentication steps. ```go package main import ( "crypto/hmac" "crypto/sha512" "crypto/tls" "encoding/hex" "encoding/json" "fmt" "net/url" "strconv" "time" "github.com/gorilla/websocket" ) func GetApiSignature(secret, channel string, requestParam []byte, ts int64) string { hash := hmac.New(sha512.New, []byte(secret)) key := fmt.Sprintf("%s\n%s\n%s\n%d", "api", channel, string(requestParam), ts) hash.Write([]byte(key)) return hex.EncodeToString(hash.Sum(nil)) } func main() { // 1. login apiKey := "xxxxx" secret := "xxxxx" requestParam := "" channel := "spot.login" ts := time.Now().Unix() requestId := fmt.Sprintf("%d-%d", time.Now().UnixMilli(), 1) req := ApiRequest{ Time: ts, Channel: "spot.login", Event: "api", Payload: ApiPayload{ ApiKey: apiKey, Signature: GetApiSignature(secret, channel, []byte(requestParam), ts), Timestamp: strconv.FormatInt(ts, 10), RequestId: requestId, RequestParam: []byte(requestParam), }, } fmt.Println(GetApiSignature(secret, channel, []byte(requestParam), ts)) marshal, _ := json.Marshal(req) fmt.Println(string(marshal)) // connect the ws u := url.URL{Scheme: "ws", Host: "xx.xx.xxx.xx:xxx", Path: "xxx"} websocket.DefaultDialer.TLSClientConfig = &tls.Config{RootCAs: nil, InsecureSkipVerify: true} c, _, err := websocket.DefaultDialer.Dial(u.String(), nil) if err != nil { panic(err) } c.SetPingHandler(nil) // read msg ``` -------------------------------- ### Python Authentication and Repayment Setup Source: https://www.gate.com/docs/developers/apiv4/en/multi-collateral-loan Sets up authentication headers and base URL for API requests in Python. Includes parameters for loan repayment. ```Python # coding: utf-8 import requests import time import hashlib import hmac host = "https://api.gateio.ws" prefix = "/api/v4" headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} url = '/loan/multi_collateral/repay' query_param = 'type=repay' ``` -------------------------------- ### Python: Authenticate and Make GET Request Source: https://www.gate.com/docs/developers/apiv4/en/futures This snippet demonstrates how to authenticate a GET request using a generated signature and send it to the Gate.io API. Ensure you have the 'requests' library installed. ```python import requests # Assume gen_sign is defined elsewhere and handles signature generation # sign_headers = gen_sign('GET', prefix + url, query_param) # Placeholder for demonstration purposes sign_headers = { "X-Signature": "YOUR_GENERATED_SIGNATURE" } host = "https://api.gateio.ws" prefix = "/api/v4" url = "/futures/usdt/autoorder/v1/trail/list" headers = { "Accept": "application/json", "Content-Type": "application/json", **sign_headers } r = requests.request('GET', host + prefix + url, headers=headers) print(r.json()) ``` -------------------------------- ### List Orders Request Example Source: https://www.gate.com/docs/developers/apiv4/en Example of an HTTP GET request to list orders. The signature string includes the method, URL, query string, hashed empty body, and timestamp. ```http GET /api/v4/futures/orders?contract=BTC_USD&status=finished&limit=50 HTTP/1.1 ``` ```text GET /api/v4/futures/orders contract=BTC_USD&status=finished&limit=50 cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e 1541993715 ``` -------------------------------- ### Subscribe to Spot Cross Loan Updates (Go) Source: https://www.gate.com/docs/developers/apiv4/ws/en This Go example demonstrates how to subscribe to spot cross loan updates via WebSocket. It requires the 'gorilla/websocket' library. Refer to the Authentication section for the 'genSign' function. ```go package main import ( "encoding/json" "fmt" "log" "time" "github.com/gorilla/websocket" ) func main() { url := "wss://api.gateio.ws/ws/v4/" conn, _, err := websocket.DefaultDialer.Dial(url, nil) if err != nil { log.Fatal("dial error:", err) } defer conn.Close() timestamp := time.Now().Unix() request := map[string]interface{}{ "time": timestamp, "channel": "spot.cross_loan", "event": "subscribe", } // refer to Authentication section for gen_sign implementation request["auth"] = genSign(request["channel"].(string), request["event"].(string), timestamp) msg, err := json.Marshal(request) if err != nil { log.Fatal("json marshal error:", err) } err = conn.WriteMessage(websocket.TextMessage, msg) if err != nil { log.Fatal("write message error:", err) } _, message, err := conn.ReadMessage() if err != nil { log.Fatal("read message error:", err) } fmt.Println(string(message)) } ``` -------------------------------- ### Get Sub-Account Cross Margin Balances (Shell) Source: https://www.gate.com/docs/developers/apiv4/en/wallet Retrieve cross margin balances for sub-accounts using cURL. This example demonstrates how to construct the signature and make the authenticated GET request. ```Shell key="YOUR_API_KEY" secret="YOUR_API_SECRET" host="https://api.gateio.ws" prefix="/api/v4" method="GET" url="/wallet/sub_account_cross_margin_balances" query_param='' body_param='' timestamp=$(date +%s) body_hash=$(printf "$body_param" | openssl sha512 | awk '{print $NF}') sign_string="$method\n$prefix$url\n$query_param\n$body_hash\n$timestamp" sign=$(printf "$sign_string" | openssl sha512 -hmac "$secret" | awk '{print $NF}') full_url="$host$prefix$url" curl -X $method $full_url \ -H "Timestamp: $timestamp" -H "KEY: $key" -H "SIGN: $sign" ``` -------------------------------- ### Get Options Contract Details Source: https://www.gate.com/docs/developers/apiv4/en/options Retrieve detailed information about a specific options contract. This snippet uses Python's requests library to make a GET request to the API. Ensure you have the 'requests' library installed. ```python # coding: utf-8 import requests host = "https://api.gateio.ws" prefix = "/api/v4" headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} url = '/options/contracts/BTC_USDT-20211130-65000-C' query_param = '' r = requests.request('GET', host + prefix + url, headers=headers) print(r.json()) ``` -------------------------------- ### Go WebSocket Client with Authentication Source: https://www.gate.com/docs/developers/apiv4/ws/en This Go example demonstrates how to establish a WebSocket connection to Gate.io, send authenticated messages, and subscribe to channels. It includes message signing and handling incoming messages in a separate goroutine. ```go package main import ( "crypto/hmac" "crypto/sha512" "crypto/tls" "encoding/hex" "encoding/json" "fmt" "io" "net/url" "time" "github.com/gorilla/websocket" ) type Msg struct { Time int64 `json:"time"` Channel string `json:"channel"` Event string `json:"event"` Payload []string `json:"payload"` Auth *Auth `json:"auth"` } type Auth struct { Method string `json:"method"` KEY string `json:"KEY"` SIGN string `json:"SIGN"` } const ( Key = "YOUR_API_KEY" Secret = "YOUR_API_SECRETY" ) func sign(channel, event string, t int64) string { message := fmt.Sprintf("channel=%s&event=%s&time=%d", channel, event, t) h2 := hmac.New(sha512.New, []byte(Secret)) io.WriteString(h2, message) return hex.EncodeToString(h2.Sum(nil)) } func (msg *Msg) sign() { signStr := sign(msg.Channel, msg.Event, msg.Time) msg.Auth = &Auth{ Method: "api_key", KEY: Key, SIGN: signStr, } } func (msg *Msg) send(c *websocket.Conn) error { msgByte, err := json.Marshal(msg) if err != nil { return err } return c.WriteMessage(websocket.TextMessage, msgByte) } func NewMsg(channel, event string, t int64, payload []string) *Msg { return &Msg{ Time: t, Channel: channel, Event: event, Payload: payload, } } func main() { u := url.URL{Scheme: "wss", Host: "api.gateio.ws", Path: "/ws/v4/"} websocket.DefaultDialer.TLSClientConfig = &tls.Config{RootCAs: nil, InsecureSkipVerify: true} c, _, err := websocket.DefaultDialer.Dial(u.String(), nil) if err != nil { panic(err) } c.SetPingHandler(nil) // read msg go func() { for { _, message, err := c.ReadMessage() if err != nil { c.Close() panic(err) } fmt.Printf("recv: %s\n", message) } }() t := time.Now().Unix() pingMsg := NewMsg("spot.ping", "", t, []string{}) err = pingMsg.send(c) if err != nil { panic(err) } // subscribe order book orderBookMsg := NewMsg("spot.order_book", "subscribe", t, []string{"BTC_USDT", "5", "100ms"}) err = orderBookMsg.send(c) if err != nil { panic(err) } // subscribe positions ordersMsg := NewMsg("spot.orders", "subscribe", t, []string{"BTC_USDT"}) ordersMsg.sign() err = ordersMsg.send(c) if err != nil { ``` -------------------------------- ### Get Delivery Candlesticks (Python) Source: https://www.gate.com/docs/developers/apiv4/en/delivery Fetches candlestick data for a specific delivery contract. Ensure you have the 'requests' library installed. ```Python # coding: utf-8 import requests host = "https://api.gateio.ws" prefix = "/api/v4" headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} url = '/delivery/usdt/candlesticks' query_param = 'contract=BTC_USDT_20200814' r = requests.request('GET', host + prefix + url + "?" + query_param, headers=headers) print(r.json()) ``` -------------------------------- ### Subscribe to Funding Balances (Go) Source: https://www.gate.com/docs/developers/apiv4/ws/en This Go code example demonstrates subscribing to funding balance updates via WebSocket. It uses the Gorilla WebSocket library and requires authentication. Refer to the Authentication section for genSign implementation. ```go package main import ( "encoding/json" "fmt" "log" "time" "github.com/gorilla/websocket" ) func main() { url := "wss://api.gateio.ws/ws/v4/" conn, _, err := websocket.DefaultDialer.Dial(url, nil) if err != nil { log.Fatal("dial error:", err) } defer conn.Close() timestamp := time.Now().Unix() request := map[string]interface{}{ "time": timestamp, "channel": "spot.funding_balances", "event": "subscribe", } // refer to Authentication section for gen_sign implementation request["auth"] = genSign(request["channel"].(string), request["event"].(string), timestamp) msg, err := json.Marshal(request) if err != nil { log.Fatal("json marshal error:", err) } err = conn.WriteMessage(websocket.TextMessage, msg) if err != nil { log.Fatal("write message error:", err) } _, message, err := conn.ReadMessage() if err != nil { log.Fatal("read message error:", err) } fmt.Println(string(message)) } Copy ``` -------------------------------- ### Shell Quick Repayment Example Source: https://www.gate.com/docs/developers/apiv4/en/unified Provides a command-line example using `curl` to perform a quick repayment. This snippet includes generating the necessary signature for authentication. ```Shell key="YOUR_API_KEY" secret="YOUR_API_SECRET" host="https://api.gateio.ws" prefix="/api/v4" method="POST" url="/unified/quick_repayment" query_param="" body_param='{"debt_currencies":["ETH"],"available_currencies":["USDT","BTC"]}' timestamp=$(date +%s) body_hash=$(printf "$body_param" | openssl sha512 | awk '{print $NF}') sign_string="$method\n$prefix$url\n$query_param\n$body_hash\n$timestamp" sign=$(printf "$sign_string" | openssl sha512 -hmac "$secret" | awk '{print $NF}') full_url="$host$prefix$url" curl -X $method $full_url -d "$body_param" -H "Content-Type: application/json" \ -H "Timestamp: $timestamp" -H "KEY: $key" -H "SIGN: $sign" ``` -------------------------------- ### Get MMP Settings (Example) Source: https://www.gate.com/docs/developers/apiv4/en/options This snippet demonstrates how to retrieve current MMP settings. It requires authentication with API key and secret. ```python import requests import time import hashlib import hmac host = "https://api.gateio.ws" prefix = "/api/v4" headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} url = '/options/mmp' query_param = '' # for `gen_sign` implementation, refer to section `Authentication` above sign_headers = gen_sign('GET', prefix + url, query_param) headers.update(sign_headers) r = requests.request('GET', host + prefix + url, headers=headers) print(r.json()) ``` -------------------------------- ### Pagination Example: Limit-Offset Method Source: https://www.gate.com/docs/developers/apiv4/en Illustrates the use of the limit-offset method for pagination, starting with an offset of 0 and a limit of 100 records. ```text limit=100&offset=0 limit=100&offset=100 limit=100&offset=200 ``` -------------------------------- ### Subscribe to Margin Balances (Go) Source: https://www.gate.com/docs/developers/apiv4/ws/en This Go example demonstrates how to subscribe to margin balance updates using the Gorilla WebSocket library. It includes JSON marshaling and authentication. Refer to the Authentication section for genSign implementation. ```go package main import ( "encoding/json" "fmt" "log" "time" "github.com/gorilla/websocket" ) func main() { url := "wss://api.gateio.ws/ws/v4/" conn, _, err := websocket.DefaultDialer.Dial(url, nil) if err != nil { log.Fatal("dial error:", err) } defer conn.Close() timestamp := time.Now().Unix() request := map[string]interface{}{ "time": timestamp, "channel": "spot.margin_balances", "event": "subscribe", } // refer to Authentication section for gen_sign implementation request["auth"] = genSign(request["channel"].(string), request["event"].(string), timestamp) msg, err := json.Marshal(request) if err != nil { log.Fatal("json marshal error:", err) } err = conn.WriteMessage(websocket.TextMessage, msg) if err != nil { log.Fatal("write message error:", err) } _, message, err := conn.ReadMessage() if err != nil { log.Fatal("read message error:", err) } fmt.Println(string(message)) } Copy ``` -------------------------------- ### Get All Spot Currency Pairs (cURL) Source: https://www.gate.com/docs/developers/apiv4/en/spot A command-line interface example for fetching all spot currency pairs. This can be used for quick checks or scripting. ```cURL curl -X GET https://api.gateio.ws/api/v4/spot/currency_pairs \ -H 'Accept: application/json' ``` -------------------------------- ### Go Example Source: https://www.gate.com/docs/developers/apiv4/en/earn Example of how to interact with the Earn API using Go. ```Go package main import ( "fmt" "io/ioutil" "net/http" ) func main() { client := &http.Client{} req, err := http.NewRequest("GET", "https://api.example.com/v4/earn", nil) if err != nil { fmt.Println(err) return } req.Header.Add("X-API-KEY", "YOUR_API_KEY") req.Header.Add("X-API-SECRET", "YOUR_API_SECRET") resp, err := client.Do(req) if err != nil { fmt.Println(err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) return } fmt.Println(string(body)) } ``` -------------------------------- ### Get Dual Investment Product List (Python) Source: https://www.gate.com/docs/developers/apiv4/en/earn Fetches a list of available Dual Investment products. Ensure the 'requests' library is installed. ```Python # coding: utf-8 import requests host = "https://api.gateio.ws" prefix = "/api/v4" headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} url = '/earn/dual/investment_plan' query_param = '' r = requests.request('GET', host + prefix + url, headers=headers) print(r.json()) ``` -------------------------------- ### Example 200 Response for User Currency Leverage Settings Source: https://www.gate.com/docs/developers/apiv4/en/unified Shows a successful response for retrieving user currency leverage settings, including currency and its associated leverage multiplier. ```JSON [ { "currency": "BTC", "leverage": "3" } ] ``` -------------------------------- ### Get All Options Positions (Shell) Source: https://www.gate.com/docs/developers/apiv4/en/options Retrieves all current options positions using cURL. This example demonstrates how to generate the necessary signature and headers for authentication. ```shell key="YOUR_API_KEY" secret="YOUR_API_SECRET" host="https://api.gateio.ws" prefix="/api/v4" method="GET" url="/options/positions" query_param="" body_param='' timestamp=$(date +%s) body_hash=$(printf "$body_param" | openssl sha512 | awk '{print $NF}') sign_string="$method\n$prefix$url\n$query_param\n$body_hash\n$timestamp" sign=$(printf "$sign_string" | openssl sha512 -hmac "$secret" | awk '{print $NF}') full_url="$host$prefix$url" curl -X $method $full_url \ -H "Timestamp: $timestamp" -H "KEY: $key" -H "SIGN: $sign" ``` -------------------------------- ### Subscribe to Spot Trades (Go) Source: https://www.gate.com/docs/developers/apiv4/ws/en Establish a WebSocket connection to Gate.io and subscribe to trade updates. This example uses the 'gorilla/websocket' library for Go. ```go package main import ( "encoding/json" "fmt" "log" "time" "github.com/gorilla/websocket" ) func main() { url := "wss://api.gateio.ws/ws/v4/" conn, _, err := websocket.DefaultDialer.Dial(url, nil) if err != nil { log.Fatal("dial error:", err) } defer conn.Close() subscribe := map[string]interface{}{ "time": time.Now().Unix(), "channel": "spot.trades_v2", "event": "subscribe", "payload": []string{"BTC_USDT"}, } msg, err := json.Marshal(subscribe) if err != nil { log.Fatal("json marshal error:", err) } err = conn.WriteMessage(websocket.TextMessage, msg) if err != nil { log.Fatal("write message error:", err) } _, message, err := conn.ReadMessage() if err != nil { log.Fatal("read message error:", err) } fmt.Println(string(message)) } ``` -------------------------------- ### Get My Options Settlements (Shell) Source: https://www.gate.com/docs/developers/apiv4/en/options Retrieve settlement information for your options trades using curl. This example demonstrates generating the necessary signature for authentication. ```Shell key="YOUR_API_KEY" secret="YOUR_API_SECRET" host="https://api.gateio.ws" prefix="/api/v4" method="GET" url="/options/my_settlements" query_param="underlying=BTC_USDT" body_param='' timestamp=$(date +%s) body_hash=$(printf "$body_param" | openssl sha512 | awk '{print $NF}') sign_string="$method\n$prefix$url\n$query_param\n$body_hash\n$timestamp" sign=$(printf "$sign_string" | openssl sha512 -hmac "$secret" | awk '{print $NF}') full_url="$host$prefix$url?$query_param" curl -X $method $full_url \ -H "Timestamp: $timestamp" -H "KEY: $key" -H "SIGN: $sign" ``` -------------------------------- ### Example 200 Response for User Currency Leverage Configuration Source: https://www.gate.com/docs/developers/apiv4/en/unified Illustrates a successful response when querying user currency leverage configuration. ```JSON { "current_leverage": "2", "min_leverage": "0", "max_leverage": "0", "debit": "0", "available_margin": "0", "borrowable": "0", "except_leverage_borrowable": "0" } ``` -------------------------------- ### Python Example for TradFi API Request Source: https://www.gate.com/docs/developers/apiv4/en/tradfi This Python snippet shows how to make a GET request to the TradFi positions endpoint, including authentication headers. ```python # coding: utf-8 import requests import time import hashlib import hmac host = "https://api.gateio.ws" prefix = "/api/v4" headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} url = '/tradfi/positions' query_param = '' body='{"price_tp":"1","price_sl":"1"}' sign_string = hmac.new(secret.encode('utf-8'), (method+prefix+url+query_param+body).encode('utf-8'), hashlib.sha512).hexdigest() request_url = host + prefix + url sign_headers = { "KEY": key, "SIGN": sign_string, "Timestamp": str(timestamp), } headers.update(sign_headers) r = requests.request(method, request_url, headers=headers, params=query_param if query_param else None, data=body if body else None) print(r.json()) ``` -------------------------------- ### Get Risk Units (Python) Source: https://www.gate.com/docs/developers/apiv4/en/unified Retrieves the risk units for the unified account. Ensure you have the 'requests' library installed and implement the 'gen_sign' function for authentication. ```Python # coding: utf-8 import requests import time import hashlib import hmac host = "https://api.gateio.ws" prefix = "/api/v4" headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} url = '/unified/risk_units' query_param = '' # for `gen_sign` implementation, refer to section `Authentication` above sign_headers = gen_sign('GET', prefix + url, query_param) headers.update(sign_headers) r = requests.request('GET', host + prefix + url, headers=headers) print(r.json()) Copy ``` -------------------------------- ### Order Status Request Setup Source: https://www.gate.com/docs/developers/apiv4/ws/en This Python code snippet demonstrates how to set up a WebSocket connection and prepare parameters for querying order status. Ensure you have the `websocket_client` library installed. Login is required before making requests. ```python #!/usr/bin/python import time import json # pip install websocket_client from websocket import create_connection time = int(time.time()) statusParam = {"order_id":"1694883366","currency_pair":"GT_USDT"} channel = "spot.order_status" ws = create_connection("wss://api.gateio.ws/ws/v4/") ``` -------------------------------- ### Python: Get Margin Positions Source: https://www.gate.com/docs/developers/apiv4/en/crossex Retrieves current cross-exchange margin positions. Ensure you have the `requests` library installed and the `gen_sign` function implemented for authentication. ```Python # coding: utf-8 import requests import time import hashlib import hmac host = "https://api.gateio.ws" prefix = "/api/v4" headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} url = '/crossex/margin_positions' query_param = '' # for `gen_sign` implementation, refer to section `Authentication` above sign_headers = gen_sign('GET', prefix + url, query_param) headers.update(sign_headers) r = requests.request('GET', host + prefix + url, headers=headers) print(r.json()) ``` -------------------------------- ### Java Example Source: https://www.gate.com/docs/developers/apiv4/en/earn Example of how to interact with the Earn API using Java (Apache HttpClient). ```Java import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class EarnApiExample { public static void main(String[] args) throws Exception { CloseableHttpClient client = HttpClients.createDefault(); HttpGet request = new HttpGet("https://api.example.com/v4/earn"); request.addHeader("X-API-KEY", "YOUR_API_KEY"); request.addHeader("X-API-SECRET", "YOUR_API_SECRET"); try (CloseableHttpResponse response = client.execute(request)) { System.out.println(response.getStatusLine()); String responseBody = EntityUtils.toString(response.getEntity()); System.out.println(responseBody); } client.close(); } } ``` -------------------------------- ### Subscribe to Order Book Data in Go Source: https://www.gate.com/docs/developers/apiv4/ws/en This Go example demonstrates how to establish a WebSocket connection and subscribe to order book data. It uses the 'gorilla/websocket' library. ```go package main import ( "encoding/json" "fmt" "log" "time" "github.com/gorilla/websocket" ) func main() { url := "wss://api.gateio.ws/ws/v4/" conn, _, err := websocket.DefaultDialer.Dial(url, nil) if err != nil { log.Fatal("dial error:", err) } defer conn.Close() subscribe := map[string]interface{}{ "time": time.Now().Unix(), "channel": "spot.order_book", "event": "subscribe", "payload": []string{"BTC_USDT", "5", "100ms"}, } msg, err := json.Marshal(subscribe) if err != nil { log.Fatal("json marshal error:", err) } err = conn.WriteMessage(websocket.TextMessage, msg) if err != nil { log.Fatal("write message error:", err) } _, message, err := conn.ReadMessage() if err != nil { log.Fatal("read message error:", err) } fmt.Println(string(message)) ``` -------------------------------- ### Pagination Example: Page-Limit Method Source: https://www.gate.com/docs/developers/apiv4/en Demonstrates how to use the page-limit method for paginating through a list of orders, starting with page 1 and a limit of 100 records. ```text page=1&limit=100 page=2&limit=100 page=3&limit=100 ``` -------------------------------- ### Get Chase Order Detail (Shell) Source: https://www.gate.com/docs/developers/apiv4/en/futures Retrieves the details of a specific chase order using cURL. This example demonstrates generating the necessary signature for authentication. ```Shell key="YOUR_API_KEY" secret="YOUR_API_SECRET" host="https://api.gateio.ws" prefix="/api/v4" method="GET" url="/futures/usdt/autoorder/v1/chase/detail" query_param="id=string" body_param='' timestamp=$(date +%s) body_hash=$(printf "$body_param" | openssl sha512 | awk '{print $NF}') sign_string="$method\n$prefix$url\n$query_param\n$body_hash\n$timestamp" sign=$(printf "$sign_string" | openssl sha512 -hmac "$secret" | awk '{print $NF}') full_url="$host$prefix$url?$query_param" curl -X $method $full_url \ -H "Timestamp: $timestamp" -H "KEY: $key" -H "SIGN: $sign" ``` -------------------------------- ### Client Subscribe Request Example Source: https://www.gate.com/docs/developers/apiv4/ws/en Example of a client request to subscribe to the 'spot.orders' channel. Includes authentication details for private channels. ```json { "time": 1611541000, "id": 123456789, "channel": "spot.orders", "event": "subscribe", "payload": ["BTC_USDT", "GT_USDT"], "auth": { "method": "api_key", "KEY": "xxxx", "SIGN": "xxxx" } } ``` -------------------------------- ### Example Response for Unified Account Mode Source: https://www.gate.com/docs/developers/apiv4/en/unified An example of a successful response when querying the unified account mode, indicating the 'portfolio' mode and enabled settings like 'spot_hedge'. ```JSON { "mode": "portfolio", "settings": { "spot_hedge": true, "usdt_futures": true, "options": true } } Copy ``` -------------------------------- ### Go Example for Futures Order Details Source: https://www.gate.com/docs/developers/apiv4/en/delivery This snippet shows how to get futures order details using Go. Authentication with API key and secret is required. ```Go package main import ( "fmt" "os" "github.com/gateio/gateapi-go/v4" ) func main() { // Please initialize your api client with your credentials. // ApiKey := "YOUR_API_KEY" // ApiSecret := "YOUR_API_SECRET" client := gateapi.NewAPIClient(gateapi.NewConfiguration()) // Get futures order details resp, _, err := client.FuturesApi.ListFuturesOrders(ctx).Limit(10).Page(1).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `FuturesApi.ListFuturesOrders`:`v%+v`\n", err) } fmt.Printf("%+v\n", resp) } ``` -------------------------------- ### Get MMP Settings (Shell Example) Source: https://www.gate.com/docs/developers/apiv4/en/options This shell command shows how to fetch MMP settings using curl. Ensure you have your API key and secret configured. ```shell key="YOUR_API_KEY" secret="YOUR_API_SECRET" host="https://api.gateio.ws" prefix="/api/v4" method="GET" url="/options/mmp" query_param="" body_param='' timestamp=$(date +%s) body_hash=$(printf "$body_param" | openssl sha512 | awk '{print $NF}') sign_string="$method $prefix$url $query_param $body_hash $timestamp" sign=$(printf "$sign_string" | openssl sha512 -hmac "$secret" | awk '{print $NF}') full_url="$host$prefix$url" curl -X $method $full_url \ -H "Timestamp: $timestamp" -H "KEY: $key" -H "SIGN: $sign" ``` -------------------------------- ### Example Response: Product List with Different Asset Source: https://www.gate.com/docs/developers/apiv4/en/earn Illustrates a successful response for a product list, featuring a different asset (ATOM) and its associated details, including lock-up period and annual rate. ```JSON { "code": 0, "message": "", "data": { "list": [ { "id": 29, "asset": "ATOM", "lock_up_period": 7, "year_rate": "0.04", "sale_status": 1 } ] }, "timestamp": 1737944009 } ``` -------------------------------- ### Subscribe to Book Ticker Channel (Go) Source: https://www.gate.com/docs/developers/apiv4/ws/en This Go code example shows how to subscribe to the 'spot.book_ticker' channel for a given currency pair. It uses the gorilla/websocket library for WebSocket communication. ```go package main import ( "encoding/json" "fmt" "log" "time" "github.com/gorilla/websocket" ) func main() { url := "wss://api.gateio.ws/ws/v4/" conn, _, err := websocket.DefaultDialer.Dial(url, nil) if err != nil { log.Fatal("dial error:", err) } defer conn.Close() subscribe := map[string]interface{}{ "time": time.Now().Unix(), "channel": "spot.book_ticker", "event": "subscribe", "payload": []string{"BTC_USDT"}, } msg, err := json.Marshal(subscribe) if err != nil { log.Fatal("json marshal error:", err) } err = conn.WriteMessage(websocket.TextMessage, msg) if err != nil { log.Fatal("write message error:", err) } _, message, err := conn.ReadMessage() if err != nil { log.Fatal("read message error:", err) } fmt.Println(string(message)) } ``` -------------------------------- ### Subscribe to User Trades Channel in Go Source: https://www.gate.com/docs/developers/apiv4/ws/en This Go code example shows how to subscribe to the 'spot.usertrades' channel using the gorilla/websocket library. It includes JSON marshaling for the request and basic error handling. Implement the genSign function for authentication. ```go package main import ( "encoding/json" "fmt" "log" "time" "github.com/gorilla/websocket" ) func main() { url := "wss://api.gateio.ws/ws/v4/" conn, _, err := websocket.DefaultDialer.Dial(url, nil) if err != nil { log.Fatal("dial error:", err) } defer conn.Close() timestamp := time.Now().Unix() request := map[string]interface{}{ "time": timestamp, "channel": "spot.usertrades", "event": "subscribe", "payload": []string{"BTC_USDT"}, } // refer to Authentication section for gen_sign implementation request["auth"] = genSign(request["channel"].(string), request["event"].(string), timestamp) msg, err := json.Marshal(request) if err != nil { log.Fatal("json marshal error:", err) } err = conn.WriteMessage(websocket.TextMessage, msg) if err != nil { log.Fatal("write message error:", err) } _, message, err := conn.ReadMessage() if err != nil { log.Fatal("read message error:", err) } fmt.Println(string(message)) } ``` -------------------------------- ### Example Response for Get Flash Swap Orders Source: https://www.gate.com/docs/developers/apiv4/en/flash-swap A successful response (200 OK) for retrieving flash swap orders, showing the structure of a single order. ```JSON [ { "id": 54646, "create_time": 1651116876378, "update_time": 1651116876378, "user_id": 11135567, "sell_currency": "BTC", "sell_amount": "0.01", "buy_currency": "USDT", "buy_amount": "10", "price": "100", "status": 1 } ] ``` -------------------------------- ### Get USDT Futures Risk Limit Tiers (Python) Source: https://www.gate.com/docs/developers/apiv4/en/futures Retrieves the risk limit tiers for USDT perpetual futures. Ensure the 'requests' library is installed. ```python # coding: utf-8 import requests host = "https://api.gateio.ws" prefix = "/api/v4" headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} url = '/futures/usdt/risk_limit_tiers' query_param = '' r = requests.request('GET', host + prefix + url, headers=headers) print(r.json()) ``` -------------------------------- ### Subscribe to Spot Trades in Go Source: https://www.gate.com/docs/developers/apiv4/ws/en This Go program demonstrates how to connect to the Gate.io WebSocket API, subscribe to spot trades, and print the initial response. It uses the 'gorilla/websocket' library. ```go package main import ( "encoding/json" "fmt" "log" "time" "github.com/gorilla/websocket" ) func main() { url := "wss://api.gateio.ws/ws/v4/" conn, _, err := websocket.DefaultDialer.Dial(url, nil) if err != nil { log.Fatal("dial error:", err) } defer conn.Close() subscribe := map[string]interface{}{ "time": time.Now().Unix(), "channel": "spot.trades", "event": "subscribe", "payload": []string{"BTC_USDT"}, } msg, err := json.Marshal(subscribe) if err != nil { log.Fatal("json marshal error:", err) } err = conn.WriteMessage(websocket.TextMessage, msg) if err != nil { log.Fatal("write message error:", err) } _, message, err := conn.ReadMessage() if err != nil { log.Fatal("read message error:", err) } fmt.Println(string(message)) } ```