CCXT Cryptocurrency Trading — Limit Orders and Market Orders [Tutorial]

ShrimpyApp
Coinmonks

--

With a name like “CryptoCurrency eXchange Trading Library”, the first thing you might want to do with the CCXT library is execute a trade.

Cryptocurrency exchanges are vastly different when it comes to how they process trades, which endpoints they provide for developers, and how these endpoints can be integrated into applications.

That’s where CCXT comes into the picture.

The complexity of cryptocurrency exchanges is what gave rise to the dire need for libraries which could unify the way developers interact with each individual exchange.

Throughout this tutorial, we will explore popular order types and how to execute these different orders on the exchange.

What are the popular trading order types in cryptocurrency?

There are a number of different order types, but the primary focus for this tutorial will be to limit orders and market orders.

Discover and review best Trading automation softwares

Limit Orders

A limit order is an order to sell or buy a cryptocurrency at a specific price or better. In the case of limit orders, both the price and quantity of the order must be specified.

While this may seem like a simple concept that cannot be broken down further, we find that exchanges have implemented multiple types of limit orders. The two most common types of limit orders are “Good Til’ Canceled” (GTC) and “Immediate Or Cancel” (IOC) orders.

Both of these are placed at a specified price and quantity, but GTC orders are intended to be left open on the exchange until they are canceled by the trader or filled by another market participant who takes the open order.

Unlike GTC orders, IOC orders are immediately canceled by the exchange as soon as they are placed. Any quantity of the order which was not filled is returned to the trader. IOC orders are typically intended to execute instantly by being the taker in the trade.

While we won’t delve too deep into the strategies for when to use these different order types, it’s good to keep these differences in mind when developing your trading strategy.

CCXT Examples

For our first example, we will explore how to use the CCXT library to execute a limit order on the Bittrex exchange. To successfully connect an exchange and execute an order, we will need to first generate API keys to authenticate our access to the exchange.

Follow steps 1–3 in this guide to generate your Bittrex API Keys.

Once you have your API keys in hand, use the following script by assigning your API keys to the appropriate ‘apiKey’ and ‘secret’ fields.

import ccxtbittrex = ccxt.bittrex({
'apiKey': '...',
'secret': '...',
})
# fetch your account balances for each asset
account_balance = bittrex.fetch_balance()
# execute the order
limit_order_placement = bittrex.create_limit_buy_order('ETH/BTC', '0.01', '0.014'))

Notice: We have hard-coded the price for our ‘ETH/BTC’ trade. To determine an accurate price point to execute the trade, it would be ideal to evaluate the current state of the order books on Bittrex to pick the specific price and quantity for the trade. Since this is an example, it is not recommended to use the default values.

In order to automate the process of trading, we will need to collect order book data from the exchange to evaluate where we should be placing the order.

account_balance = bittrex.fetch_balance()orderbook = bittrex.fetch_order_book('ETH/BTC')

Additional information on how to collect order book data can be found in one of our latest tutorials here:

Shrimpy Examples

Due to limitations with the CCXT library, we will also explore how this can be done with the Shrimpy Universal Crypto Trading APIs.

To finish the following examples, sign up for an account with the Shrimpy Crypto Data & Trading APIs. After logging into Shrimpy, generate Master API keys be selecting the button for “Create Api Master Key”. The keys that are generated from this process will be used in the following scripts. You will also need to purchase at least the lowest user subscription tier to execute trades.

Install

Before jumping into our Shrimpy example, let’s start by installing the Shrimpy Python Library.

pip install shrimpy-python

Example

Now that the library has been installed, let’s construct our script which will execute a trade on Bittrex. Once again, if you need to generate new Bittrex API keys, follow steps 1–3 in this guide.

import shrimpy
import time
# use your Shrimpy API public and private keys to create the client
public_key = '...' # shrimpy_public_key (aka Shrimpy Master Key)
secret_key = '...' # shrimpy_secret_key (aka Shrimpy Master Key)
client = shrimpy.ShrimpyApiClient(public_key, secret_key)# create a new user
user = client.create_user(
'mycustomname' # (optional) name
)
# link up to 20 exchange accounts for each user
account = client.link_account(
user['id'], # user_id
'bittrex', # exchange
'...', # public_key (aka exchange apiKey)
'...' # private_key (aka exchange secretKey)
)
# access balance data for each of your user's accounts
balance = client.get_balance(
user['id'], # user_id
account['id'] # account_id
)
# sleep for 5 seconds the first time linking an account
time.sleep(5)
# place an IOC or GTC limit order for your user
place_limit_order_response = client.place_limit_order(
user['id'], # user_id
account['id'], # account_id
'ETH', # base_symbol
'BTC', # quote_symbol
'0.01', # quantity of base_symbol
'0.026', # price
'SELL', # side
'IOC' # time_in_force ('IOC' or 'GTC')
)

To execute precise trades, we need to collect exact order book data from the exchange. This can be done using the following simple example.

orderbooks = client.get_orderbooks(
'bittrex', # exchange
'ETH', # base_symbol
'BTC', # quote_symbol
10 # limit of how much depth to return on each side
)

