Bittrex API – An Introductory Guide

8 min read

Get 10-day Free Algo Trading Course

Loading

Last Updated on April 3, 2023

Bittrex API Guide

Table of contents:

  1. What is Bittrex API?
  2. What is Bittrex?
  3. Is Bittrex API free?
  4. Why should I use Bittrex API?
  5. Why shouldn’t I use the Bittrex API?
  6. Is Bittrex API available in my country?
  7. What are the alternatives to using Bittrex API?
  8. How to get started with Bittrex API?
  9. How to get currency data with Bittrex API?
  10. How to get Price Data on Bittrex API?
  11. How to get historical data with Bittrex API?
  12. How to access technical indicators such as the 20 SMA with the Bittrex API?
  13. How to get Order Book data with Bittrex API?
  14. How to execute a trade on ETH when BTC hits a certain price with the Bittrex API?
  15. How to execute an ETH trade when BTC moves 5% in the last 5 minutes with the Bittrex API?
  16. How to cancel orders with Bittrex API?
  17. Full code

What is Bittrex API?

Bittrex API is a method that allows us to automatically trade cryptocurrencies on Bittrex via code.

Link: https://bittrex.com

What is Bittrex?

Bittrex is an online cryptocurrency exchange platform that allows its users to trade over 700 trading pairs. As one of the oldest US-based exchanges, Bittrex is known for its excellent safety practices and transaction speed.

Is Bittrex API free?

Creating a Bittrex account and using the Bittrex API is completely free, but when it comes to trading there are fees. The fees depend on the pair you’re trading and your monthly trading volume.

The monthly trading volume fees follow a maker-taker fee schema. This basically means that the more you trade, the lower do the fees get. The picture below illustrates the fee method.

Maker orders are the ones that create liquidity on a market when being entered in an order book. This means that they aren’t filled upon placement, but they wait for a future order that matches it.

On the other hand, the taker orders take the liquidity from the market. They execute instantly by matching against another order that is already placed in the order book aka our maker.

When it comes to transaction fees, there are some specific blockchain network fees that might occur when the user moves tokens on the blockchain to and from Bittrex.

There are no deposit fees issued by Bittrex while there are withdrawal fees.

Why should I use Bittrex API?

  • Bittrex is free to use
  • Has a decent range of assets to trade
  • Has competitive fees when compared to other exchanges
  • Has a decent API
  • Has a good track record

Why shouldn’t I use Bittrex API?

  • Bittrex needs more features i.e. Margin trading
  • Awful customer support (users can wait up to 3+ months to hear back from them)
  • Withdrawal fees are on the higher side
  • Has/had some trouble with their regulatory status

Is Bittrex API available in my country?

Due to regulatory requirements, customers who reside in certain countries (see the picture below) can no longer use the Bittrex platform. This list was last updated on March 23, 2021.

What are the alternatives to using Bittrex API?

Bittrex can be replaced with other websites that can be more suitable for your needs. Here are some of them:

How to get started with Bittrex API?

In order to get started with the Bittrex API, you will first need to go over to their website that is found on the following link:

https://global.bittrex.com/

In the upper right corner, you will see the “Sign up” button, be sure to click it and choose your account type, fill in your email and password. When done click the blue “Create Account” button.

The next thing is to check your email for the verification link after which you will be taken to the ToS (Terms of Service) page.

The next step is to enter your basic account info like the country of residence and birth details. After that, you will need to verify your ID and provide some additional info. And then you’ll wait for a couple of days to get fully verified by Bittrex.

How to get currency data with Bittrex API?

Currency data on Bittrex can be obtained with the Bittrex API by accessing their currencies endpoint. For this, we will use the REST API.

response = pd.DataFrame(requests.get('https://api.bittrex.com/v3/currencies').json())
response.tail()

As you can see, there are 444 available currencies on Bittrex and they usually come with “notice” messages that provide useful information about the currency.

In order to get information about a specific currency you can call the following endpoint and state at the end the name of your currency as shown below:

btc = requests.get('https://api.bittrex.com/v3/currencies/BTC').json()
btc
{'symbol': 'BTC',
 'name': 'Bitcoin',
 'coinType': 'BITCOIN',
 'status': 'ONLINE',
 'minConfirmations': 2,
 'notice': '',
 'txFee': '0.00030000',
 'IogoUrl': 'https://bittresblobstorage.blob.core.windows bef9.png',
 'prohibitedIn': [],
 'baseAddress': '1N52wHoVR79PMDishab2XmRHsbekCdGquK',
 'associatedTermsOfServicel: [],
 'tags': []} 

How to get Price Data on Bittrex API?

Price data with the Bittrex API can be obtained by calling the tickers endpoint with a specified currency and or market for that currency.

Before we access a certain ticker, let’s see what are all the available markets aka trading pairs on the Bittrex exchange:

