Script to Sell Bitcoin on a Limit Price and Then Buy Again

Understanding and using an API for cryptocurrency trading can open up a world of possibilities when information technology comes to entering and exiting positions. With some simple coding knowledge, you tin plug into an exchange'south backend to automate your trading strategies. By sidestepping the website, yous can take a much faster path to the matching engine for high-performance applications.

The purpose of this series is to introduce you to Binance's Residual API and to teach you how to interact with information technology. By the end, you should be confident in your power to query data near the markets and your position and to identify a range of different club types.

In this article, nosotros'll be using Postman to communicate with the substitution. Don't worry – nosotros won't be putting any existent funds at run a risk.

Testnet keys

We're going to utilise the testnet for our purposes. This will give united states some funds with no real-world value to play around with. They part in exactly the aforementioned style as real coins and tokens, so once you're comfortable with the API, you can offset to apply information technology to merchandise existent funds.

  1. Starting time by heading over to the Spot Test Network.
  2. To get access, you'll demand to log in with a GitHub business relationship. Create ane if you lot haven't already.
  3. Click Cosign and sign in via GitHub.
  4. Under API Keys, yous'll exist informed that you don't have keys registered. Click on Generate HMAC_SHA256 Key to create a pair.
  5. On the next screen, requite the keys a label. Call them whatever y'all want and hitting Generate.
  6. You're presented with 2 keys: the API Fundamental and the Secret Key. It'south important that yous record these at present. You'll need to start the cardinal creation process once more if you don't. We recommend storing them on your auto's notes app for like shooting fish in a barrel copy-pasting later on.

Note: labelling your keys is something worth doing when using the existent substitution in guild to manage different keys. Your account tin take multiple keys with dissimilar permissions. If y'all're running several trading bots, using separate keys with descriptive labels makes information technology easier to manage permissions or delete individual keys without changing all of your bots.

Downloading and installing Postman

Postman is an API Collaboration platform. Information technology's a perfect starting point for us – we'll have access to collections of Binance requests that we'll examination without needing to write a single line of code.

The program is bachelor for Mac, Windows, and Linux. Head over to the Downloads page and download the .zero file.

Once that's completed, locate it in your file explorer and install information technology. Fire upwards the awarding, and we're practiced to get! Annotation that you can create an account to log in, but it isn't necessary. If you want to skip that step, just select the option to practise and then at the bottom of the window.

At this stage, you should take an interface that resembles the following.

We want to first create our environment. This is just a manner for us to add variables to the fix of requests we're going to work with. To do that, we'll beginning need to grab some information from the Binance GitHub repository. Head over here and download the .zippo file.

The download shouldn't accept very long. Discover it in your file explorer and unzip it. Then, nosotros can head back into Postman.

Click on the gear icon in the summit right-mitt corner (illustrated above). You lot'll be greeted with a Manage Environments popup.

  1. Select Import, and navigate to the folder you've just extracted (binance-postman-api).
  2. Enter it, then enter the environments binder.
  3. You'll at present encounter two files (one for mainnet and one for testnet). The one we're afterward is binance_com_spot_testnet_api.postman_environment.json. Make sure you've got the correct one because our keys won't work with the other.

Nearly there. Click on Binance Spot Testnet API, and y'all'll see the variables beneath. Edit the 2 parameters outlined in reddish by pasting in the keys you saved before. Click update and exit out of the popup.

On this screen, leave the timestamp and signature fields blank. These two values will be automatically created upon each request.

There's 1 last matter to exercise. To the right of the gear icon we clicked to fix the environment earlier, y'all'll run across a dropdown card that currently says No Environment. Click it and select Binance Spot Testnet API.

Now we're going to import the collection – this is an extensive assortment of requests that do the heavy lifting for usa when we're making calls. To load it into our surroundings:

  1. Click Import in the acme left corner.
  2. In the popup, under the File tab, select Upload Files.
  3. We're looking for the binance-postman-api binder over again. Locate and open it.
  4. This time, enter collections in the subdirectory.
  5. There are 2 files here over again. One is for working with the futures API. But we're working with the spot one, so yous'll demand to select the binance_spot_api_v1.postman_collection.json file.
  6. You should now see a confirmation screen that identifies 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 accept a folder with over 100 requests. Congratulations! We're good to go. In the next section, we'll accept a look at the kinds of requests we can make.

If you expand the folders nether the Collections tab, you'll see that we have a agglomeration of unlike requests we tin make. From the color-coding, yous might annotation that there are three types of methods we tin employ:

  • GET : The Go method is used to retrieve stuff from a server. Nosotros'll utilise this to find out information nearly your account rest, nugget prices, etc.
  • Postal service : We'll mostly utilize the POST method to create information on a server. This is needed for things similar placing orders, requesting withdrawals, etc.
  • DELETE : The DELETE method is a request for 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 offset request! Nosotros're going to get the symbols we can merchandise on the exchange and the trading rules:

