简体中文
NAV
go python

Change Log

2023-09-27

2023-05-04

2022-10-28

2022-09-27

2022-08-27

2022-05-27

2022-04-13



Introduction

Welcome to the DeGate SDK documentation. This document is a guide to help traders access the services offered by DeGate protocol via SDK in both Python and Go.

What is an Asset Private Key

After a user has registered for a DeGate account, the Asset Private Key is generated from the wallet's private key signature and it is used to authorize activities such as order placement, order cancellation, on-chain order cancellation, etc without exposing the wallet private key to third parties. The Asset Private Key will be stored only within the browser's LocalStorage and will be deleted each time the browser is closed. The trading Key is regenerated each time the user logs into DeGate. Users can also reset their asset private key via Security - Reset Asset Private Key.

How to Export the Asset Private Key

Users can export the Asset Private Key through Security - View Asset Private Key and use it to call DeGate API. The Asset Private Key can be manually copied from the pop-up JSON text under the privateKey field. image Please be vigilant to keep the Asset Private Key secure to avoid any risk of losing assets. Even if a hacker managed to get hold of the user's Asset Private Key, the hacker is unable to withdraw assets to other addresses. However, there are other ways for the hacker to transfer assets through trading means.

Asset Private Key Permissions

The Asset Private Key has the ability to place orders, cancel orders, and perform on-chain cancellation.

The Asset Private Key does not have the ability to register for a DeGate account, perform withdrawals, perform transfer, reset the Asset Private Key, and export the Asset Private Key.

SDK Library & How to use AssetPrivateKey

Quick Start:

{
import (
    "encoding/json"
    "github.com/degatedev/degate-sdk-golang/conf"
    "github.com/degatedev/degate-sdk-golang/degate/spot"
    "github.com/degatedev/degate-sdk-golang/log"
)
client := &spot.Client{}
var appConfig = &conf.AppConfig{}
client.SetAppConfig(appConfig)
response,err := client.Time()
if err != nil {
    log.Error("error: %v",err)
} else if !response.Success() {
    log.Error("fail: %v",response.Code)
} else {
    log.Info("success: %v",response.Data.ServerTime)
}
client = &spot.Client{}
// AccountAddress、AssetPrivateKey、AccountId are required for user data endpoints
var appConfig = &conf.AppConfig{
    AccountId: <accountId>,
    AccountAddress: <accountAddress>,
    AssetPrivateKey:<DeGate AssetPrivateKey>,
}
client.SetAppConfig(appConfig)
// Get account and balance information
response,err := client.Account()
if err != nil {
    log.Error("error: %v",err)
} else if !response.Success() {
    log.Error("fail: %v",response.Code)
} else {
    account,_ := json.Marshal(response.Data)
    log.Info("success: %v",string(account))
}
}
from degate.spot import Spot as Client

ETH = {
    "id": 0,
    "symbol": "ETH",
}
USDC = {
    "id": 8,
    "symbol": "USDC",
}
client = Client(tokens=[ETH,USDC])
# Get server timestamp
print(client.time())
# AccountAddress、AssetPrivateKey、AccountId are required for user data endpoints
client = Client(accountAddress='<account_address>',assetPrivateKey='<DeGate AssetPrivateKey>',accountId='<account_id>',tokens=[ETH,USDC])
# Get account and balance information
print(client.account())

Go connector

This is a lightweight library that works as a connector to DeGate public API, written in Go.
The Go-based DeGate SDK can be used by configuring the accountId, accountAddress, and AssetPrivateKey in appconfig according to the code example. Once configured, you can place orders, cancel orders, and perform on-chain cancellation. according to the code examples.


Click on the link below to view the detailed use cases and the installation steps.

https://github.com/degatedev/degate-sdk-golang

Python connector

This is a lightweight library that works as a connector to DeGate public API, written in Python.
The Python-based DeGate SDK can be used by configuring the accountId, accountAddress, and AssetPrivateKey in the Client according to the code example. Once configured, you can place orders, cancel orders, and perform on-chain cancellation. according to the code examples.


Click on the link below to view the detailed use cases and the installation steps.

https://github.com/degatedev/degate-sdk-python

General Info

General API Information

Change baseurl to visit other environments:

var appConfig = &conf.AppConfig{
    BaseUrl:"https://v1-mainnet-backend.degate.com/",
}
from degate.spot import Spot as Client

client = Client(baseUrl='https://v1-mainnet-backend.degate.com/')
print(client.time())

HTTP Return Codes

{
  "code": -1121,
  "msg": "Invalid symbol."
}

Error Codes and Messages

LIMITS

General Info on Limits


IP Limits


Weight
Each interface has a corresponding Weight. The more resource-consuming the interface is, the greater the weight will be. If weight is used within a given time range, and 429 is returned, this implies that the weight has been fully utilized in the time range. The user is required to wait for the weight quota to be replenished before making the next request. Query ExchangeInfo to get the rate limit of REQUEST_WEIGHT and REQUEST_ORDER_WEIGHT.


How to check Weight used by IP address
Every response contains a header with X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter), which has the utilized weight from all the requests made by this IP address.

show headers

import (
    "encoding/json"
    "github.com/degatedev/degate-sdk-golang/conf"
    "github.com/degatedev/degate-sdk-golang/degate/spot"
    "github.com/degatedev/degate-sdk-golang/log"
)
client := &spot.Client{}
var appConfig = &conf.AppConfig{
    ShowHeader:true,
}
client.SetAppConfig(appConfig)
response,err := client.Time()
data,_ := json.Marshal(response)
log.Info("%v",string(data))
from degate.spot import Spot as Client
client = Client(show_header=True)
print(client.time())

Response

{
   "header":{
      "Content-Length":"42",
      "Content-Type":"application/json; charset=utf-8",
      "Date":"Thu, 29 Sep 2022 09:24:51 GMT",
      "Server":"openresty/1.15.8.1",
      "X-Mbx-Used-Weight-1m":"24"
   },
   "data":{
      "serverTime":1664443491000
   }
}











Order Rate Limits


Websocket Limits

Data Sources

These are the three sources, ordered by which has the most up-to-date response to the one with potential delays in updates.

Basic Configurations & Examples

Before using the SDK, some basic configurations are required.

Token config

Config Example (token&config):

import (
    "encoding/json"
    "github.com/degatedev/degate-sdk-golang/conf"
    "github.com/degatedev/degate-sdk-golang/degate/spot"
    "github.com/degatedev/degate-sdk-golang/log"
)
client := &spot.Client{}
conf.Conf.AddToken(&model.TokenInfo{
    Id:     8,
    Symbol: "USDC",
})  //USDC, tokenid = 8
conf.Conf.AddToken(&model.TokenInfo{
    Id:     0,
    Symbol: "ETH",
})  //eth, tokenid = 0
var appConfig = &conf.AppConfig{
    AccountId:        7,
    AccountAddress:   "0xBA2b5FEae299808b119FD410370D388B2fBF744b",
    AssetPrivateKey:       "1847400602630773084619040126809609832041801865548758092656011856772473440678",
    BaseUrl:          "https://v1-mainnet-backend.degate.com/",
    WebsocketBaseUrl: "wss://v1-mainnet-ws.degate.com/",
}
from degate.spot import Spot as Client
ETH = {
    "id": 0,
    "symbol": "ETH",
} #  USDC, tokenid = 8
USDC = {
    "id": 8,
    "symbol": "USDC",
}  # eth, tokenid = 0

AccountAddress = "0xba2b5feae299808b119fd410370d388b2fbf744b"
AssetPrivateKey =  "1847400602630773084619040126809609832041801865548758092656011856772473440678"
AccountId = 2475
client = Client(AccountAddress, AssetPrivateKey, AccountId, baseUrl="https://v1-mainnet-backend.degate.com/", tokens=[ETH,USDC])

Parameters: As DeGate offers permissionless listing, there could be listed tokens with the same name. token ID is used to reference a token. Hence, it is necessary to define the token and token ID before using the SDK. Note: Tokens with the same smart contract address may have different token ID across different environments.

Name Type Mandatory Description
Id INT YES token id how to get token id
Symbol STRING YES symbol

App Config

Set the following parameters correctly to interact with DeGate Parameters:

Name Type Mandatory Description
BaseUrl STRING YES base endpoint
Mainnet:https://v1-mainnet-backend.degate.com(default)
Testnet: https://v1-testnet-backend.degate.com
WebsocketBaseUrl STRING NO wss base endpoint
required when calling the push method
Mainnet: wss://v1-mainnet-ws.degate.com(default)
Testnet: wss://v1-testnet-ws.degate.com
AccountId INT NO The DeGate Account ID is a unique ID assigned to a user's wallet address after registration with DeGate. Each AccountId corresponds to one wallet address. how to get account id
AccountAddress STRING NO DeGate account Address
AssetPrivateKey STRING NO DeGate account AssetPrivateKey
required when calling the method that requires EdDSA signature

SIGNED Endpoint Examples for NewOrder

Theres a step-by-step example of how to send a vaild signed payload using SDK.

Example

import (
    "encoding/json"
    "github.com/degatedev/degate-sdk-golang/conf"
    "github.com/degatedev/degate-sdk-golang/degate/spot"
    "github.com/degatedev/degate-sdk-golang/log"
)
conf.Conf.AddToken(&model.TokenInfo{
    Symbol: "USDC",
    Id:     8,
})
conf.Conf.AddToken(&model.TokenInfo{
    Id:     0,
    Symbol: "ETH",
})
var appConfig = &conf.AppConfig{
    AccountId:      7,
    AccountAddress: "0xBA2b5FEae299808b119FD410370D388B2fBF744b",
    AssetPrivateKey:     <DeGate AssetPrivateKey>,
}
c := new(spot.Client)
c.SetAppConfig(appConfig)
c.NewOrder(&model.OrderParam{
    Symbol:   "ETHUSDC",
    Side:     "BUY",
    Quantity: 1,
    Price:    0.1,
    Type: LIMIT,
})
AccountAddress = "0xba2b5feae299808b119fd410370d388b2fbf744b"
AssetPrivateKey =  <DeGate AssetPrivateKey>
AccountId = 2475
ETH = {
    "id": 0,
    "symbol": "ETH",
}
USDC = {
    "id": 8,
    "symbol": "USDC",
}
client = Client(AccountAddress, AssetPrivateKey, AccountId,tokens=[ETH,USDC])
try:
    params = {
        "symbol": "ETHUSDC",
        "side": "SELL",
        "type": "LIMIT",
        "quantity": 0.1,
        "price": 3000,
    }
    response = client.newOrder(**params)
