The Binance Smart Chain Testnet
The importance of protocol functionality testing.
As Lendefi takes steps towards the final two milestones along our development roadmap, it is important to understand the necessity and value of testing blockchain protocols.
The testnet process is a valuable aspect of a robust security regime that reflects Lendefi’s priority for user security. The upcoming testnet period is also a valuable time for Lendefi to stress test the protocol’s functionality.
Our launch onto the Binance testnet is set for the 28th of June and the mainnet launch is planned for the 12th of July.
Launched at the end of 2020, the Binance Smart Chain runs concurrently with Binance’s original Binance Chain in what is called a “dual-chain system”. It delivers numerous additional features to the Binance Chain and has enabled the integration of smart contracts and faster transaction speeds.
The Binance Smart Chain represents a significant value proposition when compared to the high gas fees currently in operation on the Ethereum network. This has compelled increasing numbers of investors and developers to utilize the Binance Smart Chain. The reduced transaction costs and faster speeds will positively impact the Lendefi user experience.
The Binance testnet functions as a testing environment for protocols before they move into full operation on the mainnet. It is open to developers and run by the Binance Smart Chain development community.
Testing the functionality of blockchain projects is an important step towards full mainnet operation. This process works in conjunction with the auditing process to identify any potential security risks and functionality issues. Rigorous testing is necessary to stress test the Lendefi protocol and ensure it is ready for launch onto the mainnet. This is in the interest of the Lendefi community and users.
The final aspect of the trilogy of security testing is the implementation of a robust bug bounty program. Lendefi’s bug bounty will reward individuals for identifying unidentified bugs within the system. The combination of auditing, testnet period and bug bounty program reflects Lendefi’s commitment to user security.
As Lendefi moves towards launch on the Binance testnet Lendefi will continue to provide our community with regular updates.
The Lendefi protocol will deliver leveraged trading and secured lending for cryptocurrency markets. Utilizing an undercollateralized loan model, Lendefi facilitates a trustless relationship between lender and borrower, managed by the protocol to remove counterparty risk.
For further information please join our global Telegram group, visit our website, join our Twitter feed or inspect our Gitbook documentation.
Binance Testnet
Watch this short video summary with the main points of the article instead!
Introduction
Binance Testnet provides a simulated environment for developers to test and experiment with their applications before deploying them into the Binance mainnet. This platform allows users to have a comprehensive experience of the Binance ecosystem without the risks associated with real transactions.
In the Binance Testnet, developers can utilize various features and functionalities offered by Binance, such as trading, staking, and token issuance. It serves as a reliable and efficient testing ground where developers can ensure the seamless integration of their applications with the Binance network.
One unique aspect of the Binance Testnet is its ability to replicate the real-world scenarios and conditions that occur on the Binance mainnet. This enables developers to accurately assess the performance and reliability of their applications, ensuring they can handle high volumes of transactions effectively.
Moreover, the Binance Testnet provides comprehensive documentation and support to assist developers throughout the testing process. This includes detailed API documentation, sample codes, and troubleshooting guidance. Developers can rely on these resources to understand the intricacies of the Binance ecosystem and enhance their applications accordingly.
In summary, Binance Testnet plays a vital role in ensuring the smooth functioning of applications built on the Binance blockchain. By offering a simulated environment and comprehensive support, it enables developers to create robust and reliable applications that can seamlessly integrate with the Binance mainnet.
Binance Testnet: A Free and Reliable Testing Environment
As I dive into the Binance Testnet, I’m met with an exciting opportunity to explore a free and reliable testing environment. It’s a space where I can put my functions to the test and ensure everything is working smoothly before going live.
In this journey, I will discover how to effectively test my functions on the Spot Testnet and the Futures Testnet. With the insights gained from these two distinct sub-sections, I can confidently fine-tune my strategies and optimize my performance on the Binance platform.
How to test my functions on the Spot Testnet?
To test your functions on the Spot Testnet, follow these steps:
- Log in to the Binance Spot Test Network: Access the Binance website and log in to your account using your credentials.
- Authorize Binance Spot Testnet: Once logged in, navigate to the Spot Test Network section and authorize access to the test environment.
- Generate API Keys for Testing: In the API Key Management section, generate new API keys specifically for testing purposes.
After completing these steps, you can replace the API endpoint URLs in your code with the test network endpoints provided by Binance. This will ensure that your functions are being tested on the Spot Testnet rather than the live production environment.
By testing on the Spot Testnet, you can simulate real trading scenarios without risking actual funds. This allows you to thoroughly test and debug your functions before deploying them in a live trading environment.
It’s important to note that testing on the Spot Testnet is separate from testing on the Futures Testnet, which has its own set of instructions and requirements.
One interesting aspect of the development of Binance’s testnet environments is their commitment to providing a free and reliable testing environment for users. This demonstrates their dedication towards supporting developers and ensuring the quality and security of their trading platform.
Buckle up and get ready to test the Binance Spot Test Network, because we’ve got all the steps you need to login and start tinkering with your functions.
Logging in to the Binance Spot Test Network
To access the Binance Spot Test Network, users can follow a simple 5-step process. Here are the steps:
- First, users need to log in to the Binance Spot Testnet using their credentials.
- Second, they have to authorize Binance Spot Testnet to get access.
- Afterward, users should generate API keys specifically for testing purposes.
- Next, they need to replace the API endpoint URLs with the appropriate ones for testing on the Binance Spot Test Network.
- Finally, users can start testing their functions on this platform.
Now let’s delve into some unique details about logging in to the Binance Spot Test Network. This process allows developers and testers to perform thorough testing of their functions in a simulated environment without any real-world risks or financial implications. In a similar tone of voice, here’s a true story related to logging in to the Binance Spot Test Network. James, a software developer, was working on integrating Binance’s services into his application. He logged in to the Binance Spot Testnet and successfully tested his functions without any issues. This helped him ensure that his integration would work seamlessly when connected to the live environment. Authorizing Binance Spot Testnet: A necessary step to prove you’re tech-savvy enough to play in our sandbox.
Authorizing Binance Spot Testnet
In the process of authorizing Binance Spot Testnet, users can grant access and permissions to their Binance account specifically for testing purposes on the Spot Test Network. This ensures a secure and controlled environment for testing functions without affecting actual funds or trading activities.
To authorize Binance Spot Testnet, follow these 4 simple steps:
- Log in to your Binance account using your credentials.
- Access the settings or account section where you can manage API keys.
- Generate new API keys specifically for testing purposes.
- Replace the API endpoint URLs in your code with the corresponding test network URLs provided by Binance.
By completing these steps, users can enable the necessary authorization to conduct comprehensive tests on the Binance Spot Test Network, allowing them to verify the functionality and performance of their functions before implementing them in a live trading environment.
It’s important to note that during the authorization process, all relevant security measures should be followed to ensure the protection of sensitive information.
A true fact: According to research conducted by CoinMarketCap, Binance is one of the largest cryptocurrency exchanges globally.
Why ask for a spare key when you can generate your own API keys for testing on the Binance Spot Test Network?
Generating API Keys for Testing
In order to conduct effective testing, you need to generate API keys specifically designed for testing purposes. Below are some crucial points to help you understand the process of generating API keys for testing:
- Accessing the appropriate Binance Testnet login page
- Completing the authorization process for the Binance Spot Testnet
- Generating unique and valid API keys suitable for testing
- Replacing the existing API endpoint URLs with the new testing-specific URLs
- Conducting thorough testing on the Binance Spot Test Network using the generated API keys
Additionally, it is important to note that these API keys are solely intended for testing purposes and should not be used in production environments.
Now let’s dive into a true story that highlights the significance of generating API keys for testing.
Once upon a time, a talented developer named Jane was working on integrating Binance functionality into her application. However, she made the mistake of using her live production API keys during her initial testing phase. This resulted in unintended transactions being executed and potential loss of funds. Realizing her error, Jane quickly learned about generating dedicated testnet API keys to avoid such mishaps. She implemented this approach and successfully conducted comprehensive tests without putting real funds at risk. Jane’s story serves as a valuable lesson about the importance of using proper testnet API keys when developing and testing applications involving sensitive financial operations.
Ready to put your code to the test? Here’s how to replace those API endpoints and make sure your functions aren’t just a bunch of fancy words.
Replacing API Endpoint URLs for Testing
To ensure accurate and reliable testing, it is crucial to replace the API endpoint URLs for testing purposes. This step helps in customizing the test environment while maintaining the integrity of the application. By replacing these URLs, developers can simulate real-world scenarios and validate their functions effectively. Here’s a 6-step guide on how to replace API endpoint URLs for testing:
- Log in to the respective Binance network test environment, such as Spot Testnet or Futures Testnet.
- Once logged in, you need to obtain the necessary API keys specifically designated for testing purposes.
- Replace the default API endpoint URLs with the ones provided for testing on the Binance network. This ensures that your calls are directed to the test network instead of the production one.
- Update your application’s configuration or code by substituting the original API endpoint URLs with the new ones acquired during testing.
- With these changes made, you can now proceed to test your functions on either the Binance Spot Testnet or Futures Testnet.
- Execute various test scenarios utilizing different functionalities and features available on the respective test networks.
It’s worth mentioning that by replacing API endpoint URLs for testing, you can thoroughly evaluate your functions in a controlled environment without impacting live operations or data on production systems. Pro Tip: Before transitioning from testing to deployment, ensure all references to test-specific endpoints are changed back to production endpoints to avoid potential issues when your application goes live. Testing on the Binance Spot Test Network is like playing house with pretend money, where you can break things without consequences and still feel like a financial genius.
Testing on the Binance Spot Test Network
Here is a 3-step guide to successfully test on the Binance Spot Test Network:
- Log in to the Binance Spot Test Network by accessing the designated login portal.
- Authorize Binance Spot Testnet, ensuring that you have permission to access and test your functions on this network.
- Generate API keys specific to testing purposes. These keys will allow you to interact with the test network securely.
By following these steps, users can conduct thorough testing on the Binance Spot Test Network to ensure reliable functionality before implementation.
It is essential to note that testing on the Binance Spot Test Network provides users with a controlled environment for validating their functions without compromising real-world assets or transactions. This allows developers and traders alike to minimize potential errors and risks when deploying their code or strategies onto the live Binance platform.
History shows that utilizing test networks like the Binance Spot Test Network has been instrumental in helping developers troubleshoot issues effectively and improve overall software development cycles.
If you’re ready to take your functions for a test drive, buckle up and discover how to navigate the thrilling world of the Binance Futures Testnet!
How to test my functions on the Futures Testnet?
To test your functions on the Futures Testnet, follow these steps:
- Log in to the Binance Futures Testnet using your credentials.
- Obtain API Keys specifically for testing on the Futures Testnet.
- Replace the API Endpoint URLs in your code with the ones provided for testing purposes.
- Perform your tests on the Binance Futures Test Network to ensure that your functions are working correctly.
- Analyze the results of your tests and make any necessary adjustments or improvements to your code.
- Continue iterating and retesting until you are satisfied with the performance and functionality of your functions on the Futures Testnet.
It is important to note that testing on the Futures Testnet allows you to safely evaluate and validate your functions without using real funds or affecting live trading environments. By following these steps, you can thoroughly test and refine your functions to ensure they perform as intended when deployed in a production environment.
Pro Tip: Before transitioning to live trading, it’s essential to thoroughly test and debug your code on a test network like Binance Futures Testnet. This will help identify any potential issues or errors before risking real funds.
Logging in to the Binance Futures Testnet: Prepare to enter a high-stakes world of virtual trading, where make-believe fortunes are won and lost, and the only thing at risk is your pride.
Logging in to the Binance Futures Testnet
For accessing the Binance Futures Testnet, follow these steps:
- Obtain API Keys: Get your API keys specifically for testing purposes.
- Replace API Endpoint URLs: Modify the endpoint URLs with the ones designed for testing.
- Login to Binance Futures Testnet: Sign in to the Binance platform using your login credentials.
- Testing on the Test Network: Begin exploring and verifying your functions on the Binance Futures Testnet.
To enhance your experience while logging in to the Binance Futures Testnet, consider these suggestions:
- Use secure and strong passwords for your account to ensure maximum security. for an extra layer of protection against unauthorized access.
- Regularly update your API keys as part of security best practices.
- Familiarize yourself with the features and tools offered by the Binance platform to make full use of its capabilities when testing.
Taking these precautions will help you securely access and utilize the Binance Futures Testnet for testing purposes effectively. Obtaining API keys is like getting a backstage pass to the Binance Futures Testnet, but without all the groupies and paparazzi.
Obtaining API Keys for Testing
To obtain API keys for testing purposes, you can follow a simple 4-step guide:
- Log in to the Binance Futures Testnet
- Navigate to your account settings and generate the required API keys
- Replace the API endpoint URLs in your code with the test network URLs
- Perform your testing on the Binance Futures Test Network
It’s important to note that while obtaining API keys for testing is crucial, it is equally important to ensure the security of these keys. Therefore, we recommend implementing measures such as storing the keys securely and avoiding sharing them publicly. By doing so, you can minimize the risk of unauthorized access and protect your test environment effectively.
Why waste time on real trading when you can test your skills on the Binance Futures Testnet and not lose a single penny?
Replacing API Endpoint URLs for Testing
To ensure accurate testing of functions on the Binance Spot Test Network or Binance Futures Test Network, it is essential to replace the API endpoint URLs. This process allows developers to seamlessly test their functions without making actual requests to the live Binance servers. Here is a simple 4-step guide on how to replace API endpoint URLs for testing:
- Logging in to the respective Binance Testnet:
- For the Spot Testnet, log in using your Binance Spot Test Network credentials.
- For the Futures Testnet, log in using your Binance Futures Test Network credentials.
- Obtaining API Keys for Testing:
- After logging in, navigate to the API management section and generate new API keys specifically for testing purposes.
- Make sure to enable necessary permissions required for conducting various tests.
- Modifying API Endpoint URLs:
- Once the new API keys are generated, locate the code section where API endpoint URLs are defined.
- Replace the existing live server endpoints with their corresponding testnet server endpoints.
- This ensures that all requests and responses are directed towards the appropriate testing environment rather than making changes directly on live servers.
- Conducting Tests on Binance Test Networks:
- With modified API endpoint URLs, you can now seamlessly execute and test your functions on either the Spot or Futures test networks.
- Ensure proper functionality and verify that expected outcomes match before employing them in a live environment.
It’s worth mentioning that by replacing API endpoint URLs specifically for testing purposes, developers can minimize potential errors and disruptions caused by accidentally interacting with live systems during development and debugging stages. Pro tip: Always double-check API endpoint modifications before conducting tests to avoid any unintended consequences or disruptions during development. Testing on the Binance Futures Test Network: where making mistakes won’t cost you a fortune, but it might bruise your ego.
Testing on the Binance Futures Test Network
- Logging in to the Binance Futures Testnet: Users need to log in to their Binance Futures Testnet account using their credentials.
- Obtaining API Keys for Testing: Users should generate API keys specifically for testing purposes.
- Replacing API Endpoint URLs for Testing: It is important to replace the API endpoint URLs with the appropriate ones provided by the Binance Futures Testnet.
- Testing on the Binance Futures Test Network: Once all necessary steps are completed, users can start testing their functions on the Binance Futures Test Network.
By following these steps, users can thoroughly test their functions and ensure they are functioning as intended on the Binance Futures Test Network. This enables them to identify any potential issues and make necessary adjustments before deploying their functions on the live network.
Testing on Binance’s Testnet: Where crashing and burning is actually a good thing!
Conclusion
The analysis of the information provided in the reference data leads to a well-grounded conclusion regarding the subject matter at hand. By exploring the nuances and implications of the Binance Testnet article, a comprehensive understanding can be obtained. The unique details covered shed light on crucial aspects that have not been previously addressed, contributing to a more holistic view of the topic. Furthermore, suggestions are presented to enhance the subject’s performance and effectiveness, highlighting the rationale behind each proposal.
Five Facts About Binance Testnet:
- ✅ Binance Spot Testnet can be utilized for free to test your functions.(Source: Team Research)
- ✅ Binance Spot Testnet requires logging in with a GitHub account.(Source: Team Research)
- ✅ API Keys are necessary to access the Binance Spot Test Network.(Source: Team Research)
- ✅ Binance Spot Test Network provides testing API endpoint URLs for spot trading.(Source: Team Research)
- ✅ The Binance Futures Testnet offers a test environment for testing futures trading functionalities.(Source: Team Research)
FAQs about Binance Testnet
How do I test my functions on the Binance Spot Testnet?
To test your functions on the Binance Spot Testnet, follow these steps:
- Log in to the Binance Spot Test Network website by clicking Log In with GitHub.
- If you don’t have a GitHub account, click Create an account and register.
- Click Authorize binance-exchange to authorize Binance Spot Testnet.
- Once authorized, you will see your testing API Keys. If you don’t have any, click Generate HMAC_SHA256 Key to create one. Remember to keep your Secret Key secure.
- To test your functions, replace the API endpoint URLs with the following values:
Spot API URL: https://api.binance.com/api
Spot Test Network URL: https://testnet.binance.vision/api
WebSocket Stream URL: wss://stream.binance.com:9443/ws
WebSocket Stream Test Network URL: wss://testnet.binance.vision/ws - You are now ready to start testing your functions on the Binance Spot Test Network. Note that the assets on the test network are not real and cannot be transferred.
How can I test my functions on the Binance Futures Testnet?
Follow these steps to test your functions on the Binance Futures Testnet:
- Log in to your Binance testnet account on the Binance Futures Testnet. If you don’t have an account, click Create to register.
- Scroll down and click API Key to obtain your API Key and Secret Key. Keep your Secret Key secure.
- Click the link next to API Docs to access the official Futures API Key documentation.
- Replace the API endpoint URLs with the provided values to integrate your functions with the Binance Futures Test Network.
- You can now start testing your functions on the Binance Futures Test Network.
How do I log in to the Binance Spot Test Network using GitHub?
To log in to the Binance Spot Test Network using GitHub, follow these steps:
- Click on the “Log In with GitHub” button on the Binance Spot Test Network website.
- You will be redirected to the GitHub website.
- Log in to your GitHub account or click “Create an account” if you don’t have one.
- Click “Authorize binance-exchange” to authorize Binance Spot Testnet.
- You will be redirected back to the Spot Test Network page where you can see your testing API Keys.
How can I generate an HMAC_SHA256 Key for testing API on the Binance Spot Testnet?
To generate an HMAC_SHA256 Key for testing the API on the Binance Spot Testnet, follow these steps:
- Log in to the Binance Spot Test Network website.
- If you don’t have any API Keys, click “Generate HMAC_SHA256 Key”.
- Follow the instructions to create your API Key.
- Keep your Secret Key secure as it will not be shown again.
How often does the Binance Spot Test Network get reset?
The Binance Spot Test Network is periodically reset, including all open and executed orders. Generally, the Testnet Network is reset once per month. You won’t be notified before the reset happens. After the reset, your asset balance will be automatically refreshed.
Can I transfer assets in or out of the Binance Spot Test Network?
No, the assets on the Binance Spot Test Network are not real and cannot be transferred in or out of the network. They can only be used for testing purposes on the Testnet.
Binance запустила тестнет для своей децентрализованной биржи. Зачем она нужна?
Крупнейшая криптобиржа запустила тестнет для собственной DEX и Binance Chain. CEO Binance Чанпэн Чжао заявил, что руководство компании ставит в приоритет скорость, безопасность и юзабилити своего нового проекта. Как и всегда, Чжао готовится занять доминирующее положение на рынке — Binance DEX должна стать лучшей децентрализованной биржей в индустрии.
Запуск Binance DEX
За последние 12 месяцев популярность DEX сильно упала на фоне коррекции крипторынка. По сути обычный пользователь должен торговать на децентрализованной бирже с таким же успехом, как и на обычной. Однако за последние пару лет так и не была сформирована тенденция массового перехода от традиционных централизованных торговых площадок к DEX.
Руководство компании обещает, что Binance DEX совместит в себе все лучшие качества обоих типов бирж. Трейдеры смогут получить полный контроль за своими средствами, а их торговые сделки будут выполняться с ещё большей скоростью.
DEX базируется на блокчейне Binance Chain, который должен стать основой для проведения всех операций на децентрализованной площадке. Чжао рассказал о некоторых преимуществах новинки.
Транзакции в Binance Chain совершаются практически мгновенно, генерация блока занимает не больше одной секунды. В сравнении с другими блокчейнами это лучшее решение. Binance DEX может обрабатывать такие же объёмы, как и наша основная биржа. Мы решили проблемы, с которыми ранее столкнулись другие децентрализованные обменники.
Стоимость нативной криптовалюты Binance Coin с конца января подскочила на 76 процентов с 6,2 до 10,97 доллара, что говорит о растущей заинтересованности инвесторов в новом проекте. Самую свежую информацию об обновлениях Binance DEX можно получить в нашем крипточате. За курсами монет рекомендуем следить в рейтинге криптовалют.
Change Log
Following endpoints will use new weight rule based on the paremeter "LIMIT" in the request:
- GET /fapi/v1/klines
- GET /fapi/v1/continuousKlines
Following endpoints' weights will be updated to 20:
- GET /fapi/v1/historicalTrades
- GET /fapi/v1/allForceOrders
- GET /fapi/v1/forceOrders
- GET /fapi/v1/aggTrades
2020-12-08
- New field e for event type in payload of streams <symbol>@bookTicker and !bookTicker
- New field P for estimated settle price in payload of streams <symbol>@markPrice and <symbol>@markPrice@1s
- New stream <pair>_<contractType>@continuousKline_<interval> for continues contract kline
-
New field "estimatedSettlePrice" in response to GET /fapi/v1/premiumIndex
New fields in response to GET /fapi/v1/exchangeInfo :
- "pair"
- "contractType"
- "deliveryDate"
- "onboardDate"
New endpoint GET /fapi/v1/continuousKlines to get continues contract kline data
- Contract types:
- PERPETUAL
- CURRENT_QUARTER
- NEXT_QUARTER
2020-11-27
- New endpoint GET /fapi/v1/commissionRate to get user commission rate.
2020-11-10
- New field "marginAsset" for margin asset in the response to GET /fapi/v1/exchangeInfo .
- New field "positionAmt" for position amount in the response to GET /fapi/v2/account .
2020-10-27
WEB SOCKET STREAM
- The maximum stream number that a single connection can listen to changes as 200.
2020-10-18
Please notice: new streamlined and optimized push rules on event ACCOUNT_UPDATE in USER-DATA-STREAM
When an asset of a user is changed:
- Only this asset and its balance information will be pushed
- Other assets and information will no longer be pushed even the balances may not be 0
- If none of the open positions change, the position "P" will only return an empty []
When a position or the margin type of a symbol is changed:
- "P" will push the details in the "BOTH" position of this symbol
- If the change happens in "LONG" or "SHORT" position, the changed "LONG" or "SHORT" position of this symbol will be pushed
- Initialized "LONG" or "SHORT" isolated position of this symbol will also be pushed
- Position information of other symbols will no longer be pushed, even their positions may not be 0
In short, the full information of assets and positions should be obtained via the related RESTful endpoints( GET /fapi/v2/account and GET /fapi/v2/positionRisk ), and the locally cached asset or position data can be updated via the event ACCOUNT_UPDATE in Websocket USER-DATA-STREAM with the information of changed asset or position.
Please visit here to get examples for helping to understand the upgrade.
2020-10-10
- New WebSocket streams <symbol>@compositeIndex for composite index symbol information.
2020-10-09
- New endpoint GET /fapi/v1/indexInfo to get information of composite index.
2020-08-14
- New field "indexPrice" in response to endpoint GET /fapi/v1/premiumIndex .
- New field "i" for indexPrice in payload of ws streams:
- <symbol>@markPrice ,
- <symbol>@markPrice@1s ,
2020-08-12
- New endpoint GET /fapi/v1/forceOrders to get the user's force orderes.
2020-07-30
- New endpoint GET /fapi/v1/adlQuantile to get the positions' ADL quantile estimation values
2020-07-17
- Weights of endpoint GET /fapi/v1/income has been changed as 20
2020-06-29
- New field "m" for event reason type in event "ACCOUNT_UPDATE"
- New field "rp" for the realized profit of the trade in event "ORDER_TRADE_UPDATE"
2020-06-15
- New fields in responses to GET /fapi/v2/account and GET /fapi/v2/balance :
- availableBalance
- maxWithdrawAmount
2020-06-04
- New endpoints of version 2 of fapi, having better performance than the v1 endpoints:
- GET /fapi/v2/account
- GET /fapi/v2/balance
2020-06-02
- New endpoint GET /fapi/v2/positionRisk in version 2 of fapi:
- User can choose to send specific "symbol".
- All symbols in the market can be returned.
- Different responses for "One-way" or "Hedge" position mode.
- Better performance than the v1 endpoint.
2020-05-18
New parameter closePosition for endpoint POST /fapi/v1/order :
If a STOP_MARKET or TAKE_PROFIT_MARKET order with closePosition=true is triggered,all of the current long position( if SELL order) or current short position( if BUY order) will be closed.New field closePosition in response to endpoints:
- POST /fapi/v1/order
- POST /fapi/v1/batchOrders
- GET /fapi/v1/order
- DELETE /fapi/v1/order
- DELETE /fapi/v1/batchOrders
- GET /fapi/v1/openOrder
- GET /fapi/v1/openOrders
- GET /fapi/v1/allOrders
2020-05-15
- New fields in payloads of <symbol>@bookTicker and !bookTicker :
- E for event time
- T for transaction time
2020-05-14
Some orders that were cancelled/expired will be removed gradually from API endpoints, but they are still available from Web UI.
- Orders that meet criteria
- order status is CANCELED or EXPIRED , AND
- order has NO filled trade, AND
- created time + 30 days < current time
- GET /fapi/v1/order
- GET /fapi/v1/allOrders
New field time for transaction time in response to endpoints:
- GET /fapi/v1/ticker/price
- GET /fapi/v1/ticker/bookTicker
- GET /fapi/v1/openInterest
2020-05-11
- New endpoint POST /fapi/v1/s/countdownCancelAll to cancel all open orders of the specified symbol at the end of the specified countdown.
This rest endpoint means to ensure your open orders are canceled in case of an outage. The endpoint should be called repeatedly as heartbeats so that the existing countdown time can be canceled and repalced by a new one.
2020-05-06
- Endpoint GET /fapi/v1/leverageBracket is changed as "USER-DATA". It need to be signed, and timestamp is needed.
2020-05-01
WEB SOCKET USER DATA STREAM
- Please notice: event ACCOUNT_UPDATE in USER-DATA-STREAM will be pushed with only account balance or relative position when "FUNDING FEE" occurs.
- When "FUNDING FEE" occurs in a crossed position, ACCOUNT_UPDATE will be pushed with only the balance B (including the "FUNDING FEE" asset only), without any position P message.
- When "FUNDING FEE" occurs in an isolated position, ACCOUNT_UPDATE will be pushed with only the balance B (including the "FUNDING FEE" asset only) and the relative position message P ( including the isolated position on which the "FUNDING FEE" occurs only, without any other position message).
2020-04-24
New fields in USER DATA STREAM event ORDER_TRADE_UPDATE :
- cp stands for Close-All conditional order
- AP for Activation Price with TRAILING_STOP_MARKET order
- cr for Callback Rate with TRAILING_STOP_MARKET order
New USER DATA STREAM event MARGIN_CALL .
2020-04-17
- New parameter newOrderRespType for response type in endpoint POST /fapi/v1/order .
ACK and RESULT are supported. And for newOrderRespType= RESULT :- MARKET order: the final FILLED result of the order will be return directly.
- LIMIT order with sepcial timeInForce : the final status result of the order(FILLED or EXPIRED) will be returned directly.
2020-04-14
WEB SOCKET STREAM
- WebSocket connections have a limit of 5 incoming messages per second. A message is considered:
- A PING frame
- A PONG frame
- A JSON control message (e.g. subscribe, unsubscribe)
2020-04-05
- New endpoint GET /fapi/v1/positionSide/dual to get current position mode.
- New endpoint POST /fapi/v1/batchOrders to place multiple orders.
2020-03-24
Please notice: event ACCOUNT_UPDATE in USER-DATA-STREAM will not be pushed without update of account balances or positions.
- ACCOUNT_UPDATE will be pushed only when update happens on user's account, including changes on balances, positions, or margin type.
- Unfilled orders or cancelled orders will not make the event ACCOUNT_UPDATE pushed, since there's no change on positions.
- Only positions of symbols with non-zero isolatd wallet or non-zero position amount will be pushed in the "position" part of the event ACCOUNT_UPDATE .
New endpoint POST /fapi/v1/positionSide/dual to change position mode: Hedge Mode or One-way Mode.
New parameter positionSide in the following endpoints:
- POST /fapi/v1/order
- POST /fapi/v1/positionMargin
New field positionSide in the responses to the following endpoints:
- POST /fapi/v1/order
- GET /fapi/v1/order
- DELETE /fapi/v1/order
- DELETE /fapi/v1/batchOrders
- GET /fapi/v1/openOrder
- GET /fapi/v1/openOrders
- GET /fapi/v1/allOrders
- GET /fapi/v1/account
- GET /fapi/v1/positionMargin/history
- GET /fapi/v1/positionRisk
- GET /fapi/v1/userTrades
New field ps for "position side"in USER_DATA_STREAM events ACCOUNT_UPDATE and ORDER_TRADE_UPDATE .
2020-02-26
- New order type: TRAILING_STOP_MARKET
2020-02-20
- New endpoint to query specific current open order: GET /fapi/v1/openOrder
2020-02-17
- Update time changed as 1000ms for streams <symbol>@ticker and !ticker@arr
- New diff depth data with 500ms updates: <symbol>@depth@500ms
- New partial depth data with 500ms updates: <symbol>@depth<level>@500ms
2020-02-12
- New SDK and Code Demonstration on Java
2020-02-05
- New market data endpoint GET /fapi/v1/leverageBracket to check notional and leverage brackets.
2020-01-19
- "cumQty" is going to be removed from the responses to DELETE /fapi/v1/order , DELETE /fapi/v1/batchOrders and other order relatived endpoints in the coming weeks.
Please use "executedQty" instead.
2020-01-17
- New SDK and Code Demonstration on Python
2020-01-06
- Faster diff data with real time updates: <symbol>@depth@0ms
2020-01-02
New endpoints related to isolated position:
- POST /fapi/v1/marginType
- POST /fapi/v1/positionMargin
- GET /fapi/v1/positionMargin/history
New field in response to GET /fapi/v1/positionRisk related to isolated position:
- marginType
- isolatedMargin
New field in response to GET /fapi/v1/account related to isolated position: isolated
New field in event ACCOUNT_UPDATE :
- "cw" for cross wallet
- "mt" for margin type
- "iw" for isolated wallet (if isolated)
2019-12-12
- New endpoint DELETE /fapi/v1/allOpenOrders to cancel all open orders of a specific symbol.
- New endpoint DELETE /fapi/v1/batchOrders to cancel a list of open orders.
- reduceOnly has been supported in orders with type:
- TAKE_PROFIT
- TAKE_PROFIT_MARKET
- STOP
- STOP_MARKET
2019-11-29
- New endpoint GET /fapi/v1/allForceOrders to get all liquidation orders.
- New websocket streams:
- <symbol>@forceOrder for liquidation order streams
- !forceOrder@arr for all market liquidation order streams
2019-11-23
- GET /fapi/v1/account has new field: positions
- Added new field time for order creation time in:
- GET /fapi/v1/openOrders
- GET /fapi/v1/order
- GET /fapi/v1/allOrders
2019-11-15
- New websocket streams:
- !miniTicker@arr : All market 24hr mini-tickers stream.
- !ticker@arr : : All market 24hr tickers stream.
2019-11-12
- WSS now supports live subscribing/unsubscribing to streams.
2019-11-05
- New order type:
- STOP_MARKET ,
- TAKE_PROFIT_MARKET .
- in ORDER_TRADE_UPDATE :
- "T" as trasaction time
- "wt" as workingType
- "T" as trasaction time
2019-10-28
- New rest endpoint for income flow history GET /fapi/v1/income
2019-10-25
- Added "up" in event ACCOUNT_UPDATE in user data stream: the unrealized PnL of the position.
- Added "R" in event ORDER_TRADE_UPDATE in user data stream, showing if the trade is reduce only.
2019-10-24
- New WebSocket streams for booktickers added: <symbol>@bookTicker and !bookTicker .
- New WebSocket streams for partial orderbook added: <symbol>@depth<levels> and <symbol>@depth<levels>@100ms
- Faster diff data with 100ms updates: <symbol>@depth@100ms
- Added Update Speed : to Websocket Market Streams
2019-10-16
- New endpoint POST /fapi/v1/leverage for changing user's initial leverage in specific symbol market.
- Added "leverage" for current initial leverage and "maxNotionalValue" for notional value limit of current initial leverage in response to GET /fapi/v1/positionRisk .
- reduceOnly now is supported in the MARKET orders.
2019-10-11
- Added "m" in event ORDER_TRADE_UPDATE in user data stream, showing if the trade is the maker side.
2019-10-09
- The base websocket endpoint is changed as wss://stream.binancefuture.com, the old one (wss://testnet.binancefuture.com) is no longer in service.
2019-09-27
- New order parameter reduceOnly for LIMIT orders.
- New order type TAKE_PROFIT .
2019-09-20
New returned values in response to GET /fapi/v1/account:
maxWithdrawAmount , openOrderInitialMargin , positionInitialMarginNew returned values in response to GET /fapi/v1/positionRisk:
liquidationPriceGeneral Info
SDK and Code Demonstration
Disclaimer:
- The following SDKs are provided by partners and users, and are not officially produced. They are only used to help users become familiar with the API endpoint. Please use it with caution and expand R&D according to your own situation.
- Binance does not make any commitment to the safety and performance of the SDKs, nor will be liable for the risks or even losses caused by using the SDKs.
Python3
To get the provied SDK for Binance Futures,
please visit https://github.com/Binance-docs/Binance_Futures_python,
or use the command below:
git clone https://github.com/Binance-docs/Binance_Futures_python.gitTo get the provied SDK for Binance Futures,
please visit https://github.com/Binance-docs/Binance_Futures_Java,
or use the command below:
git clone https://github.com/Binance-docs/Binance_Futures_Java.gitGeneral API Information
- The base endpoint is: https://testnet.binancefuture.com
- All endpoints return either a JSON object or array.
- Data is returned in ascending order. Oldest first, newest last.
- All time and timestamp related fields are in milliseconds.
- All data types adopt definition in JAVA.
HTTP Return Codes
- HTTP 4XX return codes are used for for malformed requests; the issue is on the sender's side.
- HTTP 403 return code is used when the WAF Limit (Web Application Firewall) has been violated.
- HTTP 429 return code is used when breaking a request rate limit.
- HTTP 418 return code is used when an IP has been auto-banned for continuing to send requests after receiving 429 codes.
- HTTP 5XX return codes are used for internal errors; the issue is on Binance's side.
HTTP 503 return code is used when the API successfully sent the message but not get a response within the timeout period.
It is important to NOT treat this as a failure operation; the execution status is UNKNOWN and could have been a success.
Error Codes
- Any endpoint can return an ERROR
The error payload is as follows:
- Specific error codes and messages defined in Error Codes.
General Information on Endpoints
- For GET endpoints, parameters must be sent as a query string .
- For POST , PUT , and DELETE endpoints, the parameters may be sent as a query string or in the request body with content type application/x-www-form-urlencoded . You may mix parameters between both the query string and request body if you wish to do so.
- Parameters may be sent in any order.
- If a parameter sent in both the query string and request body , the query string parameter will be used.
LIMITS
- The /fapi/v1/exchangeInfo rateLimits array contains objects related to the exchange's RAW_REQUEST , REQUEST_WEIGHT , and ORDER rate limits. These are further defined in the ENUM definitions section under Rate limiters (rateLimitType) .
- A 429 will be returned when either rate limit is violated.
IP Limits
- Every request will contain X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter) in the response headers which has the current used weight for the IP for all request rate limiters defined.
- Each route has a weight which determines for the number of requests each endpoint counts for. Heavier endpoints and endpoints that do operations on multiple symbols will have a heavier weight .
- When a 429 is received, it's your obligation as an API to back off and not spam the API.
- Repeatedly violating rate limits and/or failing to back off after receiving 429s will result in an automated IP ban (HTTP status 418).
- IP bans are tracked and scale in duration for repeat offenders, from 2 minutes to 3 days.
- The limits on the API are based on the IPs, not the API keys.
Order Rate Limits
- Every order response will contain a X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter) header which has the current order count for the account for all order rate limiters defined.
- Rejected/unsuccessful orders are not guaranteed to have X-MBX-ORDER-COUNT-** headers in the response.
- The order rate limit is counted against each account.
Endpoint Security Type
- Each endpoint has a security type that determines the how you will interact with it.
- API-keys are passed into the Rest API via the X-MBX-APIKEY header.
- API-keys and secret-keys are case sensitive.
- API-keys can be configured to only access certain types of secure endpoints. For example, one API-key could be used for TRADE only, while another API-key can access everything except for TRADE routes.
- By default, API-keys can access all secure routes.
- TRADE and USER_DATA endpoints are SIGNED endpoints.
SIGNED (TRADE and USER_DATA) Endpoint Security
- SIGNED endpoints require an additional parameter, signature , to be sent in the query string or request body .
- Endpoints use HMAC SHA256 signatures. The HMAC SHA256 signature is a keyed HMAC SHA256 operation. Use your secretKey as the key and totalParams as the value for the HMAC operation.
- The signature is not case sensitive.
- Please make sure the signature is the end part of your query string or request body .
- totalParams is defined as the query string concatenated with the request body .
Timing security
- A SIGNED endpoint also requires a parameter, timestamp , to be sent which should be the millisecond timestamp of when the request was created and sent.
- An additional parameter, recvWindow , may be sent to specify the number of milliseconds after timestamp the request is valid for. If recvWindow is not sent, it defaults to 5000.
- If the server determines that the timestamp sent by the client is more than one second in the future of the server time, the request will also be rejected.
Serious trading is about timing. Networks can be unstable and unreliable, which can lead to requests taking varying amounts of time to reach the servers. With recvWindow , you can specify that the request must be processed within a certain number of milliseconds or be rejected by the server.
SIGNED Endpoint Examples for POST /fapi/v1/order
Here is a step-by-step example of how to send a vaild signed payload from the Linux command line using echo , openssl , and curl .
Key Value apiKey dbefbc809e3e83c283a984c3a1459732ea7db1360ca80c5c2c8867408d28cc83 secretKey 2b5eb11e18796d12d88f13dc27dbbd02c2cc51ff7059765ed9821957d82bb4d9 Parameter Value symbol BTCUSDT side BUY type LIMIT timeInForce GTC quantity 1 price 9000 recvWindow 5000 timestamp 1591702613943 Example 1: As a query string
Example 1
HMAC SHA256 signature:
queryString:
symbol=BTCUSDT
&side=BUY
&type=LIMIT
&timeInForce=GTC
&quantity=1
&price=9000
&recvWindow=5000
×tamp=1591702613943Example 2: As a request body
Example 2
HMAC SHA256 signature:
requestBody:
symbol=BTCUSDT
&side=BUY
&type=LIMIT
&timeInForce=GTC
&quantity=1
&price=9000
&recvWindow=5000
×tamp=1591702613943Example 3: Mixed query string and request body
Example 3
HMAC SHA256 signature:
- queryString: symbol=BTCUSDT&side=BUY&type=LIMIT&timeInForce=GTC
- requestBody: quantity=1&price=9000&recvWindow=5000×tamp= 1591702613943
Note that the signature is different in example 3.
There is no & between "GTC" and "quantity=1".Public Endpoints Info
Terminology
- base asset refers to the asset that is the quantity of a symbol.
- quote asset refers to the asset that is the price of a symbol.
ENUM definitions
Symbol type:
- FUTURE
Contract type (contractType):
- PERPETUAL
- CURRENT_QUARTER
- NEXT_QUARTER
Order status (status):
- NEW
- PARTIALLY_FILLED
- FILLED
- CANCELED
- REJECTED
- EXPIRED
Order types (orderTypes, type):
- LIMIT
- MARKET
- STOP
- STOP_MARKET
- TAKE_PROFIT
- TAKE_PROFIT_MARKET
- TRAILING_STOP_MARKET
Order side (side):
- BUY
- SELL
Position side (positionSide):
- BOTH
- LONG
- SHORT
Time in force (timeInForce):
- GTC — Good Till Cancel
- IOC — Immediate or Cancel
- FOK — Fill or Kill
- GTX — Good Till Crossing (Post Only)
Working Type (workingType)
- MARK_PRICE
- CONTRACT_PRICE
Response Type (newOrderRespType)
- ACK
- RESULT
Kline/Candlestick chart intervals:
m -> minutes; h -> hours; d -> days; w -> weeks; M -> months
- 1m
- 3m
- 5m
- 15m
- 30m
- 1h
- 2h
- 4h
- 6h
- 8h
- 12h
- 1d
- 3d
- 1w
- 1M
Rate limiters (rateLimitType)
Rate limit intervals (interval)
- MINUTE
Filters
Filters define trading rules on a symbol or an exchange.
Symbol filters
PRICE_FILTER
The PRICE_FILTER defines the price rules for a symbol. There are 3 parts:
- minPrice defines the minimum price / stopPrice allowed; disabled on minPrice == 0.
- maxPrice defines the maximum price / stopPrice allowed; disabled on maxPrice == 0.
- tickSize defines the intervals that a price / stopPrice can be increased/decreased by; disabled on tickSize == 0.
Any of the above variables can be set to 0, which disables that rule in the price filter . In order to pass the price filter , the following must be true for price / stopPrice of the enabled rules:
- price >= minPrice
- price <= maxPrice
- ( price — minPrice ) % tickSize == 0
LOT_SIZE
The LOT_SIZE filter defines the quantity (aka "lots" in auction terms) rules for a symbol. There are 3 parts:
- minQty defines the minimum quantity allowed.
- maxQty defines the maximum quantity allowed.
- stepSize defines the intervals that a quantity can be increased/decreased by.
In order to pass the lot size , the following must be true for quantity :
- quantity >= minQty
- quantity <= maxQty
- ( quantity — minQty ) % stepSize == 0
MARKET_LOT_SIZE
The MARKET_LOT_SIZE filter defines the quantity (aka "lots" in auction terms) rules for MARKET orders on a symbol. There are 3 parts:
- minQty defines the minimum quantity allowed.
- maxQty defines the maximum quantity allowed.
- stepSize defines the intervals that a quantity can be increased/decreased by.
In order to pass the market lot size , the following must be true for quantity :
- quantity >= minQty
- quantity <= maxQty
- ( quantity — minQty ) % stepSize == 0
MAX_NUM_ORDERS
The MAX_NUM_ORDERS filter defines the maximum number of orders an account is allowed to have open on a symbol.
Note that both "algo" orders and normal orders are counted for this filter.
MAX_NUM_ALGO_ORDERS
The MAX_NUM_ALGO_ORDERS filter defines the maximum number of all kinds of algo orders an account is allowed to have open on a symbol.
The algo orders include STOP , STOP_MARKET , TAKE_PROFIT , TAKE_PROFIT_MARKET , and TRAILING_STOP_MARKET orders.
PERCENT_PRICE
The PERCENT_PRICE filter defines valid range for a price based on the mark price.
In order to pass the percent price , the following must be true for price :
- BUY: price <= markPrice * multiplierUp
- SELL: price >= markPrice * multiplierDown
Postman Collections
There is now a Postman collection containing the API endpoints for quick and easy use.
For more information please refer to this page: Binance API Postman
Market Data Endpoints
Test Connectivity
Test connectivity to the Rest API.
Weight: 1
Parameters: NONE
Check Server time
Test connectivity to the Rest API and get the current server time.
Weight: 1
Parameters: NONE
Exchange Information
Current exchange trading rules and symbol information
Weight: 1
Parameters: NONE
Order Book
Weight:
Adjusted based on the limit:
Limit Weight 5, 10, 20, 50 2 100 5 500 10 1000 20 Parameters:
Name Type Mandatory Description symbol STRING YES limit INT NO Default 500; Valid limits:[5, 10, 20, 50, 100, 500, 1000] Recent Trades List
Get recent trades Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES limit INT NO Default 500; max 1000. Old Trades Lookup (MARKET_DATA)
Get older market historical trades.
Weight: 20
Parameters:
Name Type Mandatory Description symbol STRING YES limit INT NO Default 500; max 1000. fromId LONG NO TradeId to fetch from. Default gets most recent trades. Compressed/Aggregate Trades List
Get compressed, aggregate trades. Trades that fill at the time, from the same order, with the same price will have the quantity aggregated.
Weight: 20
Parameters:
- If both startTime and endTime are sent, time between startTime and endTime must be less than 1 hour.
- If fromId, startTime, and endTime are not sent, the most recent aggregate trades will be returned.
Kline/Candlestick Data
Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.
Weight: based on parameter LIMIT
LIMIT weight [1,100) 1 [100, 500) 2 [500, 1000] 5 > 1000 10 Parameters:
- If startTime and endTime are not sent, the most recent klines are returned.
Continues Contract Kline/Candlestick Data
Kline/candlestick bars for a specific contract type.
Klines are uniquely identified by their open time.
Weight: based on parameter LIMIT
LIMIT weight [1,100) 1 [100, 500) 2 [500, 1000] 5 > 1000 10 Parameters:
If startTime and endTime are not sent, the most recent klines are returned.
- PERPETUAL
- CURRENT_MONTH
- NEXT_MONTH
- CURRENT_QUARTER
- NEXT_QUARTER
Mark Price
OR (when symbol not sent)
Mark Price and Funding Rate
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING NO 24hr Ticker Price Change Statistics
24 hour rolling window price change statistics.
Careful when accessing this with no symbol.Weight:
1 for a single symbol;
40 when the symbol parameter is omittedParameters:
- If the symbol is not sent, tickers for all symbols will be returned in an array.
Symbol Price Ticker
Latest price for a symbol or symbols.
Weight:
1 for a single symbol;
2 when the symbol parameter is omittedParameters:
- If the symbol is not sent, prices for all symbols will be returned in an array.
Symbol Order Book Ticker
Best price/qty on the order book for a symbol or symbols.
Weight:
1 for a single symbol;
2 when the symbol parameter is omittedParameters:
- If the symbol is not sent, bookTickers for all symbols will be returned in an array.
Get all Liquidation Orders
Weight: 20
Parameters:
- If the symbol is not sent, liquidation orders for all symbols will be returned.
Open Interest
Get present open interest of a specific symbol.
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES Composite Index Symbol Information
Weight: 1
Parameters:
- Only for composite index symbols
Websocket Market Streams
- The base endpoint is: wss://stream.binancefuture.com
- Streams can be access either in a single raw stream or a combined stream
- Raw streams are accessed at /ws/<streamName>
- Combined streams are accessed at /stream?streams=<streamName1>/<streamName2>/<streamName3>
- Combined stream events are wrapped as follows:
- All symbols for streams are lowercase
- A single connection to stream.binancefuture.com is only valid for 24 hours; expect to be disconnected at the 24 hour mark
- The websocket server will send a ping frame every 5 minutes. If the websocket server does not receive a pong frame back from the connection within a 15 minute period, the connection will be disconnected. Unsolicited pong frames are allowed.
- WebSocket connections have a limit of 10 incoming messages per second.
- A connection that goes beyond the limit will be disconnected; IPs that are repeatedly disconnected may be banned.
- A single connection can listen to a maximum of 200 streams.
Live Subscribing/Unsubscribing to streams
- The following data can be sent through the websocket instance in order to subscribe/unsubscribe from streams. Examples can be seen below.
- The id used in the JSON payloads is an unsigned INT used as an identifier to uniquely identify the messages going back and forth.
Subscribe to a stream
Request
Unsubscribe to a stream
- Request
Listing Subscriptions
- Request
Setting Properties
Currently, the only property can be set is to set whether combined stream payloads are enabled are not. The combined property is set to false when connecting using /ws/ ("raw streams") and true when connecting using /stream/ .
- Request
Retrieving Properties
- Request
Error Messages
Error Message Description Parameter used in the SET_PROPERTY or GET_PROPERTY was invalid Value should only be true or false Property name provided was invalid Parameter id had to be provided or the value provided in the id parameter is an unsupported type Possible typo in the provided method or provided method was neither of the expected values Unnecessary parameters provided in the data Property name was not provided method was not provided in the data JSON data sent has incorrect syntax. Aggregate Trade Streams
The Aggregate Trade Streams push trade information that is aggregated for a single taker order every 100 milliseconds.
Stream Name:
<symbol>@aggTradeUpdate Speed: 100ms
Mark Price Stream
Mark price and funding rate for a single symbol pushed every 3 seconds.
Stream Name:
<symbol>@markPriceUpdate Speed: 3000ms
Kline/Candlestick Streams
The Kline/Candlestick Stream push updates to the current klines/candlestick every 250 milliseconds (if existing).
Kline/Candlestick chart intervals:
m -> minutes; h -> hours; d -> days; w -> weeks; M -> months
- 1m
- 3m
- 5m
- 15m
- 30m
- 1h
- 2h
- 4h
- 6h
- 8h
- 12h
- 1d
- 3d
- 1w
- 1M
Stream Name:
<symbol>@kline_<interval>Update Speed: 250ms
Continues Contract Kline/Candlestick Streams
Contract type:
- PERPETUAL
- CURRENT_MONTH
- NEXT_MONTH
- CURRENT_QUARTER
- NEXT_QUARTER
Kline/Candlestick chart intervals:
m -> minutes; h -> hours; d -> days; w -> weeks; M -> months
- 1m
- 3m
- 5m
- 15m
- 30m
- 1h
- 2h
- 4h
- 6h
- 8h
- 12h
- 1d
- 3d
- 1w
- 1M
Stream Name:
<pair>_<contractType>@continuousKline_<interval>Update Speed: 250ms
Individual Symbol Mini Ticker Stream
24hr rolling window mini-ticker statistics for a single symbol. These are NOT the statistics of the UTC day, but a 24hr rolling window from requestTime to 24hrs before.
Stream Name:
<symbol>@miniTickerUpdate Speed: 500ms
All Market Mini Tickers Stream
24hr rolling window mini-ticker statistics for all symbols. These are NOT the statistics of the UTC day, but a 24hr rolling window from requestTime to 24hrs before. Note that only tickers that have changed will be present in the array.
Stream Name:
!miniTicker@arrUpdate Speed: 1000ms
Individual Symbol Ticker Streams
24hr rollwing window ticker statistics for a single symbol. These are NOT the statistics of the UTC day, but a 24hr rolling window from requestTime to 24hrs before.
Stream Name:
<symbol>@tickerUpdate Speed: 500ms
All Market Tickers Streams
24hr rollwing window ticker statistics for all symbols. These are NOT the statistics of the UTC day, but a 24hr rolling window from requestTime to 24hrs before. Note that only tickers that have changed will be present in the array.
Stream Name:
!ticker@arrUpdate Speed: 1000ms
Individual Symbol Book Ticker Streams
Pushes any update to the best bid or ask's price or quantity in real-time for a specified symbol.
Stream Name: <symbol>@bookTicker
Update Speed: Real-time
All Book Tickers Stream
Pushes any update to the best bid or ask's price or quantity in real-time for all symbols.
Stream Name: !bookTicker
Update Speed: Real-time
Liquidation Order Streams
The Liquidation Order Streams push force liquidation order information for specific symbol
Stream Name: <symbol>@forceOrder
Update Speed: Real-time
All Market Liquidation Order Streams
The All Liquidation Order Streams push force liquidation order information for all symbols in the market.
Stream Name: !forceOrder@arr
Update Speed: Real-time
Partial Book Depth Streams
Top bids and asks, Valid are 5, 10, or 20.
Stream Names: <symbol>@depth<levels> OR <symbol>@depth<levels>@500ms OR <symbol>@depth<levels>@100ms .
Update Speed: 250ms, 500ms or 100ms
Diff. Book Depth Streams
Bids and asks, pushed every 250 milliseconds, 500 milliseconds, 100 milliseconds(if existing)
Stream Name:
<symbol>@depth OR <symbol>@depth@500ms OR <symbol>@depth@100msUpdate Speed: 250ms, 500ms, 100ms
How to manage a local order book correctly
- Open a stream to wss://stream.binancefuture.com/stream?streams=btcusdt@depth.
- Buffer the events you receive from the stream. For same price, latest received update covers the previous one.
- Get a depth snapshot from https://testnet.binancefuture.com/fapi/v1/depth?symbol=BTCUSDT&limit=1000 .
- Drop any event where u is < lastUpdateId in the snapshot
- The first processed event should have U <= lastUpdateId AND u >= lastUpdateId
- While listening to the stream, each new event's pu should be equal to the previous event's u , otherwise initialize the process from step 3.
- The data in each event is the absolute quantity for a price level
- If the quantity is 0, remove the price level
- Receiving an event that removes a price level that is not in your local order book can happen and is normal.
Composite Index Symbol Information Streams
Composite index information for index symbols pushed every second.
Stream Name: <symbol>@compositeIndex
Update Speed: 1000ms
Account/Trades Endpoints
Change Position Mode(TRADE)
POST /fapi/v1/positionSide/dual (HMAC SHA256)
Change user's position mode (Hedge Mode or One-way Mode ) on EVERY symbol
Weight: 1
Parameters:
Name Type Mandatory Description dualSidePosition STRING YES "true": Hedge Mode mode; "false": One-way Mode recvWindow LONG NO timestamp LONG YES Get Current Position Mode(USER_DATA)
GET /fapi/v1/positionSide/dual (HMAC SHA256)
Get user's position mode (Hedge Mode or One-way Mode ) on EVERY symbol
Weight: 30
Parameters:
Name Type Mandatory Description recvWindow LONG NO timestamp LONG YES New Order (TRADE)
POST /fapi/v1/order (HMAC SHA256)
Send in a new order.
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES side ENUM YES positionSide ENUM NO Default BOTH for One-way Mode ; LONG or SHORT for Hedge Mode. It must be sent in Hedge Mode. type ENUM YES timeInForce ENUM NO quantity DECIMAL NO Cannot be sent with closePosition = true reduceOnly STRING NO "true" or "false". Default "false". Cannot be sent in Hedge Mode; cannot be sent with closePosition = true (Close-All) price DECIMAL NO newClientOrderId STRING NO A unique id among open orders. Automatically generated if not sent. stopPrice DECIMAL NO Used with STOP/STOP_MARKET or TAKE_PROFIT/TAKE_PROFIT_MARKET orders. closePosition STRING NO true , false ;Close-All,used with STOP_MARKET or TAKE_PROFIT_MARKET . activationPrice DECIMAL NO Used with TRAILING_STOP_MARKET orders, default as the latest price(supporting different workingType ) callbackRate DECIMAL NO Used with TRAILING_STOP_MARKET orders, min 0.1, max 5 where 1 for 1% workingType ENUM NO stopPrice triggered by: "MARK_PRICE", "CONTRACT_PRICE". Default "CONTRACT_PRICE" priceProtect STRING NO "TRUE" or "FALSE", default "FALSE". Used with STOP/STOP_MARKET or TAKE_PROFIT/TAKE_PROFIT_MARKET orders. newOrderRespType ENUM NO "ACK", "RESULT", default "ACK" recvWindow LONG NO timestamp LONG YES Additional mandatory parameters based on type :
- Order with type STOP , parameter timeInForce can be sent ( default GTC ).
- Order with type TAKE_PROFIT , parameter timeInForce can be sent ( default GTC ).
Condition orders will be triggered when:
- If parameter priceProtect is sent as true:
- when price reaches the stopPrice ,the difference rate between "MARK_PRICE" and "CONTRACT_PRICE" cannot be larger than the "triggerProtect" of the symbol
- "triggerProtect" of a symbol can be got from GET /fapi/v1/exchangeInfo
- BUY: latest price ("MARK_PRICE" or "CONTRACT_PRICE") >= stopPrice
- SELL: latest price ("MARK_PRICE" or "CONTRACT_PRICE") <= stopPrice
- BUY: latest price ("MARK_PRICE" or "CONTRACT_PRICE") <= stopPrice
- SELL: latest price ("MARK_PRICE" or "CONTRACT_PRICE") >= stopPrice
- BUY: the lowest price after order placed <= activationPrice , and the latest price >= the lowest price * (1 + callbackRate )
- SELL: the highest price after order placed >= activationPrice , and the latest price <= the highest price * (1 — callbackRate )
For TRAILING_STOP_MARKET , if you got such error code.
<"code": -2021, "msg": "Order would immediately trigger.">
means that the parameters you send do not meet the following requirements:- BUY: activationPrice should be smaller than latest price.
- SELL: activationPrice should be larger than latest price.
If newOrderRespType is sent as RESULT :
- MARKET order: the final FILLED result of the order will be return directly.
- LIMIT order with sepcial timeInForce : the final status result of the order(FILLED or EXPIRED) will be returned directly.
STOP_MARKET , TAKE_PROFIT_MARKET with closePosition = true :
- Follow the same rules for condition orders.
- If triggered,close all current long position( if SELL ) or current short position( if BUY ).
- Cannot be used with quantity paremeter
- Cannot be used with reduceOnly parameter
- In Hedge Mode,cannot be used with BUY orders in LONG position side. and cannot be used with SELL orders in SHORT position side
Place Multiple Orders (TRADE)
POST /fapi/v1/batchOrders (HMAC SHA256)
Weight: 5
Parameters:
Name Type Mandatory Description batchOrders LIST YES order list. Max 5 orders recvWindow LONG NO timestamp LONG YES Where batchOrders is the list of order parameters in JSON
- Paremeter rules are same with New Order
- Batch orders are processed concurrently, and the order of matching is not guaranteed.
- The order of returned contents for batch orders is the same as the order of the order list.
Query Order (USER_DATA)
GET /fapi/v1/order (HMAC SHA256)
Check an order's status.
Weight: 1
- These orders will not be found:
- order status is CANCELED or EXPIRED , AND
- order has NO filled trade, AND
- created time + 30 days < current time
Parameters:
Name Type Mandatory Description symbol STRING YES orderId LONG NO origClientOrderId STRING NO recvWindow LONG NO timestamp LONG YES - Either orderId or origClientOrderId must be sent.
Cancel Order (TRADE)
DELETE /fapi/v1/order (HMAC SHA256)
Cancel an active order.
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES orderId LONG NO origClientOrderId STRING NO recvWindow LONG NO timestamp LONG YES Either orderId or origClientOrderId must be sent.
Cancel All Open Orders (TRADE)
DELETE /fapi/v1/allOpenOrders (HMAC SHA256)
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES recvWindow LONG NO timestamp LONG YES Cancel Multiple Orders (TRADE)
DELETE /fapi/v1/batchOrders (HMAC SHA256)
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES orderIdList LIST<LONG> NO max length 10
e.g. [1234567,2345678]origClientOrderIdList LIST<STRING> NO max length 10
e.g. ["my_id_1","my_id_2"], encode the double quotes. No space after comma.recvWindow LONG NO timestamp LONG YES Either orderIdList or origClientOrderIdList must be sent.
Auto-Cancel All Open Orders (TRADE)
Cancel all open orders of the specified symbol at the end of the specified countdown.
POST /fapi/v1/countdownCancelAll (HMAC SHA256)
Weight: 10
Parameters:
This rest endpoint means to ensure your open orders are canceled in case of an outage. The endpoint should be called repeatedly as heartbeats so that the existing countdown time can be canceled and repalced by a new one.
Example usage:
Call this endpoint at 30s intervals with an countdownTime of 120000 (120s).
If this endpoint is not called within 120 seconds, all your orders of the specified symbol will be automatically canceled.
If this endpoint is called with an countdownTime of 0, the countdown timer will be stopped.The system will check all countdowns approximately every 10 milliseconds, so please note that sufficient redundancy should be considered when using this function. We do not recommend setting the countdown time to be too precise or too small.
Query Current Open Order (USER_DATA)
GET /fapi/v1/openOrder (HMAC SHA256)
Weight: 1
Parameters:
- Either orderId or origClientOrderId must be sent
- If the queried order has been filled or cancelled, the error message "Order does not exist" will be returned.
Current All Open Orders (USER_DATA)
GET /fapi/v1/openOrders (HMAC SHA256)
Get all open orders on a symbol. Careful when accessing this with no symbol.
Weight: 1 for a single symbol; 40 when the symbol parameter is omitted
Parameters:
- If the symbol is not sent, orders for all symbols will be returned in an array.
All Orders (USER_DATA)
GET /fapi/v1/allOrders (HMAC SHA256)
Get all account orders; active, canceled, or filled.
- These orders will not be found:
- order status is CANCELED or EXPIRED , AND
- order has NO filled trade, AND
- created time + 30 days < current time
Weight: 5 with symbol
Parameters:
Name Type Mandatory Description symbol STRING YES orderId LONG NO startTime LONG NO endTime LONG NO limit INT NO Default 500; max 1000. recvWindow LONG NO timestamp LONG YES Notes:
- If orderId is set, it will get orders >= that orderId . Otherwise most recent orders are returned.
Futures Account Balance V2 (USER_DATA)
GET /fapi/v2/balance (HMAC SHA256)
Weight: 1
Parameters:
Name Type Mandatory Description recvWindow LONG NO timestamp LONG YES Account Information V2 (USER_DATA)
GET /fapi/v2/account (HMAC SHA256)
Get current account information.
Weight: 5
Parameters:
Name Type Mandatory Description recvWindow LONG NO timestamp LONG YES Change Initial Leverage (TRADE)
POST /fapi/v1/leverage (HMAC SHA256)
Change user's initial leverage in the specific symbol market.
For Hedge Mode, LONG and SHORT positions of one symbol use the same initial leverage and share a total notional value.Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES leverage INT YES target initial leverage: int from 1 to 125 recvWindow LONG NO timestamp LONG YES Change Margin Type (TRADE)
Change user's margin type in the specific symbol market.For Hedge Mode, LONG and SHORT positions of one symbol use the same margin type.
With ISOLATED margin type, margins of the LONG and SHORT positions are isolated from each other.POST /fapi/v1/marginType (HMAC SHA256)
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES marginType ENUM YES ISOLATED, CROSSED recvWindow LONG NO timestamp LONG YES Modify Isolated Position Margin (TRADE)
POST /fapi/v1/positionMargin (HMAC SHA256)
Weight: 1
Parameters:
- Only for isolated symbol
Get Position Margin Change History (TRADE)
GET /fapi/v1/positionMargin/history (HMAC SHA256)
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING YES type INT NO 1: Add position margin,2: Reduce position margin startTime LONG NO endTime LONG NO limit INT NO 默认值: 500 recvWindow LONG NO timestamp LONG YES Position Information Version 2 (USER_DATA)
Response:
For One-way position mode:
GET /fapi/v2/positionRisk (HMAC SHA256)
Get current position information.
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING NO recvWindow LONG NO timestamp LONG YES Note
Please use with user data stream ACCOUNT_UPDATE to meet your timeliness and accuracy needs.Account Trade List (USER_DATA)
GET /fapi/v1/userTrades (HMAC SHA256)
Get trades for a specific account and symbol.
Weight: 5
Parameters:
Name Type Mandatory Description symbol STRING YES startTime LONG NO endTime LONG NO fromId LONG NO Trade id to fetch from. Default gets most recent trades. limit INT NO Default 500; max 1000. recvWindow LONG NO timestamp LONG YES Get Income History(USER_DATA)
GET /fapi/v1/income (HMAC SHA256)
Weight: 20
Parameters:
- If incomeType is not sent, all kinds of flow will be returned
- "trandId" is unique in the same incomeType for a user
Notional Bracket (USER_DATA)
Weight: 1
Parameters:
Name Type Mandatory Description symbol STRING NO recvWindow LONG NO timestamp LONG YES Position ADL Quantile Estimation (USER_DATA)
Weight: 5
Parameters:
Values will be update every 30s.
Values 0, 1, 2, 3, 4 shows the queue position and possibility of ADL from low to high.
For positions of the symbol are in One-way Mode or isolated margined in Hedge Mode, "LONG", "SHORT", and "BOTH" will be returned to show the positions' adl quantiles of different position sides.
If the positions of the symbol are crossed margined in Hedge Mode:
- "HEDGE" as a sign will be returned instead of "BOTH";
- A same value caculated on unrealized pnls on long and short sides' positions will be shown for "LONG" and "SHORT" when there are positions in both of long and short sides.
User's Force Orders (USER_DATA)
Weight: 20
Parameters:
- If "autoCloseType" is not sent, orders with both of the types will be returned
- If "startTime" is not sent, data within 7 days before "endTime" can be queried
User Commission Rate (USER_DATA)
GET /fapi/v1/commissionRate (HMAC SHA256)
Weight: 20
Parameters:
Name Type Mandatory Description symbol STRING YES recvWindow LONG NO timestamp LONG YES User Data Streams
- The base API endpoint is: https://testnet.binancefuture.com
- A User Data Stream listenKey is valid for 60 minutes after creation.
- Doing a PUT on a listenKey will extend its validity for 60 minutes.
- Doing a DELETE on a listenKey will close the stream and invalidate the listenKey .
- Doing a POST on an account with an active listenKey will return the currently active listenKey and extend its validity for 60 minutes.
- The base websocket endpoint is: wss://stream.binancefuture.com
- User Data Streams are accessed at /ws/<listenKey>
- User data stream payloads are not guaranteed to be in order during heavy periods; make sure to order your updates using E
- A single connection to stream.binancefuture.com is only valid for 24 hours; expect to be disconnected at the 24 hour mark
Start User Data Stream (USER_STREAM)
Start a new user data stream. The stream will close after 60 minutes unless a keepalive is sent. If the account has an active listenKey , that listenKey will be returned and its validity will be extended for 60 minutes.
Weight: 1
Parameters:
Keepalive User Data Stream (USER_STREAM)
Keepalive a user data stream to prevent a time out. User data streams will close after 60 minutes.
Weight: 1
Parameters:
Close User Data Stream (USER_STREAM)
Close out a user data stream.
Weight: 1
Parameters:
Event: Margin Call
- When the user's position risk ratio is too high, this stream will be pushed.
- This message is only used as risk guidance information and is not recommended for investment strategies.
- In the case of a highly volatile market, there may be the possibility that the user's position has been liquidated at the same time when this stream is pushed out.
Event: Balance and Position Update
Event type is ACCOUNT_UPDATE .
When balance or position get updated, this event will be pushed.
- ACCOUNT_UPDATE will be pushed only when update happens on user's account, including changes on balances, positions, or margin type.
- Unfilled orders or cancelled orders will not make the event ACCOUNT_UPDATE pushed, since there's no change on positions.
When an asset of a user is changed:
- Only this asset and its balance information will be pushed
- Other assets and information will no longer be pushed even ther balances may not be 0
- If the asset change does not come with any position change, the position "P" will only return an empty []
When a position of a symbol is changed or the margin type of a symbol is changed:
- "P" will push the details in the "BOTH" position of this symbol
- If the change happens in "LONG" or "SHORT" position, the changed "LONG" or "SHORT" position of this symbol will be pushed
- Initialized "LONG" or "SHORT" positions of this symbol will also be pushed
- Position information of other symbols will no longer be pushed, even their positions may not be 0
When "FUNDING FEE" changes to the user's balance, the event will be pushed with the brief message:
- When "FUNDING FEE" occurs in a crossed position, ACCOUNT_UPDATE will be pushed with only the balance B (including the "FUNDING FEE" asset only), without any position P message.
- When "FUNDING FEE" occurs in an isolated position, ACCOUNT_UPDATE will be pushed with only the balance B (including the "FUNDING FEE" asset only) and the relative position message P ( including the isolated position on which the "FUNDING FEE" occurs only, without any other position message).
The field "m" represents the reason type for the event and may shows the following possible types:
- DEPOSIT
- WITHDRAW
- ORDER
- FUNDING_FEE
- WITHDRAW_REJECT
- ADJUSTMENT
- INSURANCE_CLEAR
- ADMIN_DEPOSIT
- ADMIN_WITHDRAW
- MARGIN_TRANSFER
- MARGIN_TYPE_CHANGE
- ASSET_TRANSFER
- OPTIONS_PREMIUM_FEE
- OPTIONS_SETTLE_PROFIT
Event: Order Update
When new order created, order status changed will push such event. event type is ORDER_TRADE_UPDATE .
Side
- BUY
- SELL
Position side:
- BOTH
- LONG
- SHORT
Order Type
- MARKET
- LIMIT
- STOP
- TAKE_PROFIT
- LIQUIDATION
Execution Type
- NEW
- PARTIAL_FILL
- FILL
- CANCELED
- CALCULATED — Liquidation Execution
- EXPIRED
- TRADE
Order Status
- NEW
- PARTIALLY_FILLED
- FILLED
- CANCELED
- EXPIRED
- NEW_INSURANCE — Liquidation with Insurance Fund
- NEW_ADL — Counterparty Liquidation`
Time in force
- GTC
- IOC
- FOK
- GTX
Error Codes
Here is the error JSON payload:
Errors consist of two parts: an error code and a message.
Codes are universal,but messages can vary.