Go /exchangeInfo

This one doesn't take whatever boosted parameters – you could re-create and paste that into your accost bar, and yous'd get a response. Only for requests where nosotros include several parameters, Postman makes information technology easy to encounter and alter them.

To load up this request, select Marketplace > Exchange Data. A tab similar the following will pop upwardly:

We don't need to practise annihilation else here, so become ahead and striking Ship. You'll then get a response:

In the uppermost highlighted section, yous'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 taken to receive the response (less than a second)

  • the size of the response (~22KB).

In the 2d box is the majority of the response. It's been pretty-printed information technology so that it'due south a flake easier on the eyes. This contains information on the exchange itself, also as the pairs you can trade and their minimum/maximum amounts.

Information technology looks similar a lot of information, but the format makes it very easy to work with programmatically. When writing scripts to interact with it, you'll easily be able to choice out specific properties of specific elements from the response.

Check the account balances

Let'southward check what assets we take, and how much of each:

                                    Get              /account                  

This one tin be found under Trade > Account Information. Click on it, and you'll see a like layout to the previous 1. You lot'll also note, however, that we have two new variables: timestamp and signature. The signature is a security measure out. Because we're at present request for sensitive information, information technology 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 up downtime, the server might receive our asking much later than intended. If too much time has passed, it will reject the asking. You tin can specify how long you want to await 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 volition be split across complimentary and locked. We oasis't locked whatever upwardly still, and then your assets should all be free.

Congratulations on your newfound (non-existent) wealth!

How to get the current price for a symbol

We can become about getting the current price of an nugget in different ways. Perhaps the simplest is with the following request:

                                    Get              /api/v3/ticker/24hr                  

As you might guess, this will give the states information about nugget prices from the past twenty-four hours. Find it in Market > 24hr Ticker Price Change Statistics. The default pair nosotros're greeted with as the symbol variable is BTCUSDT.

You lot tin send this directly away to encounter a breakdown of price information. You tin besides change the symbol (to BNBBUSD, LTCUSDT, etc.), or you can uncheck the variable to render data for 40 pairs.

Nosotros also have a simpler phone call (Market > Symbol Price Ticker) that returns the electric current price that an nugget is trading at:

                                    Get              /api/v3/price                  

Equally with the previous, you tin can change the symbol variable or remove it completely and become the latest price for all symbols.

Check the current club book depth

Lodge book depth (also referred to equally depth of marketplace, or DOM) can tell united states of america a lot well-nigh the market place. We're going to brand a call that will return some useful data:

                                    Go              api/v3/depth                  

When we send this with the default values (Market > Order Book), we're sent back a response that tells u.s.a. about the bids and asks for BTCUSDT. The testnet server won't yield as much data as the actual one, so beneath is a screenshot of what yous would expect to see in a real environment:

In the highlighted section to a higher place, we can run into the first bid. Since nosotros're looking at the book for BTCUSDT, the upper number is the price that someone is willing to pay for your BTC. Below is the amount they're willing to purchase. What this says, therefore, is that this order is asking for 0.999 BTC at a rate of 9704.65 USDT per BTC. If we continued to scroll down, nosotros would see the offering price decrease – representing buyers that would pay less.

The acme offer will naturally exist the nearly attractive one if you're looking for bang for your buck. That said, if you're trying to market sell, say, 3 BTC, you'll only exist able to sell 0.999 BTC for the best price. You'll need to take the subsequent (cheaper) offers until the entirety of your order is filled.


Go along scrolling, and yous'll see the asks. They're functionally like to bids, except they represent orders to sell BTC for USDT.

Place a exam guild

Now nosotros're going to mail a test lodge.

                                    Postal service              api/v3/order/test                  

Fifty-fifty though nosotros're merely using testnet funds, this request won't actually place an order. It can come in useful for testing orders before actually submitting them. Find information technology under Merchandise > Test New Order (Merchandise).

You tin can run across we have many more parameters involved. Let'due south walk through the checked ones:

  • symbol – we've run into 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 BTCUSDT 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
    • Marketplace
    • STOP_LOSS
    • STOP_LOSS_LIMIT
    • TAKE_PROFIT
    • TAKE_PROFIT_LIMIT
    • LIMIT_MAKER
  • timeInForce– this parameter expresses how you want the order to execute:
    • GTC (skillful till canceled) – perhaps the most popular setup, GTC will ensure that your gild is valid until it's filled, or until you abolish it.
    • FOK (fill or kill) – FOK instructs the exchange to execute an lodge all at once. If the exchange can't do so, the gild is immediately canceled.
    • IOC (immediate or cancel) – either all or part of the club must be executed immediately, or it's canceled. Unlike FOK, the orders are not canceled if they can be partially filled.
  • quantity – simply, the quantity of the asset that you want to buy or sell.
  • toll – the price at which y'all want to sell. For the BTCUSDT pair, this is expressed in USDT.
  • newClientOrderId – an identifier for the order. This isn't a mandatory field, merely you tin can gear up it to an identifier that volition make it easy to query later on. Otherwise, information technology is randomly generated by the exchange.