except Exception as e:
    logging.error(e)
Parameter Value
Symbol ETHUSDC
Side BUY
Type LIMIT
Quantity 1
Price 0.1



Advanced

Most of the content in this article can be done by configuring and calling the SDK correctly. Rarely it will involve direct endpoint interaction. If direct endpoint access is performed, it will involve further endpoint authentication and signature-related content.

Endpoint authentication

Each endpoint has an authentication type that determines how you will interact with it.

If no authentication type is stated, assume the authentication type is NONE.

By default, AssetPrivateKey can access all secure routes.

SIGNED Endpoint Security

SIGNED endpoints require an additional parameter, signature, to be sent in the header or request body.

Endpoints use EdDSA Poseidon signatures。

The signature is not case sensitive.

Public SDK Definitions

Terminology

These terms will be used throughout the documentation, so it is recommended for new users to read to help their understanding of the SDK.

ENUM definitions

Symbol status (status):

Account and Symbol Permissions (permissions):

Order status (status):

Status Description
NEW The order has been accepted by the Trading System.
PARTIALLY_FILLED A part of the order has been filled.
FILLED The order has been completed.
CANCELED The order has been canceled by the user.
EXPIRED The order was expired and cancelled by the Trading System


Order types (orderTypes, type):

Order Response Type (newOrderRespType)::

Order side (side):

Kline/Candlestick chart intervals:

m -> minutes; h -> hours; d -> days; w -> weeks; M -> months; y -> years

Rate limiters (rateLimitType)

REQUEST_WEIGHT

{
    "rateLimitType": "REQUEST_WEIGHT",
    "interval": "MINUTE",
    "intervalNum": 1,
    "limit": 2400
}

REQUEST_ORDER_WEIGHT

{
    "rateLimitType": "REQUEST_ORDER_WEIGHT",
    "interval": "MINUTE",
    "intervalNum": 1,
    "limit": 1200
}



Rate limit intervals (interval)



Wallet Endpoints

Gas Fee

Example

var appConfig = &conf.AppConfig{
    BaseUrl:          "https://v1-mainnet-backend.degate.com",
}
c := new(spot.Client)
c.SetAppConfig(appConfig)
response, err := c.GasFee()
client = Client()
try:
    logging.info(client.gasFee())
except Exception as e:
    logging.error(e)

Response:

{
    "withdrawal_gas_fees": [{  //withdraw to owner's address
        "symbol": "ETH",
        "token_id": 0,
        "quantity": "0.00185",
        "decimals": 18
    }, {
        "symbol": "USDC",
        "token_id": 8,
        "quantity": "3.36",
        "decimals": 18
    }, {
        "symbol": "USDT",
        "token_id": 9,
        "quantity": "3.36",
        "decimals": 18
    }],
    "withdrawal_other_gas_fees": [{ //withdraw to other address
        "symbol": "ETH",
        "token_id": 0,
        "quantity": "0.00185",
        "decimals": 18
    }, {
        "symbol": "USDC",
        "token_id": 8,
        "quantity": "3.36",
        "decimals": 18
    }, {
        "symbol": "USDT",
        "token_id": 9,
        "quantity": "3.36",
        "decimals": 18
    }],
    "transfer_gas_fees": [{     //transfer to an address with DeGate account registered
        "symbol": "ETH",
        "token_id": 0,
        "quantity": "0.0000704",
        "decimals": 18
    }, {
        "symbol": "USDC",
        "token_id": 8,
        "quantity": "0.128",
        "decimals": 18
    }, {
        "symbol": "USDT",
        "token_id": 9,
        "quantity": "0.128",
        "decimals": 18
    }],
    "transfer_no_id_gas_fees": [{ //transfer to an address with unregistered DeGate account
        "symbol": "ETH",
        "token_id": 0,
        "quantity": "0.000709",
        "decimals": 18
    }, {
        "symbol": "USDC",
        "token_id": 8,
        "quantity": "1.29",
        "decimals": 18
    }, {
        "symbol": "USDT",
        "token_id": 9,
        "quantity": "1.29",
        "decimals": 18
    }],
    "on_chain_cancel_order_gas_fees": [{ //cancel order on chain
        "symbol": "ETH",
        "token_id": 0,
        "quantity": "0.0000757",
        "decimals": 18
    }, {
        "symbol": "USDC",
        "token_id": 8,
        "quantity": "0.138",
        "decimals": 18
    }, {
        "symbol": "USDT",
        "token_id": 9,
        "quantity": "0.138",
        "decimals": 18
    }],
}

Check the required gas fee for deposit, transfer, on-chain order cancellation. Each operation will return the required gas fee in different token options. Users can choose to use any one of the returned tokens as the GasFee token for each of the respective operations.

Method: GasFee

Weight(IP): 1

Parameters: None

Withdraw

Example

conf.Conf.AddToken(&model.TokenInfo{
    Id:       0,
    Symbol:   "ETH",
    Decimals: 18,
})
var appConfig = &conf.AppConfig{
    AccountId:        7,
    AccountAddress:   "0xBA2b5FEae299808b119FD410370D388B2fBF744b",
    AssetPrivateKey:       <DeGate AssetPrivateKey>,
}
client := new(spot.Client)
client.SetAppConfig(appConfig)
response, err := client.Withdraw(&model.WithdrawParam{
    Address:    "0xBA2b5FEae299808b119FD410370D388B2fBF744b",
    Coin:       "ETH",
    Amount:     0.001,
    PrivateKey: <Wallet Private Key>,
})
AccountAddress = "0xba2b5feae299808b119fd410370d388b2fbf744b"
AssetPrivateKey =  <DeGate AssetPrivateKey>
AccountId = 2475
ETH = {
    "id": 0,
    "symbol": "ETH",
}

client = Client(AccountAddress, AssetPrivateKey, AccountId,tokens=[ETH])

try:
    response = client.withdraw(coin="ETH", amount=0.0001, address="0xba2b5feae299808b119fd410370d388b2fbf744b",privateKey=<Wallet Private Key>)
    logging.info(response)
except Exception as e:
    logging.error(e)

Response:

{
    "id":"7213fea8e94b4a5593d507237e5a555b"
}

Submit a withdraw request.

Method: Withdraw

Weight(IP): 10

Parameters:

Name Type Mandatory Description
Coin STRING YES Symbol
Address STRING YES Address to receive the token
Amount DECIMAL YES Amount
PrivateKey STRING YES Ethereum address private key(not the Asset Private Key)
ValidUntil LONG NO Valid until Default: 30 days
Fee STRING NO Gas fee token Default: ETH Read more

Transfer

Example

conf.Conf.AddToken(&model.TokenInfo{
    Id:       0,
    Symbol:   "ETH",
    Decimals: 18,
})
var appConfig = &conf.AppConfig{
    AccountId:        7,
    AccountAddress:   "0xBA2b5FEae299808b119FD410370D388B2fBF744b",
    AssetPrivateKey:    <DeGate AssetPrivateKey>,
}
client := new(spot.Client)
client.SetAppConfig(appConfig)
response, err := client.Transfer(&model.TransferParam{
    PrivateKey: <Wallet Private Key>,
    Address:    "0x6C6697C44b71A769482a701b3539C97952E424ef",
    Asset:      "ETH",
    Amount:     1.123456,
})
AccountAddress = "0xba2b5feae299808b119fd410370d388b2fbf744b"
AssetPrivateKey =  <DeGate AssetPrivateKey>
AccountId = 2475
ETH = {
    "id": 0,
    "symbol": "ETH",
}

client = Client(AccountAddress, AssetPrivateKey, AccountId,tokens=[ETH])

try:
    response = client.transfer(asset="ETH", amount=0.0001, address="0x5ddc2c634954e7e1133aeff98e6c7e7b034e00d4", privateKey=<Wallet Private Key>)
    logging.info(response)
except Exception as e:
    logging.error(e)

Response:

{
    "tranId":"7213fea8e94b4a5593d507237e5a555b"
}

Submit a transfer request.

Method: Transfer

Weight(IP): 10

Parameters:

Name Type Mandatory Description
Asset STRING YES Symbol
Address STRING YES Address to receive the token
Amount DECIMAL YES Amount
PrivateKey STRING YES Ethereum address private key(not the Asset Private Key)
ValidUntil LONG NO Valid until Default: 30 days
Fee STRING YES gas fee token Default: ETH Read more

Deposit History

Example

conf.Conf.AddToken(&model.TokenInfo{
    Id:       0,
    Symbol:   "ETH",
    Decimals: 18,
})
var appConfig = &conf.AppConfig{
    AccountId:        7,
    AccountAddress:   "0xBA2b5FEae299808b119FD410370D388B2fBF744b",
    AssetPrivateKey:    <DeGate AssetPrivateKey>,
}
client := new(spot.Client)
client.SetAppConfig(appConfig)
response, err := client.DepositHistory(&model.DepositsParam{
    Coin: "ETH",
    Limit: 20,
})
AccountAddress = "0xba2b5feae299808b119fd410370d388b2fbf744b"
AssetPrivateKey =  <DeGate AssetPrivateKey>
AccountId = 2475

client = Client(AccountAddress,AssetPrivateKey,AccountId)

try:
    param = {"limit":10}
    logging.info(client.depositHistory(**param))
except Exception as e:
    logging.error(e)

Response:

[
    {
        "amount":"0.00999800",
        "coin":"ETH",
        "network":"ETH",
        "status":1,
        "address":"0x788cabe9236ce061e5a892e1a59395a81fc8d62c",
        "txId":"0xaad4654a3234aa6118af9b4b335f5ae81c360b2394721c019b5d1e75328b09f3",
        "insertTime":1599621997000,
        "transferType":0,
        "confirmTimes":"12/12"
    }
]

Fetch deposit history.

Method: DepositHistory

Weight(IP): 1

Parameters:

Name Type Mandatory Description
Coin STRING YES Symbol
Status INT NO 1:success 6: credited but cannot withdraw
StartTime LONG NO
EndTime LONG NO
Offset INT NO Default: 0
Limit INT NO Default: 1000, Max: 1000
TxId STRING NO

Withdraw History

Example

conf.Conf.AddToken(&model.TokenInfo{
    Id:       0,
    Symbol:   "ETH",
    Decimals: 18,
})
var appConfig = &conf.AppConfig{
    AccountId:        7,
    AccountAddress:   "0xBA2b5FEae299808b119FD410370D388B2fBF744b",
    AssetPrivateKey:    <DeGate AssetPrivateKey>,
}
client := new(spot.Client)
client.SetAppConfig(appConfig)
response, err := client.WithdrawHistory(&model.WithdrawsParam{
    Coin: "ETH",
})
AccountAddress = "0xba2b5feae299808b119fd410370d388b2fbf744b"
AssetPrivateKey =  <DeGate AssetPrivateKey>
AccountId = 2475

client = Client(AccountAddress,AssetPrivateKey,AccountId)

try:
    logging.info(client.withdrawHistory())
except Exception as e:
    logging.error(e)

Response:

[
    {
        "address": "0x94df8b352de7f46f64b01d3666bf6e936e44ce60",
        "amount": "8.91000000",
        "applyTime": "2019-10-12 11:12:02",
        "coin": "ETH",
        "id": "b6ae22b3aa844210a7041aee7589627c",
        "network": "ETH", 
        "transferType": 0,   // 1 for internal transfer, 0 for external transfer   
        "status": 6,
        "transactionFee": "0.004",
        "confirmNo":3,  // confirm times for withdraw
        "info":"The address is not valid. Please confirm with the recipient", // reason for withdrawal failure
        "txId": "0xb5ef8c13b968a406cc62a93a8bd80f9e9a906ef1b3fcf20a2e48573c17659268"
    }
]

Fetch withdraw history.

Method: WithdrawHistory

Weight(IP): 1

Parameters:

Name Type Mandatory Description
Coin STRING NO
Status INT NO 4: Processing 5: Failure 6: Completed
StartTime LONG NO
EndTime LONG NO
Offset INT NO Default: 0
Limit INT NO Default: 1000, Max: 1000

Transfer History

Example

conf.Conf.AddToken(&model.TokenInfo{
    Id:       0,
    Symbol:   "ETH",
    Decimals: 18,
})
conf.Conf.AddToken(&model.TokenInfo{
    Id:       8,
    Symbol:   "USDC",
    Decimals: 18,
})
var appConfig = &conf.AppConfig{
    AccountId:        7,
    AccountAddress:   "0xBA2b5FEae299808b119FD410370D388B2fBF744b",
    AssetPrivateKey:    <DeGate AssetPrivateKey>,
}
client := new(spot.Client)
client.SetAppConfig(appConfig)
response, err := client.TransferHistory(&model.TransfersParam{
    Coin: "ETH,USDC",
})
AccountAddress = "0xba2b5feae299808b119fd410370d388b2fbf744b"
AssetPrivateKey =  <DeGate AssetPrivateKey>
AccountId = 2475

client = Client(AccountAddress,AssetPrivateKey,AccountId)

try:
    logging.info(client.transferHistory())
except Exception as e:
    logging.error(e)

Response:

{
    "rows":[
        {
            "asset":"USDT",
            "amount":"1",
            "status": "CONFIRMED",
            "tranId": 11415955596,
            "timestamp":1544433328000,
            "fromAccount": "",
            "toAccount": "",        
        },
        {
            "asset":"ETH",
            "amount":"2",
            "status": "CONFIRMED",
            "tranId": 11366865406,
            "timestamp":1544433328000,
            "fromAccount": "",
            "toAccount": "", 
        }
    ]
}

Method: TransferHistory

Weight(IP): 1

Parameters:

Name Type Mandatory Description
Coin STRING NO Symbol
StartTime LONG NO
EndTime LONG NO
Offset INT NO Default: 0
Limit INT NO Default: 1000,Max: 1000

Assets Balance

Example

conf.Conf.AddToken(&model.TokenInfo{
    Id:       0,
    Symbol:   "ETH",
    Decimals: 18,
})
conf.Conf.AddToken(&model.TokenInfo{
    Id:       2,
    Symbol:   "USUDC",
    Decimals: 6,
})
var appConfig = &conf.AppConfig{
    AccountId:        7,
    AccountAddress:   "0xBA2b5FEae299808b119FD410370D388B2fBF744b",
    AssetPrivateKey:    <DeGate AssetPrivateKey>,
}
client := new(spot.Client)
client.SetAppConfig(appConfig)
response, err := client.GetBalance(&model.AccountBalanceParam{
    Asset: "ETH,USDC",
})
AccountAddress = "0xba2b5feae299808b119fd410370d388b2fbf744b"
AssetPrivateKey =  <DeGate AssetPrivateKey>
AccountId = 2475

client = Client(AccountAddress,AssetPrivateKey,AccountId)

try:
    logging.info(client.getBalance())
except Exception as e:
    logging.error(e)

Responses

[
    {
        "asset": "ETH",
        "free": "1",    // available balance 
        "locked": "0",  // locked asset
        "freeze": "0",  // freezed asset
        "withdrawing": "0", // withdrawing asset amount
    }
    },
    {
        "asset": "USDC",
        "free": "1",    // available balance
        "locked": "0", // locked asset
        "freeze": "0",   // freezed asset
        "withdrawing": "0", // withdrawing asset amount
    }
]

Method: GetBalance

Weight(IP): 5

Parameters:

Name Type Mandatory Description
Asset STRING NO leave this empty will return all assets with balances

Market Data Endpoints

Test Connectivity

Example

var appConfig = &conf.AppConfig{
    BaseUrl:  "https://v1-mainnet-backend.degate.com",
}
client := new(spot.Client)
client.SetAppConfig(appConfig)
response, err := client.Ping()
client = Client()

try:
    logging.info(client.ping())
except Exception as e:
    logging.error(e)

Response:

{}

Test connectivity to the Rest API.

Method: Ping

Weight(IP): 1

Parameters: NONE

Data Source: Memory

Check Server Time

Example

var appConfig = &conf.AppConfig{
    BaseUrl:  "https://v1-mainnet-backend.degate.com",
}
c := new(spot.Client)
c.SetAppConfig(appConfig)
response, err := c.Time()
client = Client()

try:
    logging.info(client.time())
except Exception as e:
    logging.error(e)

Response

{
  "serverTime": 1499827319559
}

Test connectivity to the Rest API and get the current server time.

Method: Time

Weight(IP): 1

Parameters: None

Data Source: Memory

Exchange Information

Example

var appConfig = &conf.AppConfig{
    BaseUrl:          "https://v1-mainnet-backend.degate.com",
}
c := new(spot.Client)
c.SetAppConfig(appConfig)
response, err := c.ExchangeInfo()
client = Client()
try:
    logging.info(client.exchangeInfo())
except Exception as e:
    logging.error(e)

Response

{
  "chain_id":4,
  "minLimitOrderUSDValue":100,
  "timezone":"UTC",
  "server_time":1649239409289,
  "rateLimits": [
        {
           //These are defined in the `ENUM definitions` section under `Rate Limiters (rateLimitType)`.
           //All limits are optional
        }
  ],
}

Current exchange trading rules.

Method: ExchangeInfo

Weight(IP): 1

Parameters: None

Data Source: Memory

Order Book(Depth)

Example

conf.Conf.AddToken(&model.TokenInfo{
  Id:     8,
  Symbol: "USDC",
})
conf.Conf.AddToken(&model.TokenInfo{
  Id:     0,
  Symbol: "ETH",
})
var appConfig = &conf.AppConfig{
    BaseUrl:          "https://v1-mainnet-backend.degate.com",
}
client := new(spot.Client)
client.SetAppConfig(appConfig)
response, err := client.Depth(&model.DepthParam{
  Symbol: "ETHUSDC",
})
ETH = {
    "id": 0,
    "symbol": "ETH",
}
USDC = {
    "id": 8,
    "symbol": "USDC",
}

client = Client(tokens=[ETH,USDC])

try:
    logging.info(client.depth("ETHUSDC", limit=10))
except Exception as e:
    logging.error(e)

Response

{
  "lastUpdateId": 1027024,
  "bids": [
    [
      "4.00000000",     // PRICE
      "431.00000000"    // QTY
    ]
  ],
  "asks": [
    [
      "4.00000200",
      "12.00000000"
    ]
  ]
}

Method: Depth

Weight(IP): 5

Parameters:

Name Type Mandatory Description
Symbol STRING YES
Limit INT NO Default 100(ask:100,bid:100), Max 5000;
If limit > 5000, then the response will truncate to 5000.

Data Source: Memory

Recent Trades List

Example

conf.Conf.AddToken(&model.TokenInfo{
  Id:     8,
  Symbol: "USDC",
})
conf.Conf.AddToken(&model.TokenInfo{
  Id:     0,
  Symbol: "ETH",
})
var appConfig = &conf.AppConfig{
    BaseUrl:          "https://v1-mainnet-backend.degate.com",
}
client := new(spot.Client)
client.SetAppConfig(appConfig)
response, err := client.Trades(&model.TradeLastedParam{
  Symbol: "ETHUSDC",
  Limit:  0,
})
ETH = {
    "id": 0,
    "symbol": "ETH",
}
USDC = {
    "id": 8,
    "symbol": "USDC",
}

client = Client(tokens=[ETH,USDC])

try:
    logging.info(client.trades("ETHUSDC", limit=20))
except Exception as e:
    logging.error(e)

Response

[
  {
    "id": "28457",
    "price": "4.00000100",
    "qty": "12.00000000",
    "time": 1499865549590, //time when this trade executed ,as same as `T` in the stream
    "isBuyerMaker": true,
  }
]

Get recent trades.

Method: Trades

Weight(IP): 10

Parameters:

Name Type Mandatory Description
Symbol STRING YES
Limit INT NO Default 500; max 1000

Data Source: Database

Old Trade Lookup

Example

conf.Conf.AddToken(&model.TokenInfo{
  Id:     8,
  Symbol: "USDC",
})
conf.Conf.AddToken(&model.TokenInfo{
  Id:     0,
  Symbol: "ETH",
})
var appConfig = &conf.AppConfig{
    BaseUrl:          "https://v1-mainnet-backend.degate.com",
}
client := new(spot.Client)
client.SetAppConfig(appConfig)
response, err := client.TradesHistory(&model.TradeHistoryParam{
  Symbol: "ETHUSDC",
  Limit:  20,
})
ETH = {
    "id": 0,
    "symbol": "ETH",
}
USDC = {
    "id": 8,
    "symbol": "USDC",
}

