Binance API: Spot Trading With Postman
Main Takeaways
APIs are pieces of code that allow applications to share information and can be used to enhance cryptocurrency trading strategies.
Postman is an API platform that simplifies the process of building and using APIs.
Learn more about using Postman for spot trading in the Binance API ecosystem.
Introduction
Understanding and using an API for cryptocurrency trading can open up a world of possibilities for entering and exiting positions. With some simple coding knowledge, you can plug into an exchangeâs backend to automate your trading strategies. By sidestepping the website, you can take a much faster path to the matching engine for high-performance applications.
In this article, weâll use Postman, a simplified API platform, to communicate with the exchange. Donât worry â we wonât be putting any real funds at risk.
Prerequisites
Testnet keys
Weâre going to use the testnet for our current purposes. This simulation feature will give us some funds with no real-world value to play around with. They function the same as real coins and tokens, so once youâre comfortable with the API, you can start using it to trade real funds.
Start by heading over to the Spot Test Network.
To get access, log in with a GitHub account. Youâll need to create one if you havenât already.
Click Authenticate, and sign in via GitHub.
Under API Keys, youâll be informed that you donât have keys registered. Click on Generate HMAC_SHA256 Key to create a pair.
On the next screen, give the keys a label. Call them whatever you want and hit Generate.Â
Youâre presented with two keys: the API Key and the Secret Key. Itâs important that you record these now. If you donât youâll need to start the key creation process again. We recommend storing them on your machineâs notes app for easy copy-pasting later.
Note: labeling your keys is worth doing when using the real exchange to manage different keys. Your account can have multiple keys with different permissions. If youâre running several trading bots, using separate keys with descriptive labels makes it easier to manage permissions or delete individual keys without changing all of your bots.
Downloading and installing Postman
Postman is an API Collaboration platform. Itâs a perfect starting point for us â weâll have access to collections of Binance requests that weâll test without needing to write a single line of code.
The program is available for Mac, Windows, and Linux. Head over to the Downloads page and download the .zip file.
Once thatâs completed, locate it in your file explorer and install it. Fire up the application, and weâre good to go! You can create an account to log in, but it isnât necessary. If you want to skip this step, simply select the option to do so at the bottom of the window.
Creating the environment
At this stage, you should have an interface that resembles the following.
First, we want to create our environment. This step is just a way to add variables to the requests we will work with. Weâll first need to grab some information from the Binance GitHub repository. Head over here and download the .zip file.
The download shouldnât take very long. You can find it in your file explorer and unzip it. Then, we can head back into Postman.
Click on the gear icon in the top right-hand corner (illustrated above). Youâll be greeted with a Manage Environments popup.Â
Select Import, and navigate to your extracted folder (binance-postman-api).Â
Enter it, then enter the environments folder.
Youâll now see two files (one for mainnet and one for testnet). The one weâre after is binance_com_spot_testnet_api.postman_environment.json. Ensure you have the correct one because our keys wonât work with the other.
Almost there. Click on Binance Spot Testnet API to see the variables below. Edit the two parameters outlined in red by pasting the keys you saved earlier. Click update and exit the popup.
On this screen, leave the timestamp and signature fields blank. These two values will be automatically created upon each request.
Thereâs one last thing to do. To the right of the gear icon we clicked to set up the environment earlier, youâll see a dropdown menu that currently says No Environment. Click it and select Binance Spot Testnet API.
Importing the collection
Now we will import the collection â this is an extensive assortment of requests that do the heavy lifting for us when making calls. To load it into our environment:
Click Import in the top left corner.
In the popup, under the File tab, select Upload Files.
Weâre looking for the binance-postman-api folder again. Locate and open it.
This time, enter collections in the subdirectory.
There are two files here again. One is for working with the futures API. But weâre working with the spot one, so you must select the Binance Spot API.postman_collection.json file.
You should now see a confirmation screen identifying the import as being in the Postman Collection format. Select Import.
Under the Collections tab to the left of the window, youâll now notice that we have a folder with over 100 requests. Congratulations! Weâre good to go. In the next section, weâll look at the kinds of requests we can make.
Making Requests
If you expand the folders under the Collections tab, youâll see that we can make many different requests. From the color-coding, you might note that there are three types of methods we can use:
GET: The GET method is used to retrieve stuff from a server. Weâll use this to find information about your account balance, asset prices, etc.
POST: Weâll generally use the POST method to create information on a server. This method is needed for things like placing orders, requesting withdrawals, etc.
DELETE: The DELETE method requests the server to delete information. Itâll come in handy for canceling orders.
Find the list of symbols and the trading rules
Time for our first request! Weâre going to get the symbols we can trade on the exchange and the trading rules:
GET /api/v3/exchangeInfo
This one doesnât take any additional parameters â you could copy and paste that into your address bar, and youâd get a response. But Postman makes it easy to see and modify requests where we include several parameters.
To load up this request, select Market > Exchange Information. A tab like the following will pop up:
We donât need to do anything else here, so go ahead and hit Send. Youâll then get a response:
In the uppermost highlighted section, youâll see some important information:
The status of the response (200 means weâve been successful, 400-499 means weâve run into an issue).
The time that was taken to receive the response (less than a second).
The size of the response (~22KB).
In the second box is the bulk of the response. This box contains information on the exchange, the pairs you can trade, and their minimum/maximum amounts.
It looks like a lot of information, but the format makes it easy to work with programmatically. When writing scripts to interact with it, youâll easily be able to pick out specific properties of specific elements from the response.
Check the account balances
Letâs check what assets we have and how much of each:
GET /api/v3/account
You can find this one under Trade > Account Information. Click on it to see a layout similar to the previous one. Youâll also note, however, that we have two new variables: timestamp and signature. The signature is a security measure. Because weâre now asking for sensitive information, it will prove that weâre the account holder.Â
The timestamp tells the server when the request was sent. Because networks can be unreliable or face downtime, the server might receive our request much later than intended. If too much time has passed, it will reject the request. You can specify how long you want to wait with the recvWindow parameter, which defaults to 5000 milliseconds.
Postman handles the generation of both of these fields for us. Click send, and youâll get a response. Under balances, you should see six assets â BNB, BTC, BUSD, ETH, LTC, and TRX. The balance will be split across free and locked assets. We havenât locked any up yet, so your assets should all be free.
Get the current price for a symbol
We can go about getting the current price of an asset in different ways. Perhaps the simplest is with the following request:
GET /api/v3/ticker/24hr
As you might guess, this will give us information about asset prices from the past twenty-four hours. You can find it in Market > 24hr Ticker Price Change Statistics. The default pair weâre greeted with as the symbol variable is BTC/USDT.Â
You can send this straight away to see a breakdown of price information. You can also change the symbol (to BNB/USDT, LTC/USDT, etc.) or uncheck the variable to return data for 40 pairs.
We also have a simpler call (Market > Symbol Price Ticker) that returns the current price that an asset is trading at:
GET /api/v3/price
As with the previous, you can change the symbol variable or remove it completely and get the latest price for all symbols.
Check the current order book depth
The order book depth â also referred to as the depth of market (DOM) â can tell us a lot about the market. Weâre going to make a call that will return some useful information:
GET /api/v3/depth
When we send this with the default values (Market > Order Book), we receive a response that tells us about the bids and asks for BTC/USDT. The testnet server wonât yield as much data as the actual one, so below is a screenshot of what you would expect to see in a real environment:
In the highlighted section above, we can see the first bid. Since weâre looking at the book for BTC/USDT, the upper number is the price that someone is willing to pay for your BTC. Below is the amount theyâre willing to buy. Therefore, this says that this order is asking for 0.999 BTC at a rate of 9704.65 USDT per BTC. If we continued to scroll down, we would see the offer price decrease â representing buyers that would pay less.Â
The top offer will naturally be the most attractive if youâre looking for a bang for your buck. Still, if youâre trying to sell 3 BTC, for example, youâll only be able to sell 0.999 BTC for the best price. Youâll need to take the subsequent (cheaper) offers until your order is filled.
Keep scrolling, and youâll see the asks. Theyâre functionally similar to bids, except they represent orders to sell BTC for USDT.Â
Place a test order
Now weâre going to post a test order.
POST /api/v3/order/test
Even though weâre just using testnet funds, this request wonât actually place an order. It can be helpful for testing orders before actually submitting them. Find it under Trade > Test New Order (TRADE).
You can see we have many more parameters involved. Letâs walk through the checked ones:
symbol â weâve come across this one previously. This is the pair you want to trade.
side â here, youâll stipulate whether you want to BUY or SELL. With the BTC/USDT pair, BUY indicates that you want to buy BTC for USDT, whereas sell will sell BTC for USDT.
type â the type of order you want to submit. Possible values (detailed here):
LIMIT
MARKET
STOP_LOSS
STOP_LOSS_LIMIT
TAKE_PROFIT
TAKE_PROFIT_LIMIT
LIMIT_MAKER
timeInForce â this parameter expresses how you want the order to execute:
GTC (good till canceled) â perhaps the most popular setup, GTC will ensure that your order is valid until itâs filled or canceled.
FOK (fill or kill) â FOK instructs the exchange to execute an order all at once. If the exchange canât do so, the order is canceled immediately.
IOC (immediate or cancel) â either all or part of the order must be executed immediately, or itâs canceled. Unlike FOK, the orders are not canceled if they can be partially filled.
quantity â the quantity of the asset you want to buy or sell.
price â the price at which you want to sell. For the BTC/USDT pair, this is expressed in USDT.
newClientOrderId â an identifier for the order. This isnât a mandatory field, but you can set it to an identifier that will make it easy to query later. Otherwise, it is randomly generated by the exchange.
Okay! Letâs create a test order now. We will proceed with the automatically-generated values: a limit order to sell 0.1 BTC for USDT at $9000. Hit Send. If this is successful, weâll get {} as a response.Â
Place a real order
Time to place a real order.Â
POST /api/v3/order
Navigate to Trade > New Order. Youâre familiar with test orders by now, so the parameters here will be no surprise. Letâs leave all the values as they are but change the price weâre selling to 40,000 USD. Tweak the price value to reflect this. Then, hit Send.
Your response returns a bunch of details about the order if successful.Â
Check an open orderâs status
We got confirmation that the order was placed in the previous section, but what if we want to recheck it later? We have a few requests at our disposal.
GET /api/v3/openOrders
Youâll find this in Trade > Current Open Orders (USER_DATA). BTC/USDT is selected by default. If you hit Send, youâll get all of your open BTC/USDT orders (so far, you should only see the one we set previously). You can also choose not to specify a symbol, which will return all your open orders instead.
GET /api/v3/allOrders
Trade > All Orders (USER_DATA) gives you an overview of all orders â not just open ones. Here, you must provide a symbol. orderId, startTime, endTime, and limit are optional parameters that can help you refine your search. Weâll leave them out here, so uncheck them. Hit Send, and youâll see the same response as before. If you had any closed or canceled orders, youâd see them here too.Â
Lastly, we can query specific orders with the following:
GET /api/v3/order
Get this under Trade > Query Order (USER_DATA). Youâll need to provide either the orderId or the origClientOrderId (the optional tag ânewClientOrderIdâ you can add to orders). Uncheck orderId. For origClientOrderId, we will provide the default tag from earlier â âmy_order_id_1â. Fill in the field and hit Send to get the response.
Cancel an order
After some time, we might decide that the 40,000 USD target is too optimistic, so we want to cancel it. In that case, weâd use the following:
DELETE /api/v3/order
Under Trade > Cancel Order is a request that will allow us to single out orders for cancelation. Uncheck orderId and newClientOrderId and pass âmy_order_id_1â as the value for origClientOrderId.
When you send this request, the order will be returned. If you scroll down to âstatus,â youâll see itâs indeed canceled. To confirm this, use the GET /api/v3/openOrders endpoint again (giving you an empty list) or GET /api/v3/order with the origClientOrderId.
Place an order that fills instantly
Our previous order wasnât filled because it was a limit order that would only trigger when the BTC price hit 40,000 USD. With a market order, we essentially say: âBuy or sell at whatever price the asset is currently trading at.â This will fill instantly.
For that, letâs head back to Trade > New Order. We will demonstrate the response type (newOrderRespType), which is a parameter we can tweak depending on the response we want from the server. There are three options here: ACK, RESULT, or FULL â you can see examples of each response here. We will go with ACK, which gives us a simple acknowledgment that the order was received.
Below, you can see that weâre about to submit a market order to sell BNB for BUSD at the current market price.
Note that the response gives us minimal information:
You can verify that the order was filled with the /api/v3/allOrders endpoint.
Checking your trades
Letâs lastly look at the endpoint for checking your trades:
GET /api/v3/myTrades
This is located under Trade > Account Trade List (USER_DATA). It allows you to check each trade for a particular symbol. If you want to see all your trades for the default symbol (BTC/USDT), simply uncheck startTime, endTime, and fromId. The response will return up to 500 trades â simply tweak the limit if you want to see more.
Debugging With Postman
In Postman, itâs possible to reveal the raw HTTP request and response further.
This menu will open the Postman console, which prints out the details of each request.
Get Started With Binance API
The purpose of this guide was to gently introduce you to the Binance API without writing a single line of code. If youâve followed along, you should now have an idea of how we can request and submit information.
Questions in the meantime? Head to our growing Binance Developer Community forum or look at the documentation.