markets = pd.DataFrame(requests.get('https://api.bittrex.com/v3/markets').json())
markets.tail()

As you see, there are over 750 available trading pairs on Bittrex. Now, let’s obtain the price data for a certain ticker.

ticker = requests.get('https://api.bittrex.com/v3/markets/BTC-USD/ticker').json()
ticker
{'symbol': 'BTCC-USD',
 'last-TradeRate': '63552.35400000',
 'bidRate': '63540.27100000',
 'askRate': '63555.76000080'} 

If you want price data for all of the available trading pairs you can write the following:

tickers = pd.DataFrame(requests.get('https://api.bittrex.com/v3/markets/tickers').json())
tickers.tail()

How to get historical data with Bittrex API?

Bittrex API can obtain the historical price data by accessing the markets historical endpoint where the user can set the starting date, ticker, and candle interval to obtain.

historical = pd.DataFrame(requests.get('https://api.bittrex.com/v3//markets/BTC-USD/candles/DAY_1/historical/2019').json())
historical.tail()

But what if we want to create some custom indicators and a nice interactive graph with this data?

How to access technical indicators such as the 20 SMA with the Bittrex API?

Bittrex API doesn’t have in-built technical indicators but custom ones can be created by utilizing various libraries. For example, we can use the pandas rolling window to create a 20 day Simple Moving Average (20 SMA).

historical['20 SMA'] = historical.close.rolling(20).mean()
historical.tail()

For more sophisticated indicators there is a nice library called btalib that you can check out. Now, let us create a nice interactive graph of the data we have.

import plotly.graph_objects as go
fig = go.Figure(data=[go.Candlestick(x = historical.index,
                                    open = historical['open'],
                                    high = historical['high'],
                                    low = historical['low'],
                                    close = historical['close'],
                                    ),
                     go.Scatter(x=historical.index, y=historical['20 SMA'], line=dict(color='purple', width=1))])


fig.show()

How to get Order Book data with Bittrex API?

Order Book data can be obtained by using the Bittrex REST API markets order book endpoint. I’ll also show you how to create separate data frames or merged ones for bids and asks.

orderbook = requests.get('https://api.bittrex.com/v3/markets/BTC-USD/orderbook').json()

# If you want separate data frames
bids = pd.DataFrame(orderbook['bid'])
asks = pd.DataFrame(orderbook['ask'])

# You can also merge the two into one
df = pd.merge(bids, asks, left_index=True, right_index=True)
df = df.rename({"rate_x":"Bid Price","quantity_x":"Bid Amount",
                "rate_y":"Ask Price","quantity_y":"Ask Amount"}, axis='columns')
df.head()

How to execute a trade on ETH when BTC hits a certain price with the Bittrex API?

In this first example, I will show you how to correctly and securely launch an order with specified requirements. The thing that we want to do is to launch a trade on ETH when BTC hits a certain price (e.g. $50k).

In order to make this work, we will need to set our order foundation and then create a loop that will check if the price level is hit. If the price is hit, we will execute a market order. On the contrary, we will continue looping around.

When the price is executed we will wait for a few seconds and check if the order was really filled. This additional step is very important to add to your trading strategies as the exchange server may encounter some troubles.

We will also create a custom function that will make it easier for us to handle Bittrex private endpoints that require authentication.

Now that the logic is set, let’s import the relevant libraries and set up the trading:

import hmac
import time
import hashlib
import requests
import json
import pandas as pd

apiKey = ""
apiSecret = ""

def auth(uri, method, payload, apiKey, apiSecret):
    timestamp = str(round(time.time()*1000))
    contentHash = hashlib.sha512(payload).hexdigest()
    
    array = [timestamp, uri, method, contentHash]
    s= ''
    preSign = s.join(str(v) for v in array)
    signature = hmac.new(apiSecret.encode() ,preSign.encode(), hashlib.sha512).hexdigest()

    headers = {
     'Accept':'application/json',
     'Api-Key':apiKey,
     'Api-Timestamp':timestamp,
     'Api-Content-Hash':contentHash,
     'Api-Signature':signature,
     'Content-Type':'application/json'
    }
    
    return headers