Note: This trading example only executes an individual trade, if you would like to trade your entire portfolio to one asset using limit orders, Shrimpy supports an endpoint to do exactly that.

You can allocate a portfolio by using the following request.

client.allocate(
'701e0d16-1e9e-42c9-b6a1-4cada1f395b8', # user_id
123, # account_id
{
'isDynamic': False,
'allocations': [
{ 'symbol': 'BTC', 'percent': '100' }
]
}
)

Boom! Just like that Shrimpy will automatically go through your entire portfolio and sell everything you own to Bitcoin. This will even handle edge cases where there are no trading pairs between the base currency and BTC.

Market Orders

Executing market orders is a bit easier to grasp than the different types of limit orders. Rather than placing the order at a specific price, market orders simply take the best price at the given time until the order amount is filled.

That means if you want to sell LTC to buy BTC, the exchange will continue selling LTC at the market rate until it reaches the order size you specified.

CCXT Example

Our first example will cover how to do this with CCXT. Like previous scripts, it will require us to enter API public and secret keys in order to connect to our desired exchange.

import ccxtbittrex = ccxt.bittrex({
'apiKey': '...',
'secret': '...',
})
# get account balances to determine how much can be traded
account_balance = bittrex.fetch_balance()
# sell .001 ETH for market price and receive BTC right now
market_order_placement = bittrex.create_market_sell_order('ETH/BTC', .001)

To develop a full strategy that buys and sells cryptocurrencies, we will need to access more market data to make our trading decisions. For example, if we want to trigger a trade based on the current market rate of an asset, we will need to have access to live price tickers that track the price of each asset.

In a previous article, we discuss how to build a crypto price ticker using CCXT.

Shrimpy Example

Now that we have demonstrated how we can execute market orders using CCXT, let’s construct a script that will show how this can be done using the Shrimpy Crypto Trading APIs.

Note: If you followed the last Shrimpy example for limit orders, you should already have a user created and an exchange account linked to your Shrimpy Developer API keys. That means for this next example, we won’t need to create another user or link a new exchange account. You can simply retrieve your previously created user and balance data to execute more trades.

import shrimpy# use your Shrimpy API public and private keys to create the client
public_key = '...'
secret_key = '...'
client = shrimpy.ShrimpyApiClient(public_key, secret_key)# note: since we created a user in our last example script,
# we can just retrieve our list of users.
users = client.list_users()
first_user_id = users[0]['id']
# retrieve the accounts associated with this user
accounts = client.list_accounts(
first_user_id
)
first_account_id = accounts[0]['id']
# access balance data for the user account you previously created
balance = client.get_balance(
first_user_id, # user_id
first_account_id # account_id
)
# execute a market order
smart_order_response = client.create_trade(
first_user_id, # user_id
first_account_id, # account_id
'BTC', # from_symbol
'ETH', # to_symbol
'0.01' # amount of from_symbol
)

Notice how you can access all the accounts associated with a user. If you link 1 Binance, 3 Bittrex, 2 KuCoin, and 4 Kraken exchange accounts for one user, they can all be accessed through the same user without relinking the keys each time. This allows you to easily manage thousands of users without struggling to maintain API keys for each user.

Smart Trading

As a bonus, we will provide an example of smart order routing. If you don’t look closely, you may think this next script is identical to the last example. However, if you look closely at the request to “Create Trade”, you will notice a single parameter has been added which automatically allows us to execute a Smart Order Routing Strategy.

It’s so easy!

import shrimpy# use your Shrimpy API public and private keys to create the client
public_key = '...'
secret_key = '...'
client = shrimpy.ShrimpyApiClient(public_key, secret_key)# note: since we created a user in our last example script,
# we can just retrieve our list of users.
users = client.list_users()
first_user_id = users[0]['id']
# retrieve the accounts associated with this user
accounts = client.list_accounts(
first_user_id
)
first_account_id = accounts[0]['id']
# access balance data for the user account you previously created
balance = client.get_balance(
first_user_id, # user_id
first_account_id # account_id
)
# execute a market order
smart_order_response = client.create_trade(
first_user_id, # user_id
first_account_id, # account_id
'BTC', # from_symbol
'ETH', # to_symbol
'0.01' # amount of from_symbol
True # enable smart_routing
)

Notice how Shrimpy can execute a complete Smart Order Routing (SOR) strategy with a single request. There is no need to constantly re-evaluate the market and carefully place orders across the exchange to execute the perfect SOR strategy. Shrimpy will do all the heavy lifting for you!

Try out the Shrimpy Trading & Data APIs today. It’s the easiest way to get started trading on cryptocurrency exchanges. Collect historical market data, access real-time websockets, execute advanced trading strategies, and manage an unlimited number of users.

Don’t forget to follow us on Twitter and Facebook for updates, and ask any questions to our amazing, active community on Telegram.

The Shrimpy Team

Get Best Software Deals Directly In Your Inbox

--

--

ShrimpyApp
Coinmonks

Shrimpy is a crypto exchange trading bot for portfolio management, indexing the market, rebalancing, and strategy backtesting. Join now at shrimpy.io.