client = Client(tokens=[ETH,USDC])

try:
    logging.info(client.tradesHistory("ETHUSDC", limit=20))
except Exception as e:
    logging.error(e)

Response

[
  {
    "id": "28457",
    "price": "4.00000100",
    "qty": "12.00000000",
    "quoteQty": "48.000012",
    "time": 1499865549590, // Trade executed timestamp, as same as `T` in the stream
    "isBuyerMaker": true,
  }
]

Get older market trades.

Method: TradesHistory

Weight(IP): 10

Parameters:

Name Type Mandatory Description
Symbol STRING YES
Limit INT NO Default 500; max 1000
FromId STRING NO Trade id to fetch from. By default it will get the most recent trades.

Data Source: Database

Kline/Candlestick Data

Example

conf.Conf.AddToken(&model.TokenInfo{
  Id:     8,
  Symbol: "USDC",
})
conf.Conf.AddToken(&model.TokenInfo{
  Id:     0,
  Symbol: "ETH",
})
var appConfig = &conf.AppConfig{
    BaseUrl:          "https://v1-mainnet-backend.degate.com",
}
client := new(spot.Client)
client.SetAppConfig(appConfig)
response, err := client.Klines(&model.KlineParam{
  Symbol: "ETHUSDC",
  Limit:  20,
})
ETH = {
    "id": 0,
    "symbol": "ETH",
}
USDC = {
    "id": 8,
    "symbol": "USDC",
}

client = Client(tokens=[ETH,USDC])

try:
    logging.info(client.klines("ETHUSDC", "1m", limit=10))
    logging.info(client.klines("ETHUSDC", "1h", limit=10))
except Exception as e:
    logging.error(e)

Response

[
  [
    1499040000000,      // Open time
    "0.01634790",       // Price at Open time
    "0.80000000",       // Highest price
    "0.01575800",       // Lowest price
    "0.01577100",       // Close price(or most recent price)
    "148976.11427815",  // Volume
    1499644799999,      // Close time
    "2434.19055334",    // Quote asset trade volume
    308,                // Number of trades
    "1756.87402397",    // Taker bought base asset volume
    "28.46694368",      // Taker bought quote asset volume
    "17928899.62484339" // Ignore this param
  ]
]

Each Kline/candlestick bars for Symbol.
Klines are uniquely identified by their open time.

Method: Klines

Weight(IP): 1

Parameters:

Name Type Mandatory Description
Symbol STRING YES
Interval ENUM YES kline interval
StartTime LONG NO
EndTime LONG NO
Limit INT NO Default 500; max 1000

Data Source: Memory

24hr Ticker Price Change Statistics

Example

conf.Conf.AddToken(&model.TokenInfo{
  Id:     8,
  Symbol: "USDC",
})
conf.Conf.AddToken(&model.TokenInfo{
  Id:     0,
  Symbol: "ETH",
})
var appConfig = &conf.AppConfig{
    BaseUrl:          "https://v1-mainnet-backend.degate.com",
}
client := new(spot.Client)
client.SetAppConfig(appConfig)
response, err := client.Ticker24(&model.TickerParam{
  Symbol: "ETHUSDC",
})
ETH = {
    "id": 0,
    "symbol": "ETH",
}
USDC = {
    "id": 8,
    "symbol": "USDC",
}

client = Client(tokens=[ETH,USDC])

try:
    logging.info(client.ticker24("ETHUSDC"))
except Exception as e:
    logging.error(e)

Response

{
  "symbol": "ETHUSDC",
  "priceChange": "-94.99999800",
  "priceChangePercent": "-95.960",
  "weightedAvgPrice": "0.29628482",
  "prevClosePrice": "0.10002000",
  "lastPrice": "4.00000200",
  "lastQty": "200.00000000",
  "bidPrice": "4.00000000",
  "bidQty": "100.00000000",
  "askPrice": "4.00000200",
  "askQty": "100.00000000",
  "openPrice": "99.00000000",
  "highPrice": "100.00000000",
  "lowPrice": "0.10000000",
  "volume": "8913.30000000",
  "quoteVolume": "15.30000000",
  "openTime": 1499783499040,
  "closeTime": 1499869899040,
  "firstId": "28385",   // First tradeId
  "lastId": "28460",    // Last tradeId
  "count": 76,           // Trade count
  "makerFee": "0",
  "takerFee": "1.0",
  "pairId": 1
}

24 hour rolling window price change statistics.

Method: Ticker24

Weight(IP): 5

Parameters:

Name Type Mandatory Description
Symbol STRING YES

Data Source: Memory

Symbol Price Ticker

Example

conf.Conf.AddToken(&model.TokenInfo{
  Id:     8,
  Symbol: "USDC",
})
conf.Conf.AddToken(&model.TokenInfo{
  Id:     0,
  Symbol: "ETH",
})
conf.Conf.AddToken(&model.TokenInfo{
  Id:     9,
  Symbol: "USDT",
})
var appConfig = &conf.AppConfig{
    BaseUrl:          "",
}
client := new(spot.Client)
client.SetAppConfig(appConfig)
response, err := client.TickerPrice(&model.PairPriceParam{
  Symbol: "ETHUSDC,ETHUSDT",
})
ETH = {
    "id": 0,
    "symbol": "ETH",
}
USDC = {
    "id": 8,
    "symbol": "USDC",
}
USDT = {
    "id": 9,
    "symbol": "USDT",
}

spot_client = Client(tokens=[ETH,USDC,USDT])

try:
    logging.info(spot_client.tickerPrice("ETHUSDC,ETHUSDT"))
except Exception as e:
    logging.error(e)

Response

[
  {
    "symbol": "ETHUSDC",
    "price": "4.00000200",
     "pairId": 1
  },
  {
    "symbol": "ETHUSDT",
    "price": "4.00000200",
     "pairId": 2
  }
]

Latest price for a symbol or symbols.

Method: TickerPrice

Weight(IP): 1

Parameters:

Name Type Mandatory Description
Symbol STRING YES separated by ','

Data Source: Memory

Symbol Order Book Ticker

Example

conf.Conf.AddToken(&model.TokenInfo{
  Id:     8,
  Symbol: "USDC",
})
conf.Conf.AddToken(&model.TokenInfo{
  Id:     0,
  Symbol: "ETH",
})
var appConfig = &conf.AppConfig{
    BaseUrl:          "https://v1-mainnet-backend.degate.com",
}
client := new(spot.Client)
client.SetAppConfig(appConfig)
response, err := client.BookTicker(&model.BookTickerParam{
  Symbol: "ETHUSDC",
})
ETH = {
    "id": 0,
    "symbol": "ETH",
}
USDC = {
    "id": 8,
    "symbol": "USDC",
}

client = Client(tokens=[ETH,USDC])

try:
    logging.info(client.bookTicker("ETHUSDC"))
except Exception as e:
    logging.error(e)

Response

{
  "symbol": "ETHUSDC",
  "bidPrice": "4.00000000",
  "bidQty": "431.00000000",
  "askPrice": "4.00000200",
  "askQty": "9.00000000"
}

Best price/qty on the order book for a symbol or symbols.

Method: BookTicker

Weight(IP): 1

Parameters:

Name Type Mandatory Description
Symbol STRING YES

Data Source: Memory

Spot Account/Trade

Query Token

Example

var appConfig = &conf.AppConfig{
    BaseUrl:  "https://v1-mainnet-backend.degate.com",
}
c := new(spot.Client)
c.SetAppConfig(appConfig)
response, err := c.TokenList(&model.TokenListParam{
  Symbols: "eth,usdc",
})
client = Client()

try:
    logging.info(client.tokenList("ETH,USDC"))
except Exception as e:
    logging.error(e)

Response RESULT:

[
  {
    "id": 0,         // token id
    "symbol": "ETH",
    "code": "",      // token contract address
    "decimals":18,   
  },
  {
    "id": 8,         // token id
    "symbol": "USDC",
    "code": "0x953873a4e0b57179d88a9275cfb5243d3e631f1b", // token contract address
    "decimals":18,   
  }
]

Query token info

Method: TokenList

Weight(IP): 1

Parameters:

Name Type Mandatory Description
Symbols STRING YES separated by ','

New Order

Example

conf.Conf.AddToken(&model.TokenInfo{
  Symbol: "ETH",
  Id:     0,
})
conf.Conf.AddToken(&model.TokenInfo{
  Symbol: "USDC",
  Id:     8,
})
var appConfig = &conf.AppConfig{
    AccountId:        7,
    AccountAddress:   "0xBA2b5FEae299808b119FD410370D388B2fBF744b",
    AssetPrivateKey:    <DeGate AssetPrivateKey>,
}
c := new(spot.Client)
c.SetAppConfig(appConfig)
response, err := c.NewOrder(&model.OrderParam{
  Symbol:   "ETHUSDC",
  Side:     "sell",
  Quantity: 1,
  Price:    5000,
  Type:     "LIMIT",
})
AccountAddress = "0xba2b5feae299808b119fd410370d388b2fbf744b"
AssetPrivateKey =  <DeGate AssetPrivateKey>
AccountId = 2475
ETH = {
    "id": 0,
    "symbol": "ETH",
}
USDC = {
    "id": 8,
    "symbol": "USDC",
}

client = Client(AccountAddress, AssetPrivateKey, AccountId,tokens=[ETH,USDC])

try:
    params = {
        "symbol": "ETHUSDC",
        "side": "SELL",
        "type": "LIMIT",
        "quantity": 0.1,
        "price": 3000,
    }
    response = client.newOrder(**params)
    logging.info(response)
except Exception as e:
    logging.error(e)

try:
    params = {
        "symbol": "ETHUSDC",
        "side": "SELL",
        "type": "MARKET",
        "quantity": 0.1,
    }
    response = client.newOrder(**params)
    logging.info(response)
except Exception as e:
    logging.error(e)

Response ACK:

{
  "symbol": "ETHUSDC",
  "orderId": "28",
  "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
  "transactTime": 1507725176595
}

Response RESULT:

{
  "symbol": "ETHUSDC",
  "orderId": "28",
  "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
  "transactTime": 1507725176595,
  "price": "1.00000000",
  "origQty": "10.00000000",
  "executedQty": "10.00000000",
  "cummulativeQuoteQty": "10.00000000",
  "status": "FILLED",
  "timeInForce": "GTC",
  "type": "MARKET",
  "side": "SELL"
}

Response FULL:

{
  "symbol": "ETHUSDC",
  "orderId": "28",
  "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
  "transactTime": 1507725176595,
  "price": "1.00000000",
  "origQty": "10.00000000",
  "executedQty": "10.00000000",
  "cummulativeQuoteQty": "10.00000000",
  "status": "FILLED",
  "timeInForce": "GTC",
  "type": "MARKET",
  "side": "SELL",
  "fills": [
    {
      "price": "4000.00000000",
      "qty": "1.00000000",
      "commission": "4.00000000",
      "commissionAsset": "USDT",
      "tradeId": 56
    },
    {
      "price": "3999.00000000",
      "qty": "5.00000000",
      "commission": "19.99500000",
      "commissionAsset": "USDT",
      "tradeId": 57
    }
  ]
}

Place a new order.

Method: NewOrder

Weight(IP): 10

Parameters:

Name Type Mandatory Description
Symbol STRING YES
Side ENUM YES defined in the ENUM definitions: Order Side
Type ENUM YES defined in the ENUM definitions: Order type
Quantity DECIMAL NO Quantity should only consist up to 6 significant numbers, eg: 0.123456,1.23456,123456
QuoteOrderQty DECIMAL NO QuoteOrderQty should only consist of up to 6 significant numbers. If both Quantity and QuoteOrderQty are sent, only Quantity will be counted
Price DECIMAL NO Price in normal Trading pairs should only consist of up to 5 significant numbers. If there are more than 5 significant numbers in the integer part of the price, significant numbers can be up to 6. Stablecoin trading pairs should only consist of up to 4 significant numbers, when the price is greater than 1, significant numbers can be up to 5. Correct Example: 0.12345,12345.6 , Wrong Example: 0.123456,1.23456
NewClientOrderId STRING NO A unique id among open orders. Automatically generated if not sent
NewOrderRespType ENUM NO Set the response JSON. ACK, RESULT, or FULL; MARKET and LIMIT order types default to FULL, all other orders default to ACK
ValidUntil LONG NO Order validity, by default, is 60 days. After the expiration date, the remaining unfilled part of the pending order will be automatically cancelled. If the user does not initiate an on-chain cancellation, the order signature will be permanently valid. Setting the order validity period can play a role in preventing nodes from doing evil (such as resuming orders).

Additional mandatory parameters based on order type:

Type Additional mandatory parameters
LIMIT quantity, price
MARKET quantity

Other info:

NewOrderRespType

Data Source: Trading System

Cancel Order

Example

var appConfig = &conf.AppConfig{
    AccountId:        7,
    AccountAddress:   "0xBA2b5FEae299808b119FD410370D388B2fBF744b",
    AssetPrivateKey:    <DeGate AssetPrivateKey>,
}
c := new(spot.Client)
c.SetAppConfig(appConfig)
response, err := c.CancelOrder(&model.CancelOrderParam{
  OrderId: "188759499725809833483796742269",
})
AccountAddress = "0xba2b5feae299808b119fd410370d388b2fbf744b"
AssetPrivateKey =  <DeGate AssetPrivateKey>
AccountId = 2475

client = Client(AccountAddress, AssetPrivateKey, AccountId)

try:
    response = client.cancelOrder(orderId="196120192698583504448505788760278")
    logging.info(response)
except Exception as e:
    logging.error(e)

Response

{
  "symbol": "ETHUSDC",
  "origClientOrderId": "myOrder1",
  "orderId": "4",
  "clientOrderId": "cancelMyOrder1",
  "price": "2.00000000",
  "origQty": "1.00000000",
  "executedQty": "0.00000000",
  "cummulativeQuoteQty": "0.00000000",
  "status": "CANCELED",
  "timeInForce": "GTC",
  "type": "LIMIT",
  "side": "BUY"
}

Cancel an active order.

Method: CancelOrder

Weight(IP): 10

Parameters:

Name Type Mandatory Description
OrderId STRING NO
OrigClientOrderId STRING NO User-defined orderid

Either orderId or origClientOrderId must be sent.

Data Source: Trading System

Cancel all Open Orders

Example

var appConfig = &conf.AppConfig{
    AccountId:        7,
    AccountAddress:   "0xBA2b5FEae299808b119FD410370D388B2fBF744b",
    AssetPrivateKey:    <DeGate AssetPrivateKey>,
}
c := new(spot.Client)
c.SetAppConfig(appConfig)
response, err := c.CancelOpenOrders(false)
AccountAddress = "0xba2b5feae299808b119fd410370d388b2fbf744b"
AssetPrivateKey =  <DeGate AssetPrivateKey>
AccountId = 2475

client = Client(AccountAddress, AssetPrivateKey, AccountId)

try:
    response = client.cancelOpenOrders()
    logging.info(response)
except Exception as e:
    logging.error(e)

Response

{}

Cancels all active orders.

Method: CancelOpenOrders

Weight(IP): 1

Parameters:

Name Type Mandatory Description
IncludeGrid Bool NO include gird orders, Default:false

Data Source: Trading System

On-chain Order Cancellation

Example

var appConfig = &conf.AppConfig{
    AccountId:        7,
    AccountAddress:   "0xBA2b5FEae299808b119FD410370D388B2fBF744b",
    AssetPrivateKey:    <DeGate AssetPrivateKey>,
}
c := new(spot.Client)
c.SetAppConfig(appConfig)
response, err := c.CancelOrderOnChain(&model.CancelOrderParam{
  OrderId: "188820328196434284078497267922",
})
AccountAddress = "0xba2b5feae299808b119fd410370d388b2fbf744b"
AssetPrivateKey =  <DeGate AssetPrivateKey>
AccountId = 2475

client = Client(AccountAddress, AssetPrivateKey, AccountId)

try:
    response = client.cancelOrderOnChain(orderId="196120192698583504448505788760278")
    logging.info(response)
except Exception as e:
    logging.error(e)

Response

{}

On-chain order cancellation can only be done for an order that has been canceled on the order book.

Method: CancelOrderOnChain

Weight(IP): 10

Parameters:

Name Type Mandatory Description
OrderId STRING NO
OrigClientOrderId STRING NO

Either orderId or origClientOrderId must be sent.

Query Order

Example

var appConfig = &conf.AppConfig{
    AccountId:        7,
    AccountAddress:   "0xBA2b5FEae299808b119FD410370D388B2fBF744b",
    AssetPrivateKey:    <DeGate AssetPrivateKey>,
}
c := new(spot.Client)
c.SetAppConfig(appConfig)
_, response, err := c.GetOrder(&model.OrderDetailParam{
  OrderId: "1297850191237108107827054903296",
})
AccountAddress = "0xba2b5feae299808b119fd410370d388b2fbf744b"
AssetPrivateKey =  <DeGate AssetPrivateKey>
AccountId = 2475

client = Client(AccountAddress, AssetPrivateKey, AccountId)

try:
    response = client.getOrder(orderId="196120192698583504448505788760278")
    logging.info(response)
except Exception as e:
    logging.error(e)

Response

{
  "symbol": "ETHUSDC", // trading pair symbol
  "orderId": "1", // order id in system 
  "clientOrderId": "myOrder1",// order id set by user
  "price": "0.1",  // order price
  "origQty": "1.0", // original quantity
  "executedQty": "0.0", // executed quantity
  "cummulativeQuoteQty": "0.0",  // cummulated qoute quantity
  "status": "NEW", // order status
  "timeInForce": "GTC",
  "type": "LIMIT", // order type
  "side": "BUY", // order side
  "time": 1499827319559, //ordertime 
  "updateTime": 1499827319559, // last update time
  "isWorking": true,  //whether the order appears in the orderbook
  "origQuoteOrderQty": "0.000000" // original qouted order quantity
}

Check an order's status.

Method: GetOrder

Weight(IP): 5

Parameters:

Name Type Mandatory Description
OrderId STRING NO
OrigClientOrderId STRING NO

Data Source: Database

Current Open Orders

Example

conf.Conf.AddToken(&model.TokenInfo{
  Symbol: "ETH",
  Id:     0,
})
conf.Conf.AddToken(&model.TokenInfo{
  Symbol: "USDC",
  Id:     8,
})
var appConfig = &conf.AppConfig{
    AccountId:        7,
    AccountAddress:   "0xBA2b5FEae299808b119FD410370D388B2fBF744b",
    AssetPrivateKey:    <DeGate AssetPrivateKey>,
}
c := new(spot.Client)
c.SetAppConfig(appConfig)
response, err := c.GetOpenOrders(&model.OrdersParam{
  Symbol: "ETHUSDC",
})
AccountAddress = "0xba2b5feae299808b119fd410370d388b2fbf744b"
AssetPrivateKey =  <DeGate AssetPrivateKey>
AccountId = 2475
ETH = {
    "id": 0,
    "symbol": "ETH",
}
USDC = {
    "id": 8,
    "symbol": "USDC",
}

client = Client(AccountAddress, AssetPrivateKey, AccountId,tokens=[ETH,USDC])

try:
    response = client.getOpenOrders("ETHUSDC")
    logging.info(response)
except Exception as e:
    logging.error(e)

Response

[
  {
    "symbol": "ETHUSDC",
    "orderId": "1",
    "clientOrderId": "myOrder1",
    "price": "0.1",
    "origQty": "1.0",
    "executedQty": "0.0",
    "cummulativeQuoteQty": "0.0",
    "status": "NEW",
    "timeInForce": "GTC",
    "type": "LIMIT",
    "side": "BUY",
    "time": 1499827319559,
    "updateTime": 1499827319559,
    "isWorking": true,
    "origQuoteOrderQty": "0.000000"
  }
]

Get all open orders on a symbol. Careful when accessing this with no symbol.

Method: GetOpenOrders

Weight(IP): 10

Parameters:

Name Type Mandatory Description
Symbol STRING NO

Data Source: Database

Historical Orders

Example

conf.Conf.AddToken(&model.TokenInfo{
  Symbol: "ETH",
  Id:     0,
})
conf.Conf.AddToken(&model.TokenInfo{
  Symbol: "USDC",
  Id:     8,
})
var appConfig = &conf.AppConfig{
    AccountId:        7,
    AccountAddress:   "0xBA2b5FEae299808b119FD410370D388B2fBF744b",
    AssetPrivateKey:    <DeGate AssetPrivateKey>,
}
c := new(spot.Client)
c.SetAppConfig(appConfig)
response, err := c.GetHistoryOrders(&model.OrdersParam{
  Symbol:    "ETHUSDC",
  Limit: 20,
})
AccountAddress = "0xba2b5feae299808b119fd410370d388b2fbf744b"
AssetPrivateKey =  <DeGate AssetPrivateKey>
AccountId = 2475
ETH = {
    "id": 0,
    "symbol": "ETH",
}
USDC = {
    "id": 8,
    "symbol": "USDC",
}

client = Client(AccountAddress, AssetPrivateKey, AccountId,tokens=[ETH,USDC])

try:
    response = client.getHistoryOrders("ETHUSDC",limit=20)
    logging.info(response)
except Exception as e:
    logging.error(e)

Response:

[
  {
    "symbol": "ETHUSDC",
    "orderId": "1",
    "clientOrderId": "myOrder1",
    "price": "0.1",
    "origQty": "1.0",
    "executedQty": "0.0",
    "cummulativeQuoteQty": "0.0",
    "status": "NEW",
    "timeInForce": "GTC",
    "type": "LIMIT",
    "side": "BUY",
    "time": 1499827319559,
    "updateTime": 1499827319559,
    "isWorking": true,
    "origQuoteOrderQty": "0.000000"
  }
]

Get all history orders; canceled, or filled.

Method: GetHistoryOrders

Weight(IP): 10

Parameters:

Name Type Mandatory Description
Symbol STRING YES
OrderId STRING NO
StartTime LONG NO
EndTime LONG NO
Limit INT NO Default 500; max 1000

Notes:

Data Source: Database

Account Trade List

Example

conf.Conf.AddToken(&model.TokenInfo{
  Symbol: "ETH",
  Id:     0,
})
conf.Conf.AddToken(&model.TokenInfo{
  Symbol: "USDC",
  Id:     8,
})
var appConfig = &conf.AppConfig{
    AccountId:        7,
    AccountAddress:   "0xBA2b5FEae299808b119FD410370D388B2fBF744b",
    AssetPrivateKey:    <DeGate AssetPrivateKey>,
}
client := new(spot.Client)
client.SetAppConfig(appConfig)
response, err := client.MyTrades(&model.AccountTradesParam{
  Symbol: "ETHUSDC",
  Limit:  20,
})
AccountAddress = "0xba2b5feae299808b119fd410370d388b2fbf744b"
AssetPrivateKey =  <DeGate AssetPrivateKey>
AccountId = 2475
ETH = {
    "id": 0,
    "symbol": "ETH",
}
USDC = {
    "id": 8,
    "symbol": "USDC",
}

client = Client(AccountAddress, AssetPrivateKey, AccountId,tokens=[ETH,USDC])

try:
    logging.info(client.myTrades("ETHUSDC", limit=20))
except Exception as e:
    logging.error(e)

Response

[
  {
    "symbol": "ETHUSDC", //trading pair symbol
    "id": "28457",       // trade id
    "orderId": "100234", // order id
    "price": "4.00000100", // price
    "qty": "12.00000000", // quantity
    "quoteQty": "48.000012", // qoute quantity
    "commission": "10.10000000", //commission
    "commissionAsset": "ETH", //commission Asset
    "time": 1499865549590,// time 
    "isBuyer": true, 
    "isMaker": false,
  }
]

Get trades for a specific account and symbol.

Method: MyTrades

Weight(IP): 10

Parameters:

Name Type Mandatory Description
Symbol STRING YES
OrderId STRING NO This can only be used in combination with symbol
StartTime LONG NO
EndTime LONG NO
FromId STRING NO TradeId to fetch from. Default gets most recent trades
Limit INT NO Default 500; max 1000

Notes:

Data Source: Database

Account Information

Users can use this method to get the AccountId.

Example

var appConfig = &conf.AppConfig{
    AccountAddress:   "0xBA2b5FEae299808b119FD410370D388B2fBF744b",
    AssetPrivateKey:    <DeGate AssetPrivateKey>,
}
client := new(spot.Client)
client.SetAppConfig(appConfig)
response, err := client.Account()
AccountAddress = "0xba2b5feae299808b119fd410370d388b2fbf744b"
AssetPrivateKey =  <DeGate AssetPrivateKey>

client = Client(AccountAddress,AssetPrivateKey)

try:
    logging.info(client.account())
except Exception as e:
    logging.error(e)

Response

{'id': 655,
 'owner': '0x79e106a68dba9b432718a65d0dd2798024104231',
 'public_key_x': '0x230b3f70e830d82fb946e7c940886bba3d86a67daa80894d297aa2ea015a580f',
 'public_key_y': '0x01484c45c6e3e2dce8221e699a5bd87aeb1b2e02cb6c8149937480cc326311f0',
 'referrer_id': 0,
 'nonce': 0,
 'makerCommission': 0,
 'takerCommission': 0,
 'buyerCommission': 0,
 'sellerCommission': 0,
 'canTrade': False,
 'canWithdraw': False,
 'canDeposit': False,
 'updateTime': 0,
 'accountType': 'SPOT',
 'balances': [{'asset': 'USDT',
   'free': '12416.2884578',
   'locked': '',
   'freeze': '0',
   'withdrawing': ''},
  {'asset': 'ETH',
   'free': '8.384506045504639607',
   'locked': '',
   'freeze': '0',
   'withdrawing': ''}],
 'permissions': ['SPOT']}

Get current account information.

Method: Account

Weight(IP): 1

Parameters:

Name Type Mandatory Description
AccountAddress STRING YES
AssetPrivateKey STRING YES

Data Source: Memory => Database

Error Codes

Errors consist of two parts: an error code and a message. Codes are universal, but messages can vary.

100000 UNKNOWN

100001

100004

100006

100007

100008

100009

100010

100012

100013

101001

101002

101003

101004

102001

102002

102003

102007

102008

102011

102012

102013

102014

102015

102016

102023

102024

102026

102027

102028

102029

102030

102032

102033

102035

102118

103000

104005

105000

106000

107004



Market Streams

SDK Market Streams

Trade Streams

Example:

conf.Conf.AddToken(&model.TokenInfo{
  Symbol: "ETH",
  Id:     0,
})
conf.Conf.AddToken(&model.TokenInfo{
  Symbol: "USDC",
  Id:     8,
})
var appConfig = &conf.AppConfig{
    WebsocketBaseUrl: "wss://v1-mainnet-ws.degate.com",
}
c := websocket.WebSocketClient{}
c.Init(appConfig)
err := c.SubscribeTrade(&model.SubscribeTradeParam{
  Symbol: "ETHUSDC",
}, func(message string) {
  log.Info(message)
})
ETH = {
    "id": 0,
    "symbol": "ETH",
}
USDC = {
    "id": 8,
    "symbol": "USDC",
}

def message_handler(message):
    if message is not None:
        print(message.decode("utf-8"))

wsClient = SpotWebsocketClient(tokens=[ETH,USDC])
wsClient.start()
wsClient.subscribeTrade(
    symbol="ETHUSDC",
    interval="1m",
    id=1,
    callback=message_handler,
)

Payload:

{
  "e": "trade",     // Event type
  "E": 123456789,   // Event time
  "s": "ETHUSDC",    // Symbol
  "t": 12345,       // Trade ID
  "p": "0.001",     // Price
  "q": "100",       // Quantity
  "b": 88,          // Buyer order ID
  "a": 50,          // Seller order ID
  "T": 123456785,   // Trade time
  "m": true,        // Is the buyer the market maker?
  "M": true         // Ignore
}

The Trade Streams push raw trade information; each trade has a unique buyer and seller.

Method: SubscribeTrade

Parameters:

Name Type Mandatory Description
Symbol STRING YES

Kline/Candlestick Streams

Example:

conf.Conf.AddToken(&model.TokenInfo{
  Symbol: "ETH",
  Id:     0,
})
conf.Conf.AddToken(&model.TokenInfo{
  Symbol: "USDC",
  Id:     8,
})
var appConfig = &conf.AppConfig{
    WebsocketBaseUrl: "wss://v1-mainnet-ws.degate.com",
}
c := &websocket.WebSocketClient{}
c.Init(appConfig)
err := c.SubscribeKline(&model.SubscribeKlineParam{
  Symbol:   "ETHUSDC",
  Interval: "1m",
}, func(message string) {
  log.Info(message)
})
ETH = {
    "id": 0,
    "symbol": "ETH",
}
USDC = {
    "id": 8,
    "symbol": "USDC",
}

def message_handler(message):
    if message is not None:
        print(message.decode("utf-8"))

wsClient = SpotWebsocketClient(tokens=[ETH,USDC])
wsClient.start()
try:
    wsClient.subscribeKline(symbol="ETHUSDC", id=10, interval="1m", callback=message_handler)
except Exception as e:
    logging.error(e)

Payload:

{
  "e": "kline",     // Event type
  "E": 123456789,   // Event time
  "s": "ETHUSDC",    // Symbol
  "k": {
    "t": 123400000, // Kline start time
    "T": 123460000, // Kline close time
    "s": "ETHUSDC",  // Symbol
    "i": "1m",      // Interval
    "f": 100,       // First trade ID
    "L": 200,       // Last trade ID
    "o": "0.0010",  // Open price
    "c": "0.0020",  // Close price
    "h": "0.0025",  // High price
    "l": "0.0015",  // Low price
    "v": "1000",    // Base asset volume
    "n": 100,       // Number of trades
    "x": false,     // Is this kline closed?
    "q": "1.0000",  // Quote asset volume
    "V": "500",     // Taker buy base asset volume
    "Q": "0.500",   // Taker buy quote asset volume
    "B": "123456"   // Ignore
  }
}

The Kline/Candlestick Stream push updates to the current klines/candlestick every second.

Method: SubscribeKline

Update Speed: 2000ms

Parameters:

Name Type Mandatory Description
Symbol STRING YES
Interval STRING YES Kline interval enum definition

Individual Symbol Ticker Streams

Example:

conf.Conf.AddToken(&model.TokenInfo{
  Symbol: "ETH",
  Id:     0,
})
conf.Conf.AddToken(&model.TokenInfo{
  Symbol: "USDC",
  Id:     8,
})
var appConfig = &conf.AppConfig{
    WebsocketBaseUrl: "wss://v1-mainnet-ws.degate.com",
}
c := websocket.WebSocketClient{}
c.Init(appConfig)
err := c.SubscribeTicker(&model.SubscribeTickerParam{
  Symbol: "ETHUSDC",
}, func(message string) {
  log.Info(message)
})
ETH = {
    "id": 0,
    "symbol": "ETH",
}
USDC = {
    "id": 8,
    "symbol": "USDC",
}

def message_handler(message):
    if message is not None:
        print(message.decode("utf-8"))

wsClient = SpotWebsocketClient(tokens=[ETH,USDC])
wsClient.start()
wsClient.subscribeTicker(
    symbol="ETHUSDC",
    id=1,
    callback=message_handler,
)

Payload:

{
  "e": "24hrTicker",  // Event type
  "E": 123456789,     // Event time
  "s": "ETHUSDC",      // Symbol
  "p": "0.0015",      // Price change
  "P": "250.00",      // Price change percent
  "w": "0.0018",      // Weighted average price
  "x": "0.0009",      // First trade(F)-1 price (first trade before the 24hr rolling window)
  "c": "0.0025",      // Last price
  "Q": "10",          // Last quantity
  "b": "0.0024",      // Best bid price
  "B": "10",          // Best bid quantity
  "a": "0.0026",      // Best ask price
  "A": "100",         // Best ask quantity
  "o": "0.0010",      // Open price
  "h": "0.0025",      // High price
  "l": "0.0010",      // Low price
  "v": "10000",       // Total traded base asset volume
  "q": "18",          // Total traded quote asset volume
  "O": 0,             // Statistics open time
  "C": 86400000,      // Statistics close time
  "F": "0",           // First trade ID
  "L": "18150",       // Last trade Id
  "n": 18151          // Total number of trades
}

24hr rolling window ticker statistics for a single trading pair symbol. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs.

Method: SubscribeTicker

Update Speed: 1000ms

Parameters:

Name Type Mandatory Description
Symbol STRING YES

Individual Symbol Book Ticker Streams

Example:

conf.Conf.AddToken(&model.TokenInfo{
  Symbol: "ETH",
  Id:     0,
})
conf.Conf.AddToken(&model.TokenInfo{
  Symbol: "USDC",
  Id:     8,
})
var appConfig = &conf.AppConfig{
    WebsocketBaseUrl: "wss://v1-mainnet-ws.degate.com",
}
c := websocket.WebSocketClient{}
c.Init(appConfig)
err := c.SubscribeBookTicker(&model.SubscribeBookTickerParam{
  Symbol: "ETHUSDC",
}, func(message string) {
  log.Info(message)
})
ETH = {
    "id": 0,
    "symbol": "ETH",
}
USDC = {
    "id": 8,
    "symbol": "USDC",
}

def message_handler(message):
    if message is not None:
        print(message.decode("utf-8"))

wsClient = SpotWebsocketClient(tokens=[ETH,USDC])
wsClient.start()
wsClient.subscribeBookTicker(
    symbol="ETHUSDC",
    id=18,
    callback=message_handler,
)

Payload:

{
  "e":"bookTicker",  // Event type
  "s":"ETHUSDC",     // symbol
  "b":"25.35190000", // best bid price
  "B":"31.21000000", // best bid qty
  "a":"25.36520000", // best ask price
  "A":"40.66000000"  // best ask qty
}

Pushes any update to the best bid or ask's price or quantity in real-time for a specified symbol.

Method: SubscribeBookTicker

Update Speed: Real-time

Parameters:

Name Type Mandatory Description
Symbol STRING YES

Partial Book Depth Streams

Example:

conf.Conf.AddToken(&model.TokenInfo{
  Symbol: "ETH",
  Id:     0,
})
conf.Conf.AddToken(&model.TokenInfo{
  Symbol: "USDC",
  Id:     8,
})
var appConfig = &conf.AppConfig{
    WebsocketBaseUrl: "wss://v1-mainnet-ws.degate.com",
}
c := websocket.WebSocketClient{}
c.Init(appConfig)
err := c.SubscribeDepth(&model.SubscribeDepthParam{
  Symbol: "ETHUSDC",
  Level:  5,
  Speed:  100,
}, func(message string) {
  log.Info(message)
})
ETH = {
    "id": 0,
    "symbol": "ETH",
}
USDC = {
    "id": 8,
    "symbol": "USDC",
}

def message_handler(message):
    if message is not None:
        print(message.decode("utf-8"))

wsClient = SpotWebsocketClient(tokens=[ETH,USDC])
wsClient.start()
wsClient.subscribeDepth(
    symbol="ETHUSDC",
    level=5,
    speed=100,
    id=39,
    callback=message_handler,
)

Payload:

{
  "lastUpdateId": 160,  // Last update ID
  "bids": [             // Bids to be updated
    [
      "0.0024",         // Price level to be updated
      "10"              // Quantity
    ]
  ],
  "asks": [             // Asks to be updated
    [
      "0.0026",         // Price level to be updated
      "100"             // Quantity
    ]
  ]
}

Pushes partial book depth streams.

Method: SubscribeDepth

Parameters:

Name Type Mandatory Description
Symbol STRING YES
Level INT YES 5/10/20
Speed INT YES 1000ms or 100ms

Diff. Depth Stream

Example:

conf.Conf.AddToken(&model.TokenInfo{
  Symbol: "ETH",
  Id:     0,
})
conf.Conf.AddToken(&model.TokenInfo{
  Symbol: "USDC",
  Id:     8,
})
var appConfig = &conf.AppConfig{
    WebsocketBaseUrl: "wss://v1-mainnet-ws.degate.com",
}
c := websocket.WebSocketClient{}
c.Init(appConfig)
err := c.SubscribeDepthUpdate(&model.SubscribeDepthUpdateParam{
  Symbol: "ETHUSDC",
  Speed:  100,
}, func(message string) {
  log.Info(message)
})
ETH = {
    "id": 0,
    "symbol": "ETH",
}
USDC = {
    "id": 8,
    "symbol": "USDC",
}

def message_handler(message):
    if message is not None:
        print(message.decode("utf-8"))

wsClient = SpotWebsocketClient(tokens=[ETH,USDC])
wsClient.start()
wsClient.subscribeDepthUpdate(
    symbol="ETHUSDC",
    speed=100,
    id=20,
    callback=message_handler,
)

Payload:

{
  "e": "depthUpdate", // Event type
  "E": 123456789,     // Event time
  "s": "DGBTC",      // Symbol
  "U": 157,           // First update ID in event
  "u": 160,           // Final update ID in event
  "b": [              // Bids to be updated
    [
      "0.0024",       // Price level to be updated
      "10"            // Quantity
    ]
  ],
  "a": [              // Asks to be updated
    [
      "0.0026",       // Price level to be updated
      "100"           // Quantity
    ]
  ]
}

Push the changed portion of the order book every second or every 100 milliseconds (if available).

Method: SubscribeDepthUpdate

Parameters:

Name Type Mandatory Description
Symbol STRING YES
Speed INT YES 1000ms or 100ms

Websocket Market Streams

Live Subscribing/Unsubscribing to streams

Subscribe to a stream

Response

  {
    "result": null,
    "id": 1
  }

In the DeGate Testnet, the TokenID for ETH is 0 and the TokenID for USDC is 2. Therefore, '0.2' is passed into the requests representing ETH and USDC.
* Request

{
"method": "SUBSCRIBE",
"params":
[
"0.2@aggTrade",
"0.2@depth"
],
"id": 1
}

Unsubscribe to a stream

Response

  {
    "result": null,
    "id": 312
  }

{
"method": "UNSUBSCRIBE",
"params":
[
"0.2@depth"
],
"id": 312
}

Listing Subscriptions

Response

  {
    "result": [
      "ethusdc@aggTrade"
    ],
    "id": 3
  }

{
"method": "LIST_SUBSCRIPTIONS",
"id": 3
}

Trade Streams

Payload:

{
  "e": "trade",     // Event type
  "E": 123456789,   // Event time
  "s": "DGBTC",    // Symbol
  "t": 12345,       // Trade ID
  "p": "0.001",     // Price
  "q": "100",       // Quantity
  "b": 88,          // Buyer order ID
  "a": 50,          // Seller order ID
  "T": 123456785,   // Trade time
  "m": true,        // Is the buyer the market maker?
  "M": true         // Ignore
}

Stream Name: <symbol>@trade

The Trade Streams push raw trade information; each trade has a unique buyer and seller.

Kline/Candlestick Streams

Payload:

{
  "e": "kline",     // Event type
  "E": 123456789,   // Event time
  "s": "ETHUSDC",    // Symbol
  "k": {
    "t": 123400000, // Kline start time
    "T": 123460000, // Kline close time
    "s": "ETHUSDC",  // Symbol
    "i": "1m",      // Interval
    "f": 100,       // First trade ID
    "L": 200,       // Last trade ID
    "o": "0.0010",  // Open price
    "c": "0.0020",  // Close price
    "h": "0.0025",  // High price
    "l": "0.0015",  // Low price
    "v": "1000",    // Base asset volume
    "n": 100,       // Number of trades
    "x": false,     // Is this kline closed?
    "q": "1.0000",  // Quote asset volume
    "V": "500",     // Taker buy base asset volume
    "Q": "0.500",   // Taker buy quote asset volume
    "B": "123456"   // Ignore
  }
}

The Kline/Candlestick Stream push updates to the current klines/candlestick every second.

Stream Name: <symbol>@kline_<interval>

Update Speed: 2000ms

Kline/Candlestick chart intervals: enum definition

Individual Symbol Ticker Streams

Payload:

{
  "e": "24hrTicker",  // Event type
  "E": 123456789,     // Event time
  "s": "ETHUSDC",      // Symbol
  "p": "0.0015",      // Price change
  "P": "250.00",      // Price change percent
  "w": "0.0018",      // Weighted average price
  "x": "0.0009",      // First trade(F)-1 price (first trade before the 24hr rolling window)
  "c": "0.0025",      // Last price
  "Q": "10",          // Last quantity
  "b": "0.0024",      // Best bid price
  "B": "10",          // Best bid quantity
  "a": "0.0026",      // Best ask price
  "A": "100",         // Best ask quantity
  "o": "0.0010",      // Open price
  "h": "0.0025",      // High price
  "l": "0.0010",      // Low price
  "v": "10000",       // Total traded base asset volume
  "q": "18",          // Total traded quote asset volume
  "O": 0,             // Statistics open time
  "C": 86400000,      // Statistics close time
  "F": 0,             // First trade ID
  "L": 18150,         // Last trade Id
  "n": 18151          // Total number of trades
}

24hr rolling window ticker statistics for a single symbol. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs.

Stream Name: <symbol>@ticker

Update Speed: 1000ms

Individual Symbol Book Ticker Streams

Payload:

{
  "u":400900217,     // order book updateId
  "s":"ETHUSDC",     // symbol
  "b":"25.35190000", // best bid price
  "B":"31.21000000", // best bid qty
  "a":"25.36520000", // best ask price
  "A":"40.66000000"  // best ask qty
}

Pushes any update to the best bid or ask's price or quantity in real-time for a specified symbol.

Stream Name: <symbol>@bookTicker

Update Speed: Real-time

Partial Book Depth Streams

Payload:

{
  "lastUpdateId": 160,  // Last update ID
  "bids": [             // Bids to be updated
    [
      "0.0024",         // Price level to be updated
      "10"              // Quantity
    ]
  ],
  "asks": [             // Asks to be updated
    [
      "0.0026",         // Price level to be updated
      "100"             // Quantity
    ]
  ]
}

Top bids and asks, Valid levels are 5, 10, or 20.

Stream Names: <symbol>@depth<levels> or <symbol>@depth<levels>_100ms.

Update Speed: 1000ms or 100ms

Diff. Depth Stream

Payload:

{
  "e": "depthUpdate", // Event type
  "E": 123456789,     // Event time
  "s": "DGBTC",      // Symbol
  "U": 157,           // First update ID in event
  "u": 160,           // Final update ID in event
  "b": [              // Bids to be updated
    [
      "0.0024",       // Price level to be updated
      "10"            // Quantity
    ]
  ],
  "a": [              // Asks to be updated
    [
      "0.0026",       // Price level to be updated
      "100"           // Quantity
    ]
  ]
}

Push the changed portion of the order book every second or every 100 milliseconds (if available).

Stream Name: <symbol>@depth or <symbol>@depth@100ms

Update Speed: 1000ms or 100ms

User Data Streams

Listen KEY

Example:

var appConfig = &conf.AppConfig{
    AccountId:        7,
    AccountAddress:   "0xBA2b5FEae299808b119FD410370D388B2fBF744b",
    AssetPrivateKey:       <DeGate AssetPrivateKey>,
}
c := new(spot.Client)
c.SetAppConfig(appConfig)
response, err := c.NewListenKey()
AccountAddress = "0xba2b5feae299808b119fd410370d388b2fbf744b"
AssetPrivateKey =  <DeGate AssetPrivateKey>
AccountId = 2475

client = Client(AccountAddress, AssetPrivateKey, AccountId)
try:
    response = client.newListenKey()
    logging.info(response["listenKey"])
except Exception as e:
    logging.error(e)

Response

{
  "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1"
}

Create a ListenKey

Method: NewListenKey

Start a new user data stream. The stream will close after 60 minutes unless a keepalive is sent. If the account has an active listenKey, that listenKey will be returned and its validity will be extended for 60 minutes.

Weight(IP): 1

Parameters:

NONE

Data Source: Memory


Ping/Keep-alive a ListenKey

Method: ReNewListenKey

Keepalive a user data stream to prevent a time out. User data streams will close after 60 minutes. It's recommended to send a ping in every 30 minutes.

Weight(IP): 1

Parameters:

Name Type Mandatory Description
ListenKey STRING YES

Data Source: Memory

Example

var appConfig = &conf.AppConfig{
    AccountId:        7,
    AccountAddress:   "0xBA2b5FEae299808b119FD410370D388B2fBF744b",
    AssetPrivateKey:       <DeGate AssetPrivateKey>,
}
c := new(spot.Client)
c.SetAppConfig(appConfig)
response, err := c.ReNewListenKey(&model.ListenKeyParam{
        ListenKey: "",
})
AccountAddress = "0xba2b5feae299808b119fd410370d388b2fbf744b"
AssetPrivateKey =  <DeGate AssetPrivateKey>
AccountId = 2475
client = Client(AccountAddress, AssetPrivateKey, AccountId)
try:
    response = client.reNewListenKey("")
    logging.info(response)
except Exception as e:
    logging.error(e)

Response

{}


Close a ListenKey

Method: DeleteListenKey

Close out a user data stream.

Weight(IP): 1

Parameters:

Name Type Mandatory Description
ListenKey STRING YES

Data Source: Memory

Example

var appConfig = &conf.AppConfig{
    AccountId:        7,
    AccountAddress:   "0xBA2b5FEae299808b119FD410370D388B2fBF744b",
    AssetPrivateKey:       <DeGate AssetPrivateKey>,
}
c := new(spot.Client)
c.SetAppConfig(appConfig)
response, err := c.DeleteListenKey(&model.ListenKeyParam{
        ListenKey: "",
})
AccountAddress = "0xba2b5feae299808b119fd410370d388b2fbf744b"
AssetPrivateKey =  <DeGate AssetPrivateKey>
AccountId = 2475
client = Client(AccountAddress, AssetPrivateKey, AccountId)
try:
    response = client.deleteListenKey("")
    logging.info(response)
except Exception as e:
    logging.error(e)

Response

{}

Subscribe

Example

var appConfig = &conf.AppConfig{
    WebsocketBaseUrl: "wss://v1-mainnet-ws.degate.com",
}
c := websocket.WebSocketClient{}
c.Init(appConfig)
c.SubscribeUserData(&model.SubscribeUserDataParam{
  ListenKey: "",
}, func(message string) {
  log.Info(message)
})
def message_handler(message):
    if message is not None:
        print(message.decode("utf-8"))

AccountAddress = "0xba2b5feae299808b119fd410370d388b2fbf744b"
AssetPrivateKey =  <DeGate AssetPrivateKey>
AccountId = 2475
client = Client(AccountAddress, AssetPrivateKey, AccountId)
response = client.new_listen_key()
ws_client = SpotWebsocketClient()
ws_client.start()
ws_client.user_data(
    listen_key=response["listenKey"],
    id=1,
    callback=message_handler,
)

Method: SubscribeUserData

Parameters:

Name Type Mandatory Description
ListenKey STRING YES

Payload: Account Update

Payload

{
  "e": "outboundAccountPosition", //Event type
  "E": 1564034571105,             //Event Time
  "u": 1564034571073,             //Time of last account update
  "B": [                          //Balances Array
    {
      "a": "ETH",                 //Asset
      "f": "10000.000000",        //Free
      "l": "0.000000"             //Locked
      "i": 0,                     //token id
    }
  ]
}

outboundAccountPosition is sent any time an account balance has changed and contains the assets that were possibly changed by the event that generated the balance change.

Payload: Balance Update

Payload

{
  "e": "balanceUpdate",         //Event Type
  "E": 1573200697110,           //Event Time
  "a": "ABC",                   //Asset
  "v": "100.00000000",          //Balance available
  "T": 1573200697068            //Clear Time
  "i": 0,                       //token id
}

Balance Update occurs during the following:

Payload: Order Update

Payload

{
  "e": "executionReport",        // Event type
  "E": 1499405658658,            // Event time
  "s": "ETHUSDC",                // Symbol
  "c": "mUvoqJxFIILMdfAW5iGSOW", // Client order ID
  "S": "BUY",                    // Side
  "o": "LIMIT",                  // Order type
  "q": "1.00000000",             // Order quantity
  "p": "0.10264410",             // Order price
  "x": "NEW",                    // Current execution type
  "X": "NEW",                    // Current order status
  "r": "",                       // Order reject reason;
  "i": "4293153",                // Order ID
  "z": "0.00000000",             // Cumulative filled quantity
  "n": "0",                      // Commission amount
  "N": null,                     // Commission asset
  "T": 1499405658657,            // Transaction time
  "t": "",                       // Trade ID
  "w": true,                     // Is the order on the book?
  "O": 1499405658657,            // Order creation time
  "Z": "0.00000000",             // Cumulative quote asset transacted quantity
  "Q": "0.00000000"              // Quote Order Qty
  "l": "0.00000000",             // Last executed quantity
  "L": "0.00000000",             // Last executed price
  "m": true,                     // Is this trade the maker side?
  "Y": "0.00000000",             // Last quote asset transacted quantity (i.e. lastPrice * lastQty)
  "W": 1499405658657,            // Working Time; This is only visible if the order has been placed on the book.
  "P": 1,                        // pair id
  "B": 0,                        // base token id
  "U": 2,                        // quote token id 
}

Orders are updated with the executionReport event.

Check the Public API Definitions and below for relevant enum definitions.

Average price can be calculated by doing Z(the cumulative turnover) divided by z(the cumulative volume of orders filled).

Execution types:

Payload: Trade Streams

Payload:

{
  "e": "accountTrade",     // event type
  "E": 123456789,   // event time
  "s": "ETHUSDC",   // pair name
  "B": 1,           // baseTokenID
  "U": 0,           // quoteTokenID
  "P": 10,          // pair id
  "t": 12345,       // trade id
  "p": "0.001",     // price
  "q": "100",       // amount
  "Q": "10",        // quote amount
  "b": 88,          // buyer order id
  "y": 0,           // buyer order type
  "c": "100",       // buyer order order amount
  "o": 10,          // buyer token id
  "k": true,        // buyer is market?
  "a": 50,          // seller order ID
  "Y": 0,           // Seller order type
  "C": "100",       // seller order amount
  "O": 11,          // seller token id
  "K": false,       // is seller market?
  "f":"10",         // gas fee
  "x":"10",         // max gas fee
  "i": 20,          // fee ratio
  "r": "20"         // feeratio ‱
  "T": 123456785,   // time 
  "m": true,        // Whether the buyer is a market maker. If true, then this transaction is an active sell order, otherwise it is an active buy order.
  "M": true,        // is buy
}

The Trade Streams push raw trade information; each trade has a unique buyer and seller.