while True:
    try:
        ticker = requests.get('https://api.bittrex.com/v3/markets/BTC-USD/ticker').json()
    except Exception as e:
        print(f'Unable to obtain ticker data: {e}')
    
    if float(ticker['bidRate']) >= 50000:

        uri = 'https://api.bittrex.com/v3/orders'

        content = { "marketSymbol":"USDC-ETH",
         "direction":"SELL",
         "type":"LIMIT",
         "limit":"0.0005",
         "quantity":"20",
         "timeInForce":"GOOD_TIL_CANCELLED"
        }

        payload = bytes(json.dumps(content),'utf-8')
        
        try:
            data = requests.post(uri, 
                                 data=payload, 
                                 headers = auth(uri, 'POST', payload, apiKey, apiSecret),
                                 timeout=10
                                ).json()
            print(data)
        except Exception as e:
            print(f'Unable to place order: {e}')
        
        sleep(2)
        
        try:
            payload = ""
            uri = f'https://api.bittrex.com/v3/orders/{data["id"]}'

            check = requests.get(uri, 
                                 data=payload, 
                                 headers=auth(uri, 'GET', payload.encode(), apiKey, apiSecret), 
                                 timeout=10
                                ).json()
            print(check)
        except Exception as e:
            print(f'Unable to check order: {e}')
        
        if check_order == 'OPEN':
            print ('Order placed at {}'.format(pd.Timestamp.now()))
            break
        else:
            print ('Order closed at {}'.format(pd.Timestamp.now()))
            break
    else:
        sleep(60)
        continue

Take note: if you want to trade other USD pairs the symbols are often in reverse order e.g. “ETH-USDT”.

How to execute an ETH trade when BTC moves 5% in the last 5 minutes with the Bittrex API?

The main task will be to execute an ETH trade when BTC moves 5% in the last 5 minutes. This means that we will want to create a loop that will obtain BTC prices in certain intervals and calculate the percentage change between them.

If the percentage change is less than 5%, the script will be sleeping for 5 minutes and calculating the percentage change again. If the percentage change is equal to or more than 5% the trade will execute.

After the trade execution, we will sleep for a few seconds and then check on the trade if it was filled or not. Have in mind that the code up to the loop part remains the same as in the previous example.

Now that the logic is set, it is time to code it out:

while True:
    try:
        btc_old = requests.get('https://api.bittrex.com/v3/markets/BTC-USD/ticker').json()
    except Exception as e:
        print(f'Unable to obtain ticker data: {e}')
    
    sleep(300)
    
    try:
        btc_new = requests.get('https://api.bittrex.com/v3/markets/BTC-USD/ticker').json()
    except Exception as e:
        print(f'Unable to obtain ticker data: {e}')
    
    percent = (((float(btc_new['bidRate']) - float(btc_old['bidRate'])) * 100) / float(btc_old['bidRate']))
    
    if percent >= 5:

        uri = 'https://api.bittrex.com/v3/orders'

        content = { "marketSymbol":"USDC-ETH",
         "direction":"SELL",
         "type":"LIMIT",
         "limit":"0.0005",
         "quantity":"20",
         "timeInForce":"GOOD_TIL_CANCELLED"
        }

        payload = bytes(json.dumps(content),'utf-8')
        
        try:
            data = requests.post(uri, 
                                 data=payload, 
                                 headers = auth(uri, 'POST', payload, apiKey, apiSecret),
                                 timeout=10
                                ).json()
            print(data)
        except Exception as e:
            print(f'Unable to place order: {e}')
        
        sleep(2)
        
        try:
            payload = ""
            uri = f'https://api.bittrex.com/v3/orders/{data["id"]}'

            check = requests.get(uri, 
                                 data=payload, 
                                 headers=auth(uri, 'GET', payload.encode(), apiKey, apiSecret), 
                                 timeout=10
                                ).json()
            print(check)
        except Exception as e:
            print(f'Unable to check order: {e}')
        
        if check_order == 'OPEN':
            print ('Order placed at {}'.format(pd.Timestamp.now()))
            break
        else:
            print ('Order closed at {}'.format(pd.Timestamp.now()))
            break
    else:
        print(f'Requirment not reached. Percentage move at {percent}')
        continue

How to cancel orders with Bittrex API?

To cancel an order with Bittrex you will need to utilize the DELETE orders endpoint and pass the order id of the order you want to cancel. For this you can use our previous example for reference:

uri = "https://api.bittrex.com/v3/orders/{orderId}"
payload = ""
data = requests.delete(uri, 
                     data=payload, 
                     headers = auth(uri, 'DELETE', payload.encode(), apiKey, apiSecret),
                     timeout=10
                     ).json()

Can Bittrex API be used in Google Sheets?

Yes, you can use the Bittrex API in google sheets by writing a simple JS script that does the same thing to the response like our Python code did. I’ll show you an example script that pulls the last ticker price for our assets.

The first thing that we need to do is to open up a blank Google Sheets sheet and the go to Tools and select the Script Editor that will appear in the dropdown menu.

When there, you will copy the following code and click the save icon:

function Ticker_Last(symbol)
{
  var url = "https://api.bittrex.com/v3/markets/" + symbol + "/ticker";
  var response = UrlFetchApp.fetch(url);
  var myjson = JSON.parse(response.getContentText());
  var lastprice = myjson.lastTradeRate;
  return lastprice;
}

Now you can go back to your Sheet and add the Cryptos you’re interested in into cells. When done you can pull the Last price data by using the function like the following:

=Ticker_Last(<cell>)

Full code

GitHub Link

Igor Radovanovic