Okay! Let'due south create a test club now. We're going to go with the automatically-generated values: a limit order to sell 0.one BTC for USDT at $9000. Hit Ship. If this was successful, and then we'll but get {} every bit a response.

Place a existent order

Time to place a real fake club.

                                    Mail              /api/v3/guild                  

Navigate to Trade > New Society. You're familiar with test orders past at present, so the parameters here will come as no surprise. Permit's leave all the values every bit they are, but since we're permabulls, we'll change the price that nosotros're selling at to $xl,000. Tweak the price value to reflect this. Then, striking Send.

Your response returns a bunch of details about the order if successful.

Check an open gild's condition

We got confirmation that the order was placed in the previous section, but what if we want to bank check information technology again later? We have a few requests at our disposal.

                                    Go              /api/v3/openOrders                  

Yous'll find this in Trade > Electric current Open Orders (USER_DATA). BTCUSDT is selected by default. If you hitting Send, you'll become all of your open BTCUSDT orders (and so far, you should only see the i nosotros ready previously). Y'all tin can choose non to specify a symbol, which volition render all of your open up orders instead.

                                    GET              /api/v3/allOrders                  

Merchandise > All Orders (USER_DATA) gives y'all an overview of all orders – not merely open up ones. Hither, you must provide a symbol. orderId, startTime, endTime, and limit are optional parameters that tin help yous refine your search. We'll go out them out here, so uncheck them. Hit Transport, and you lot'll run across the same response as before. If you had any closed or canceled orders, you'd see them here besides.

Lastly, we tin query specific orders with:

                                    GET              /api/v3/order                  

Get this under Merchandise > Query Order (USER_DATA). Y'all'll demand to provide either the orderId or the origClientOrderId (the optional tag "newClientOrderId" you tin add to orders). Uncheck orderId. For origClientOrderId, we're going to provide the default tag from earlier – "my_order_id_1". Fill in the field and hit Ship to get the response.

Cancel an order

After some time, we might determine that the $40,000 target is a fiddling as well optimistic, so we want to cancel it. In that case, nosotros'd employ:

                                    DELETE              /api/v3/society                  

Under Trade > Cancel Order is a asking that will allow us to single out orders for cancelation. Uncheck orderId and newClientOrderId and laissez passer "my_order_id_1" as the value for origClientOrderId.

When y'all send this request, the order will be returned. If y'all scroll downwardly to "status," you'll see that it's indeed canceled. To ostend this, use the Go  /api/v3/openOrders endpoint over again (giving you an empty list) or Get  /api/v3/order with the origClientOrderId.

Place an club 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. With a market order, nosotros're basically maxim "purchase/sell at any price the nugget is currently trading at." This will fill instantly.

For that, allow's caput dorsum to Merchandise > New Gild. We're going to demonstrate the response type (newOrderRespType), which is a parameter we tin can tweak depending on the response we want to get from the server. There are three options here: ACK, Issue, or Full – you can run into examples of each response here. We're going to go with ACK, which will give us a simple acknowledgment that the order was received.

Below, you lot can see that we're near to submit a marketplace order to sell BNB for BUSD at the current market price.

Note that the response gives us minimal data:

Yous can verify that the order was filled with the /api/v3/allOrders endpoint.

Checking your trades

Permit's lastly look at the endpoint for checking your trades:

                                    GET              /api/v3/myTrades                  

This is located under Trade > Account Merchandise List (USER_DATA). It allows you to cheque each merchandise for a particular symbol. If you want to see all of your trades for the default symbol (BTCUSDT), simply uncheck startTime, endTime and fromId. The response will return upwardly to 500 trades – simply tweak the limit if you want to run into more.

In Postman, information technology's possible to further reveal the raw HTTP request and response.

This menu will open the Postman console, which prints out the details of each request.

The purpose of this guide was to gently introduce you to the Binance API without writing a unmarried line of code. If you've followed along, you should now have an idea of how nosotros tin can request and submit information.

In the next installments in this series, we'll innovate some basic coding concepts that allow the states to automate the buying and selling of cryptocurrencies and other digital assets.

Questions in the meantime? Head over to our growing Binance Developer Community forum, or have a look at the documentation.

bullockmilteven.blogspot.com

Source: https://academy.binance.com/en/articles/binance-api-series-pt-1-spot-trading-with-postman

0 Response to "Script to Sell Bitcoin on a Limit Price and Then Buy Again"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel