# Gate API v4 v4.74.1

    Scroll down for code samples, example requests and responses. Select a language for code samples from the tabs above or the mobile navigation menu.

    Welcome to Gate.io API

    APIv4 provides spot, margin and futures trading operations. There are public APIs to retrieve the real-time market statistics, and private APIs which needs authentication to trade on user's behalf.

    # Access URL

    REST API BaseURL:

    • Live trading: https://api.gateio.ws/api/v4
    • Futures TestNet trading: https://fx-api-testnet.gateio.ws/api/v4
    • Futures live trading alternative (futures only): https://fx-api.gateio.ws/api/v4

    # SDK

    Available SDK:

    Besides API examples, some SDK provides an additional demo application. The demo application is a relatively complete example demonstrating how to use the SDK. It can be built and run separately. Refer to corresponding repository for details.

    # About APIv4 key improvement

    Previously(before April 2020) futures APIv4 key are separated from spot one, but this is no longer the case anymore. You can create multiple keys with each key having multiple permissions now. e.g. you can create one key with spot read/write and futures read/write permission which can be used in both spot and futures trading.

    History API keys will not be affected by this improvement. Previous spot key and futures key are now one key with only spot permissions enabled, another only futures permission enabled. You can reconfigure their permissions after migration.

    # Comparison with APIv2

    APIv4 is a standalone brand-new HTTP REST API, currently used in parallel with APIv2. APIv4 provides complete trading operations, with more highly secured authentication method. What's more, APIv4 specification is written following OpenAPI Specification (opens new window). SDKs and documents are all generated from the same spec, which ensures consistency between documents and implementation.

    The ways APIv4 and APIv2 differ are:

    1. Their API keys are separated from each other. Once logged into the web console, v2 API keys are generated on "APIKeys" page, while v4 "APIv4Keys" page.
    2. APIv2 supports only spot trading, while v4 supports all trading operations in spot, margin and futures.

    Which one to choose:

    1. If margin or futures trading are needed, choose APIv4.
    2. If only spot trading or wallet operation is required, choose on your own.

    # Application for Marketers

    In order to further improve the platform's opening depth and trading liquidity, we will recruit institutional market makers in an open and transparent way, and provide a professional market maker's service rate scheme for professional institutional market makers according to their contribution to the platform's liquidity.

    1. Provide Gateio UID
    2. Provide other transaction volume screenshot or VIP level
    3. Brief introduction of market making method and scale

    Provide the above content and submit to [email protected] , we will accept within 3 working days.

    TIP

    Vip11 and above need to open GT deduction in the personal center to enjoy the professional market rate.

    # Technical Support

    If you have any questions or suggestions during the use, you can contact us in any of the following ways:

    • Submit Work Order Feedback
    • Online Work Order Feedback
    • Send your contact information and questions to [email protected] We will assign technical specialists to serve you.

    If you encounter API errors, it is recommended that you sort out the following content, so that we can quickly analyze the problem for you:

    1. Problem Description
    2. Gateio UID
    3. Request URI and parameters
    4. Error Code
    5. Responses

    DANGER

    Even if you submit a problem, you should not submit the API key information to customer service or others, otherwise there will be serious asset risk. If it has been accidentally leaked, please delete the existing API and rebuild it.

    # Changelog

    v4.74.1

    2024-06-11

    • Optimization of DOM for the visible area on mobile devices

    v4.74.0

    2024-05-29

    • New feature: add GET /unified/loan_margin_tiers endpoint, list loan margin tiers

    v4.73.0

    2024-05-27

    • Add is_all parameter in POST /wallet/small_balance endpoint
    • Add text field in POST /spot/cancel_batch_orders response
    • Add fundingfunding_versionuse_funding field in GET /unified/accounts response

    v4.72.0

    2024-05-13

    • Add last_access field in GET /sub_accounts/{user_id}/keys response
    • Add contract field in GET /futures/{settle}/risk_limit_tiers response

    v4.71.0

    2024-04-23

    • Add page parameter in GET /wallet/saved_address endpoint
    • New feature: add GET /api/v4/rebate/user/info endpoint, retrieve user rebate information
    • New feature: add POST /unified/portfolio_calculator endpoint, portfolio margin calculator
    • New feature: add GET /unified/risk_units endpoint, retrieve user risk unit
    • New feature: add PUT /unified/unified_mode endpoint, set unified account mode
    • New feature: add GET /unified/unified_mode endpoint, retrieve unified account mode

    v4.70.0

    2024-04-08

    • Add pnl_pnlpnl_fundpnl_fee field in GET /futures/{settle}/positions response
    • Add pnl_pnlpnl_fundpnl_fee field in GET /futures/{settle}/position_close response

    v4.69.0

    2024-03-25

    • Add text field in POST /delivery/{settle}/price_orders response

    v4.68.0

    2024-03-18

    • New feature: add GET /unified/currency_discount_tiers endpoint, list currency discount tiers
    • Add type parameter in GET /unified/loans endpoint
    • Add type parameter in GET /unified/interest_records endpoint

    v4.67.0

    2024-03-11

    • Add filled_amount field in POST /spot/orders,POST /spot/batch_orders response
    • In frequency limit rule for the wallet withdrawal interface, the speed limit description has been corrected from 10r/10s to 1r/3s(No modification to the original rate limiting behavior)

    v4.66.1

    2024-02-19

    • New feature: add GET /wallet/small_balance endpoint, list small balance.
    • New feature: add GET /wallet/small_balance_history endpoint, list small balance history.
    • New feature: add GET /unified/estimate_rate endpoint, get unified estimate rate.

    v4.65.0

    2024-01-29

    • Add debit_fee field in GET /spot/batch_fee response
    • Add user_id parameter in DELETE /account/stp_groups/{stp_id}/users endpoint
    • Spot API introduces asynchronous support modes for create orders: ACK, RESULT, FULL. For details, please refer to SPOT API

    v4.64.0

    2024-01-22

    • Add order_type parameter in GET /loan/multi_collateral/orders endpoint
    • Add order_type,fixed_type,fixed_rate,expire_time,auto_renew,auto_repay field in GET /loan/multi_collateral/orders response
    • Add before_ltv,after_ltv field in GET /loan/multi_collateral/repay response
    • New feature: add GET /loan/multi_collateral/fixed_rate endpoint, query multi-collateral fix rate.
    • Add unrealised_pnl,borrowed field in GET /wallet/total_balance response

    v4.63.0

    2024-01-15

    • Add decimal field in GET /wallet/currency_chains response
    • New feature: add GET /futures/{settle}/risk_limit_tiers endpoint, list risk limit tiers.

    v4.62.0

    2024-01-02

    • New feature: add POST /futures/{settle}/batch_cancel_orders endpoint, users have the ability to batch cancel orders.
    • New feature: add multi-collateral-loan api. (/loan/multi_collateral/**)

    v4.61.0

    2023-12-18

    • New features: The broker obtains the user's commission rebate records in GET /rebate/broker/commission_history and GET /rebate/broker/commission_history endpoints

    v4.60.0

    2023-12-01

    • Breaking change: New Unified API is online. The old /portfoli/* endpoints are deprecated.
    • New features: add earn product api. (/earn/**)
    • Add trade_id field in GET /futures/{settle}/account_book response

    v4.59.0

    2023-11-22

    • Add funding_cap_ratio field in GET /futures/{settle}/contracts response
    • Add contract field in GET /delivery/{settle}/account_book response
    • Add withdraw_percent_on_chains field in GET /wallet/withdraw_status response
    • Add leverage field in GET /portfolio/accounts response

    v4.58.0

    2023-11-03

    • Add loanable field in GET /margin/cross/currencies response
    • Add biz_info field in GET /futures/{settle}/orders/{order_id} response
    • Add tier field in GET /account/detail response
    • Add max_base_amountmax_quote_amount field in GET /spot/currency_pairs response

    v4.57.0

    2023-10-20

    • New feature: API Gateway inbound & outbound time, For more details, please refer to the API Gateway in/out time
    • New feature: support portfolio account in POST /spot/orders endpoint
    • New feature: add PUT /earn/uni/interest_reinvest endpoint, users have the option to enable or disable interest reinvestment.
    • New feature: add POST /spot/amend_batch_orders endpoint, users have the ability to batch modify orders.
    • Add sequence_id field in GET /spot/trades response
    • Add text field in GET /spot/account_book response
    • Add text field in GET /spot/my_trades response
    • GET /portfolio/spot/ordersGET /portfolio/spot/ordersGET /portfolio/spot/orders/{order_id}DELETE /portfolio/spot/orders/{order_id} and PATCH /portfolio/spot/orders/{order_id} have been deprecated. We will remove the endpoints by the end of October 2023. Please use /spot/orders instead.

    v4.56.0

    2023-09-25

    • Add repayment_type field in GET /margin/cross/repayments and GET /portfolio/loan_records endpoints.
    • Add request parameter holding in GET /futures/{settle}/positions endpoint
    • Add request parameter role in GET /futures/{settle}/my_trades_timerange endpoint
    • Add request parameter side and pnl in GET /futures/{settle}/position_close endpoint

    v4.55.0

    2023-09-12

    • Add new POST /portfolio/account_mode endpoint, allow to change the mode.

    v4.54.0

    2023-08-28

    • Add contract_address field in GET /wallet/currency_chains endpoint.
    • Add GET /portfolio/spot/currency_pairs and GET /portfolio/spot/currency_pairs/{currency_pair} endpoints, list portfolio spot's currency pairs.

    v4.53.0

    2023-08-14

    • New feature: delete user in STP group in DELETE /account/stp_groups/{stp_id}/users endpoint

    v4.52.0

    2023-08-07

    • New feature: add collateral loan api

    v4.51.0

    2023-07-29

    • Adjusted and optimized the account book types
    • Add mode field in GET /account/detail edpoint.

    v4.50.0

    2023-07-14

    • New feature: New Portfolio API. Currently, these services are only available to whitelisted users. If you are interested in accessing these APIs, please contact our institutional department for further information.
    • Add new endpoint GET /flash_swap/currency_pairs, list all flash swap currency pair

    v4.49.0

    2023-07-03

    • Add new frequency limit rule,the new rule is expected to take effect on 2023-07-10 (UTC+8)
    • In the GET /futures/{settle}/orders API endpoint, the request field contract has been modified to be optional instead of mandatory.

    v4.48.0

    2023-06-16

    • Add client_order_id fields in GET /wallet/sub_account_transfers edpoint.

    v4.47.0

    2023-05-23

    • New feature: add STP group admin api
    • New feature: query estimated interest rates of margin and cross margin in GET /margin/uni/estimate_rate and GET /margin/cross/estimate_rate endpoints.
    • New feature: list futures order by time range in GET /futures/{settle}/orders_timerange endpoint
    • Add underlyingunderlying_pricemark_ivdeltagammavegatheta fields in GET /options/positions/{contract} endpoint.

    v4.46.0

    2023-05-08

    • New feature: query spot account book in GET /spot/account_book endpoint
    • New feature: query user futures trading fee in GET /futures/{settle}/fee endpoint
    • Add is_internal field in GET /futures/{settle}/trades endpoint

    v4.45.0

    2023-04-21

    • The margin loan has been migrated to the Lend & Earn. For more information, please refer to the Margin Migration Instructions
    • New feature: Get interest records for the cross margin account in GET /margin/cross/interest_records endpoint.
    • New feature: Add Self-Trade Prevention feature in the POST /futures/{settle}/batch_orders endpoint.
    • Add futures_infutures_out two fields in GET /margin/cross/account_book endpoint.

    v4.44.0

    2023-04-07

    • Add ORDER_BOOK_NOT_FOUND and FAILED_RETRIEVE_ASSETS error messages.

    v4.43.0

    2023-03-27

    • New feature: Add Self-Trade Prevention feature in the POST /spot/orders endpoint. Fore more detail, please refer to STP overview
    • New feature: Get API key's ip whitelist in GET /account/detail endpoint.
    • Add amend_text in PATCH /spot/orders/{order_id} endpoint.
    • Add lowest_ask and highest_bid fields in GET /futures/{settle}/tickers endpoint

    v4.42.0

    2023-03-13

    • New feature: add Lend & Earn API
    • New feature: Add Self-Trade Prevention feature in the POST /futures/{settle}/orders endpoint. Fore more detail, please refer to STP overview
    • Add delivery account type in POST /wallet/sub_account_transfers endpoint
    • Add amend_text field in PUT /futures/{settle}/orders/{order_id} endpoint

    v4.41.0

    2023-03-03

    • Add negative_liab, futures_pos_liab, equity, total_freeze, total_liab, portfolio_margin_total_liab, portfolio_margin_total_equity fields in GET /margin/cross/accounts endpoint

    v4.40.0

    2023-02-24

    • New feature: List Auto-Deleveraging history endpoint Get /futures/{settle}/auto_deleverages
    • Add sum field in GET /futures/{settle}/candlesticks endpoint

    v4.39.0

    2023-02-09

    • New feature: Query a batch of user trading fee rate endpoint GET /spot/batch_fee
    • Add enable_bonusenable_credit fields in GET /futures/{settle}/contracts endpoint

    v4.38.0

    2023-02-04

    • New feature: time range query for my futures trade endpoint GET /futures/{settle}/my_trades_timerange
    • Add withdraw_order_id field in POST /withdrawals endpoint

    v4.37.0

    2023-01-20

    • Add new rebate API endpoints.

    v4.36.0

    2022-12-23

    • Hiding all amount is not supported any more when using iceberg in POST /spot/orders and POST /spot/batch_orders endpoints

    v4.35.0

    2022-12-09

    • New feature: amend order endpoint /spot/orders/{order_id}
    • Add avg_deal_price field in GET /spot/orders response
    • Add portfolio_margin_total field in ``GET /margin/cross/accounts` response
    • Support market order in POST /spot/batch_orders endpoint

    v4.34.0

    2022-11-25

    • Support market order in POST /spot/orders endpoint

    v4.33.0

    2022-11-11

    • New feature: Futures Premium Index endpoint GET /futures/{settle}/premium_index
    • Allow to specify password and email when creating a sub-account.

    v4.32.0

    2022-10-28

    • Improve options api document

    v4.31.0

    2022-10-14

    • Allow to transfer futures and cross_margin funds between two sub-accounts in POST /wallet/sub_account_to_sub_account endpoint

    v4.30.0

    2022-09-23

    • New feature: manage sub-accounts API Key
    • New feature: lock and unlock sub-account endpoint
    • Allow to transfer between two sub-accounts in POST /wallet/sub_account_to_sub_account endpoint

    v4.29.0

    2022-09-09

    • New feature: create and list sub-accounts
    • Add settle parameter in GET /wallet/fee endpoint
    • Add refr field in option order
    • The maximum number of API Keys changes to 20

    v4.28.0

    2022-08-12

    • Add offset parameter in GET /futures/{settle}/trades
    • new countdown cancel orders endpoint for spot and futures.

    v4.27.0

    2022-07-29

    • Add basis_ratebasis_value fields in GET /delivery/{settle}/tickers response
    • Add X-Client-Request-Id http header for tracking request
    • new create a batch of futures order endpoint POST /futures/{settle}/batch_orders
    • new FOK tif type for futures order

    v4.26.0

    2022-07-15

    • Spot Price-Trigger order supports portfolio margin account
    • Add GET /wallet/saved_address to list saved address
    • POST /wallet/transfers returns tx_id field
    • Add GET /wallet/sub_account_cross_margin_balances to query subaccount's cross_margin account
    • Add status field in GET /margin/currency_pairs response

    v4.25.1

    2022-07-06

    • New GET /spot/time endpoint which get system's time info.
    • New GET /options/my_settlements endpoint which list my selttlements.
    • Add change_utc0, change_utc8 fields in GET /spot/tickers endpoint

    v4.25.0

    2022-06-24

    • Support portfolio margin account API
    • Cross-margin add more fields. Please refer to endpoint document for more details.
    • Add status field in GET /margin/cross/currencies endpoint, determine whether the cross currency is disabled 0-disable 1-enable
    • New POST /spot/cross_liquidate_orders spot trading endpoint that close position when the cross-currency is disabled
    • Add bouns and history fields in GET /futures/{settle}/accounts endpoint
    • Add textfee and point_fee fields in GET /futures/{settle}/my_trades endpoint
    • Fix typo for cancel a price-triggered order endpoints
    • POST /wallet/sub_account_transfers supports transferring to cross_margin

    v4.24.0

    2022-05-20

    • Support flash swap operations with new API group /flash_swap. Spot operation permission is required.
    • New wallet APIs GET /wallet/sub_account_margin_balances and GET /wallet/sub_account_futures_balances to help main account retrieving sub accounts' margin and perpetual contract balances
    • New perpetual contract API GET /futures/{settle}/index_constituents/{index} to retrieve index price constituents
    • Fix missing fields like order_type in FuturesPriceTriggeredOrder

    v4.23.4

    2022-04-25

    • Add PUT /futures/{settle}/orders/{order_id} to amend perpetual futures orders
    • Spot candlesticks supports 30d interval

    v4.23.3

    2022-04-01

    1. Spot candlestick API returns base currency amount
    2. Spot currency detail add chain field.
    3. Add withdrawal and deposit status in GET /wallet/currency_chains response
    4. Add missing cross_leverage_limit in perpetual contract's dual mode position leverage update API
    5. Support more intervals in perpetual and delivery contract candlesticks

    v4.23.2

    2022-01-21

    1. Add fee in withdrawal and deposit history
    2. Add fix fee rate in spot Currency

    v4.23.1

    2021-12-23

    1. Spot orders support new time_in_force FOK
    2. New FOK_NOT_FILL error label

    v4.23.0

    2021-12-09

    1. Add options API
    2. Add detailed rate limiting rules
    3. Add GET /wallet/currency_chains to retrieve chains supported by currency
    4. Add additional status for deposit and withdrawal history

    v4.22.4

    2021-11-01

    1. Data type of ctime and ftime in SpotPriceTriggeredOrder should be int64

    v4.22.3

    2021-10-27

    1. GET /spot/trades supports time range based query using from and to.

    v4.22.2

    2021-09-29

    1. Add more status in withdrawal or deposit record model
    2. Add new write only field auto_size in FuturesOrder to support closing dual mode position.

    v4.22.1

    2021-09-07

    1. New wallet API GET /wallet/total_balance to retrieve all user's estimate balance.
    2. Add locked and risk in margin account response
    3. Margin and cross margin loans support custom text input.

    v4.22.0

    2021-08-13

    1. Delivery contract API supports BTC settled
    2. Spot API GET /spot/orders and GET /spot/my_trades supports query by time range
    3. Add margin and cross margin max borrowable API
    4. Multiple document enhancements.

    v4.21.6

    2021-08-12

    1. Fix incorrect address field name in GET /wallet/deposit_address

    v4.21.5

    2021-06-30

    • GET /spot/orders, GET /spot/orders/{order_id} and GET /spot/my_trades allow empty currency_pair if operated against finished orders
    • Add fixed withdrawal fee on multiple chains in GET /wallet/withdraw_status response
    • Add GET /margin/transferable and GET /margin/cross/transferable to retrieve maximum transferable amount from margin and cross margin account
    • Add from and to parameter to specify time range for futures position closes history API

    v4.21.4

    2021-06-23

    • Add cross margin account change history API GET /margin/cross/account_book
    • Add millisecond timestamp in GET /margin/account_book response

    v4.21.3

    2021-06-17

    • Add order book timestamp for both spot and futures trading

    v4.21.2

    2021-06-07

    • Futures API support cross margin leverage modification
    • Add new spot cross margin API /margin/cross
    • Add spot order operations using spot cross margin account
    • Add unpaid interests in spot margin account query
    • Add new millisecond fields create_time_ms and update_time_ms in spot orders.
    • Add DELETE /withdrawals/{withdrawal_id} to cancel withdrawal operation

    v4.20.1

    2021-04-14

    • Update document links

    v4.20.0

    2021-03-25

    • Support spot auto orders with API group /spot/price_orders

    v4.19.6

    2021-03-22

    • Add trading timestamp in spot currency pair

    v4.19.5

    2021-03-18

    • Spot and Futures operations based on order ID also accept user custom ID(but only for 30 minutes since creation)

    v4.19.4

    2021-03-10

    • /wallet/sub_account_transfers supports transferals with sub user's perpetual contract account

    v4.19.3

    2021-03-04

    • Add margin loans auto repay API /margin/auto_repay
    • Add multichain_address in /wallet/deposit_address for currencies with multiple deposit addresses
    • Optimize documentation

    v4.19.2

    2021-03-01

    • Add /wallet/fee API to retrieve trading fee. Previous /spot/fee is deprecated in favour of this one.
    • Add new field chain in withdrawal operation.
    • Add new field with_id in /futures/{settle}/order_book API and id field in its response
    • Add new offset in API /futures/{settle}/position_close to retrieve position close history with pagination.
    • Add contract value calculation. Refer to Contract model for details.
    • Fix incorrect field type in futures stats API

    v4.18.4

    2021-01-22

    • Add field create_time_ms in spot Trade model
    • ETF currency pairs' ticker add net value related info

    v4.18.1

    2021-01-07

    • Add iceberg order support for spot orders
    • Fix incorrect field types in /futures/{settle}/contract_stats

    v4.18.0

    2020-12-21

    • Add new spot API/spot/currencies and /spot/currencies/{currency} to retrieve currency info
    • Add more fields, e.g., top_lsr_account, top_lsr_size, in futures ContractStat model.

    v4.17.1

    2020-12-16

    • Increase maximum of limit in /spot/order_book to 100

    v4.17.0

    2020-12-15

    • Add /wallet/sub_account_balances to retrieve sub accounts' balances.

    v4.16.1

    2020-12-10

    • Fix mistaken field name dual_mode in futures position model which should be mode instead.

    v4.16.0

    2020-12-09

    Spot

    • Increase order number limit each currency pair to 10 in POST /spot/batch_orders
    • Add new query parameter reverse in GET /spot/trades to trace back trading history

    Futures

    • Add perpetual contract dual mode position support. Use /futures/{settle}/dual_mode to set position's dual mode. For dual mode position operations, refer to /futures/{settle}/dual_comp/positions API group
    • Add perpetual contract new field in_dual_mode in futures account response model; dual_mode in position response model.
    • Add new perpetual contract public API /futures/{settle}/liq_orders to query liquidated orders in markets

    v4.15.5

    2020-11-04

    • Add /futures/{settle}/contract_stats API to retrieve contract stats
    • Add /margin/{currency_pair} to retrieve single margin currency pair detail

    v4.15.4

    2020-09-01

    • Add point_type in GET /spot/fee response
    • Add GET /wallet/withdraw_status API
    • Add C# SDK entry

    v4.15.2

    2020-08-12

    • Add GET /spot/fee to retrieve spot order trading fee rates

    v4.15.1

    2020-08-04

    • Add GET /spot/open_orders to retrieve all open orders in spot trading
    • Add GET /margin/account_book to retrieve margin account balance history

    v4.14.1

    2020-07-08

    • maximum length of text field in order extends to 28(prefix excluded)

    v4.14.0

    2020-07-06

    • New Delivery contract APIs /delivery

    v4.13.1

    2020-06-28

    • Add GET /wallet/sub_account_transfers to list sub account transfer records

    v4.13.0

    2020-05-20

    • APIv4 now supports withdraw API. Refer to POST /withdrawals and "Authentication" section for details.
    • POST /wallet/transfers supports transferring between spot and futures account
    • Wallet API supports retrieving deposits and withdrawals history
    • Futures orders and personal trades retrieving now supports offset field
    • Futures Contract model add new field in_delisting

    v4.12.0

    2020-04-08

    • APIv4 Key management improved. Keys are no longer separated with different trading types. Every key can now have multiple operation permissions. Refer to "About APIv4 key improvement" for details.
    • Add POST /wallet/sub_account_transfers to support transferring between main and sub account
    • GET /spot/candlesticks adds query parameters from and to to support retrieving history data points

    v4.11.2

    2020-03-29

    • Add filled_total in Order to replace fill_price (the latter is badly named)
    • Add new error label POC_FILL_IMMEDIATELY

    v4.11.1

    2020-03-23

    • Add role in GET /spot/my_trades response
    • Fix missing currency account in GET /margin/funding_accounts

    v4.11.0

    2020-03-20

    • Spot order supports GT fee discount
    • Spot order time in force supports poc

    v4.10.1

    2020-02-24

    • Add trade_status in spot currency pair

    v4.10.0

    2020-02-17

    • Margin order creation adds new field auto_borrow(write only) to borrow the insufficient part by the system if balance is not enough
    • Add new API POST /spot/cancel_batch_orders to support batch cancellation with specified order IDs
    • Add new document section "Error handling" and "Which one to choose, APIv4 or APIv2?"

    v4.9.1

    2020-01-07

    • Add fee and recent modification time in Order and BatchOrder
    • Add fee in GET /spot/my_trades response

    v4.9.0

    2019-12-17

    • last_id in GET /futures/{settle}/trades is deprecated. Use from and to to retrieve trading history

    v4.8.2

    2019-12-02

    • Add /spot/batch_orders to support creating a bundle of spot or margin orders
    • Fee rate of margin loan repayment enjoys VIP discount
    • Loan add new fields fee_rate(fee rate of lending loan) and orig_id(original loan ID if loan is auto renewed)

    v4.8.1

    2019-11-27

    • Fix missing settle in GET /futures/{settle}/positions docs and code snippet

    v4.8.0

    2019-11-07

    • Futures API now supports settling in USDT.
    • Change /futures to /futures/{settle} in ALL futures API to support futures operations in different settle currency.
    • currency field in /futures/{settle}/accounts response adds new value: USDT
    • Add volume_24h_base, volume_24h_quote and volume_24h_settle in /futures/{setttle}/tickers response to replace volume_24h_btc and volume_24h_usd. The latter two are still preserved for compatibility usage, but are NOT recommended for any futures operations.

    To use USDT futures, just replace /futures with /futures/usdt, e.g. use GET /futures/usdt/accounts to retrieve futures accounts settled in USDT, while GET /futures/btc/accounts returns accounts in BTC.

    For compatibility, GET /futures/xxx defaults to GET /futures/btc/xxx, e.g. GET /futures/accounts will be treated as GET /futures/btc/accounts

    v4.7.3

    2019-07-18

    • Add text in /spot/orders and /futures/orders to support user defined order information

    v4.6.3

    2019-06-11

    • Add point information in Futures account and position

    v4.7.2

    2019-05-29

    • Change rate in Loan as non-required for lending side.

    v4.7.1

    2019-04-17

    • Add wallet v4 API. Support transfers between spot and margin account for now.
    • GET /margin/loans can sort by rate and support an optional parameter currency_pair
    • Fix miscellaneous document issues

    v4.6.2

    2019-04-24

    • Fix price-triggered futures order's docs incorrect override docs for GET /futures/orders/{order_id} and DELETE /futures/orders/{order_id}

    v4.6.1

    2019-04-02

    • Add high_24h, low_24h and funding_rate_indicative in futures ticker

    v4.6.0

    2019-03-21

    SDK related only

    • Rename futures order related function name in SDKs to avoid duplication with spot order API in Go
    • Fix query parameter not decoded while generating authentication signature

    v4.5.2

    2019-03-14

    • currency_pair in /spot/order_book should be a required parameter
    • Optimize document code samples

    v4.5.1

    2019-03-11

    • Fix missing URL parameter description

    v4.5.0

    2019-03-05

    To avoid version confusion, all versions in APIv4 (documents and SDKs are both included) will start with 4 from now on

    • Add Spot v4 API to provide improved API capability
    • Add Margin v4 API to provide support for margin loans and trading
    • Add Futures price triggered auto order API support. Refer to /futures/price_orders for details
    • Base URL of all Gate API v4 real trading changed to https://api.gateio.ws/api/v4

    v1.3.0

    2019-02-13

    Important update

    • Domain of base URLs are changed to fx-api.gateio.ws and fx-api-testnet.gateio.ws respectively, *.gateio.io is deprecated and will soon be out of service.

    v1.2.1

    2019-02-13

    • Add volumn_24h_usd and volume_24h_btc in GET /futures/tickers response

    v1.2.0

    2019-01-17

    • Add GET /futures/contracts/{contract} to get one single contract
    • Add GET /futures/positions/{contract} to get one single position
    • Add GET /futures/account_book to retrieve user account balance history
    • Add config_change_time in Contract model
    • fix miscellaneous document issues

    v1.1.0

    2019-01-08

    • Add more fields to Contract, Position, FuturesOrder
    • Add API GET /futures/position_close to retrieve position close history
    • Add optional order_id support for API GET /futures/my_trades
    • Change the status code of DELETE /futures/orders and DELETE /futures/orders/{order_id} from 204 to 200, with cancelled order details returned on success.
    • Request DELETE /futures/orders/{order_id} with invalid order ID or order that has been finished will return 404 instead of ignoring the error
    • POST /futures/orders now supports POC, iceberg

    v1.0.0

    2018-12-30

    • Initial release

    # General

    # Matching mechanism

    # Matching priority

    Gate.io Order matching follows Price Priority > Time priority principle.

    Suppose that the order book is as follows:

    Order Order time Ask/Selling price
    A 10:00 100
    B 10:00 102
    C 10:01 100

    If the current price of 10:02 pays 102, the final transaction order is: A, C, B

    # Order life cycle

    A valid order sent to the matching engine is immediately confirmed and executed with existing orders, with the executing result sent back to the client.

    If an order is fully executed, then it is closed. If any part of the order is not executed immediately, orders with TimeInForce set to IOC will be cancelled, while others will be appended to the price list, waiting for subsequent filling or being cancelled.

    # Data Center

    Gate.io data center is located in AWS Japan's ap-northeast-1 region.

    # API Overview

    API Classification Category Links Overview
    host + /api/v4/spot/* Spot Trading Including currency status, market information, order, transaction records and other functions
    host + /api/v4/margin/* Margin Trading Margin account management, lending, repayment, etc
    host + /api/v4/wallet/* Wallet Management Charge and withdrawal records, balance inquiries, fund transfers, etc.
    host + /api/v4/withdrawals/* Withdrawal Withdrawal of digital currency

    # Margin Migration Instructions

    Between 14:00 (UTC+8) on April 13, 2023 and 14:00 (UTC+8) on April 23, 2023, the platform will gradually migrate the assets that have not been borrowed in the lending market to the Lend & Earn through an automated system process. At the same time, assets that have already been borrowed will be cancelled for automatic lending. After the migration is complete, you can check your investment details in the Lend & Earn. During this period, borrowing funds through the lending market will be temporarily suspended. You can also manually transfer your assets from the lending market to the Lend & Earn to obtain investment returns in advance.

    After the automatic migration, the old version of the borrowing and lending endpoint will be deprecated, and the new version of the endpoint can be found in the /margin/uni endpoint group. For detailed endpoint migration, please refer to the following table:"

    Margin account related endpoints:

    Name Path Deprecated New Path
    Margin account list GET /margin/accounts No -
    List margin account balance change history GET /margin/account_book No -
    Funding account list GET /margin/funding_accounts No -
    Update user's auto repayment setting POST /margin/auto_repay No -
    Querying user's automatic repayment settings GET /margin/auto_repay No -
    Get the max transferable amount for a specific margin currency GET /margin/transferable No -

    The margin lending and borrowing related APIs have been migrated to the /margin/uni API group:

    Name Old Path Deprecated New Path
    List all supported currency pairs supported in margin trading GET /margin/currency_pairs Yes GET /margin/uni/currency_pairs
    Query one single margin currency pair GET /margin/currency_pairs/{currency_pair} Yes GET /margin/uni/currency_pairs/{currency_pair}
    Lend or borrow POST /margin/loans Yes POST /margin/uni/loans
    Retrieve one single loan detail GET /margin/loans/{loan_id} Yes -
    List all loans GET /margin/loans Yes GET /margin/uni/loans
    Repay a loan POST /margin/loans/{loan_id}/repayment Yes POST /margin/uni/loans
    List loan repayment records GET /margin/loans/{loan_id}/repayment Yes GET /margin/uni/loan_records
    Get the max borrowable amount for a specific margin currency GET /margin/borrowable Yes GET /margin/uni/borrowable
    List interest records - - GET /margin/uni/interest_records

    The earn related APIs have been migrated to the /earn/uni API group):

    Name Old Path Deprecated New Path
    List all supported currency pairs supported in margin trading GET /margin/currency_pairs Yes GET /earn/uni/currencies
    Query one single margin currency pair GET /margin/currency_pairs/{currency_pair} Yes GET /earn/uni/currencies/{currency}
    Lend or borrow POST /margin/loans Yes POST /earn/uni/lends
    List all loans GET /margin/loans Yes GET /earn/uni/lends
    Order book of lending loans GET /margin/funding_book Yes -
    Merge multiple lending loans POST /margin/merged_loans Yes -
    Modify a loan PATCH /margin/loans/{loan_id} Yes PATCH /earn/uni/lends
    Cancel lending loan DELETE /margin/loans/{loan_id} Yes POST /earn/uni/lends
    List repayment records of a specific loan GET /margin/loan_records Yes GET /earn/uni/lend_records
    Get one single loan record GET /margin/loan_records/{loan_record_id} Yes -
    Modify a loan record PATCH /margin/loan_records/{loan_record_id} Yes -
    List interest records - - GET /earn/uni/interest_records

    # API

    # HTTP convention

    • All read endpoints use GET method. They accept only request parameters. No request body will be read.
    • DELETE methods remove resources(like orders), but not all removing operation using DELETE, as DELETEs don't read request body either. For complex removing operations, POST method is used with parameters filled in request body.
    • Updating is done using POST, PUT or PATCH method. Their parameters are either in body or request parameters for different endpoints. Refer to endpoint detail for how to send the request.
    • All endpoints return HTTP status code 2xx on success. 401 is returned on authentication failure. Other 4xx codes mean the request is malformed. 5xx means the server encounter some critical error on processing the request. Commit issues if 5xx is met.

    # Time

    All time related fields are unix timestamp in seconds if no extra note, but they may differ in formats(int64, number or string). Possible values like the following may be returned:

    • 1596531048
    • "1596531048"
    • 1596531048.285
    • "1596531048.285"

    The best way to handle time fields is parsing them as a number with decimal places. If higher precision is not needed, you can safely cast them to integer(or long). Our SDKs listed above has already taken proper deserialization to handle them

    # API Gateway in/out time

    In every API request, the response header will always include the following fields:

    • X-In-Time: The timestamp when the API gateway receives a request, in Unix timestamp format, measured in microseconds.

    • X-Out-Time: The timestamp when the API gateway returns a response, in Unix timestamp format, measured in microseconds.

    For example:

    X-In-Time: 1695715091540163
    X-Out-Time: 1695715091551905
    

    # Pagination

    Pagination is achieved using one of the following method

    • page-limit
    • limit-offset

    In both method, limit limits the maximum number of records returned in one request. If no additional explanation, it defaults to 100 if not provided and its maximum value is limited to 1000.

    page starts from 1, mimicking common paging used in web pages. To iterate the whole list, use the same limit and increment page by 1 until the records' length is shorter than the limit

    offset starts from 0, behaving like common DB search. To iterate the whole list, increment offset by limit until the records' length is shorter than the limit.

    For example, if the total number of orders is 201. Using page-limit method, send request parameters like the following:

    1. page=1&limit=100
    2. page=2&limit=100
    3. page=3&limit=100

    Using limit-offset method, send request parameters like:

    1. limit=100&offset=0
    2. limit=100&offset=100
    3. limit=100&offset=200

    Some endpoints may return additional pagination metadata. If present, they are sent back through the response header. Take GET /futures/{settle}/orders as an example, following headers will be returned

    • X-Pagination-Limit: request limit
    • X-Pagination-Offset: request offset
    • X-Pagination-Total: total record number satisfying the request

    # Frequency limit rule

    Markets Endpoints Limits Based On Include
    All public endpoints Public endpoints 200r/10s per endpoint IP Orderbook, Candlestick, Ticker, etc.
    Wallet Private endpoints Withdrawal(POST /withdrawals) : 1r/3s
    Transfer between trading accounts (POST /wallet/transfers) 80r/10s
    Transfer between main and sub accounts (POST /wallet/sub_account_transfers) 80r/10s
    Transfer from a sub-account to another sub-account (POST /wallet/sub_account_to_sub_account) 80r/10s
    Retrieve user's total balances (GET /wallet/total_balance) 80r/10s
    Retrieve sub account balances (GET /wallet/sub_account_balances) 80r/10s
    Query sub accounts' margin balances (GET /wallet/sub_account_margin_balances) 80r/10s
    Query sub accounts' futures account balances (GET /wallet/sub_account_futures_balances) 80r/10s
    Query subaccount's cross_margin account info(GET /wallet/sub_account_cross_margin_balances) 80r/10s
    The Others: 200r/10s per endpoint
    UID Withdrawal.
    Query personal account balance.
    Query subaccount balance.
    Spot Private endpoints The rate limit for batch/single order placement and amend an order are total of 10r/s (UID+Market)
    The rate limit for batch/single order cancellation is total of 200r/s
    The Others: 200r/10s per endpoint
    UID Spot order placement and cancellation.
    Trade history and fee rates.
    Perpetual Futures Private endpoints The rate limit for batch/single order placement and amend an order are total of 100r/s
    The maximum rate limit for the order cancellation (bulk/single) is 200r/s
    The Others: 200r/10s per endpoint
    UID Futures order placement and cancellation
    Trade history and fee rates
    Delivery Private endpoints The maximum rate limit for the order placement (bulk/single) is 500r/10s
    The maximum rate limit for the order cancellation (bulk/single) is 500r/10s
    The Others: 200r/10s per endpoint
    UID Order placement and cancellation
    Options Private endpoints The maximum rate limit for the order placement (bulk/single) is 200r/s
    The maximum rate limit for the order cancellation (bulk/single) is 200r/s
    The Others: 200r/10s per endpoint
    UID Order placement and cancellation
    Subaccount Private endpoints 80r/10s per endpoint UID Create a sub-account.
    Retrieve the list of sub-accounts.
    Disable or enable API key for a sub-account.
    Unified Private endpoints Borrow or repay 15/10s UID Borrow or repay(POST /unified/loans)
    Other Private endpoints Private endpoints 150r/10s per endpoint UID Earning, collateral etc

    The rate limit is counted against each sub-account or main account.

    Rate Limit

    Each request to the API response header will contain the following fields::

    • X-Gate-RateLimit-Requests-Remain - your remaining requests for current endpoint
    • X-Gate-RateLimit-Limit - your current limit for current endpoint
    • X-Gate-RateLimit-Reset-Timestamp - the timestamp indicating when your request limit resets if you have exceeded your rate_limit. Otherwise, this is just the current timestamp (it may not exactly match timeNow).

    WebSocket:

    • The message limit sent to the server: unlimited.
    • Number of connections per IP: ≤ 300

    # Return Format

    All API responses are in JSON format, and users need to transform and extract data by themselves.

    The HTTP status code 2XX will be returned when all operations are successful. 401 indicates that there is a problem with the certification. Other 4xx status codes indicate that the request is invalid. If it is a 5xx error, the server has encountered an unknown serious error when processing the request. Please give feedback as soon as possible。

    Return Status

    Status Code Description
    200/201 Request succeeded
    202 Request accepted by the server, but processing is not done yet
    204 Request succeeded, but the server doesn't return body
    400 Invalid request
    401 Authentication failed
    404 Not found
    429 Too many requests
    5xx Server error

    # Data Type

    Type Description
    string String type, in double quotation marks. Price and amount are also formatted in string format
    integer 32-bit integer,Mainly related to status codes, size, times, etc.
    integer(int64) 64-bit integer,Mainly involves ID and higher precision timestamp
    float Floating point number. Some time and stat fields use float.
    object Object,Contains a child object{}
    array List,Includes multiple groups of content
    boolean true is true,false is false

    # Portfolio Margin Account

    TIP

    The Portfolio Margin Account is no longer maintained, please refer to the new version of the Unified Account

    Since version 4.25.0, we start supporting portfolio margin account. Gate.io's Portfolio Margin Account is a new feature of Gate.io's trading system. Its main function is to break the capital isolation between cross-margin leverage account and USD cross-margin perpetual contract account inside a Classic Account and achieve the multi-currency margin sharing among multi-product lines. Thanks to the margin sharing, users don't need to transfer funds between the two accounts, and the profit and loss of positions among different trading products can offset each other and effectively improve the capital utilization rate. See more details in the Help Center

    Before using the portfolio margin account's API key, you should create the API key on the API management page. The API key supports spot and perpetual contracts trading only.

    If permissions of the API key can't be checked, ensure your cross-margin account has available balance first.

    # Transfer

    The classic account and portfolio margin account are two different capital isolation accounts. If you want to achieve multi-currency margin sharing among multi-product lines, use the portfolio margin account please.

    The funds of the portfolio margin account come from the classic account. Due to the change of funds in the classic account, the transfer of funds can only be performed using the API Key of the classic account.

    The portfolio margin account is upgraded based on the cross-margin account of the original classic account, so the classic account only needs to transfer its spot funds to the cross-margin account to deposit the portfolio margin account. Similarly, withdrawals from portfolio margin account can be achieved by the classic account performing transferals from the cross margin to its spot account.

    The API Key of the portfolio margin account can only perform transferals among its own multiple accounts. Due to the sharing of margin, the portfolio margin account does not need to transfer funds to its futures account (we also restrict doing so). If the futures account has PNL funds that need to be withdrawn, it must be transferred by the portfolio margin account's API key to its cross-margin account first, so that the classic account can perform withdrawals from portfolio margin account.

    # Spot trading

    The spot trading of the portfolio margin account is almost the same as the classic account, except that cross_margin must be specified in the account parameter when placing orders. For example, if you want to place a buy order for the BTC_USDT currency pair, the order request will be similar to

    POST /spot/orders
    
    {
      "currency_pair": "BTC_USDT",
      "account": "cross_margin",
      "side": "buy",
      ...
    }
    

    For other related restrictions, please refer to the document of the API endpoint directly.

    TIP

    It should be noted that the portfolio margin account is upgraded from the classic account's cross-margin account. The API Key of the classic account originally supports the operation of the cross-margin account. In order not to affect the existing operations of the classic account, we still retain this function of the classic account. So whether it is the API Key of the classic account or the portfolio margin account, both can operate the same the cross margin account (note that the futures accounts are separate)

    # Futures trading

    The API operation of the perpetual contract of the portfolio margin account is exactly the same as that of the classic account, but currently only supports USD settlement

    TIP

    In the futures trading, it should be noted that there is no compatibility for cross-margin accounts like using the API Key of the classic account in spot trading. Therefore, when using the API Key of the classic account for futures trading, assets are kept under classic account-futures, and when using portfolio margin account API Key for futures trading, assets are kept under portfolio margin account-futures. These two are different futures accounts. In addition, funds under classic account-spot cannot share margin with classic account-futures.

    # Request ID

    It is allowed to set an X-Client-Request-Id header in the request, and the API will also carry this header in the response. You can use this field to locate the corresponding request that the API responds to, which is convenient for users to set the request id for tracking.

    # Self-Trade Prevention (STP)

    # Concepts

    Self-Trade Prevention: STP will prevent any user's orders from being matched with each other.

    CN: Cancel new, Cancel new orders and keep old ones.

    CO: Cancel old, Cancel old orders and keep new ones.

    CB: Cancel both, Both old and new orders will be cancelled.

    # STP Strategies

    We support three STP strategies, which are CN , CO and CB.

    STP is achieved by adding users to one STP trading group. When a user in a STP group place orders, and trading could happen with existing orders of users in the same group, orders will be cancelled. The prevention strategy depends on the stp_act parameter specified when placing the order as taker. If not specified, the CN strategy will be used by default.

    A user has to be added to a STP trading group before using STP. When a user does not belong to any STP trading group, and place orders with the stp_act parameter, the orders will be rejected.

    # API Parameter Adjustment

    Take placing futures order as an example:

    POST /futures/{settle}/orders
    

    New request body parameter:

    Name Position Type Required Description
    stp_act body string No STP Strategies, including:
    - cn
    - co
    - cb

    New response fields:

    Name Type Required Restriction Description
    stp_act string No none STP Strategies, including:
    - cn
    - co
    - cb
    stp_id integer(int64) No readonly The ID of the STP trading group to which user belongs.
    finish_as string No readonly order finish type:
    - stp: The order has been canceled due to the STP

    # User case

    There are multiple accounts under Organization A, and the IDs of several accounts are 101, 102, and 103

    In order to prevent self-trading of orders placed by internal accounts of the organization, the administrator created a STP trading group with group ID 100, and added accounts 101 and 102 to the STP trading group. In this case, the members in the group are [101,102].

    T1: The STP strategy version released.

    T2: After the organization A account 101 places a short order, there is no matching order in the market order book to match the transaction. At this time, the role of the order is maker, and the order status is open. The key response fields returned are:

    {
    	"status":"open",
    	"stp_act":"cn",
    	"stp_id":100
    }
    

    T3: Organization A account 101/102 places a long order, and it can reach a trade with account 101’s short order. The match engine finds both two orders' stp_id are 100, so it applies the STP strategy of the taker order, which defaults to cn , and cancels the long order. Order's finish_as will be set to stp. The key response fields returned are:

    {
    	"status":"finished",
    	"stp_act":"cn",
    	"stp_id":100,
    	"finish_as":"stp"
    }
    
    • If stp_act is co , the order placed by taker will be retained, the order status will be open, and the system will cancel the order of maker.

    • If stp_act is cb, both the long and short orders will be cancelled. Orders' finish_as will be set to stp. The key response fields returned are:

    {
    	"status":"finished",
    	"stp_act":"cb",
    	"stp_id":100,
    	"finish_as":"stp"
    }
    

    T3': If account 103 places a long order, and it can reach a trade with account 101’s short order, the transaction will be made since account 103 has not been added to account 101’s STP group. The key response fields returned are:

    {
    	"status":"finished",
    	"stp_id":0,
    	"finish_as":"filled"
    }
    

    # Unified Account

    # Description

    Once a user upgrades their account to the unified account, they can utilize the assets from their spot account as collateral for trading. The assets in the account, denominated in various currencies, will be adjusted based on their liquidity and converted to USD for consistent calculation of the account's assets and position value.

    The maximum borrowing limit for margin trading represents the maximum amount that a user can borrow for a given trading market. The platform calculates the user's maximum borrowing limit based on factors such as available margin and platform risk control rules. Once the margin trading generates automatic borrowing, the platform immediately starts accruing interest on the borrowed digital assets.

    Currently, the ability to switch to cross_margin orusdt_futures mode is available. In the future, we will gradually introduce support for various combination margin accounts, including Futures, Delivery, Options and more. Stay tuned for further updates.

    Please refer to the documentation for unified API. Once you have upgraded your account, you will be able to make use of these endpoints.

    Related endpoint can be found in the Unified Account API doc. After enabling the Unified Account, you can proceed to call them. For more detailed information, please refer to here

    # API Integration Process

    • Create a new API KEY or update the permissions of an existing API KEY, checking the unified permission
    • Use the classic account's API KEY to call the POST /api/v4/unified/account_mode endpoint, or upgrade from the WEB page to the Unified Account
    • Use the /api/v4/spot/** API for spot-related operations (ordering, modifying orders, querying orders), with the account=unified option
    • Use the /api/v4/futures/** API for perpetual futures-related operations (ordering, modifying orders, querying orders)
    • Use the /api/v4/unified/** API for Unified Account-related operations (account querying, loan querying)

    # SPOT Trading

    The spot trading in the Unified Account is consistent with that in the classical account. In order operations, specify account=unified, or specify account=spot and the system will automatically handle the order as a unified account order when detecting the account as a unified account. For example, to place a buy order for the BTC_USDT currency pair, the order creation request would be similar to

    POST /spot/orders
    
    {
      "currency_pair": "BTC_USDT",
      "account": "unified",
      "side": "buy",
      ...
    }
    

    For other related restrictions, please refer to the document of the API endpoint directly.

    # Formula

    Name Cross Margin
    portfolio_margin_total_equity Account Equity = ∑(Equity * Index Price)
    total_margin_balance Account Margin Balance = ∑(Positive Equity x Index Price x Adjustment Factor) + ∑(Negative Equity x Index Price) - Haircut Loss
    total_initial_margin_rate Account Initial Margin Level = Account Margin Balance / Account Initial Margin
    total_maintenance_margin_rate Account Maintenance Margin Level = Account Margin Balance / Account Maintenance Margin
    total_initial_margin Account Initial Margin = Total Liabilities x Spot Initial Margin Rate
    total_maintenance_margin Account Maintenance Margin = Total Liabilities x Spot Maintenance Margin Rate
    equity Equity = Coin Balance - Borrowed
    available Available Balance = Principal + Borrowed
    freeze Occupied = Assets Occupied by Spot Open Orders

    # AccountBook type

    # General

    • unknown: Unknown
    • login: Log In
    • withdraw: Withdrawals
    • ch_pass: Change Password
    • ch_fund_pass: Change Fund Pass
    • login_failed: Login Failed
    • axs_account: Access Account
    • req_pass_ch: Request Password Change
    • req_fund_pass_ch: Request Fund Pass Change
    • fund_pass_ent: Fund Pass Entered
    • bank_card_add: Bank Card Added
    • frw: Face Recognition For Withdrawal

    # Order

    • new_order: Order Placed
    • cancel_order: Order Cancelled
    • order_fill: Order Filled
    • order_rej: Order Rejected
    • order_fee: Trading Fees
    • system_fee: Trading Fee System Account

    # Withdraw-Deposit

    • withdraw: Withdrawals
    • deposit: Deposits
    • deposit_rej: Deposit Rejected
    • withdraw_rej: Withdrawal Rejected
    • cancel_withdraw: Cancel Withdrawal
    • withdraw_gatecode: GateCode Withdrawals
    • withdraw_fireblock: Fireblocks Withdrawals
    • withdraw_copper: Copper Withdrawals
    • startup_withdraw: Token Withdrawal From Startup
    • deposit_gatecode: GateCode Deposits
    • deposit_fireblock: Fireblocks Deposits
    • deposit_copper: Copper Deposits
    • buy_cl: Buy Crypto Legend
    • buy_cc: Buy Crypto Cabital
    • deposit_finmo: Gate connect Finmo Deposit

    # Startup

    • startup_prtcp: Startup Sale Participation
    • startup_refund: Startup Sale Refund
    • startup_sale: Startup Sale
    • startup_sale_rb: Startup Sale Rolled Back

    # Rebate

    • referral_rebate: Referral Superior Rebate
    • sec_rebate_out: Secondary Rebate Financial Account Transfer Out
    • sec_rebate_in: Affiliate Indirect Superior Rebate Income
    • ab_rebate: API Broker Rebate Income
    • eb_rebate: Exchange Broker Rebate Income
    • u_rebate: Referral Rebate Income
    • ads_rebate: Affiliate Direct Superior Rebate Income
    • au_rebate: Affiliate User Rebate Income
    • pis_rebate: Partner Indirect Superior Rebate Income
    • pds_rebate: Partner Direct Superior Rebate Income
    • pu_rebate: Partner User Rebate Income

    # Convert

    • eth_swap: ETH Swap
    • dust_swap_dctd: Dust Swap-Small Balances Deducted
    • dust_swap_gt_add: Dust Swap-GT Added
    • dust_swap_fee: Dust Swap-Fees Deducted
    • cv_buy: Quick Buy-Bought
    • cv_sell: Quick Sell-Sold

    # C2C

    • c2c_mop: C2C Merchant Order Placed
    • c2c_moc: C2C Merchant Order Canceled
    • c2c_rop: C2C Retail Order Placed
    • c2c_roc: C2C Retail Order Canceled
    • c2c_om: C2C Order Matched
    • c2c_or: C2C Order Rejected
    • c2c_fee: C2C Fees

    # Reward

    • deposit_bonus: Deposit Bonus
    • trading_rewards: Trading Rewards
    • purchase_bonus: Purchase Bonus
    • airdrop: Airdrop
    • award: Award
    • mining_rewards: Mining Rewards

    # Account Transfer In-Out

    • margin_in: Isolated Margin-Transferred In
    • margin_out: Isolated Margin- Transferred Out
    • spot_settle_out: Spot Settlement Transfer Out
    • spot_settle_in: Spot Settlement Transfer Out
    • lending_in: Lending-Transferred In
    • lending_out: Lending-Transferred Out
    • cross_in: PortfolioMarginAccountTransferIn
    • cross_out: PortfolioMarginAccountTransferOut
    • perp_in: Perps- Transferred In
    • perp_out: Perps- Transferred Out
    • perp_settle_in: Perpetual Multi-currency Settlement Transfer In
    • perp_settle_out: Perpetual Multi-currency Settlement Transfer Out
    • delivery_in: Delivery- Transferred In
    • delivery_out: Delivery- Transferred Out
    • ai_in: Auto-Invest-Transferred In
    • ai_out: Auto-Invest-Transferred Out
    • e_options_in: Easy Options- Transferred In
    • e_options_out: Easy Options- Transferred Out
    • options_in: Options- Transferred In
    • options_out: Options- Transferred Out
    • cbbc_in: CBBC- Transferred In
    • cbbc_out: CBBC- Transferred Out
    • warrant_in: Warrant- Transferred In
    • warrant_out: Warrant- Transferred Out
    • subaccount_trf: Subaccount Transfer
    • quant_in: Quant- Transferred In
    • quant_out: Quant- Transferred Out
    • pay_in: Payment Account- Transferred In
    • pay_out: Payment Account- Transferred Out
    • fct_in: Futures Copy Trading - Funds Transfer In
    • fct_out: Futures Copy Trading - Funds Transfer Out

    # Points

    • points_purchase: Points Purchase
    • points_expiration: Points With Expiration
    • points_trf: Points Transfer
    • points_trf_rej: Points Transfer Rejected

    # Finance

    • lending_lent: Lending-Lent
    • collected: Collected
    • interest_in: Interest Income
    • lending_fee: Lending-Fees Deducted
    • hodl_int: HODL Interest
    • redeem: Redeem
    • lend: Lend
    • dual_purchased: Dual C-Purchased
    • dual_settled: Dual C-Settled
    • liq_add: Liquidity Added
    • liq_rm: Liquidity Removed
    • liq_rebalanced: Liquidity Rebalanced
    • slot_int_in: Slot Auction Staking Interest Income
    • str_int_in: Structured Products Staking Interest Income

    # Loan

    • borrow: Borrow
    • repay: Repay
    • margin_borrow: Isolated Margin-Transferred In
    • margin_repay: Isolated Margin- Transferred Out
    • margin_interest_out: Isolated Margin-Interest Deduction
    • cl_borrow: Cryptoloan- Borrowed
    • cl_repay: Cryptoloan- Repaid
    • cl_dctd: Cryptoloan- Collateral Deducted
    • cl_rtd: Cryptoloan- Collateral Returned
    • cross_borrow: PortfolioMarginAccountBorrowIn
    • cross_repay: PortfolioMarginAccountRepay
    • interest_out: Interest

    # Moments

    • donation: Donation
    • rp_sent: Red Packet Sent
    • rp_rcvd: Red Packet Received
    • rp_rej: Red Packet Rejected
    • ls_offered: Live Stream-Reward Offered
    • ls_rcvd: Live Stream- Reward Received
    • pt_offered: Posts- Reward Offered
    • pt_rcvd: Posts- Reward Received
    • subs_deduct: Subscription-Fees Deducted
    • subs_in: Subscription-Fees Received
    • subs_refund: Subscription- Refund
    • subs_in_rcvd: Subscription- Refunds Received

    # PUSH Trading

    • push_dctd: Push- Deduction
    • push_rcvd_dctd: Push- Received-Deducted
    • push_canceled: Push Canceled
    • push_rej: Push Rejected
    • push_sent: Push Sent
    • push_rcvd: Push Received

    # Copy Trading

    • quant_return: Quant- Transaction Returned
    • quant_cmn_in: Quant-Commission Transferred In
    • quant_cmn_out: Quant-Commission Transferred Out
    • quant_cmn_rtd: Quant-Commission Returned
    • fct_refund: Futures Copy Trading - Funds Auto Transfer Out
    • fct_rcvd: Futures Lead Trading - Performance Fee Received
    • fct_fee: Futures Copy Trading - Performance Fee Paid
    • fct_fee_refund: Futures Copy Trading - Performance Fee Refund

    # NFT

    • nft_mp: NFT Auction-Margin Paid
    • nft_bm: NFT Auction-Bid Made
    • nft_om: NFT Auction-Offer Made
    • ntf_mr: NFT Auction-Margin Returned
    • nft_amr: NFT Auction-Aborted-Margin rcvd
    • nft_ocb: NFT Auction-Order Canceled-Back
    • nft_fb: Fixed Price-Bought
    • nft_fs: Fixed Price-For Sale
    • nft_ob: NFT Make-Offer Bought
    • nft_os: NFT Make-Offer Sale
    • nft_cr: Cancel offer refund
    • nft_ir: Refund for invalid offer
    • nft_wf: Withdrawal service fee
    • nft_wfr: Withdrawal service fee
    • ntf_mf: Multi-copy creation service fee
    • ntf_mfr: Multi-copy creation service fee refund
    • ntf_royalty: Royalties
    • nft_cd: NFT Auction-Order Canceled-Deducted
    • nft_crd: NFT Auction-Order Canceled-Rotalty-Deducted
    • nft_cf: crowdfunding
    • nft_cfr: crowdfunding refund
    • nft_ammf: Nft-Amm Frozen
    • nft_ammw: Nft-Amm Withdraw
    • nft_ammdf: Nft-Amm Deal Fee
    • nft_ammd: Nft-Amm Deal

    # Error Handling

    For all abnormal requests, APIv4 will return non-2xx status code, with a response body in JSON format to explain the error.

    The error response body follows a format like:

    {
      "label": "INVALID_PARAM_VALUE",
      "message": "Invalid parameter `text` with value: abc"
    }
    
    • label: denotes error type in string format. Its value are chosen from a certain list(see below). Programs can use label to identify and catch a specific error.
    • message(or detail): detailed error message. A longer explanation showing why the error is generated or how to avoid it. Its purpose is helping to better understand the API. Error handling mechanism with this field is highly NOT recommended.

    Take Python requests (opens new window) for example, error handling can be written like:

    Following examples only deal with business-related errors. Network timeout or other common errors need to be handled separately:

    import requests
    
    r = requests.get("https://api.gateio.ws/api/v4/futures/btc/contracts/BTC_USD")
    try:
        r.raise_for_status()
    except requests.HTTPError:
        # catch 2xx errors, parse error message in body, and do something based on `label`
        if r.json()['label'] == 'xxx':
            print(r.json())
    

    or with Python SDK (opens new window):

    import json
    from gate_api import FuturesApi
    from gate_api.rest import ApiException
    
    api = FuturesApi()
    try:
        api.get_futures_contract(settle='btc', contract="BTC_USD")
    except ApiException as e:  # ApiException wraps whole error information, see implementation for details
        detail = json.loads(e.value.body)
        if detail['label'] == 'xxx':
            print(detail)
    

    # label list

    • Request parameter or format related
    label Meaning
    INVALID_PARAM_VALUE Invalid parameter value
    INVALID_PROTOCOL Invalid parameter value
    INVALID_ARGUMENT Invalid argument
    INVALID_REQUEST_BODY Invalid request body
    MISSING_REQUIRED_PARAM Missing required parameter
    BAD_REQUEST Invalid request
    INVALID_CONTENT_TYPE Invalid Content-Type header
    NOT_ACCEPTABLE Invalid Accept- Header
    METHOD_NOT_ALLOWED Request method is not allowed
    NOT_FOUND Request URL not exists
    • Authentication related
    label Meaning
    INVALID_CREDENTIALS Invalid credentials provided
    INVALID_KEY Invalid API Key
    IP_FORBIDDEN Request IP not in whitelist
    READ_ONLY API key is read-only
    INVALID_SIGNATURE Invalid signature
    MISSING_REQUIRED_HEADER Missing required authentication header
    REQUEST_EXPIRED Request Timestamp is far from the server time
    ACCOUNT_LOCKED Account is locked
    FORBIDDEN Account has no permission to request operation
    • Wallet related
    label Meaning
    SUB_ACCOUNT_NOT_FOUND Sub account not found
    SUB_ACCOUNT_LOCKED Sub account is locked
    MARGIN_BALANCE_EXCEPTION Abnormal margin account
    MARGIN_TRANSFER_FAILED Failed to transfer with margin account
    TOO_MUCH_FUTURES_AVAILABLE Futures balance exceeds max allowed
    FUTURES_BALANCE_NOT_ENOUGH Futures balance not enough
    ACCOUNT_EXCEPTION Abnormal account
    SUB_ACCOUNT_TRANSFER_FAILED Failed to transfer with sub account
    ADDRESS_NOT_USED Address never being used in web console
    TOO_FAST Withdrawing request exceeds frequency limit
    WITHDRAWAL_OVER_LIMIT Withdrawal limit exceeded
    API_WITHDRAW_DISABLED API withdrawal operation is disabled temporarily
    INVALID_WITHDRAW_ID Invalid withdraw ID
    INVALID_WITHDRAW_CANCEL_STATUS Cancelling withdrawal not allowed with current status
    DUPLICATE_REQUEST Duplicate request
    ORDER_EXISTS Order already exists, do not resubmit
    INVALID_CLIENT_ORDER_ID The client_order_id is invalid
    • Spot and margin trading related
    label Meaning
    INVALID_PRECISION Invalid precision
    INVALID_CURRENCY Invalid currency
    INVALID_CURRENCY_PAIR Invalid currency pair
    POC_FILL_IMMEDIATELY Order would match and take immediately so it's cancelled
    ORDER_NOT_FOUND Order not found
    ORDER_CLOSED Order already closed
    ORDER_CANCELLED Order already cancelled
    QUANTITY_NOT_ENOUGH Amount is not enough
    BALANCE_NOT_ENOUGH Balance is not enough
    MARGIN_NOT_SUPPORTED Request currency pair doesn't provide margin trading
    MARGIN_BALANCE_NOT_ENOUGH Margin balance is not enough
    AMOUNT_TOO_LITTLE Amount does not reach minimum required
    AMOUNT_TOO_MUCH Amount exceeds maximum allowed
    REPEATED_CREATION Repeated creation
    LOAN_NOT_FOUND Margin loan is not found
    LOAN_RECORD_NOT_FOUND Margin loan record is not found
    NO_MATCHED_LOAN No loan can match request borrow requirement
    NOT_MERGEABLE Request loans cannot be merged
    NO_CHANGE No change is made
    REPAY_TOO_MUCH Repay more than required
    TOO_MANY_CURRENCY_PAIRS Too many currency pairs in batch orders creation
    TOO_MANY_ORDERS Too many orders in one currency pair in batch orders creation
    MIXED_ACCOUNT_TYPE More than one account type is used in batch orders creation
    AUTO_BORROW_TOO_MUCH Auto borrow exceeds maximum allowed
    TRADE_RESTRICTED Trading is restricted due to high debt ratio
    FOK_NOT_FILL FOK order cannot be filled completely
    INITIAL_MARGIN_TOO_LOW User's total initial margin rate is too low
    NO_MERGEABLE_ORDERS Orders can be merged not found
    ORDER_BOOK_NOT_FOUND Insufficient liquidity
    FAILED_RETRIEVE_ASSETS Failed to retrieve account assets
    CANCEL_FAIL Order cancel failed
    • Futures related
    label Meaning
    USER_NOT_FOUND User has no futures account
    CONTRACT_NO_COUNTER No counter order found
    CONTRACT_NOT_FOUND Contract not found
    RISK_LIMIT_EXCEEDED Risk limit exceeded
    INSUFFICIENT_AVAILABLE Balance is not enough
    LIQUIDATE_IMMEDIATELY Operation may cause liquidation
    LEVERAGE_TOO_HIGH leverage too high
    LEVERAGE_TOO_LOW leverage too low
    ORDER_NOT_FOUND Order not found
    ORDER_NOT_OWNED Order not owned
    ORDER_FINISHED Order already finished
    TOO_MANY_ORDERS Too many open orders
    POSITION_CROSS_MARGIN margin updating is not allowed in cross margin
    POSITION_IN_LIQUIDATION Position is being liquidated
    POSITION_IN_CLOSE Position is closing
    POSITION_EMPTY Position is empty
    REMOVE_TOO_MUCH Changed margin exceeds allowed
    RISK_LIMIT_NOT_MULTIPLE Risk limit is not a multiple of step
    RISK_LIMIT_TOO_HIGH Risk limit too high
    RISK_LIMIT_TOO_lOW Risk limit too low
    PRICE_TOO_DEVIATED Order price deviates too much from mark price
    SIZE_TOO_LARGE Order size exceeds maximum
    SIZE_TOO_SMALL Order size does not reach minimum
    PRICE_OVER_LIQUIDATION Price to increase position can not exceeds liquidation price
    PRICE_OVER_BANKRUPT Price to decrease position cannot exceeds bankrupting price
    ORDER_POC_IMMEDIATE POC order will be finished immediately
    INCREASE_POSITION POC order will increase position
    CONTRACT_IN_DELISTING Contract is delisting, only reduce-only order or close order is allowed
    POSITION_NOT_FOUND Position not found
    POSITION_DUAL_MODE Operation forbidden in dual-mode
    ORDER_PENDING Operation forbidden with pending orders
    POSITION_HOLDING Operation forbidden with holding position
    REDUCE_EXCEEDED Reduce order would exceed position in dual-mode
    NO_CHANGE No change is made
    AMEND_WITH_STOP Amend forbidden with stop order
    ORDER_FOK Killed for FOK
    • Collateral Loan related
    label Meaning
    COL_NOT_ENOUGH Collateral balance not enough
    COL_TOO_MUCH Exceed collateral currency quota
    INIT_LTV_TOO_HIGH Init ltv too high
    REDEEMED_LTV_TOO_HIGH Ltv too high after redeem
    BORROWABLE_NOT_ENOUGH Left borrowable not enough
    ORDER_TOO_MANY_TOTAL Exceed platform order count one day
    ORDER_TOO_MANY_DAILY Exceed single user order count one day
    ORDER_TOO_MANY_USER Exceed single user order count total
    ORDER_NOT_EXIST Order id not exist
    ORDER_FINISHED Order id finished
    ORDER_NO_PAY Order unpaid amount is zero
    ORDER_EXIST Order exist
    ORDER_HISTORY_EXIST Order history exist
    ORDER_REPAYING Order is repaying
    ORDER_LIQUIDATING Order is liquidating
    BORROW_TOO_LITTLE Less than currency min borrow amount
    BORROW_TOO_LARGE Greater than total max borrow amount quantity
    REPAY_AMOUNT_INVALID Repay request amount invalid
    REPAY_GREATER_THAN_AVAILABLE Repay greater than available
    POOL_BALANCE_NOT_ENOUGH Pool balance not enough
    CURRENCY_SETTLING Currency settlement in progress
    RISK_REJECT Risk reject, please try again later
    LOAN_FAILED Loan failed, you can borrow again
    • Portfolio related
    label Meaning
    USER_LIAB User has liab
    USER_PENDING_ORDERS User has pending orders
    MODE_SET already set portfolio_margin mode
    • Earn related
    label 含义
    ERR_BALANCE_NOT_ENOUGH balance not enough
    ERR_PRODUCT_SELL_OUT Target quota reached
    ERR_PRODUCT_BUY The project is not yet open for purchase
    ERR_CREATE_ORDER Put order fail
    ERR_QUOTA_LOWER_LIMIT Not meeting the minimum order amount
    ERR_QUOTA_SUPERIOR_LIMIT The maximum order limit has been reached
    ERR_ORDER_NUMBER_LIMIT The maximum order quantity has been reached
    ERR_PRODUCT_CLOSE Project closed
    COPIES_NOT_ENOUGH Not enough shares available to subscribe
    COPIES_TOO_SMALL Investment share is too small
    COPIES_TOO_BIG The number of investment shares exceeds the upper limit
    TOTAL_AMOUNT_24 The total amount of pledge and redemption within 24 hours exceeds the limit
    TOTAL_BUYCOUNT_24 Pledge and redemption times exceeding the limit within 24 hours
    REDEEM_24_LIMIT Redemption are allowed 24 hours after the last staking
    • Server errors
    label Meaning
    INTERNAL Internal server error
    SERVER_ERROR Internal server error
    TOO_BUSY Server is too busy at the moment

    # Authentication

    # Generate API key

    Before calling the private API interface, the API key of the account needs to be generated to verify the identity. You can log in on the website and generate it in [account management] - > [APIv4 keys], or click here to generate API keys.

    Each account can create 20 API keys, and the permission configuration of each key is independent of each other. It is recommended to set a note name for each key to indicate its purpose.

    Key Access Key Secret Key The key used for signature authentication encryption

    Besides, you can attach an IP whitelist, which requires the server only accept requests from specified IPs. Each key can have at most 20 IPs formatted in IPv4(not supporting IP range though). If IP whitelist is not set, the server will skip client IP validation.

    Each user can create at most 5 keys with separate permissions. It is recommended to set a name for key denoting how the key will be used.

    TIP

    Note: If the key is named with spot or futures, then it could be the default name after APIv4 migration. For details refer to About APIv4 key improvement section

    Created key can also be updated or deleted, but any modification(s) can take up to 5 minutes to take effect.

    Please note that futures TestNet trading is a separate environment from futures real trading. Real trading API keys cannot be used in TestNet. If you want to test futures API with TestNet, you need to log into the console to generate TestNet API keys(in "Futures TestNet APIKeys" tab on " APIv4Keys" page). Making futures requests are identical between real and TestNet trading, with the only exceptions are different base URLs and different API keys.

    # APIv4 Permissions

    When creating a Key, you can configure whether to enable spot, margin, contract, wallet, or withdrawal permissions for the Key, and whether to enable read-write or read-only permissions.

    Products Permissions
    spot/margin Read-only query orders Read-write query orders & place orders
    perpetual contract Read-only query orders Read-write query orders & place orders
    delivery contract Read-only query orders Read-write query orders & place orders
    wallet Read-only Query for withdrawal transfer records Read-write Query for account records & fund transfers
    withdrawal Read-only Query cash withdrawal records Read-write Query cash withdrawal records & withdrawals

    All GET operations are read requests, while others are write requests. Each permission group can be set to disabled, read-only or read-write.

    Please note that even though withdrawal API has only one operation(i.e. POST /withdrawals), for general concern, it is still separated from wallet API into a standalone permission group, while withdrawal history retrieving API stays inside wallet operations( i.e., GET /wallet/withdrawals).

    # APIv4 signed request requirements

    1. Generate APIv4 Key pairs in web console, and make sure it has the right permissions.
    2. Set request header KEY to the key.
    3. Set request header Timestamp to current time formatted in Unix time in seconds. Pay attention that the gap between its value and current time cannot exceed 60 seconds.
    4. Set request header SIGN to encrypted request signature. Refer to next section for how signature string is generated. Signature generation method is HexEncode(HMAC_SHA512(secret, signature_string)), i.e., the hexadecimal digest output of HMAC-SHA512 with APIv4 secret as secret and signature string as message,
    5. Make sure request client's IP is in your APIv4 Key's IP whitelist.

    # API Signature string generation

    In APIv4, signature string is concatenated as the following way:

    Request Method + "\n" + Request URL + "\n" + Query String + "\n" + HexEncode(SHA512(Request Payload)) + "\n" + Timestamp

    # Request Method

    Request method in UPPERCASE, e.g. POST, GET

    # Request URL

    Request url. Protocol, host and port are not included, e.g. /api/v4/futures/orders

    # Query String

    Request query string without URL encode. query parameters order should be the same as how they are concatenated in the request URL, e.g. status=finished&limit=50. Use empty string("") if no query parameters.

    # HexEncode(SHA512(Request Payload))

    Hash the request body with SHA512 and output its Hex encoded form. If no request body, use empty string's hashed result, i.e. cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e

    # Timestamp

    Timestamp request header value.

    Examples

    Note: all example signature string are broken into multiple lines for displaying purpose only. Only the \n character in signature string is reserved in reality.

    Suppose the key we used is key, while the secret is secret.

    1. List all orders
    	GET /api/v4/futures/orders?contract=BTC_USD&status=finished&limit=50 HTTP/1.1
    

    Signature string:

    	GET\n
    	/api/v4/futures/orders\n
    	contract=BTC_USD&status=finished&limit=50\n
    	cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e\n
    	1541993715
    

    Explanation:

    • /api/v4/futures/orders: request url
    • contract=BTC_USD&status=finished&limit=50: keep the query string as it is in the request url
    • request body use empty string's hashed result
    • 1541993715: Unix timestamp in seconds

    Signature generated

    55f84ea195d6fe57ce62464daaa7c3c02fa9d1dde954e4c898289c9a2407a3d6fb3faf24deff16790d726b66ac9f74526668b13bd01029199cc4fcc522418b8a

    1. Create an order
    	POST /api/v4/futures/orders HTTP/1.1
    
    	{"contract":"BTC_USD","type":"limit","size":100,"price":6800,"time_in_force":"gtc"}
    

    Signature string:

    	POST\n
    	/api/v4/futures/orders\n
    	\n
    	ad3c169203dc3026558f01b4df307641fa1fa361f086b2306658886d5708767b1854797c68d9e62fef2f991645aa82673622ebf417e091d0bd22bafe5d956cca\n
    	1541993715
    

    Explanation:

    • request query string is empty, use plain empty string
    • use the hashed result of the json-string-formatted request body

    Signature generated

    eae42da914a590ddf727473aff25fc87d50b64783941061f47a3fdb92742541fc4c2c14017581b4199a1418d54471c269c03a38d788d802e2c306c37636389f0

    
    # example authentication implementation in Python
    
    """
    Python SDK is recommended as it has already implemented the authentication process for every API:
    """
    
    import time
    import hashlib
    import hmac
    import requests
    import json
    
    def gen_sign(method, url, query_string=None, payload_string=None):
        key = ''        # api_key
        secret = ''     # api_secret
    
        t = time.time()
        m = hashlib.sha512()
        m.update((payload_string or "").encode('utf-8'))
        hashed_payload = m.hexdigest()
        s = '%s\n%s\n%s\n%s\n%s' % (method, url, query_string or "", hashed_payload, t)
        sign = hmac.new(secret.encode('utf-8'), s.encode('utf-8'), hashlib.sha512).hexdigest()
        return {'KEY': key, 'Timestamp': str(t), 'SIGN': sign}
    
    if __name__ == "__main__":
        host = "https://api.gateio.ws"
        prefix = "/api/v4"
        common_headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
    
        url = '/futures/orders'
        body = {"contract": "BTC_USD", "size": 100, "price": "30", "tif": "gtc"}
        request_content = json.dumps(body)
        sign_headers = gen_sign('POST', prefix + url, "", request_content)
        sign_headers.update(common_headers)
        print('signature headers: %s' % sign_headers)
        res = requests.post(host + prefix + url, headers=sign_headers, data=request_content)
        print(res.status_code)
        print(res.content)
    

    # FAQ

    • How to retrieve POST /wallet/transfers history?

      Records of transfers generated through POST /wallet/transfers has multiple methods to be retrieved based on account, including:

      • GET /margin/account_book to retrieve transferals from or to margin account.
      • GET /futures/{settle}/account_book?type=dnw to retrieve perpetual contract account history
      • GET /delivery/{settle}/account_book?type=dnw to retrieve delivery contract account history
    • How to create margin orders?

      Margin order creation has been merged into spot order APIs. In POST /spot/orders or POST /spot/batch_orders, set account to margin to create margin orders.

    • Futures operation returns error USER_NOT_FOUND

      Futures account is not initialized yet. Making a deposit to your futures account will help. Note that each settle currency is associated with an independent futures account.

    • Futures operation returns error CONTRACT_NOT_FOUND

      Every settle currency has its own contract list. Make sure the contract you specified is supported by the settle currency. You can query the list with

      GET /futures/{settle}/contracts or GET /delivery/{settle}/contracts

    • Difference between sub account and main account

      • Sub account API Key cannot operate transferals between main and sub account, i.e., POST /wallet/sub_account_transfers
      • Sub account API Key cannot operate withdrawal, i.e., POST /withdrawals
      • If sub account does not have some business permission, even if its API key has the permission, the operations will be rejected too.
    • I have other question(s) not covered above

      Contact support for the issue. If the problem is related to one of the SDKs, you can also open an issue in the corresponding GitHub repository.

      When submitting an issue, please include the following information to help identify the problem:

      • User ID
        • Original request URL, request parameters and request body
        • What API key was used and where was it used, TestNet or real trading(API secret is not needed)
        • Programming language. Providing a code snippet will be better
        • Whether SDK was used. If so, which method caused the problem

    # Withdrawal

    Withdrawal operations

    # Withdraw

    Code samples

    # 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 = '/withdrawals'
    query_param = ''
    body='{"withdraw_order_id":"order_123456","currency":"USDT","address":"1HkxtBAMrA3tP5ENnYY2CZortjZvFDH5Cs","amount":"222.61","memo":"","chain":"TRX"}'
    # 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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="POST"
    url="/withdrawals"
    query_param=""
    body_param='{"withdraw_order_id":"order_123456","currency":"USDT","address":"1HkxtBAMrA3tP5ENnYY2CZortjZvFDH5Cs","amount":"222.61","memo":"","chain":"TRX"}'
    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"
    
    

    POST /withdrawals

    Withdraw

    Withdrawals to Gate addresses do not incur transaction fees.

    Body parameter

    {
      "withdraw_order_id": "order_123456",
      "currency": "USDT",
      "address": "1HkxtBAMrA3tP5ENnYY2CZortjZvFDH5Cs",
      "amount": "222.61",
      "memo": "",
      "chain": "TRX"
    }
    

    Parameters

    Name In Type Required Description
    body body object true none
    » withdraw_order_id body string false Client order id, up to 32 length and can only include 0-9, A-Z, a-z, underscore(_), hyphen(-) or dot(.)
    » amount body string true Currency amount
    » currency body string true Currency name
    » address body string false Withdrawal address. Required for withdrawals
    » memo body string false Additional remarks with regards to the withdrawal
    » chain body string true Name of the chain used in withdrawals

    Example responses

    202 Response

    {
      "id": "210496",
      "timestamp": "1542000000",
      "withdraw_order_id": "order_123456",
      "currency": "USDT",
      "address": "1HkxtBAMrA3tP5ENnYY2CZortjZvFDH5Cs",
      "txid": "128988928203223323290",
      "amount": "222.61",
      "memo": "",
      "status": "DONE",
      "chain": "TRX"
    }
    

    Responses

    Status Meaning Description Schema
    202 Accepted (opens new window) Withdraw request is accepted. Refer to withdrawal records for status Inline

    Response Schema

    Status Code 202

    Name Type Description
    » id string Record ID
    » txid string Hash record of the withdrawal
    » withdraw_order_id string Client order id, up to 32 length and can only include 0-9, A-Z, a-z, underscore(_), hyphen(-) or dot(.)
    » timestamp string Operation time
    » amount string Currency amount
    » currency string Currency name
    » address string Withdrawal address. Required for withdrawals
    » memo string Additional remarks with regards to the withdrawal
    » status string Record status.

    - DONE: done
    - CANCEL: cancelled
    - REQUEST: requesting
    - MANUAL: pending manual approval
    - BCODE: GateCode operation
    - EXTPEND: pending confirm after sending
    - FAIL: pending confirm when fail
    - INVALID: invalid order
    - VERIFY: verifying
    - PROCES: processing
    - PEND: pending
    - DMOVE: required manual approval
    - SPLITPEND: the order is automatically split due to large amount
    » chain string Name of the chain used in withdrawals

    # Enumerated Values

    Property Value
    status DONE
    status CANCEL
    status REQUEST
    status MANUAL
    status BCODE
    status EXTPEND
    status FAIL
    status INVALID
    status VERIFY
    status PROCES
    status PEND
    status DMOVE
    status SPLITPEND

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Cancel withdrawal with specified ID

    Code samples

    # 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 = '/withdrawals/210496'
    query_param = ''
    # for `gen_sign` implementation, refer to section `Authentication` above
    sign_headers = gen_sign('DELETE', prefix + url, query_param)
    headers.update(sign_headers)
    r = requests.request('DELETE', host + prefix + url, headers=headers)
    print(r.json())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="DELETE"
    url="/withdrawals/210496"
    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"
    
    

    DELETE /withdrawals/{withdrawal_id}

    Cancel withdrawal with specified ID

    Parameters

    Name In Type Required Description
    withdrawal_id path string true none

    Example responses

    202 Response

    {
      "id": "210496",
      "timestamp": "1542000000",
      "withdraw_order_id": "order_123456",
      "currency": "USDT",
      "address": "1HkxtBAMrA3tP5ENnYY2CZortjZvFDH5Cs",
      "txid": "128988928203223323290",
      "amount": "222.61",
      "memo": "",
      "status": "DONE",
      "chain": "TRX"
    }
    

    Responses

    Status Meaning Description Schema
    202 Accepted (opens new window) Cancellation accepted. Refer to record status for the cancellation result Inline

    Response Schema

    Status Code 202

    Name Type Description
    » id string Record ID
    » txid string Hash record of the withdrawal
    » withdraw_order_id string Client order id, up to 32 length and can only include 0-9, A-Z, a-z, underscore(_), hyphen(-) or dot(.)
    » timestamp string Operation time
    » amount string Currency amount
    » currency string Currency name
    » address string Withdrawal address. Required for withdrawals
    » memo string Additional remarks with regards to the withdrawal
    » status string Record status.

    - DONE: done
    - CANCEL: cancelled
    - REQUEST: requesting
    - MANUAL: pending manual approval
    - BCODE: GateCode operation
    - EXTPEND: pending confirm after sending
    - FAIL: pending confirm when fail
    - INVALID: invalid order
    - VERIFY: verifying
    - PROCES: processing
    - PEND: pending
    - DMOVE: required manual approval
    - SPLITPEND: the order is automatically split due to large amount
    » chain string Name of the chain used in withdrawals

    # Enumerated Values

    Property Value
    status DONE
    status CANCEL
    status REQUEST
    status MANUAL
    status BCODE
    status EXTPEND
    status FAIL
    status INVALID
    status VERIFY
    status PROCES
    status PEND
    status DMOVE
    status SPLITPEND

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Wallet

    Wallet

    # List chains supported for specified currency

    Code samples

    # coding: utf-8
    import requests
    
    host = "https://api.gateio.ws"
    prefix = "/api/v4"
    headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
    
    url = '/wallet/currency_chains'
    query_param = 'currency=GT'
    r = requests.request('GET', host + prefix + url + "?" + query_param, headers=headers)
    print(r.json())
    
    
    
    curl -X GET https://api.gateio.ws/api/v4/wallet/currency_chains?currency=GT \
      -H 'Accept: application/json'
    
    

    GET /wallet/currency_chains

    List chains supported for specified currency

    Parameters

    Name In Type Required Description
    currency query string true Currency name

    Example responses

    200 Response

    [
      {
        "chain": "ETH",
        "name_cn": "以太坊ERC20",
        "name_en": "ETH/ERC20",
        "is_disabled": 0,
        "is_deposit_disabled": 0,
        "is_withdraw_disabled": 0
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successfully retrieved [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    » chain string Chain name
    » name_cn string Chain name in Chinese
    » name_en string Chain name in English
    » contract_address string Smart contract address for the currency; if no address is available, it will be an empty string
    » is_disabled integer(int32) If it is disabled. 0 means NOT being disabled
    » is_deposit_disabled integer(int32) Is deposit disabled. 0 means not
    » is_withdraw_disabled integer(int32) Is withdrawal disabled. 0 means not
    » decimal string Withdrawal precision

    # Generate currency deposit address

    Code samples

    # 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 = '/wallet/deposit_address'
    query_param = 'currency=USDT'
    # 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 + "?" + query_param, headers=headers)
    print(r.json())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/wallet/deposit_address"
    query_param="currency=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"
    
    

    GET /wallet/deposit_address

    Generate currency deposit address

    Parameters

    Name In Type Required Description
    currency query string true Currency name

    Example responses

    200 Response

    {
      "currency": "USDT",
      "address": "LPXtk1kWHioP62SzfqwKbYE3Z7Wt2ujYEc",
      "multichain_addresses": [
        {
          "chain": "TRX",
          "address": "LPXtk1kWHioP62SzfqwKbYE3Z7Wt2ujYEc",
          "payment_id": "",
          "payment_name": "",
          "obtain_failed": 0
        }
      ]
    }
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Address successfully generated Inline

    Response Schema

    Status Code 200

    Name Type Description
    » currency string Currency detail
    » address string Deposit address
    » multichain_addresses array none
    »» MultiChainAddressItem object none
    »»» chain string Name of the chain
    »»» address string Deposit address
    »»» payment_id string Notes that some currencies required(e.g., Tag, Memo) when depositing
    »»» payment_name string Note type, Tag or Memo
    »»» obtain_failed integer The obtain failed status- 0: address successfully obtained- 1: failed to obtain address

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Retrieve withdrawal records

    Code samples

    # 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 = '/wallet/withdrawals'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/wallet/withdrawals"
    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 /wallet/withdrawals

    Retrieve withdrawal records

    Record time range cannot exceed 30 days

    Parameters

    Name In Type Required Description
    currency query string false Filter by currency. Return all currency records if not specified
    from query integer(int64) false Time range beginning, default to 7 days before current time
    to query integer(int64) false Time range ending, default to current time
    limit query integer false Maximum number of records to be returned in a single list
    offset query integer false List offset, starting from 0

    Example responses

    200 Response

    [
      {
        "id": "210496",
        "timestamp": "1542000000",
        "withdraw_order_id": "order_123456",
        "currency": "USDT",
        "address": "1HkxtBAMrA3tP5ENnYY2CZortjZvFDH5Cs",
        "txid": "128988928203223323290",
        "amount": "222.61",
        "fee": "0.01",
        "memo": "",
        "status": "DONE",
        "chain": "TRX"
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) List retrieved [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    » id string Record ID
    » txid string Hash record of the withdrawal
    » withdraw_order_id string Client order id, up to 32 length and can only include 0-9, A-Z, a-z, underscore(_), hyphen(-) or dot(.)
    » timestamp string Operation time
    » amount string Currency amount
    » fee string fee
    » currency string Currency name
    » address string Withdrawal address. Required for withdrawals
    » memo string Additional remarks with regards to the withdrawal
    » status string Record status.

    - DONE: done
    - CANCEL: cancelled
    - REQUEST: requesting
    - MANUAL: pending manual approval
    - BCODE: GateCode operation
    - EXTPEND: pending confirm after sending
    - FAIL: pending confirm when fail
    - INVALID: invalid order
    - VERIFY: verifying
    - PROCES: processing
    - PEND: pending
    - DMOVE: required manual approval
    - SPLITPEND: the order is automatically split due to large amount
    » chain string Name of the chain used in withdrawals

    # Enumerated Values

    Property Value
    status DONE
    status CANCEL
    status REQUEST
    status MANUAL
    status BCODE
    status EXTPEND
    status FAIL
    status INVALID
    status VERIFY
    status PROCES
    status PEND
    status DMOVE
    status SPLITPEND

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Retrieve deposit records

    Code samples

    # 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 = '/wallet/deposits'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/wallet/deposits"
    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 /wallet/deposits

    Retrieve deposit records

    Record time range cannot exceed 30 days

    Parameters

    Name In Type Required Description
    currency query string false Filter by currency. Return all currency records if not specified
    from query integer(int64) false Time range beginning, default to 7 days before current time
    to query integer(int64) false Time range ending, default to current time
    limit query integer false The maximum number of entries returned in the list is limited to 500 transactions.
    offset query integer false List offset, starting from 0

    Example responses

    200 Response

    [
      {
        "id": "210496",
        "timestamp": "1542000000",
        "withdraw_order_id": "order_123456",
        "currency": "USDT",
        "address": "1HkxtBAMrA3tP5ENnYY2CZortjZvFDH5Cs",
        "txid": "128988928203223323290",
        "amount": "222.61",
        "memo": "",
        "status": "DONE",
        "chain": "TRX"
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) List retrieved [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    None array none
    » id string Record ID
    » txid string Hash record of the withdrawal
    » withdraw_order_id string Client order id, up to 32 length and can only include 0-9, A-Z, a-z, underscore(_), hyphen(-) or dot(.)
    » timestamp string Operation time
    » amount string Currency amount
    » currency string Currency name
    » address string Withdrawal address. Required for withdrawals
    » memo string Additional remarks with regards to the withdrawal
    » status string Record status.

    - DONE: done
    - CANCEL: cancelled
    - REQUEST: requesting
    - MANUAL: pending manual approval
    - BCODE: GateCode operation
    - EXTPEND: pending confirm after sending
    - FAIL: pending confirm when fail
    - INVALID: invalid order
    - VERIFY: verifying
    - PROCES: processing
    - PEND: pending
    - DMOVE: required manual approval
    - SPLITPEND: the order is automatically split due to large amount
    » chain string Name of the chain used in withdrawals

    # Enumerated Values

    Property Value
    status DONE
    status CANCEL
    status REQUEST
    status MANUAL
    status BCODE
    status EXTPEND
    status FAIL
    status INVALID
    status VERIFY
    status PROCES
    status PEND
    status DMOVE
    status SPLITPEND

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Transfer between trading accounts

    Code samples

    # 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 = '/wallet/transfers'
    query_param = ''
    body='{"currency":"BTC","from":"spot","to":"margin","amount":"1","currency_pair":"BTC_USDT"}'
    # 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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="POST"
    url="/wallet/transfers"
    query_param=""
    body_param='{"currency":"BTC","from":"spot","to":"margin","amount":"1","currency_pair":"BTC_USDT"}'
    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"
    
    

    POST /wallet/transfers

    Transfer between trading accounts

    Transfer between different accounts. Currently support transfers between the following:

    1. spot - margin
    2. spot - futures(perpetual)
    3. spot - delivery
    4. spot - cross margin
    5. spot - options

    Body parameter

    {
      "currency": "BTC",
      "from": "spot",
      "to": "margin",
      "amount": "1",
      "currency_pair": "BTC_USDT"
    }
    

    Parameters

    Name In Type Required Description
    body body object true none
    » currency body string true Transfer currency. For futures account, currency can be set to POINT or settle currency
    » from body string true Account to transfer from
    » to body string true Account to transfer to
    » amount body string true Transfer amount
    » currency_pair body string false Margin currency pair. Required if transfer from or to margin account
    » settle body string false Futures settle currency. Required if transferring from or to futures account

    # Enumerated Values

    Parameter Value
    » from spot
    » from margin
    » from futures
    » from delivery
    » from cross_margin
    » from options
    » to spot
    » to margin
    » to futures
    » to delivery
    » to cross_margin
    » to options

    Example responses

    200 Response

    {
      "tx_id": 59636381286
    }
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Balance transferred Inline

    Response Schema

    Status Code 200

    TransactionID

    Name Type Description
    » tx_id integer(int64) Order id

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Transfer between main and sub accounts

    Code samples

    # 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 = '/wallet/sub_account_transfers'
    query_param = ''
    body='{"client_order_id":"da3ce7a088c8b0372b741419c7829033","currency":"BTC","sub_account":"10002","direction":"to","amount":"1","sub_account_type":"spot"}'
    # 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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="POST"
    url="/wallet/sub_account_transfers"
    query_param=""
    body_param='{"client_order_id":"da3ce7a088c8b0372b741419c7829033","currency":"BTC","sub_account":"10002","direction":"to","amount":"1","sub_account_type":"spot"}'
    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"
    
    

    POST /wallet/sub_account_transfers

    Transfer between main and sub accounts

    Support transferring with sub user's spot or futures account. Note that only main user's spot account is used no matter which sub user's account is operated.

    Body parameter

    {
      "client_order_id": "da3ce7a088c8b0372b741419c7829033",
      "currency": "BTC",
      "sub_account": "10002",
      "direction": "to",
      "amount": "1",
      "sub_account_type": "spot"
    }
    

    Parameters

    Name In Type Required Description
    body body object true none
    » currency body string true Transfer currency name
    » sub_account body string true Sub account user ID
    » direction body string true Transfer direction. to - transfer into sub account; from - transfer out from sub account
    » amount body string true Transfer amount
    » client_order_id body string false The custom ID provided by the customer serves as a safeguard against duplicate transfers. It can be a combination of letters (case-sensitive), numbers, hyphens '-', and underscores '_', with a length ranging from 1 to 64 characters.
    » sub_account_type body string false Target sub user's account. spot - spot account, futures - perpetual contract account, cross_margin - cross margin account, delivery - delivery account

    Responses

    Status Meaning Description Schema
    204 No Content (opens new window) Balance transferred None

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Retrieve transfer records between main and sub accounts

    Code samples

    # 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 = '/wallet/sub_account_transfers'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/wallet/sub_account_transfers"
    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 /wallet/sub_account_transfers

    Retrieve transfer records between main and sub accounts

    Record time range cannot exceed 30 days

    Note: only records after 2020-04-10 can be retrieved

    Parameters

    Name In Type Required Description
    sub_uid query string false User ID of sub-account, you can query multiple records separated by ,. If not specified, it will return the records of all sub accounts
    from query integer(int64) false Time range beginning, default to 7 days before current time
    to query integer(int64) false Time range ending, default to current time
    limit query integer false Maximum number of records to be returned in a single list
    offset query integer false List offset, starting from 0

    Example responses

    200 Response

    [
      {
        "uid": "10001",
        "timest": "1592809000",
        "source": "web",
        "client_order_id": "da3ce7a088c8b0372b741419c7829033",
        "currency": "BTC",
        "sub_account": "10002",
        "direction": "to",
        "amount": "1",
        "sub_account_type": "spot"
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) List retrieved [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    None array none
    » currency string Transfer currency name
    » sub_account string Sub account user ID
    » direction string Transfer direction. to - transfer into sub account; from - transfer out from sub account
    » amount string Transfer amount
    » uid string Main account user ID
    » client_order_id string The custom ID provided by the customer serves as a safeguard against duplicate transfers. It can be a combination of letters (case-sensitive), numbers, hyphens '-', and underscores '_', with a length ranging from 1 to 64 characters.
    » timest string Transfer timestamp
    » source string Where the operation is initiated from
    » sub_account_type string Target sub user's account. spot - spot account, futures - perpetual contract account, cross_margin - cross margin account, delivery - delivery account

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Sub-account transfers to sub-account

    Code samples

    # 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 = '/wallet/sub_account_to_sub_account'
    query_param = ''
    body='{"currency":"usdt","sub_account_from":"10001","sub_account_from_type":"spot","sub_account_to":"10002","sub_account_to_type":"spot","amount":"1"}'
    # 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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="POST"
    url="/wallet/sub_account_to_sub_account"
    query_param=""
    body_param='{"currency":"usdt","sub_account_from":"10001","sub_account_from_type":"spot","sub_account_to":"10002","sub_account_to_type":"spot","amount":"1"}'
    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"
    
    

    POST /wallet/sub_account_to_sub_account

    Sub-account transfers to sub-account

    It is possible to perform balance transfers between two sub-accounts under the same main account. You can use either the API Key of the main account or the API Key of the sub-account to initiate the transfer.

    Body parameter

    {
      "currency": "usdt",
      "sub_account_from": "10001",
      "sub_account_from_type": "spot",
      "sub_account_to": "10002",
      "sub_account_to_type": "spot",
      "amount": "1"
    }
    

    Parameters

    Name In Type Required Description
    body body object true none
    » currency body string true Transfer currency name
    » sub_account_type body string false Transfer from the account. (deprecate, use sub_account_from_type and sub_account_to_type instead)
    » sub_account_from body string true Transfer from the user id of the sub-account
    » sub_account_from_type body string true The sub-account's outgoing trading account, spot - spot account, futures - perpetual contract account, delivery - delivery contract account, cross_margin - cross-margin account."
    » sub_account_to body string true Transfer to the user id of the sub-account
    » sub_account_to_type body string true The sub-account's incoming trading account, spot - spot account, futures - perpetual contract account, delivery - delivery contract account, cross_margin - cross-margin account.
    » amount body string true Transfer amount

    Responses

    Status Meaning Description Schema
    204 No Content (opens new window) Balance transferred None

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Retrieve withdrawal status

    Code samples

    # 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 = '/wallet/withdraw_status'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/wallet/withdraw_status"
    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 /wallet/withdraw_status

    Retrieve withdrawal status

    Parameters

    Name In Type Required Description
    currency query string false Retrieve data of the specified currency

    Example responses

    200 Response

    [
      {
        "currency": "GT",
        "name": "GateToken",
        "name_cn": "GateToken",
        "deposit": "0",
        "withdraw_percent": "0%",
        "withdraw_fix": "0.01",
        "withdraw_day_limit": "20000",
        "withdraw_day_limit_remain": "20000",
        "withdraw_amount_mini": "0.11",
        "withdraw_eachtime_limit": "20000",
        "withdraw_fix_on_chains": {
          "BTC": "20",
          "ETH": "15",
          "TRX": "0",
          "EOS": "2.5"
        },
        "withdraw_percent_on_chains": {
          "ETH": "0%",
          "GTEVM": "0%"
        }
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) List retrieved [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    » currency string Currency
    » name string Currency name
    » name_cn string Currency Chinese name
    » deposit string Deposits fee
    » withdraw_percent string Withdrawal fee rate percentage
    » withdraw_fix string Fixed withdrawal fee
    » withdraw_day_limit string Daily allowed withdrawal amount
    » withdraw_amount_mini string Minimum withdrawal amount
    » withdraw_day_limit_remain string Daily withdrawal amount left
    » withdraw_eachtime_limit string Maximum amount for each withdrawal
    » withdraw_fix_on_chains object Fixed withdrawal fee on multiple chains
    »» additionalProperties string none
    » withdraw_percent_on_chains object Percentage withdrawal fee on multiple chains
    »» additionalProperties string none

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Retrieve sub account balances

    Code samples

    # 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 = '/wallet/sub_account_balances'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/wallet/sub_account_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 /wallet/sub_account_balances

    Retrieve sub account balances

    Parameters

    Name In Type Required Description
    sub_uid query string false User ID of sub-account, you can query multiple records separated by ,. If not specified, it will return the records of all sub accounts

    Example responses

    200 Response

    [
      {
        "uid": "10003",
        "available": {
          "BTC": "0.1",
          "GT": "2000",
          "USDT": "10"
        }
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) List retrieved [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    » uid string User ID
    » available object Available balances of currencies
    »» additionalProperties string none

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Query sub accounts' margin balances

    Code samples

    # 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 = '/wallet/sub_account_margin_balances'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/wallet/sub_account_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 /wallet/sub_account_margin_balances

    Query sub accounts' margin balances

    Parameters

    Name In Type Required Description
    sub_uid query string false User ID of sub-account, you can query multiple records separated by ,. If not specified, it will return the records of all sub accounts

    Example responses

    200 Response

    [
      {
        "uid": "10000",
        "available": [
          {
            "locked": false,
            "currency_pair": "BTC_USDT",
            "risk": "9999.99",
            "base": {
              "available": "0.1",
              "borrowed": "0",
              "interest": "0",
              "currency": "BTC",
              "locked": "0"
            },
            "quote": {
              "available": "0",
              "borrowed": "0",
              "interest": "0",
              "currency": "USDT",
              "locked": "0"
            }
          }
        ]
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) List retrieved [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    » uid string User ID
    » available array Margin account balances
    »» None object Margin account detail. base refers to base currency, while `quotes to quote currency
    »»» currency_pair string Currency pair
    »»» locked boolean Whether account is locked
    »»» risk string Current risk rate of margin account
    »»» base object Account currency details
    »»»» currency string Currency name
    »»»» available string Amount suitable for margin trading.
    »»»» locked string Locked amount, used in margin trading
    »»»» borrowed string Borrowed amount
    »»»» interest string Unpaid interests
    »»» quote object Account currency details
    »»»» currency string Currency name
    »»»» available string Amount suitable for margin trading.
    »»»» locked string Locked amount, used in margin trading
    »»»» borrowed string Borrowed amount
    »»»» interest string Unpaid interests

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Query sub accounts' futures account balances

    Code samples

    # 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 = '/wallet/sub_account_futures_balances'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/wallet/sub_account_futures_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 /wallet/sub_account_futures_balances

    Query sub accounts' futures account balances

    Parameters

    Name In Type Required Description
    sub_uid query string false User ID of sub-account, you can query multiple records separated by ,. If not specified, it will return the records of all sub accounts
    settle query string false Query only balances of specified settle currency

    Example responses

    200 Response

    [
      {
        "uid": "10003",
        "available": {
          "BTC": "0.1",
          "GT": "2000",
          "USDT": "10"
        }
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) List retrieved [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    » uid string User ID
    » available object Futures account balances
    »» additionalProperties object none
    »»» total string total is the balance after the user's accumulated deposit, withdraw, profit and loss (including realized profit and loss, fund, fee and referral rebate), excluding unrealized profit and loss.
    total = SUM(history_dnw, history_pnl, history_fee, history_refr, history_fund)
    »»» unrealised_pnl string Unrealized PNL
    »»» position_margin string Position margin
    »»» order_margin string Order margin of unfinished orders
    »»» available string The available balance for transferring or trading(including bonus. Bonus can't be be withdrawn. The transfer amount needs to deduct the bonus)
    »»» point string POINT amount
    »»» currency string Settle currency
    »»» in_dual_mode boolean Whether dual mode is enabled
    »»» enable_credit boolean Whether portfolio margin account mode is enabled
    »»» position_initial_margin string Initial margin position, applicable to the portfolio margin account model
    »»» maintenance_margin string Maintenance margin position, applicable to the portfolio margin account model
    »»» bonus string Perpetual Contract Bonus
    »»» enable_evolved_classic boolean Classic account margin mode, true - enable new mode, false - revert to old mode.
    »»» history object Statistical data
    »»»» dnw string total amount of deposit and withdraw
    »»»» pnl string total amount of trading profit and loss
    »»»» fee string total amount of fee
    »»»» refr string total amount of referrer rebates
    »»»» fund string total amount of funding costs
    »»»» point_dnw string total amount of point deposit and withdraw
    »»»» point_fee string total amount of point fee
    »»»» point_refr string total amount of referrer rebates of point fee
    »»»» bonus_dnw string total amount of perpetual contract bonus transfer
    »»»» bonus_offset string total amount of perpetual contract bonus deduction

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Query subaccount's cross_margin account info

    Code samples

    # 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 = '/wallet/sub_account_cross_margin_balances'
    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())
    
    
    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 /wallet/sub_account_cross_margin_balances

    Query subaccount's cross_margin account info

    Parameters

    Name In Type Required Description
    sub_uid query string false User ID of sub-account, you can query multiple records separated by ,. If not specified, it will return the records of all sub accounts

    Example responses

    200 Response

    [
      {
        "uid": "100000",
        "available": {
          "user_id": 100003,
          "locked": false,
          "total": "20.000000",
          "borrowed": "0.000000",
          "interest": "0",
          "borrowed_net": "0",
          "net": "20",
          "leverage": "3",
          "risk": "9999.99",
          "total_initial_margin": "0.00",
          "total_margin_balance": "20.00",
          "total_maintenance_margin": "0.00",
          "total_initial_margin_rate": "9999.9900",
          "total_maintenance_margin_rate": "9999.9900",
          "total_available_margin": "20.00",
          "balances": {
            "USDT": {
              "available": "20.000000",
              "freeze": "0.000000",
              "borrowed": "0.000000",
              "interest": "0.000000"
            }
          }
        }
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) List retrieved [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    » uid string User ID
    » available object none
    »» user_id integer(int64) User ID of the cross margin account. 0 means that the subaccount has not yet opened a cross margin account
    »» locked boolean Whether account is locked
    »» balances object none
    »»» CrossMarginBalance object none
    »»»» available string Available amount
    »»»» freeze string Locked amount
    »»»» borrowed string Borrowed amount
    »»»» interest string Unpaid interests
    »»» total string Total account value in USDT, i.e., the sum of all currencies' (available+freeze)*price*discount
    »»» borrowed string Total borrowed value in USDT, i.e., the sum of all currencies' borrowed*price*discount
    »»» borrowed_net string Total borrowed value in USDT * borrowed factor
    »»» net string Total net assets in USDT
    »»» leverage string Position leverage
    »»» interest string Total unpaid interests in USDT, i.e., the sum of all currencies' interest*price*discount
    »»» risk string Risk rate. When it belows 110%, liquidation will be triggered. Calculation formula: total / (borrowed+interest)
    »»» total_initial_margin string Total initial margin
    »»» total_margin_balance string Total margin balance
    »»» total_maintenance_margin string Total maintenance margin
    »»» total_initial_margin_rate string Total initial margin rate
    »»» total_maintenance_margin_rate string Total maintenance margin rate
    »»» total_available_margin string Total available margin

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Query saved address

    Code samples

    # 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 = '/wallet/saved_address'
    query_param = 'currency=USDT'
    # 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 + "?" + query_param, headers=headers)
    print(r.json())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/wallet/saved_address"
    query_param="currency=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"
    
    

    GET /wallet/saved_address

    Query saved address

    Parameters

    Name In Type Required Description
    currency query string true Currency
    chain query string false Chain name
    limit query string false Maximum number returned, 100 at most
    page query integer false Page number

    Example responses

    200 Response

    [
      {
        "currency": "usdt",
        "chain": "TRX",
        "address": "TWYirLzw2RARB2jfeFcfRPmeuU3rC7rakT",
        "name": "gate",
        "tag": "",
        "verified": "1"
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) List retrieved [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    » currency string Currency
    » chain string Chain name
    » address string Address
    » name string Name
    » tag string Tag
    » verified string Whether to pass the verification 0-unverified, 1-verified

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Retrieve personal trading fee

    Code samples

    # 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 = '/wallet/fee'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/wallet/fee"
    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 /wallet/fee

    Retrieve personal trading fee

    Parameters

    Name In Type Required Description
    currency_pair query string false Specify a currency pair to retrieve precise fee rate
    settle query string false Specify the settlement currency of the contract to get more accurate rate settings

    # Detailed descriptions

    currency_pair: Specify a currency pair to retrieve precise fee rate

    This field is optional. In most cases, the fee rate is identical among all currency pairs

    settle: Specify the settlement currency of the contract to get more accurate rate settings

    This field is optional. Generally, the rate settings for all settlement currencies are the same.

    # Enumerated Values

    Parameter Value
    settle BTC
    settle USDT
    settle USD

    Example responses

    200 Response

    {
      "user_id": 10001,
      "taker_fee": "0.002",
      "maker_fee": "0.002",
      "futures_taker_fee": "-0.00025",
      "futures_maker_fee": "0.00075",
      "gt_discount": false,
      "gt_taker_fee": "0",
      "gt_maker_fee": "0",
      "loan_fee": "0.18",
      "point_type": "1",
      "delivery_taker_fee": "0.00016",
      "delivery_maker_fee": "-0.00015",
      "debit_fee": 3
    }
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successfully retrieved Inline

    Response Schema

    Status Code 200

    Name Type Description
    » user_id integer(int64) User ID
    » taker_fee string taker fee rate
    » maker_fee string maker fee rate
    » gt_discount boolean If GT deduction is enabled
    » gt_taker_fee string Taker fee rate if using GT deduction. It will be 0 if GT deduction is disabled
    » gt_maker_fee string Maker fee rate if using GT deduction. It will be 0 if GT deduction is disabled
    » loan_fee string Loan fee rate of margin lending
    » point_type string Point type. 0 - Initial version. 1 - new version since 202009
    » futures_taker_fee string Futures trading taker fee
    » futures_maker_fee string Future trading maker fee
    » delivery_taker_fee string Delivery trading taker fee
    » delivery_maker_fee string Delivery trading maker fee
    » debit_fee integer Deduction types for rates, 1 - GT deduction, 2 - Point card deduction, 3 - VIP rates

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Retrieve user's total balances

    Code samples

    # 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 = '/wallet/total_balance'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/wallet/total_balance"
    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 /wallet/total_balance

    Retrieve user's total balances

    This endpoint returns an approximate sum of exchanged amount from all currencies to input currency for each account.The exchange rate and account balance could have been cached for at most 1 minute. It is not recommended to use its result for any trading calculation.

    For trading calculation, use the corresponding account query endpoint for each account type. For example:

    • GET /spot/accounts to query spot account balance
    • GET /margin/accounts to query margin account balance
    • GET /futures/{settle}/accounts to query futures account balance

    Parameters

    Name In Type Required Description
    currency query string false Currency unit used to calculate the balance amount. BTC, CNY, USD and USDT are allowed. USDT is the default.

    Example responses

    200 Response

    {
      "details": {
        "cross_margin": {
          "amount": "0",
          "currency": "USDT"
        },
        "spot": {
          "currency": "USDT",
          "amount": "42264489969935775.5160259954878034182418"
        },
        "finance": {
          "amount": "662714381.70310327810191647181",
          "currency": "USDT"
        },
        "margin": {
          "amount": "1259175.664137668554329559",
          "currency": "USDT",
          "borrowed": "0.00"
        },
        "quant": {
          "amount": "591702859674467879.6488202650892478553852",
          "currency": "USDT"
        },
        "futures": {
          "amount": "2384175.5606114082065",
          "currency": "USDT",
          "unrealised_pnl": "0.00"
        },
        "delivery": {
          "currency": "USDT",
          "amount": "1519804.9756702",
          "unrealised_pnl": "0.00"
        },
        "warrant": {
          "amount": "0",
          "currency": "USDT"
        },
        "cbbc": {
          "currency": "USDT",
          "amount": "0"
        }
      },
      "total": {
        "currency": "USDT",
        "amount": "633967350312281193.068368815439797304437",
        "unrealised_pnl": "0.00",
        "borrowed": "0.00"
      }
    }
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Request is valid and is successfully responded Inline

    Response Schema

    Status Code 200

    User's balance in all accounts

    Name Type Description
    » total object Total balances calculated with specified currency unit
    »» amount string Account total balance amount
    »» currency string Currency
    »» unrealised_pnl string Unrealised_pnl, this field will only appear in futures, options, delivery, and total accounts
    »» borrowed string Borrowed,this field will only appear in margin and cross_margin accounts
    » details object Total balances in different accounts

    - cross_margin: cross margin account
    - spot: spot account
    - finance: finance account
    - margin: margin account
    - quant: quant account
    - futures: futures account
    - delivery: delivery account
    - warrant: warrant account
    - cbbc: cbbc account
    »» additionalProperties object Total balances calculated with specified currency unit
    »»» amount string Account total balance amount
    »»» currency string Currency
    »»» unrealised_pnl string Unrealised_pnl, this field will only appear in futures, options, delivery, and total accounts
    »»» borrowed string Borrowed,this field will only appear in margin and cross_margin accounts

    # Enumerated Values

    Property Value
    currency BTC
    currency CNY
    currency USD
    currency USDT
    currency BTC
    currency CNY
    currency USD
    currency USDT

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # List small balance

    Code samples

    # 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 = '/wallet/small_balance'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/wallet/small_balance"
    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 /wallet/small_balance

    List small balance

    Example responses

    200 Response

    [
      {
        "currency": "FLOKI",
        "available_balance": "182.29400000",
        "estimated_as_btc": "0.00000012",
        "convertible_to_gt": "0.001080"
      },
      {
        "currency": "MBLK",
        "available_balance": "0.91723337",
        "estimated_as_btc": "0.00000102",
        "convertible_to_gt": "0.009188"
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Success Inline

    Response Schema

    Status Code 200

    Convert Small Balance

    Name Type Description
    » currency string Currency
    » available_balance string Available balance
    » estimated_as_btc string Estimated as BTC
    » convertible_to_gt string Estimated conversion to GT

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Convert small balance

    Code samples

    # 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 = '/wallet/small_balance'
    query_param = ''
    body='{"currency":["FLOKI","MBLK"],"is_all":true}'
    # 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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="POST"
    url="/wallet/small_balance"
    query_param=""
    body_param='{"currency":["FLOKI","MBLK"],"is_all":true}'
    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"
    
    

    POST /wallet/small_balance

    Convert small balance

    Body parameter

    {
      "currency": [
        "FLOKI",
        "MBLK"
      ],
      "is_all": true
    }
    

    Parameters

    Name In Type Required Description
    body body object true none
    » currency body array false Currency
    » is_all body boolean false Whether to exchange all

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Success None

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # List small balance history

    Code samples

    # 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 = '/wallet/small_balance_history'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/wallet/small_balance_history"
    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 /wallet/small_balance_history

    List small balance history

    Parameters

    Name In Type Required Description
    currency query string false Currency
    page query integer(int32) false Page number
    limit query integer(int32) false Maximum response items. Default: 100, minimum: 1, Maximum: 100

    Example responses

    200 Response

    [
      {
        "id": "28583810",
        "create_time": 1706670777,
        "currency": "FLOKI",
        "amount": "182.29400000",
        "gt_amount": "0.001079"
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Success Inline

    Response Schema

    Status Code 200

    Convert Small Balance

    Name Type Description
    » id string Order ID
    » currency string Currency
    » amount string amount
    » gt_amount string GT amount
    » create_time integer(int64) Exchange time (in seconds)

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # SubAccount

    Sub-accounts management

    # Create a new sub-account

    Code samples

    # 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 = '/sub_accounts'
    query_param = ''
    body='{"remark":"remark","login_name":"sub_account_for_trades"}'
    # 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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="POST"
    url="/sub_accounts"
    query_param=""
    body_param='{"remark":"remark","login_name":"sub_account_for_trades"}'
    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"
    
    

    POST /sub_accounts

    Create a new sub-account

    Body parameter

    {
      "remark": "remark",
      "login_name": "sub_account_for_trades"
    }
    

    Parameters

    Name In Type Required Description
    body body object true none
    » remark body string false custom text
    » login_name body string true Sub-account login name: Only letters, numbers and underscores are supported, and cannot contain other illegal characters
    » password body string false The sub-account's password. (Default: the same as main account's password)
    » email body string false The sub-account's email address. (Default: the same as main account's email address)

    Example responses

    201 Response

    {
      "remark": "remark",
      "login_name": "sub_account_for_trades",
      "user_id": 10001,
      "state": 1,
      "create_time": 168888888
    }
    

    Responses

    Status Meaning Description Schema
    201 Created (opens new window) Created Successfully Inline

    Response Schema

    Status Code 201

    Name Type Description
    » remark string custom text
    » login_name string Sub-account login name: Only letters, numbers and underscores are supported, and cannot contain other illegal characters
    » password string The sub-account's password. (Default: the same as main account's password)
    » email string The sub-account's email address. (Default: the same as main account's email address)
    » state integer(int32) State: 1-normal, 2-locked"
    » type integer(int32) "Sub-account type: 1 - sub-account, 3 - cross margin account
    » user_id integer(int64) The user id of the sub-account
    » create_time integer(int64) Created time

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # List sub-accounts

    Code samples

    # 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 = '/sub_accounts'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/sub_accounts"
    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 /sub_accounts

    List sub-accounts

    Parameters

    Name In Type Required Description
    type query string false 0 to list all types of sub-accounts (currently supporting cross margin accounts and sub-accounts).

    # Detailed descriptions

    type: 0 to list all types of sub-accounts (currently supporting cross margin accounts and sub-accounts). 1 to list sub-accounts only. If no parameter is passed, only sub-accounts will be listed by default.

    Example responses

    200 Response

    [
      {
        "remark": "remark",
        "login_name": "sub_account_for_trades",
        "user_id": 10001,
        "state": 1,
        "create_time": 168888888
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) List retrieved [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    None array none
    » remark string custom text
    » login_name string Sub-account login name: Only letters, numbers and underscores are supported, and cannot contain other illegal characters
    » password string The sub-account's password. (Default: the same as main account's password)
    » email string The sub-account's email address. (Default: the same as main account's email address)
    » state integer(int32) State: 1-normal, 2-locked"
    » type integer(int32) "Sub-account type: 1 - sub-account, 3 - cross margin account
    » user_id integer(int64) The user id of the sub-account
    » create_time integer(int64) Created time

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Get the sub-account

    Code samples

    # 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 = '/sub_accounts/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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/sub_accounts/0"
    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 /sub_accounts/{user_id}

    Get the sub-account

    Parameters

    Name In Type Required Description
    user_id path integer(int64) true Sub-account user id

    Example responses

    200 Response

    {
      "remark": "remark",
      "login_name": "sub_account_for_trades",
      "user_id": 10001,
      "state": 1,
      "create_time": 168888888
    }
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successful Inline

    Response Schema

    Status Code 200

    Name Type Description
    » remark string custom text
    » login_name string Sub-account login name: Only letters, numbers and underscores are supported, and cannot contain other illegal characters
    » password string The sub-account's password. (Default: the same as main account's password)
    » email string The sub-account's email address. (Default: the same as main account's email address)
    » state integer(int32) State: 1-normal, 2-locked"
    » type integer(int32) "Sub-account type: 1 - sub-account, 3 - cross margin account
    » user_id integer(int64) The user id of the sub-account
    » create_time integer(int64) Created time

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Create API Key of the sub-account

    Code samples

    # 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 = '/sub_accounts/0/keys'
    query_param = ''
    body='{"mode":1,"name":"spot","perms":[{"read_only":false,"name":"options"},{"read_only":false,"name":"spot"},{"read_only":false,"name":"delivery"},{"read_only":false,"name":"wallet"},{"read_only":false,"name":"futures"}],"ip_whitelist":["127.0.0.1","127.0.0.2"]}'
    # 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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="POST"
    url="/sub_accounts/0/keys"
    query_param=""
    body_param='{"mode":1,"name":"spot","perms":[{"read_only":false,"name":"options"},{"read_only":false,"name":"spot"},{"read_only":false,"name":"delivery"},{"read_only":false,"name":"wallet"},{"read_only":false,"name":"futures"}],"ip_whitelist":["127.0.0.1","127.0.0.2"]}'
    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"
    
    

    POST /sub_accounts/{user_id}/keys

    Create API Key of the sub-account

    Body parameter

    {
      "mode": 1,
      "name": "spot",
      "perms": [
        {
          "read_only": false,
          "name": "options"
        },
        {
          "read_only": false,
          "name": "spot"
        },
        {
          "read_only": false,
          "name": "delivery"
        },
        {
          "read_only": false,
          "name": "wallet"
        },
        {
          "read_only": false,
          "name": "futures"
        }
      ],
      "ip_whitelist": [
        "127.0.0.1",
        "127.0.0.2"
      ]
    }
    

    Parameters

    Name In Type Required Description
    user_id path integer(int64) true Sub-account user id
    body body SubAccountKey true none
    » mode body integer(int32) false Mode: 1 - classic 2 - portfolio account
    » name body string false API key name
    » perms body array false none
    »» name body string false Permission name (all permissions will be removed if no value is passed)
    »» read_only body boolean false read only
    » ip_whitelist body array false ip white list (list will be removed if no value is passed)

    # Detailed descriptions

    »» name: Permission name (all permissions will be removed if no value is passed)

    • wallet: wallet
    • spot: spot/margin
    • futures: perpetual contract
    • delivery: delivery
    • earn: earn
    • options: options\m- account: Account
    • unified: unified
    • loan: Loan

    # Enumerated Values

    Parameter Value
    »» name wallet
    »» name spot
    »» name futures
    »» name delivery
    »» name earn
    »» name options
    »» name account
    »» name unified
    »» name loan

    Example responses

    200 Response

    {
      "state": 1,
      "name": "spot",
      "user_id": 100000,
      "perms": [
        {
          "name": "options",
          "read_only": false
        },
        {
          "name": "spot",
          "read_only": false
        },
        {
          "name": "delivery",
          "read_only": false
        },
        {
          "name": "wallet",
          "read_only": false
        },
        {
          "name": "futures",
          "read_only": false
        }
      ],
      "ip_whitelist": [
        "127.0.0.1",
        "127.0.0.2"
      ],
      "mode": 1,
      "secret": "cddcc6e5e78060e013860bdbe5e737830b96821c027664586fb38b411808f4fd",
      "key": "eb8815bf99d7bb5f8ad6497bdc4774a8",
      "created_at": 1663683330,
      "updated_at": 1663683330
    }
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Created Successfully Inline

    Response Schema

    Status Code 200

    Name Type Description
    » user_id string User ID
    » mode integer(int32) Mode: 1 - classic 2 - portfolio account
    » name string API key name
    » perms array none
    »» name string Permission name (all permissions will be removed if no value is passed)

    - wallet: wallet
    - spot: spot/margin
    - futures: perpetual contract
    - delivery: delivery
    - earn: earn
    - options: options\m- account: Account
    - unified: unified
    - loan: Loan
    »» read_only boolean read only
    » ip_whitelist array ip white list (list will be removed if no value is passed)
    » key string API Key
    » state integer(int32) State 1 - normal 2 - locked 3 - frozen
    » created_at integer(int64) Creation time
    » updated_at integer(int64) Last update time
    » last_access integer(int64) Last access time

    # Enumerated Values

    Property Value
    name wallet
    name spot
    name futures
    name delivery
    name earn
    name options
    name account
    name unified
    name loan

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # List all API Key of the sub-account

    Code samples

    # 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 = '/sub_accounts/0/keys'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/sub_accounts/0/keys"
    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 /sub_accounts/{user_id}/keys

    List all API Key of the sub-account

    Parameters

    Name In Type Required Description
    user_id path integer true Sub-account user id

    Example responses

    200 Response

    [
      {
        "state": 1,
        "name": "spot",
        "user_id": 1000000,
        "perms": [
          {
            "name": "futures",
            "read_only": false
          },
          {
            "name": "wallet",
            "read_only": false
          },
          {
            "name": "delivery",
            "read_only": false
          },
          {
            "name": "options",
            "read_only": false
          },
          {
            "name": "spot",
            "read_only": false
          }
        ],
        "mode": 1,
        "ip_whitelist": [
          "127.0.0.1",
          "127.0.0.2"
        ],
        "key": "75c3264105b74693d8cb5c7f1a8e2420",
        "created_at": 1663642892,
        "last_access": 1663642892,
        "update_at": 1663642892
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) List retrieved [SubAccountKey]

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Update API key of the sub-account

    Code samples

    # 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 = '/sub_accounts/0/keys/string'
    query_param = ''
    body='{"mode":1,"name":"spot","perms":[{"read_only":false,"name":"options"},{"read_only":false,"name":"spot"},{"read_only":false,"name":"delivery"},{"read_only":false,"name":"wallet"},{"read_only":false,"name":"futures"}],"ip_whitelist":["127.0.0.1","127.0.0.2"]}'
    # for `gen_sign` implementation, refer to section `Authentication` above
    sign_headers = gen_sign('PUT', prefix + url, query_param, body)
    headers.update(sign_headers)
    r = requests.request('PUT', host + prefix + url, headers=headers, data=body)
    print(r.json())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="PUT"
    url="/sub_accounts/0/keys/string"
    query_param=""
    body_param='{"mode":1,"name":"spot","perms":[{"read_only":false,"name":"options"},{"read_only":false,"name":"spot"},{"read_only":false,"name":"delivery"},{"read_only":false,"name":"wallet"},{"read_only":false,"name":"futures"}],"ip_whitelist":["127.0.0.1","127.0.0.2"]}'
    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"
    
    

    PUT /sub_accounts/{user_id}/keys/{key}

    Update API key of the sub-account

    Body parameter

    {
      "mode": 1,
      "name": "spot",
      "perms": [
        {
          "read_only": false,
          "name": "options"
        },
        {
          "read_only": false,
          "name": "spot"
        },
        {
          "read_only": false,
          "name": "delivery"
        },
        {
          "read_only": false,
          "name": "wallet"
        },
        {
          "read_only": false,
          "name": "futures"
        }
      ],
      "ip_whitelist": [
        "127.0.0.1",
        "127.0.0.2"
      ]
    }
    

    Parameters

    Name In Type Required Description
    user_id path integer true Sub-account user id
    key path string true The API Key of the sub-account
    body body SubAccountKey true none
    » mode body integer(int32) false Mode: 1 - classic 2 - portfolio account
    » name body string false API key name
    » perms body array false none
    »» name body string false Permission name (all permissions will be removed if no value is passed)
    »» read_only body boolean false read only
    » ip_whitelist body array false ip white list (list will be removed if no value is passed)

    # Detailed descriptions

    »» name: Permission name (all permissions will be removed if no value is passed)

    • wallet: wallet
    • spot: spot/margin
    • futures: perpetual contract
    • delivery: delivery
    • earn: earn
    • options: options\m- account: Account
    • unified: unified
    • loan: Loan

    # Enumerated Values

    Parameter Value
    »» name wallet
    »» name spot
    »» name futures
    »» name delivery
    »» name earn
    »» name options
    »» name account
    »» name unified
    »» name loan

    Responses

    Status Meaning Description Schema
    204 No Content (opens new window) Updated None

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Delete API key of the sub-account

    Code samples

    # 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 = '/sub_accounts/0/keys/string'
    query_param = ''
    # for `gen_sign` implementation, refer to section `Authentication` above
    sign_headers = gen_sign('DELETE', prefix + url, query_param)
    headers.update(sign_headers)
    r = requests.request('DELETE', host + prefix + url, headers=headers)
    print(r.json())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="DELETE"
    url="/sub_accounts/0/keys/string"
    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"
    
    

    DELETE /sub_accounts/{user_id}/keys/{key}

    Delete API key of the sub-account

    Parameters

    Name In Type Required Description
    user_id path integer true Sub-account user id
    key path string true The API Key of the sub-account

    Responses

    Status Meaning Description Schema
    204 No Content (opens new window) Delete successfully None

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Get the API Key of the sub-account

    Code samples

    # 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 = '/sub_accounts/0/keys/string'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/sub_accounts/0/keys/string"
    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 /sub_accounts/{user_id}/keys/{key}

    Get the API Key of the sub-account

    Parameters

    Name In Type Required Description
    user_id path integer true Sub-account user id
    key path string true The API Key of the sub-account

    Example responses

    200 Response

    {
      "state": 1,
      "name": "spot",
      "user_id": 1000000,
      "perms": [
        {
          "name": "futures",
          "read_only": false
        },
        {
          "name": "wallet",
          "read_only": false
        },
        {
          "name": "delivery",
          "read_only": false
        },
        {
          "name": "options",
          "read_only": false
        },
        {
          "name": "spot",
          "read_only": false
        }
      ],
      "mode": 1,
      "ip_whitelist": [
        "127.0.0.1",
        "127.0.0.2"
      ],
      "key": "75c3264105b74693d8cb5c7f1a8e2420",
      "created_at": 1663642892,
      "last_access": 1663642892,
      "update_at": 1663642892
    }
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successful SubAccountKey

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Lock the sub-account

    Code samples

    # 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 = '/sub_accounts/0/lock'
    query_param = ''
    # for `gen_sign` implementation, refer to section `Authentication` above
    sign_headers = gen_sign('POST', prefix + url, query_param)
    headers.update(sign_headers)
    r = requests.request('POST', host + prefix + url, headers=headers)
    print(r.json())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="POST"
    url="/sub_accounts/0/lock"
    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"
    
    

    POST /sub_accounts/{user_id}/lock

    Lock the sub-account

    Parameters

    Name In Type Required Description
    user_id path integer(int64) true The user id of the sub-account

    Responses

    Status Meaning Description Schema
    204 No Content (opens new window) Lock successfully None

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Unlock the sub-account

    Code samples

    # 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 = '/sub_accounts/0/unlock'
    query_param = ''
    # for `gen_sign` implementation, refer to section `Authentication` above
    sign_headers = gen_sign('POST', prefix + url, query_param)
    headers.update(sign_headers)
    r = requests.request('POST', host + prefix + url, headers=headers)
    print(r.json())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="POST"
    url="/sub_accounts/0/unlock"
    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"
    
    

    POST /sub_accounts/{user_id}/unlock

    Unlock the sub-account

    Parameters

    Name In Type Required Description
    user_id path integer(int64) true The user id of the sub-account

    Responses

    Status Meaning Description Schema
    204 No Content (opens new window) Unlock successfully None

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Unified

    Unified account

    # Get unified account information

    Code samples

    # 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/accounts'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/unified/accounts"
    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 /unified/accounts

    Get unified account information

    The assets of each currency in the account will be adjusted according to their liquidity, defined by corresponding adjustment coefficients, and then uniformly converted to USD to calculate the total asset value and position value of the account.

    You can refer to the Formula in the documentation

    Parameters

    Name In Type Required Description
    currency query string false Retrieve data of the specified currency

    Example responses

    200 Response

    {
      "user_id": 10001,
      "locked": false,
      "balances": {
        "ETH": {
          "available": "0",
          "freeze": "0",
          "borrowed": "0.075393666654",
          "negative_liab": "0",
          "futures_pos_liab": "0",
          "equity": "1016.1",
          "total_freeze": "0",
          "total_liab": "0",
          "spot_in_use": "1.111"
        },
        "POINT": {
          "available": "9999999999.017023138734",
          "freeze": "0",
          "borrowed": "0",
          "negative_liab": "0",
          "futures_pos_liab": "0",
          "equity": "12016.1",
          "total_freeze": "0",
          "total_liab": "0",
          "spot_in_use": "12"
        },
        "USDT": {
          "available": "0.00000062023",
          "freeze": "0",
          "borrowed": "0",
          "negative_liab": "0",
          "futures_pos_liab": "0",
          "equity": "16.1",
          "total_freeze": "0",
          "total_liab": "0",
          "spot_in_use": "12"
        }
      },
      "total": "230.94621713",
      "borrowed": "161.66395521",
      "total_initial_margin": "1025.0524665088",
      "total_margin_balance": "3382495.944473949183",
      "total_maintenance_margin": "205.01049330176",
      "total_initial_margin_rate": "3299.827135672679",
      "total_maintenance_margin_rate": "16499.135678363399",
      "total_available_margin": "3381470.892007440383",
      "unified_account_total": "3381470.892007440383",
      "unified_account_total_liab": "0",
      "unified_account_total_equity": "100016.1",
      "leverage": "2",
      "spot_order_loss": "12",
      "spot_hedge": false
    }
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) List retrieved Inline

    Response Schema

    Status Code 200

    Name Type Description
    » user_id integer(int64) User ID
    » refresh_time integer(int64) Time of the most recent refresh
    » locked boolean Whether account is locked
    » balances object none
    »» UnifiedBalance object none
    »»» available string Available amount
    »»» freeze string Locked amount
    »»» borrowed string Borrowed amount
    »»» negative_liab string Negative Liabilities
    »»» futures_pos_liab string Borrowing to Open Positions in Futures
    »»» equity string Equity
    »»» total_freeze string Total freeze
    »»» total_liab string Total liabilities
    »»» spot_in_use string Spot hedging utilization
    »»» funding string Quantity of funding
    »»» funding_version string Funding version
    »» total string The total asset value in USD, calculated as the sum of the product of (available + freeze) * price for all currencies.
    »» borrowed string The total borrowed amount in USD, calculated as the sum of the product of borrowed * price for all currencies (excluding points cards).
    »» total_initial_margin string Total initial margin
    »» total_margin_balance string Total margin balance
    »» total_maintenance_margin string Total maintenance margin
    »» total_initial_margin_rate string Total initial margin rate
    »» total_maintenance_margin_rate string Total maintenance margin rate
    »» total_available_margin string Total available margin
    »» unified_account_total string Total amount of the portfolio margin account
    »» unified_account_total_liab string Total liabilities of the portfolio margin account
    »» unified_account_total_equity string Total equity of the portfolio margin account
    »» leverage string Leverage
    »» spot_order_loss string Total order loss, in USDT
    »» spot_hedge boolean Spot hedging status, true - enabled, false - not enabled.
    »» use_funding boolean Whether to use funds as margin

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Set unified account mode (deprecated)

    Code samples

    # 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/account_mode'
    query_param = ''
    body='{"mode":"cross_margin","enabled":true}'
    # 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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="POST"
    url="/unified/account_mode"
    query_param=""
    body_param='{"mode":"cross_margin","enabled":true}'
    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"
    
    

    POST /unified/account_mode

    Set unified account mode (deprecated)

    Body parameter

    {
      "mode": "cross_margin",
      "enabled": true
    }
    

    Parameters

    Name In Type Required Description
    body body object true none
    » mode body string true Portfolio mode
    » enabled body boolean true Is it enabled?

    # Detailed descriptions

    » mode: Portfolio mode

    • cross_margin : cross margin
    • usdt_futures : usdt futures

    Example responses

    200 Response

    {
      "cross_margin": true,
      "usdt_futures": true
    }
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Success Inline

    Response Schema

    Status Code 200

    Name Type Description
    » additionalProperties boolean none

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Inquire about unified account mode (deprecated)

    Code samples

    # 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/account_mode'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/unified/account_mode"
    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 /unified/account_mode

    Inquire about unified account mode (deprecated)

    cross_margin - Spot full-margin trading, usdt_futures - USDT perpetual futures

    Example responses

    200 Response

    {
      "cross_margin": true,
      "usdt_futures": true
    }
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successfully retrieved Inline

    Response Schema

    Status Code 200

    Name Type Description
    » additionalProperties boolean none

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Query about the maximum borrowing for the unified account

    Code samples

    # 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/borrowable'
    query_param = 'currency=BTC'
    # 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 + "?" + query_param, headers=headers)
    print(r.json())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/unified/borrowable"
    query_param="currency=BTC"
    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"
    
    

    GET /unified/borrowable

    Query about the maximum borrowing for the unified account

    Parameters

    Name In Type Required Description
    currency query string true Retrieve data of the specified currency

    Example responses

    200 Response

    {
      "currency": "ETH",
      "amount": "10000"
    }
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successfully retrieved Inline

    Response Schema

    Status Code 200

    UnifiedBorrowable

    Name Type Description
    » currency string Currency detail
    » amount string Max borrowable amount

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Query about the maximum transferable for the unified account

    Code samples

    # 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/transferable'
    query_param = 'currency=BTC'
    # 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 + "?" + query_param, headers=headers)
    print(r.json())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/unified/transferable"
    query_param="currency=BTC"
    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"
    
    

    GET /unified/transferable

    Query about the maximum transferable for the unified account

    Parameters

    Name In Type Required Description
    currency query string true Retrieve data of the specified currency

    Example responses

    200 Response

    {
      "currency": "ETH",
      "amount": "10000"
    }
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successfully retrieved Inline

    Response Schema

    Status Code 200

    UnifiedTransferable

    Name Type Description
    » currency string Currency detail
    » amount string The maximum amount that can be transferred out

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Borrow or repay

    Code samples

    # 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/loans'
    query_param = ''
    body='{"currency":"BTC","amount":"0.1","type":"borrow","repaid_all":false,"text":"t-test"}'
    # 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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="POST"
    url="/unified/loans"
    query_param=""
    body_param='{"currency":"BTC","amount":"0.1","type":"borrow","repaid_all":false,"text":"t-test"}'
    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"
    
    

    POST /unified/loans

    Borrow or repay

    When borrowing, it is essential to ensure that the borrowed amount is not below the minimum borrowing threshold for the specific cryptocurrency and does not exceed the maximum borrowing limit set by the platform and the user.

    The interest on the loan will be automatically deducted from the account at regular intervals. It is the user's responsibility to manage the repayment of the borrowed amount.

    For repayment, the option to repay the entire borrowed amount is available by setting the parameter repaid_all=true

    Body parameter

    {
      "currency": "BTC",
      "amount": "0.1",
      "type": "borrow",
      "repaid_all": false,
      "text": "t-test"
    }
    

    Parameters

    Name In Type Required Description
    body body object true none
    » currency body string true Currency
    » type body string true type: borrow - borrow, repay - repay
    » amount body string true The amount of lending or repaying
    » repaid_all body boolean false Full repayment is solely for repayment operations. When set to 'true,' it overrides the 'amount,' allowing for direct full repayment.
    » text body string false User defined custom ID

    # Enumerated Values

    Parameter Value
    » type borrow
    » type repay

    Responses

    Status Meaning Description Schema
    204 No Content (opens new window) Operated successfully None

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # List loans

    Code samples

    # 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/loans'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/unified/loans"
    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 /unified/loans

    List loans

    Parameters

    Name In Type Required Description
    currency query string false Retrieve data of the specified currency
    page query integer(int32) false Page number
    limit query integer(int32) false Maximum response items. Default: 100, minimum: 1, Maximum: 100
    type query string false Loan type, platform - platform, margin - margin

    Example responses

    200 Response

    [
      {
        "currency": "USDT",
        "currency_pari": "GT_USDT",
        "amount": "1",
        "type": "margin",
        "change_time": 1673247054000,
        "create_time": 1673247054000
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successfully retrieved [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    None array [Loan]
    » None object Loan
    »» currency string Currency
    »» currency_pair string Currency pair
    »» amount string amount
    »» type string Loan type, platform - platform, margin - margin
    »» create_time integer(int64) Created time
    »» update_time integer(int64) Updated time

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Get load records

    Code samples

    # 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/loan_records'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/unified/loan_records"
    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 /unified/loan_records

    Get load records

    Parameters

    Name In Type Required Description
    type query string false The types of lending records, borrow - indicates the action of borrowing funds, repay - indicates the action of repaying the borrowed funds
    currency query string false Retrieve data of the specified currency
    page query integer(int32) false Page number
    limit query integer(int32) false Maximum response items. Default: 100, minimum: 1, Maximum: 100

    Example responses

    200 Response

    [
      {
        "id": 16442,
        "type": "borrow",
        "margin_mode": "cross",
        "currency_pair": "AE_USDT",
        "currency": "USDT",
        "amount": "1000",
        "create_time": 1673247054000,
        "repayment_type": "auto_repay"
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successfully retrieved [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    » None object Loan records
    »» id integer(int64) id
    »» type string type: borrow - borrow, repay - repay
    »» repayment_type string Repayment type: none - no repayment type, manual_repay - manual repayment, auto_repay - automatic repayment, cancel_auto_repay - automatic repayment after cancellation
    »» currency_pair string Currency pair
    »» currency string Currency
    »» amount string The amount of lending or repaying
    »» create_time integer(int64) Created time

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # List interest records

    Code samples

    # 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/interest_records'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/unified/interest_records"
    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 /unified/interest_records

    List interest records

    Parameters

    Name In Type Required Description
    currency query string false Retrieve data of the specified currency
    page query integer(int32) false Page number
    limit query integer(int32) false Maximum response items. Default: 100, minimum: 1, Maximum: 100
    type query string false Loan type, platform - platform, margin - margin

    Example responses

    200 Response

    [
      {
        "status": 1,
        "currency_pair": "BTC_USDT",
        "currency": "USDT",
        "actual_rate": "0.00000236",
        "interest": "0.00006136",
        "type": "platform",
        "create_time": 1673247054000
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successfully retrieved [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    None array [Interest record]
    » None object Interest record
    »» currency string Currency name
    »» currency_pair string Currency pair
    »» actual_rate string Actual rate
    »» interest string Interest
    »» status integer Status: 0 - fail, 1 - success
    »» type string Type, platform - platform,margin - margin
    »» create_time integer(int64) Created time

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Retrieve user risk unit details, only valid in portfolio margin mode

    Code samples

    # 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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/unified/risk_units"
    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 /unified/risk_units

    Retrieve user risk unit details, only valid in portfolio margin mode

    Example responses

    200 Response

    {
      "user_id": 0,
      "spot_hedge": true,
      "risk_units": [
        {
          "symbol": "BTC",
          "spot_in_use": "-13500.000001223",
          "maintain_margin": "2334.002",
          "initial_margin": "2334.002",
          "delta": "0.22",
          "gamma": "0.42",
          "theta": "0.29",
          "vega": "0.22"
        }
      ]
    }
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successfully retrieved Inline

    Response Schema

    Status Code 200

    Name Type Description
    » user_id integer(int64) User ID
    » spot_hedge boolean Spot hedging status, true - enabled, false - not enabled.
    » risk_units array Risk unit
    »» RiskUnits object none
    »»» symbol string Risk unit flag
    »»» spot_in_use string Spot hedging utilization
    »»» maintain_margin string Maintenance margin for risk unit
    »»» initial_margin string Initial margin for risk unit
    »»» delta string Total Delta of risk unit
    »»» gamma string Total Gamma of risk unit
    »»» theta string Total Theta of risk unit
    »»» vega string Total Vega of risk unit

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Set mode of the unified account

    Code samples

    # 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/unified_mode'
    query_param = ''
    body='{"mode":"portfolio","settings":{"spot_hedge":true}}'
    # for `gen_sign` implementation, refer to section `Authentication` above
    sign_headers = gen_sign('PUT', prefix + url, query_param, body)
    headers.update(sign_headers)
    r = requests.request('PUT', host + prefix + url, headers=headers, data=body)
    print(r.json())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="PUT"
    url="/unified/unified_mode"
    query_param=""
    body_param='{"mode":"portfolio","settings":{"spot_hedge":true}}'
    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"
    
    

    PUT /unified/unified_mode

    Set mode of the unified account

    Switching between different account modes requires only passing the parameters n\corresponding to the target account mode. It also supports opening or closing configuration switches for the corresponding account mode when switching- When enabling classic account mode,mode=classic

        PUT /unified/unified_mode
        {
          "mode": "classic"
        }
    
    • When enabling multi-currency margin mode, mode=multi_currency
        PUT /unified/unified_mode
        {
          "mode": "multi_currency",
          "settings": {
             "usdt_futures": true
          }
        }
    
    • When enabling portfolio margin mode,mode=portfolio
        PUT /unified/unified_mode
        {
          "mode": "portfolio",
          "settings": {
             "spot_hedge": true
          }
        }
    

    Body parameter

    {
      "mode": "portfolio",
      "settings": {
        "spot_hedge": true
      }
    }
    

    Parameters

    Name In Type Required Description
    body body object true none
    » mode body string true Unified account mode:
    » settings body object false none
    »» usdt_futures body boolean false USDT contract switch. This parameter is required when the mode is multi-currency margin mode
    »» spot_hedge body boolean false Spot hedging switch. This parameter is required when the mode is portfolio margin mode
    »» use_funding body boolean false When the mode is set to combined margin mode, will funds be used as margin

    # Detailed descriptions

    » mode: Unified account mode:

    • classic: Classic account mode
    • multi_currency: Multi-currency margin mode
    • portfolio: Portfolio margin mode

    Responses

    Status Meaning Description Schema
    204 No Content (opens new window) Success None

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Query mode of the unified account

    Code samples

    # 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/unified_mode'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/unified/unified_mode"
    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 /unified/unified_mode

    Query mode of the unified account

    Unified account mode:

    • classic: Classic account mode
    • multi_currency: Multi-currency margin mode
    • portfolio: Portfolio margin mode

    Example responses

    200 Response

    {
      "mode": "portfolio",
      "settings": {
        "spot_hedge": true
      }
    }
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successfully retrieved Inline

    Response Schema

    Status Code 200

    Name Type Description
    » mode string Unified account mode:
    - classic: Classic account mode
    - multi_currency: Multi-currency margin mode
    - portfolio: Portfolio margin mode
    » settings object none
    »» usdt_futures boolean USDT contract switch. This parameter is required when the mode is multi-currency margin mode
    »» spot_hedge boolean Spot hedging switch. This parameter is required when the mode is portfolio margin mode
    »» use_funding boolean When the mode is set to combined margin mode, will funds be used as margin

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Get unified estimate rate

    Code samples

    # 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/estimate_rate'
    query_param = 'currencies=BTC,GT'
    # 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 + "?" + query_param, headers=headers)
    print(r.json())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/unified/estimate_rate"
    query_param="currencies=BTC,GT"
    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"
    
    

    GET /unified/estimate_rate

    Get unified estimate rate

    Due to fluctuations in lending depth, hourly interest rates may vary, and thus, I cannot provide exact rates. When a currency is not supported, the interest rate returned will be an empty string.

    Parameters

    Name In Type Required Description
    currencies query array[string] true Specify the currency names for querying in an array, separated by commas, with a maximum of 10 currencies.

    Example responses

    200 Response

    {
      "BTC": "0.000002",
      "GT": "0.000001",
      "ETH": ""
    }
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successfully retrieved Inline

    Response Schema

    Status Code 200

    Estimate the current hourly lending rates, categorized by currency

    Name Type Description
    » additionalProperties string none

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # List currency discount tiers

    Code samples

    # coding: utf-8
    import requests
    
    host = "https://api.gateio.ws"
    prefix = "/api/v4"
    headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
    
    url = '/unified/currency_discount_tiers'
    query_param = ''
    r = requests.request('GET', host + prefix + url, headers=headers)
    print(r.json())
    
    
    
    curl -X GET https://api.gateio.ws/api/v4/unified/currency_discount_tiers \
      -H 'Accept: application/json'
    
    

    GET /unified/currency_discount_tiers

    List currency discount tiers

    Example responses

    200 Response

    [
      [
        {
          "currency": "USDT",
          "discount_tiers": [
            {
              "tier": "1",
              "discount": "1",
              "lower_limit": "0",
              "upper_limit": "+"
            }
          ]
        },
        {
          "currency": "USDC",
          "discount_tiers": [
            {
              "tier": "1",
              "discount": "1",
              "lower_limit": "0",
              "upper_limit": "10000000"
            },
            {
              "tier": "2",
              "discount": "0.98",
              "lower_limit": "10000000",
              "upper_limit": "15000000"
            },
            {
              "tier": "3",
              "discount": "0.95",
              "lower_limit": "15000000",
              "upper_limit": "20000000"
            },
            {
              "tier": "4",
              "discount": "0.925",
              "lower_limit": "20000000",
              "upper_limit": "50000000"
            },
            {
              "tier": "5",
              "discount": "0.9",
              "lower_limit": "50000000",
              "upper_limit": "100000000"
            },
            {
              "tier": "6",
              "discount": "0",
              "lower_limit": "100000000",
              "upper_limit": "+"
            }
          ]
        },
        {
          "currency": "BTC",
          "discount_tiers": [
            {
              "tier": "1",
              "discount": "0.98",
              "lower_limit": "0",
              "upper_limit": "1000"
            },
            {
              "tier": "2",
              "discount": "0.95",
              "lower_limit": "1000",
              "upper_limit": "10000"
            },
            {
              "tier": "3",
              "discount": "0.9",
              "lower_limit": "10000",
              "upper_limit": "50000"
            },
            {
              "tier": "4",
              "discount": "0.85",
              "lower_limit": "50000",
              "upper_limit": "+"
            }
          ]
        },
        {
          "currency": "ETH",
          "discount_tiers": [
            {
              "tier": "1",
              "discount": "0.98",
              "lower_limit": "0",
              "upper_limit": "1000"
            },
            {
              "tier": "2",
              "discount": "0.95",
              "lower_limit": "1000",
              "upper_limit": "10000"
            },
            {
              "tier": "3",
              "discount": "0.9",
              "lower_limit": "10000",
              "upper_limit": "50000"
            },
            {
              "tier": "4",
              "discount": "0.85",
              "lower_limit": "50000",
              "upper_limit": "+"
            }
          ]
        }
      ]
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successfully retrieved [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    » None object Currency discount tiers
    »» currency string Currency name
    »» discount_tiers array Tiered discount
    »»» tier string Tier
    »»» discount string Discount
    »»» lower_limit string Lower limit
    »»» upper_limit string Upper limit,+ indicates positive infinity

    # List loan margin tiers

    Code samples

    # coding: utf-8
    import requests
    
    host = "https://api.gateio.ws"
    prefix = "/api/v4"
    headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
    
    url = '/unified/loan_margin_tiers'
    query_param = ''
    r = requests.request('GET', host + prefix + url, headers=headers)
    print(r.json())
    
    
    
    curl -X GET https://api.gateio.ws/api/v4/unified/loan_margin_tiers \
      -H 'Accept: application/json'
    
    

    GET /unified/loan_margin_tiers

    List loan margin tiers

    Example responses

    200 Response

    [
      {
        "currency": "USDT",
        "margin_tiers": [
          {
            "tier": "1",
            "margin_rate": "0.02",
            "lower_limit": "200000",
            "upper_limit": "400000"
          }
        ]
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successfully retrieved [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    » None object Unified margin tiers
    »» currency string Currency name
    »» margin_tiers array Margin tiers
    »»» MarginTiers object none
    »»»» tier string Tier
    »»»» margin_rate string Discount
    »»»» lower_limit string Lower limit
    »»»» upper_limit string Upper limit, "" indicates greater than (the last tier)

    # Portfolio margin calculator

    Code samples

    # coding: utf-8
    import requests
    
    host = "https://api.gateio.ws"
    prefix = "/api/v4"
    headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
    
    url = '/unified/portfolio_calculator'
    query_param = ''
    body='{"spot_balances":[{"currency":"BTC","equity":"-1","freeze":"10"}],"spot_orders":[{"currency_pairs":"BTC_USDT","order_price":"344","size":"100","left":"100","type":"sell"}],"futures_positions":[{"contract":"BTC_USDT","size":"100"}],"futures_orders":[{"contract":"BTC_USDT","size":"10","left":"8"}],"options_positions":[{"options_name":"BTC_USDT-20240329-32000-C","size":"10"}],"options_orders":[{"options_name":"BTC_USDT-20240329-32000-C","size":"100","left":"80"}],"spot_hedge":false}'
    r = requests.request('POST', host + prefix + url, headers=headers, data=body)
    print(r.json())
    
    
    
    curl -X POST https://api.gateio.ws/api/v4/unified/portfolio_calculator \
      -H 'Content-Type: application/json' \
      -H 'Accept: application/json'
    
    

    POST /unified/portfolio_calculator

    Portfolio margin calculator

    Portfolio Margin Calculator When inputting a simulated position portfolio, each position includes the position name and quantity held, supporting markets within the range of BTC and ETH perpetual contracts, options, and spot markets. When inputting simulated orders, each order includes the market identifier, order price, and order quantity, supporting markets within the range of BTC and ETH perpetual contracts, options, and spot markets. Market orders are not included.

    Body parameter

    {
      "spot_balances": [
        {
          "currency": "BTC",
          "equity": "-1",
          "freeze": "10"
        }
      ],
      "spot_orders": [
        {
          "currency_pairs": "BTC_USDT",
          "order_price": "344",
          "size": "100",
          "left": "100",
          "type": "sell"
        }
      ],
      "futures_positions": [
        {
          "contract": "BTC_USDT",
          "size": "100"
        }
      ],
      "futures_orders": [
        {
          "contract": "BTC_USDT",
          "size": "10",
          "left": "8"
        }
      ],
      "options_positions": [
        {
          "options_name": "BTC_USDT-20240329-32000-C",
          "size": "10"
        }
      ],
      "options_orders": [
        {
          "options_name": "BTC_USDT-20240329-32000-C",
          "size": "100",
          "left": "80"
        }
      ],
      "spot_hedge": false
    }
    

    Parameters

    Name In Type Required Description
    body body object true none
    » spot_balances body array false Spot
    »» None body object false Spot
    »»» currency body string true Currency name
    »»» equity body string true Currency equity, where equity = balance - borrowed, represents the net delta exposure
    »» spot_orders body array false Spot orders
    »»» None body object false Spot orders
    »»»» currency_pairs body string true Currency pair
    »»»» order_price body string true Price
    »»»» count body string false Initial order quantity for spot trading pairs, not involved in actual calculation.
    »»»» left body string true Unfilled quantity, involved in actual calculation.
    »»»» type body string true Order type, sell - sell order, buy - buy order.
    »»» futures_positions body array false Futures positions
    »»»» None body object false Futures positions
    »»»»» contract body string true Futures name, currently only supports perpetual futures for BTC and ETH with USDT.
    »»»»» size body string true Position size, measured in contract units.
    »»»» futures_orders body array false Futures order
    »»»»» None body object false Futures order
    »»»»»» contract body string true Futures name, currently only supports perpetual futures for BTC and ETH with USDT.
    »»»»»» size body string true Futures quantity, representing the initial order quantity, not involved in actual settlement.
    »»»»»» left body string true Unfilled contract quantity, involved in actual calculation
    »»»»» options_positions body array false Options positions
    »»»»»» None body object false Options positions
    »»»»»»» options_name body string true Option name, currently only supports options for BTC and ETH with USDT.
    »»»»»»» size body string true Position size, measured in contract units.
    »»»»»» options_orders body array false Option orders
    »»»»»»» None body object false Option orders
    »»»»»»»» options_name body string true Option name, currently only supports options for BTC and ETH with USDT.
    »»»»»»»» size body string true Initial order quantity, not involved in actual calculation
    »»»»»»»» left body string true Unfilled contract quantity, involved in actual calculation
    »»»»»»» spot_hedge body boolean false Whether to enable spot hedging.

    # Detailed descriptions

    »»» equity: Currency equity, where equity = balance - borrowed, represents the net delta exposure of your spot positions, which can be negative. Currently only supports three currencies: BTC, ETH.

    »»»» count: Initial order quantity for spot trading pairs, not involved in actual calculation. Currently only supports three currencies: BTC, ETH.

    Example responses

    200 Response

    {
      "maintain_margin_total": "0.000000000000",
      "initial_margin_total": "0.000000000000",
      "calculate_time": "1709014486",
      "risk_unit": [
        {
          "symbol": "BTC",
          "margin_result": [
            {
              "type": "original_position",
              "profit_loss_ranges": [
                {
                  "price_percentage": "-0.200000000000",
                  "implied_volatility_percentage": "-0.300000000000",
                  "profit_loss": "0.000000000000"
                },
                {
                  "price_percentage": "-0.160000000000",
                  "implied_volatility_percentage": "-0.300000000000",
                  "profit_loss": "0.000000000000"
                },
                {
                  "price_percentage": "-0.120000000000",
                  "implied_volatility_percentage": "-0.300000000000",
                  "profit_loss": "0.000000000000"
                },
                {
                  "price_percentage": "-0.080000000000",
                  "implied_volatility_percentage": "-0.300000000000",
                  "profit_loss": "0.000000000000"
                },
                {
                  "price_percentage": "-0.040000000000",
                  "implied_volatility_percentage": "-0.300000000000",
                  "profit_loss": "0.000000000000"
                },
                {
                  "price_percentage": "0.000000000000",
                  "implied_volatility_percentage": "-0.300000000000",
                  "profit_loss": "0.000000000000"
                },
                {
                  "price_percentage": "0.040000000000",
                  "implied_volatility_percentage": "-0.300000000000",
                  "profit_loss": "0.000000000000"
                },
                {
                  "price_percentage": "0.080000000000",
                  "implied_volatility_percentage": "-0.300000000000",
                  "profit_loss": "0.000000000000"
                },
                {
                  "price_percentage": "0.120000000000",
                  "implied_volatility_percentage": "-0.300000000000",
                  "profit_loss": "0.000000000000"
                },
                {
                  "price_percentage": "0.160000000000",
                  "implied_volatility_percentage": "-0.300000000000",
                  "profit_loss": "0.000000000000"
                },
                {
                  "price_percentage": "0.200000000000",
                  "implied_volatility_percentage": "-0.300000000000",
                  "profit_loss": "0.000000000000"
                }
              ],
              "max_loss": {
                "price_percentage": "-0.200000000000",
                "implied_volatility_percentage": "-0.300000000000",
                "profit_loss": "0.000000000000"
              },
              "mr1": "0.000000000000",
              "mr2": "0.000000000000",
              "mr3": "0.000000000000",
              "mr4": "0.000000000000"
            }
          ],
          "maintain_margin": "0.000000000000",
          "initial_margin": "0.000000000000"
        }
      ]
    }
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successfully retrieved Inline

    Response Schema

    Status Code 200

    The output of the portfolio margin calculator.

    Name Type Description
    » maintain_margin_total string Total maintenance margin, including only the portfolio margin calculation results for positions in the risk unit,
    excluding borrowed margin. If borrowing exists, conventional borrowing margin requirements will still apply.
    » initial_margin_total string Total initial margin, calculated as the maximum of the following three combinations: position,
    position + positive delta orders, position + negative delta orders.
    » calculate_time integer(int64) Calculate time
    » risk_unit array Risk unit
    »» None object Risk unit
    »»» symbol string Risk unit name
    »»» spot_in_use string Spot usage
    »»» maintain_margin string Maintenance margin
    »»» initial_margin string Initial margin
    »»» margin_result array Margin result
    »»»» None object Margin result
    »»»»» type string Position combination type
    original_position - Original position
    long_delta_original_position - Positive delta + Original position
    short_delta_original_position - Negative delta + Original position
    »»»»» profit_loss_ranges array The results of 33 pressure scenarios for MR1
    »»»»»» None object Profit and loss range
    »»»»»»» price_percentage string Percentage change in price
    »»»»»»» implied_volatility_percentage string Percentage change in implied volatility
    »»»»»»» profit_loss string PNL
    »»»»»» max_loss object Profit and loss range
    »»»»»»» price_percentage string Percentage change in price
    »»»»»»» implied_volatility_percentage string Percentage change in implied volatility
    »»»»»»» profit_loss string PNL
    »»»»»» mr1 string Stress testing
    »»»»»» mr2 string Basis spread risk
    »»»»»» mr3 string Volatility spread risk
    »»»»»» mr4 string Option short risk
    »»»»» delta string Total Delta of risk unit
    »»»»» gamma string Total Gamma of risk unit
    »»»»» theta string Total Theta of risk unit
    »»»»» vega string Total Vega of risk unit

    # Spot

    Spot trading

    # List all currencies' details

    Code samples

    # coding: utf-8
    import requests
    
    host = "https://api.gateio.ws"
    prefix = "/api/v4"
    headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
    
    url = '/spot/currencies'
    query_param = ''
    r = requests.request('GET', host + prefix + url, headers=headers)
    print(r.json())
    
    
    
    curl -X GET https://api.gateio.ws/api/v4/spot/currencies \
      -H 'Accept: application/json'
    
    

    GET /spot/currencies

    List all currencies' details

    Currency has two forms:

    1. Only currency name, e.g., BTC, USDT
    2. <currency>_<chain>, e.g., HT_ETH

    The latter one occurs when one currency has multiple chains. Currency detail contains a chain field whatever the form is. To retrieve all chains of one currency, you can use use all the details which has the name of the currency or name starting with <currency>_.

    Example responses

    200 Response

    [
      {
        "currency": "GT",
        "delisted": false,
        "withdraw_disabled": false,
        "withdraw_delayed": false,
        "deposit_disabled": false,
        "trade_disabled": false,
        "chain": "GT"
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) List retrieved [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    None array none
    » currency string Currency name
    » delisted boolean Whether currency is de-listed
    » withdraw_disabled boolean Whether currency's withdrawal is disabled
    » withdraw_delayed boolean Whether currency's withdrawal is delayed
    » deposit_disabled boolean Whether currency's deposit is disabled
    » trade_disabled boolean Whether currency's trading is disabled
    » fixed_rate string Fixed fee rate. Only for fixed rate currencies, not valid for normal currencies
    » chain string Chain of currency

    # Get details of a specific currency

    Code samples

    # coding: utf-8
    import requests
    
    host = "https://api.gateio.ws"
    prefix = "/api/v4"
    headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
    
    url = '/spot/currencies/GT'
    query_param = ''
    r = requests.request('GET', host + prefix + url, headers=headers)
    print(r.json())
    
    
    
    curl -X GET https://api.gateio.ws/api/v4/spot/currencies/GT \
      -H 'Accept: application/json'
    
    

    GET /spot/currencies/{currency}

    Get details of a specific currency

    Parameters

    Name In Type Required Description
    currency path string true Currency name

    Example responses

    200 Response

    {
      "currency": "GT",
      "delisted": false,
      "withdraw_disabled": false,
      "withdraw_delayed": false,
      "deposit_disabled": false,
      "trade_disabled": false,
      "chain": "GT"
    }
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successfully retrieved Inline

    Response Schema

    Status Code 200

    Name Type Description
    » currency string Currency name
    » delisted boolean Whether currency is de-listed
    » withdraw_disabled boolean Whether currency's withdrawal is disabled
    » withdraw_delayed boolean Whether currency's withdrawal is delayed
    » deposit_disabled boolean Whether currency's deposit is disabled
    » trade_disabled boolean Whether currency's trading is disabled
    » fixed_rate string Fixed fee rate. Only for fixed rate currencies, not valid for normal currencies
    » chain string Chain of currency

    # List all currency pairs supported

    Code samples

    # coding: utf-8
    import requests
    
    host = "https://api.gateio.ws"
    prefix = "/api/v4"
    headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
    
    url = '/spot/currency_pairs'
    query_param = ''
    r = requests.request('GET', host + prefix + url, headers=headers)
    print(r.json())
    
    
    
    curl -X GET https://api.gateio.ws/api/v4/spot/currency_pairs \
      -H 'Accept: application/json'
    
    

    GET /spot/currency_pairs

    List all currency pairs supported

    Example responses

    200 Response

    [
      {
        "id": "ETH_USDT",
        "base": "ETH",
        "quote": "USDT",
        "fee": "0.2",
        "min_base_amount": "0.001",
        "min_quote_amount": "1.0",
        "max_base_amount": "10000",
        "max_quote_amount": "10000000",
        "amount_precision": 3,
        "precision": 6,
        "trade_status": "tradable",
        "sell_start": 1516378650,
        "buy_start": 1516378650
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) All currency pairs retrieved [CurrencyPair]

    # Get details of a specifc currency pair

    Code samples

    # coding: utf-8
    import requests
    
    host = "https://api.gateio.ws"
    prefix = "/api/v4"
    headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
    
    url = '/spot/currency_pairs/ETH_BTC'
    query_param = ''
    r = requests.request('GET', host + prefix + url, headers=headers)
    print(r.json())
    
    
    
    curl -X GET https://api.gateio.ws/api/v4/spot/currency_pairs/ETH_BTC \
      -H 'Accept: application/json'
    
    

    GET /spot/currency_pairs/{currency_pair}

    Get details of a specifc currency pair

    Parameters

    Name In Type Required Description
    currency_pair path string true Currency pair

    Example responses

    200 Response

    {
      "id": "ETH_USDT",
      "base": "ETH",
      "quote": "USDT",
      "fee": "0.2",
      "min_base_amount": "0.001",
      "min_quote_amount": "1.0",
      "max_base_amount": "10000",
      "max_quote_amount": "10000000",
      "amount_precision": 3,
      "precision": 6,
      "trade_status": "tradable",
      "sell_start": 1516378650,
      "buy_start": 1516378650
    }
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successfully retrieved CurrencyPair

    # Retrieve ticker information

    Code samples

    # coding: utf-8
    import requests
    
    host = "https://api.gateio.ws"
    prefix = "/api/v4"
    headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
    
    url = '/spot/tickers'
    query_param = ''
    r = requests.request('GET', host + prefix + url, headers=headers)
    print(r.json())
    
    
    
    curl -X GET https://api.gateio.ws/api/v4/spot/tickers \
      -H 'Accept: application/json'
    
    

    GET /spot/tickers

    Retrieve ticker information

    Return only related data if currency_pair is specified; otherwise return all of them

    Parameters

    Name In Type Required Description
    currency_pair query string false Currency pair
    timezone query string false Timezone

    # Enumerated Values

    Parameter Value
    timezone utc0
    timezone utc8
    timezone all

    Example responses

    200 Response

    [
      {
        "currency_pair": "BTC3L_USDT",
        "last": "2.46140352",
        "lowest_ask": "2.477",
        "highest_bid": "2.4606821",
        "change_percentage": "-8.91",
        "change_utc0": "-8.91",
        "change_utc8": "-8.91",
        "base_volume": "656614.0845820589",
        "quote_volume": "1602221.66468375534639404191",
        "high_24h": "2.7431",
        "low_24h": "1.9863",
        "etf_net_value": "2.46316141",
        "etf_pre_net_value": "2.43201848",
        "etf_pre_timestamp": 1611244800,
        "etf_leverage": "2.2803019447281203"
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successfully retrieved [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    » currency_pair string Currency pair
    » last string Last trading price
    » lowest_ask string Recent lowest ask
    » highest_bid string Recent highest bid
    » change_percentage string Change percentage in the last 24h
    » change_utc0 string utc0 timezone, the percentage change in the last 24 hours
    » change_utc8 string utc8 timezone, the percentage change in the last 24 hours
    » base_volume string Base currency trade volume in the last 24h
    » quote_volume string Quote currency trade volume in the last 24h
    » high_24h string Highest price in 24h
    » low_24h string Lowest price in 24h
    » etf_net_value string ETF net value
    » etf_pre_net_value string|null ETF previous net value at re-balancing time
    » etf_pre_timestamp integer(int64)|null ETF previous re-balancing time
    » etf_leverage string|null ETF current leverage

    # Retrieve order book

    Code samples

    # coding: utf-8
    import requests
    
    host = "https://api.gateio.ws"
    prefix = "/api/v4"
    headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
    
    url = '/spot/order_book'
    query_param = 'currency_pair=BTC_USDT'
    r = requests.request('GET', host + prefix + url + "?" + query_param, headers=headers)
    print(r.json())
    
    
    
    curl -X GET https://api.gateio.ws/api/v4/spot/order_book?currency_pair=BTC_USDT \
      -H 'Accept: application/json'
    
    

    GET /spot/order_book

    Retrieve order book

    Order book will be sorted by price from high to low on bids; low to high on asks

    Parameters

    Name In Type Required Description
    currency_pair query string true Currency pair
    interval query string false Order depth. 0 means no aggregation is applied. default to 0
    limit query integer false Maximum number of order depth data in asks or bids
    with_id query boolean false Return order book ID

    Example responses

    200 Response

    {
      "id": 123456,
      "current": 1623898993123,
      "update": 1623898993121,
      "asks": [
        [
          "1.52",
          "1.151"
        ],
        [
          "1.53",
          "1.218"
        ]
      ],
      "bids": [
        [
          "1.17",
          "201.863"
        ],
        [
          "1.16",
          "725.464"
        ]
      ]
    }
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successfully retrieved Inline

    Response Schema

    Status Code 200

    Name Type Description
    » id integer(int64) Order book ID, which is updated whenever the order book is changed. Valid only when with_id is set to true
    » current integer(int64) The timestamp of the response data being generated (in milliseconds)
    » update integer(int64) The timestamp of when the orderbook last changed (in milliseconds)
    » asks array Asks order depth
    »» None array price and amount
    » bids array Bids order depth
    »» None array price and amount

    # Retrieve market trades

    Code samples

    # coding: utf-8
    import requests
    
    host = "https://api.gateio.ws"
    prefix = "/api/v4"
    headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
    
    url = '/spot/trades'
    query_param = 'currency_pair=BTC_USDT'
    r = requests.request('GET', host + prefix + url + "?" + query_param, headers=headers)
    print(r.json())
    
    
    
    curl -X GET https://api.gateio.ws/api/v4/spot/trades?currency_pair=BTC_USDT \
      -H 'Accept: application/json'
    
    

    GET /spot/trades

    Retrieve market trades

    You can use from and to to query by time range, or use last_id by scrolling page. The default behavior is by time range.

    Scrolling query using last_id is not recommended any more. If last_id is specified, time range query parameters will be ignored.

    Parameters

    Name In Type Required Description
    currency_pair query string true Currency pair
    limit query integer(int32) false Maximum number of records to be returned in a single list. Default: 100, Minimum: 1, Maximum: 1000
    last_id query string false Specify list staring point using the id of last record in previous list-query results
    reverse query boolean false Whether the id of records to be retrieved should be less than the last_id specified. Default to false.
    from query integer(int64) false Start timestamp of the query
    to query integer(int64) false Time range ending, default to current time
    page query integer(int32) false Page number

    # Detailed descriptions

    reverse: Whether the id of records to be retrieved should be less than the last_id specified. Default to false.

    When last_id is specified. Set reverse to true to trace back trading history; false to retrieve latest tradings.

    No effect if last_id is not specified.

    Example responses

    200 Response

    [
      {
        "id": "1232893232",
        "create_time": "1548000000",
        "create_time_ms": "1548000000123.456",
        "order_id": "4128442423",
        "side": "buy",
        "role": "maker",
        "amount": "0.15",
        "price": "0.03",
        "fee": "0.0005",
        "fee_currency": "ETH",
        "point_fee": "0",
        "gt_fee": "0",
        "sequence_id": "588018",
        "text": "t-test"
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) List retrieved [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    None array none
    » id string Trade ID
    » create_time string Trading time
    » create_time_ms string Trading time, with millisecond precision
    » currency_pair string Currency pair
    » side string Order side
    » role string Trade role. No value in public endpoints
    » amount string Trade amount
    » price string Order price
    » order_id string Related order ID. No value in public endpoints
    » fee string Fee deducted. No value in public endpoints
    » fee_currency string Fee currency unit. No value in public endpoints
    » point_fee string Points used to deduct fee. No value in public endpoints
    » gt_fee string GT used to deduct fee. No value in public endpoints
    » amend_text string The custom data that the user remarked when amending the order
    » sequence_id string Represents a unique and consecutive trade ID within a single market.
    It is used to track and identify trades in the specific market
    » text string User defined information. No value in public endpoints

    # Enumerated Values

    Property Value
    side buy
    side sell
    role taker
    role maker

    # Market candlesticks

    Code samples

    # coding: utf-8
    import requests
    
    host = "https://api.gateio.ws"
    prefix = "/api/v4"
    headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
    
    url = '/spot/candlesticks'
    query_param = 'currency_pair=BTC_USDT'
    r = requests.request('GET', host + prefix + url + "?" + query_param, headers=headers)
    print(r.json())
    
    
    
    curl -X GET https://api.gateio.ws/api/v4/spot/candlesticks?currency_pair=BTC_USDT \
      -H 'Accept: application/json'
    
    

    GET /spot/candlesticks

    Market candlesticks

    Maximum of 1000 points can be returned in a query. Be sure not to exceed the limit when specifying from, to and interval

    Parameters

    Name In Type Required Description
    currency_pair query string true Currency pair
    limit query integer false Maximum recent data points to return. limit is conflicted with from and to. If either from or to is specified, request will be rejected.
    from query integer(int64) false Start time of candlesticks, formatted in Unix timestamp in seconds. Default toto - 100 * interval if not specified
    to query integer(int64) false End time of candlesticks, formatted in Unix timestamp in seconds. Default to current time
    interval query string false Interval time between data points. Note that 30d means 1 natual month, not 30 days

    # Enumerated Values

    Parameter Value
    interval 10s
    interval 1m
    interval 5m
    interval 15m
    interval 30m
    interval 1h
    interval 4h
    interval 8h
    interval 1d
    interval 7d
    interval 30d

    Example responses

    200 Response

    [
      [
        "1539852480",
        "971519.677",
        "0.0021724",
        "0.0021922",
        "0.0021724",
        "0.0021737",
        "true"
      ]
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successfully retrieved [[string]]

    Response Schema

    Status Code 200

    Name Type Description
    » None array K-line data for each time granularity, arranged from left to right:

    - Unix timestamp with second precision
    - Trading volume in quote currency
    - Closing price
    - Highest price
    - Lowest price
    - Opening price
    - Trading volume in base currency
    - Whether the window is closed; true indicates the end of this segment of candlestick chart data, false indicates that this segment of candlestick chart data is not yet complete

    # Query user trading fee rates

    Code samples

    # 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 = '/spot/fee'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/spot/fee"
    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 /spot/fee

    Query user trading fee rates

    This API is deprecated in favour of new fee retrieving API /wallet/fee.

    Parameters

    Name In Type Required Description
    currency_pair query string false Specify a currency pair to retrieve precise fee rate

    # Detailed descriptions

    currency_pair: Specify a currency pair to retrieve precise fee rate

    This field is optional. In most cases, the fee rate is identical among all currency pairs

    Example responses

    200 Response

    {
      "user_id": 10001,
      "taker_fee": "0.002",
      "maker_fee": "0.002",
      "gt_discount": false,
      "gt_taker_fee": "0",
      "gt_maker_fee": "0",
      "loan_fee": "0.18",
      "point_type": "1",
      "currency_pair": "BTC_USDT",
      "debit_fee": 3
    }
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successfully retrieved Inline

    Response Schema

    Status Code 200

    Name Type Description
    » user_id integer(int64) User ID
    » taker_fee string taker fee rate
    » maker_fee string maker fee rate
    » gt_discount boolean If GT deduction is enabled
    » gt_taker_fee string Taker fee rate if using GT deduction. It will be 0 if GT deduction is disabled
    » gt_maker_fee string Maker fee rate if using GT deduction. It will be 0 if GT deduction is disabled
    » loan_fee string Loan fee rate of margin lending
    » point_type string Point type. 0 - Initial version. 1 - new version since 202009
    » currency_pair string Currency pair
    » debit_fee integer Deduction types for rates, 1 - GT deduction, 2 - Point card deduction, 3 - VIP rates

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Query a batch of user trading fee rates

    Code samples

    # 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 = '/spot/batch_fee'
    query_param = 'currency_pairs=BTC_USDT,ETH_USDT'
    # 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 + "?" + query_param, headers=headers)
    print(r.json())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/spot/batch_fee"
    query_param="currency_pairs=BTC_USDT,ETH_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"
    
    

    GET /spot/batch_fee

    Query a batch of user trading fee rates

    Parameters

    Name In Type Required Description
    currency_pairs query string true A request can only query up to 50 currency pairs

    Example responses

    200 Response

    {
      "BTC_USDT": {
        "user_id": 10001,
        "taker_fee": "0.002",
        "maker_fee": "0.002",
        "gt_discount": false,
        "gt_taker_fee": "0",
        "gt_maker_fee": "0",
        "loan_fee": "0.18",
        "point_type": "1",
        "currency_pair": "BTC_USDT",
        "debit_fee": 3
      },
      "GT_USDT": {
        "user_id": 10001,
        "taker_fee": "0.002",
        "maker_fee": "0.002",
        "gt_discount": false,
        "gt_taker_fee": "0",
        "gt_maker_fee": "0",
        "loan_fee": "0.18",
        "point_type": "1",
        "currency_pair": "GT_USDT",
        "debit_fee": 3
      },
      "ETH_USDT": {
        "user_id": 10001,
        "taker_fee": "0.002",
        "maker_fee": "0.002",
        "gt_discount": false,
        "gt_taker_fee": "0",
        "gt_maker_fee": "0",
        "loan_fee": "0.18",
        "point_type": "1",
        "currency_pair": "ETH_USDT",
        "debit_fee": 3
      }
    }
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Successfully retrieved Inline

    Response Schema

    Status Code 200

    Name Type Description
    » additionalProperties object none
    »» user_id integer(int64) User ID
    »» taker_fee string taker fee rate
    »» maker_fee string maker fee rate
    »» gt_discount boolean If GT deduction is enabled
    »» gt_taker_fee string Taker fee rate if using GT deduction. It will be 0 if GT deduction is disabled
    »» gt_maker_fee string Maker fee rate if using GT deduction. It will be 0 if GT deduction is disabled
    »» loan_fee string Loan fee rate of margin lending
    »» point_type string Point type. 0 - Initial version. 1 - new version since 202009
    »» currency_pair string Currency pair
    »» debit_fee integer Deduction types for rates, 1 - GT deduction, 2 - Point card deduction, 3 - VIP rates

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # List spot accounts

    Code samples

    # 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 = '/spot/accounts'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/spot/accounts"
    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 /spot/accounts

    List spot accounts

    Parameters

    Name In Type Required Description
    currency query string false Retrieve data of the specified currency

    Example responses

    200 Response

    [
      {
        "currency": "ETH",
        "available": "968.8",
        "locked": "0",
        "update_id": 98
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) List retrieved [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    » currency string Currency detail
    » available string Available amount
    » locked string Locked amount, used in trading
    » update_id integer Version number

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Query account book

    Code samples

    # 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 = '/spot/account_book'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/spot/account_book"
    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 /spot/account_book

    Query account book

    Record time range cannot exceed 30 days

    Parameters

    Name In Type Required Description
    currency query string false Retrieve data of the specified currency
    from query integer(int64) false Start timestamp of the query
    to query integer(int64) false Time range ending, default to current time
    page query integer(int32) false Page number
    limit query integer false Maximum number of records to be returned in a single list
    type query string false Only retrieve changes of the specified type. All types will be returned if not specified.

    Example responses

    200 Response

    [
      {
        "id": "123456",
        "time": 1547633726123,
        "currency": "BTC",
        "change": "1.03",
        "balance": "4.59316525194",
        "type": "margin_in",
        "text": "3815099"
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) List retrieved [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    » id string Balance change record ID
    » time integer(int64) The timestamp of the change (in milliseconds)
    » currency string Currency changed
    » change string Amount changed. Positive value means transferring in, while negative out
    » balance string Balance after change
    » type string Account book type. Please refer to account book type for more detail
    » text string Additional information

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Create a batch of orders

    Code samples

    # 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 = '/spot/batch_orders'
    query_param = ''
    body='[{"text":"t-abc123","currency_pair":"BTC_USDT","type":"limit","account":"unified","side":"buy","amount":"0.001","price":"65000","time_in_force":"gtc","iceberg":"0"}]'
    # 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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="POST"
    url="/spot/batch_orders"
    query_param=""
    body_param='[{"text":"t-abc123","currency_pair":"BTC_USDT","type":"limit","account":"unified","side":"buy","amount":"0.001","price":"65000","time_in_force":"gtc","iceberg":"0"}]'
    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"
    
    

    POST /spot/batch_orders

    Create a batch of orders

    Batch orders requirements:

    1. custom order field text is required
    2. At most 4 currency pairs, maximum 10 orders each, are allowed in one request
    3. No mixture of spot orders and margin orders, i.e. account must be identical for all orders

    Body parameter

    [
      {
        "text": "t-abc123",
        "currency_pair": "BTC_USDT",
        "type": "limit",
        "account": "unified",
        "side": "buy",
        "amount": "0.001",
        "price": "65000",
        "time_in_force": "gtc",
        "iceberg": "0"
      }
    ]
    

    Parameters

    Name In Type Required Description
    body body array[Order] true none

    Example responses

    200 Response

    [
      {
        "order_id": "12332324",
        "amend_text": "t-123456",
        "text": "t-123456",
        "succeeded": true,
        "label": "",
        "message": "",
        "id": "12332324",
        "create_time": "1548000000",
        "update_time": "1548000100",
        "create_time_ms": 1548000000123,
        "update_time_ms": 1548000100123,
        "currency_pair": "ETC_BTC",
        "status": "cancelled",
        "type": "limit",
        "account": "spot",
        "side": "buy",
        "amount": "1",
        "price": "5.00032",
        "time_in_force": "gtc",
        "iceberg": "0",
        "left": "0.5",
        "filled_amount": "1.242",
        "filled_total": "2.50016",
        "avg_deal_price": "5.00032",
        "fee": "0.005",
        "fee_currency": "ETH",
        "point_fee": "0",
        "gt_fee": "0",
        "gt_discount": false,
        "rebated_fee": "0",
        "rebated_fee_currency": "BTC",
        "stp_act": "cn",
        "finish_as": "stp",
        "stp_id": 10240
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) Request is completed [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    None array [Batch order details]
    » None object Batch order details
    »» order_id string Order ID
    »» amend_text string The custom data that the user remarked when amending the order
    »» text string User defined information. If not empty, must follow the rules below:

    1. prefixed with t-
    2. no longer than 28 bytes without t- prefix
    3. can only include 0-9, A-Z, a-z, underscore(_), hyphen(-) or dot(.)
    »» succeeded boolean Whether the batch of orders succeeded
    »» label string Error label, if any, otherwise an empty string
    »» message string Detailed error message, if any, otherwise an empty string
    »» id string Order ID
    »» create_time string Creation time of order
    »» update_time string Last modification time of order
    »» create_time_ms integer(int64) Creation time of order (in milliseconds)
    »» update_time_ms integer(int64) Last modification time of order (in milliseconds)
    »» status string Order status

    - open: to be filled
    - closed: filled
    - cancelled: cancelled
    »» currency_pair string Currency pair
    »» type string Order Type

    - limit : Limit Order
    - market : Market Order
    »» account string Account type. spot - use spot account; margin - use margin account; cross_margin - use cross margin account, unified - unified account
    »» side string Order side
    »» amount string Trade amount
    »» price string Order price
    »» time_in_force string Time in force

    - gtc: GoodTillCancelled
    - ioc: ImmediateOrCancelled, taker only
    - poc: PendingOrCancelled, makes a post-only order that always enjoys a maker fee
    - fok: FillOrKill, fill either completely or none
    »» iceberg string Amount to display for the iceberg order. Null or 0 for normal orders. Hiding all amount is not supported.
    »» auto_repay boolean Enable or disable automatic repayment for automatic borrow loan generated by cross margin order. Default is disabled. Note that:

    1. This field is only effective for cross margin orders. Margin account does not support setting auto repayment for orders.
    2. auto_borrow and auto_repay can be both set to true in one order.
    »» left string Amount left to fill
    »» filled_amount string Amount traded to fill
    »» fill_price string Total filled in quote currency. Deprecated in favor of filled_total
    »» filled_total string Total filled in quote currency
    »» avg_deal_price string Average fill price
    »» fee string Fee deducted
    »» fee_currency string Fee currency unit
    »» point_fee string Points used to deduct fee
    »» gt_fee string GT used to deduct fee
    »» gt_discount boolean Whether GT fee discount is used
    »» rebated_fee string Rebated fee
    »» rebated_fee_currency string Rebated fee currency unit
    »» stp_id integer Orders between users in the same stp_id group are not allowed to be self-traded

    1. If the stp_id of two orders being matched is non-zero and equal, they will not be executed. Instead, the corresponding strategy will be executed based on the stp_act of the taker.
    2. stp_id returns 0 by default for orders that have not been set for STP group
    »» stp_act string Self-Trading Prevention Action. Users can use this field to set self-trade prevetion strategies

    1. After users join the STP Group, he can pass stp_act to limit the user's self-trade prevetion strategy. If stp_act is not passed, the default is cn strategy。
    2. When the user does not join the STP group, an error will be returned when passing the stp_act parameter。
    3. If the user did not use 'stp_act' when placing the order, 'stp_act' will return '-'

    - cn: Cancel newest, Cancel new orders and keep old ones
    - co: Cancel oldest, Cancel old orders and keep new ones
    - cb: Cancel both, Both old and new orders will be cancelled
    »» finish_as string How the order was finished.

    - open: processing
    - filled: filled totally
    - cancelled: manually cancelled
    - ioc: time in force is IOC, finish immediately
    - stp: cancelled because self trade prevention

    # Enumerated Values

    Property Value
    status open
    status closed
    status cancelled
    type limit
    type market
    account spot
    account margin
    account cross_margin
    account unified
    side buy
    side sell
    time_in_force gtc
    time_in_force ioc
    time_in_force poc
    time_in_force fok
    stp_act cn
    stp_act co
    stp_act cb
    stp_act -
    finish_as open
    finish_as filled
    finish_as cancelled
    finish_as ioc
    finish_as stp

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # List all open orders

    Code samples

    # 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 = '/spot/open_orders'
    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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/spot/open_orders"
    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 /spot/open_orders

    List all open orders

    List open orders in all currency pairs.

    Note that pagination parameters affect record number in each currency pair's open order list. No pagination is applied to the number of currency pairs returned. All currency pairs with open orders will be returned.

    Spot,portfolio and margin orders are returned by default. To list cross margin orders, account must be set to cross_margin

    Parameters

    Name In Type Required Description
    page query integer(int32) false Page number
    limit query integer false Maximum number of records returned in one page in each currency pair
    account query string false Specify operation account. Default to spot ,portfolio and margin account if not specified. Set to cross_margin to operate against margin account. Portfolio margin account must set to cross_margin only

    Example responses

    200 Response

    [
      {
        "currency_pair": "ETH_BTC",
        "total": 1,
        "orders": [
          {
            "id": "12332324",
            "text": "t-123456",
            "create_time": "1548000000",
            "update_time": "1548000100",
            "currency_pair": "ETH_BTC",
            "status": "open",
            "type": "limit",
            "account": "spot",
            "side": "buy",
            "amount": "1",
            "price": "5.00032",
            "time_in_force": "gtc",
            "left": "0.5",
            "filled_total": "2.50016",
            "fee": "0.005",
            "fee_currency": "ETH",
            "point_fee": "0",
            "gt_fee": "0",
            "gt_discount": false,
            "rebated_fee": "0",
            "rebated_fee_currency": "BTC"
          }
        ]
      }
    ]
    

    Responses

    Status Meaning Description Schema
    200 OK (opens new window) List retrieved [Inline]

    Response Schema

    Status Code 200

    Name Type Description
    » currency_pair string Currency pair
    » total integer The total number of pending orders for this trading pair on the current page
    » orders array none
    »» None object Spot order details
    »»» id string Order ID
    »»» text string User defined information. If not empty, must follow the rules below:

    1. prefixed with t-
    2. no longer than 28 bytes without t- prefix
    3. can only include 0-9, A-Z, a-z, underscore(_), hyphen(-) or dot(.)

    Besides user defined information, reserved contents are listed below, denoting how the order is created:

    - 101: from android
    - 102: from IOS
    - 103: from IPAD
    - 104: from webapp
    - 3: from web
    - 2: from apiv2
    - apiv4: from apiv4
    »»» amend_text string The custom data that the user remarked when amending the order
    »»» create_time string Creation time of order
    »»» update_time string Last modification time of order
    »»» create_time_ms integer(int64) Creation time of order (in milliseconds)
    »»» update_time_ms integer(int64) Last modification time of order (in milliseconds)
    »»» status string Order status

    - open: to be filled
    - closed: filled
    - cancelled: cancelled
    »»» currency_pair string Currency pair
    »»» type string Order Type

    - limit : Limit Order
    - market : Market Order
    »»» account string Account types, spot - spot account, margin - margin account, unified - unified account, cross_margin - cross margin account. Portfolio margin accounts can only be set to cross_margin
    »»» side string Order side
    »»» amount string When type is limit, it refers to base currency. For instance, BTC_USDT means BTC
    When type is market, it refers to different currency according to side
    - side : buy means quote currency, BTC_USDT means USDT
    - side : sell means base currency,BTC_USDT means BTC
    »»» price string Price can't be empty when type= limit
    »»» time_in_force string Time in force

    - gtc: GoodTillCancelled
    - ioc: ImmediateOrCancelled, taker only
    - poc: PendingOrCancelled, makes a post-only order that always enjoys a maker fee
    - fok: FillOrKill, fill either completely or none
    Only ioc and fok are supported when type=market
    »»» iceberg string Amount to display for the iceberg order. Null or 0 for normal orders. Hiding all amount is not supported.
    »»» auto_repay boolean Enable or disable automatic repayment for automatic borrow loan generated by cross margin order. Default is disabled. Note that:

    1. This field is only effective for cross margin orders. Margin account does not support setting auto repayment for orders.
    2. auto_borrow and auto_repay can be both set to true in one order.
    »»» left string Amount left to fill
    »»» filled_amount string Amount traded to fill
    »»» fill_price string Total filled in quote currency. Deprecated in favor of filled_total
    »»» filled_total string Total filled in quote currency
    »»» avg_deal_price string Average fill price
    »»» fee string Fee deducted
    »»» fee_currency string Fee currency unit
    »»» point_fee string Points used to deduct fee
    »»» gt_fee string GT used to deduct fee
    »»» gt_maker_fee string GT used to deduct maker fee
    »»» gt_taker_fee string GT used to deduct taker fee
    »»» gt_discount boolean Whether GT fee discount is used
    »»» rebated_fee string Rebated fee
    »»» rebated_fee_currency string Rebated fee currency unit
    »»» stp_id integer Orders between users in the same stp_id group are not allowed to be self-traded

    1. If the stp_id of two orders being matched is non-zero and equal, they will not be executed. Instead, the corresponding strategy will be executed based on the stp_act of the taker.
    2. stp_id returns 0 by default for orders that have not been set for STP group
    »»» stp_act string Self-Trading Prevention Action. Users can use this field to set self-trade prevetion strategies

    1. After users join the STP Group, he can pass stp_act to limit the user's self-trade prevetion strategy. If stp_act is not passed, the default is cn strategy。
    2. When the user does not join the STP group, an error will be returned when passing the stp_act parameter。
    3. If the user did not use 'stp_act' when placing the order, 'stp_act' will return '-'

    - cn: Cancel newest, Cancel new orders and keep old ones
    - co: Cancel oldest, Cancel old orders and keep new ones
    - cb: Cancel both, Both old and new orders will be cancelled
    »»» finish_as string How the order was finished.

    - open: processing
    - filled: filled totally
    - cancelled: manually cancelled
    - ioc: time in force is IOC, finish immediately
    - stp: cancelled because self trade prevention

    # Enumerated Values

    Property Value
    status open
    status closed
    status cancelled
    type limit
    type market
    side buy
    side sell
    time_in_force gtc
    time_in_force ioc
    time_in_force poc
    time_in_force fok
    stp_act cn
    stp_act co
    stp_act cb
    stp_act -
    finish_as open
    finish_as filled
    finish_as cancelled
    finish_as ioc
    finish_as stp

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # close position when cross-currency is disabled

    Code samples

    # 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 = '/spot/cross_liquidate_orders'
    query_param = ''
    body='{"currency_pair":"GT_USDT","amount":"12","price":"10.15","text":"t-34535"}'
    # 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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="POST"
    url="/spot/cross_liquidate_orders"
    query_param=""
    body_param='{"currency_pair":"GT_USDT","amount":"12","price":"10.15","text":"t-34535"}'
    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"
    
    

    POST /spot/cross_liquidate_orders

    close position when cross-currency is disabled

    Currently, only cross-margin accounts are supported to close position when cross currencies are disabled. Maximum buy quantity = (unpaid principal and interest - currency balance - the amount of the currency in the order book) / 0.998

    Body parameter

    {
      "currency_pair": "GT_USDT",
      "amount": "12",
      "price": "10.15",
      "text": "t-34535"
    }
    

    Parameters

    Name In Type Required Description
    body body object true none
    » text body string false User defined information. If not empty, must follow the rules below:
    » currency_pair body string true Currency pair
    » amount body string true Trade amount
    » price body string true Order price
    » action_mode body string false Processing Mode:

    # Detailed descriptions

    » text: User defined information. If not empty, must follow the rules below:

    1. prefixed with t-
    2. no longer than 28 bytes without t- prefix
    3. can only include 0-9, A-Z, a-z, underscore(_), hyphen(-) or dot(.)

    » action_mode: Processing Mode:

    Different fields are returned when placing an order based on action_mode. This field is only valid during the request, and it is not included in the response result ACK: Asynchronous mode, only returns key order fields RESULT: No clearing information FULL: Full mode (default)

    Example responses

    201 Response

    {
      "id": "1852454420",
      "text": "t-abc123",
      "amend_text": "-",
      "create_time": "1710488334",
      "update_time": "1710488334",
      "create_time_ms": 1710488334073,
      "update_time_ms": 1710488334074,
      "status": "closed",
      "currency_pair": "BTC_USDT",
      "type": "limit",
      "account": "unified",
      "side": "buy",
      "amount": "0.001",
      "price": "65000",
      "time_in_force": "gtc",
      "iceberg": "0",
      "left": "0",
      "filled_amount": "0.001",
      "fill_price": "63.4693",
      "filled_total": "63.4693",
      "avg_deal_price": "63469.3",
      "fee": "0.00000022",
      "fee_currency": "BTC",
      "point_fee": "0",
      "gt_fee": "0",
      "gt_maker_fee": "0",
      "gt_taker_fee": "0",
      "gt_discount": false,
      "rebated_fee": "0",
      "rebated_fee_currency": "USDT",
      "finish_as": "filled"
    }
    

    Responses

    Status Meaning Description Schema
    201 Created (opens new window) order created Order

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # Create an order

    Code samples

    # 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 = '/spot/orders'
    query_param = ''
    body='{"text":"t-abc123","currency_pair":"BTC_USDT","type":"limit","account":"unified","side":"buy","amount":"0.001","price":"65000","time_in_force":"gtc","iceberg":"0"}'
    # 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())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="POST"
    url="/spot/orders"
    query_param=""
    body_param='{"text":"t-abc123","currency_pair":"BTC_USDT","type":"limit","account":"unified","side":"buy","amount":"0.001","price":"65000","time_in_force":"gtc","iceberg":"0"}'
    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"
    
    

    POST /spot/orders

    Create an order

    You can place orders with spot, portfolio, margin or cross margin account through setting the accountfield. It defaults to spot, which means spot account is used to place orders. If the user is using unified account, it defaults to the unified account.

    When margin account is used, i.e., account is margin, auto_borrow field can be set to true to enable the server to borrow the amount lacked using POST /margin/loans when your account's balance is not enough. Whether margin orders' fill will be used to repay margin loans automatically is determined by the auto repayment setting in your margin account, which can be updated or queried using /margin/auto_repay API.

    When cross margin account is used, i.e., account is cross_margin, auto_borrow can also be enabled to achieve borrowing the insufficient amount automatically if cross account's balance is not enough. But it differs from margin account that automatic repayment is determined by order's auto_repay field and only current order's fill will be used to repay cross margin loans.

    Automatic repayment will be triggered when the order is finished, i.e., its status is either cancelled or closed.

    Order status

    An order waiting to be filled is open, and it stays open until it is filled totally. If fully filled, order is finished and its status turns to closed.If the order is cancelled before it is totally filled, whether or not partially filled, its status is cancelled. Iceberg order

    iceberg field can be used to set the amount shown. Set to -1 to hide the order completely. Note that the hidden part's fee will be charged using taker's fee rate. Self Trade Prevention

    • Set stp_act to decide the strategy of self-trade prevention. For detailed usage, refer to the stp_act parameter in request body

    Body parameter

    {
      "text": "t-abc123",
      "currency_pair": "BTC_USDT",
      "type": "limit",
      "account": "unified",
      "side": "buy",
      "amount": "0.001",
      "price": "65000",
      "time_in_force": "gtc",
      "iceberg": "0"
    }
    

    Parameters

    Name In Type Required Description
    body body Order true none
    » text body string false User defined information. If not empty, must follow the rules below:
    » currency_pair body string true Currency pair
    » type body string false Order Type
    » account body string false Account types, spot - spot account, margin - margin account, unified - unified account, cross_margin - cross margin account. Portfolio margin accounts can only be set to cross_margin
    » side body string true Order side
    » amount body string true When type is limit, it refers to base currency. For instance, BTC_USDT means BTC
    » price body string false Price can't be empty when type= limit
    » time_in_force body string false Time in force
    » iceberg body string false Amount to display for the iceberg order. Null or 0 for normal orders. Hiding all amount is not supported.
    » auto_borrow body boolean false Used in margin or cross margin trading to allow automatic loan of insufficient amount if balance is not enough.
    » auto_repay body boolean false Enable or disable automatic repayment for automatic borrow loan generated by cross margin order. Default is disabled. Note that:
    » stp_act body string false Self-Trading Prevention Action. Users can use this field to set self-trade prevetion strategies
    » action_mode body string false Processing Mode:

    # Detailed descriptions

    » text: User defined information. If not empty, must follow the rules below:

    1. prefixed with t-
    2. no longer than 28 bytes without t- prefix
    3. can only include 0-9, A-Z, a-z, underscore(_), hyphen(-) or dot(.)

    Besides user defined information, reserved contents are listed below, denoting how the order is created:

    • 101: from android
    • 102: from IOS
    • 103: from IPAD
    • 104: from webapp
    • 3: from web
    • 2: from apiv2
    • apiv4: from apiv4

    » type: Order Type

    • limit : Limit Order
    • market : Market Order

    » amount: When type is limit, it refers to base currency. For instance, BTC_USDT means BTC When type is market, it refers to different currency according to side

    • side : buy means quote currency, BTC_USDT means USDT
    • side : sell means base currency,BTC_USDT means BTC

    » time_in_force: Time in force

    • gtc: GoodTillCancelled
    • ioc: ImmediateOrCancelled, taker only
    • poc: PendingOrCancelled, makes a post-only order that always enjoys a maker fee
    • fok: FillOrKill, fill either completely or none Only ioc and fok are supported when type=market

    » auto_repay: Enable or disable automatic repayment for automatic borrow loan generated by cross margin order. Default is disabled. Note that:

    1. This field is only effective for cross margin orders. Margin account does not support setting auto repayment for orders.
    2. auto_borrow and auto_repay can be both set to true in one order.

    » stp_act: Self-Trading Prevention Action. Users can use this field to set self-trade prevetion strategies

    1. After users join the STP Group, he can pass stp_act to limit the user's self-trade prevetion strategy. If stp_act is not passed, the default is cn strategy。
    2. When the user does not join the STP group, an error will be returned when passing the stp_act parameter。
    3. If the user did not use 'stp_act' when placing the order, 'stp_act' will return '-'
    • cn: Cancel newest, Cancel new orders and keep old ones
    • co: Cancel oldest, Cancel old orders and keep new ones
    • cb: Cancel both, Both old and new orders will be cancelled

    » action_mode: Processing Mode: When placing an order, different fields are returned based on action_mode. This field is only valid during the request and is not included in the response result ACK: Asynchronous mode, only returns key order fields RESULT: No clearing information FULL: Full mode (default)

    # Enumerated Values

    Parameter Value
    » type limit
    » type market
    » side buy
    » side sell
    » time_in_force gtc
    » time_in_force ioc
    » time_in_force poc
    » time_in_force fok
    » stp_act cn
    » stp_act co
    » stp_act cb
    » stp_act -

    Example responses

    ACK response body example

    {
      "id": "12332324",
      "text": "t-123456",
      "amend_text": "test2"
    }
    

    RESULT response body example

    {
      "id": "12332324",
      "text": "t-123456",
      "create_time": "1548000000",
      "update_time": "1548000100",
      "create_time_ms": 1548000000123,
      "update_time_ms": 1548000100123,
      "currency_pair": "ETH_BTC",
      "status": "cancelled",
      "type": "limit",
      "account": "spot",
      "side": "buy",
      "iceberg": "0",
      "amount": "1",
      "price": "5.00032",
      "time_in_force": "gtc",
      "auto_borrow": false,
      "left": "0.5",
      "filled_total": "2.50016",
      "avg_deal_price": "5.00032",
      "stp_act": "cn",
      "finish_as": "stp",
      "stp_id": 10240
    }
    

    FULL response body example

    {
      "id": "1852454420",
      "text": "t-abc123",
      "amend_text": "-",
      "create_time": "1710488334",
      "update_time": "1710488334",
      "create_time_ms": 1710488334073,
      "update_time_ms": 1710488334074,
      "status": "closed",
      "currency_pair": "BTC_USDT",
      "type": "limit",
      "account": "unified",
      "side": "buy",
      "amount": "0.001",
      "price": "65000",
      "time_in_force": "gtc",
      "iceberg": "0",
      "left": "0",
      "filled_amount": "0.001",
      "fill_price": "63.4693",
      "filled_total": "63.4693",
      "avg_deal_price": "63469.3",
      "fee": "0.00000022",
      "fee_currency": "BTC",
      "point_fee": "0",
      "gt_fee": "0",
      "gt_maker_fee": "0",
      "gt_taker_fee": "0",
      "gt_discount": false,
      "rebated_fee": "0",
      "rebated_fee_currency": "USDT",
      "finish_as": "filled"
    }
    

    Responses

    Status Meaning Description Schema
    201 Created (opens new window) Order created. Order

    WARNING

    To perform this operation, you must be authenticated by API key and secret

    # List orders

    Code samples

    # 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 = '/spot/orders'
    query_param = 'currency_pair=BTC_USDT&status=open'
    # 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 + "?" + query_param, headers=headers)
    print(r.json())
    
    
    key="YOUR_API_KEY"
    secret="YOUR_API_SECRET"
    host="https://api.gateio.ws"
    prefix="/api/v4"
    method="GET"
    url="/spot/orders"
    query_param="currency_pair=BTC_USDT&status=open"
    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"
    
    

    GET /spot/orders

    List orders

    Spot, portfolio and margin orders are returned by default. If cross margin orders are needed, account must be set to cross_margin

    When status is open, i.e., listing open orders, only pagination parameters page and limit are supported and limit cannot be larger than 100. Query by side and time range parameters from and to are not supported.

    When status is finished, i.e., listing finished orders, pagination parameters, time range parameters from and to, and side parameters are all supported. Time range parameters are handled as order finish time.

    Parameters

    Name In Type Required