Programming your first Cryptobot

in #cryptocurrency7 years ago

Programming a crypto-trading bot is a great way to start trading algorithmically. This post will outline how to program your own simple bot by interfacing with the Bittrex API.

For this guide you will need Python 3 installed, and a competent text editor. This post will not cover the basics of programming, as there are hundreds of resources that already cover that angle. If you have any questions feel free to comment below.

To begin, you will need an API key from Bittrex. Login to your account, and then head to the settings page. Click on the API Keys section, and then create a new one. If you have 2FA enabled, you will need to enter your key before creating it.

api_key.png

Now that we have our key, let's create our bot. The architecture will be very simple. The bot will run indefinitely and query for markets every 30 seconds. Using our simple algorithm the bot will open buy / sell positions. The resulting bot will be extremely dumb, but this guide should serve as a base for you to develop your own trading algorithm.

Begin with a fresh Python file, and the contents from below. Make sure to adjust the API_KEY and API_SECRET_KEY values.

import time
import requests
import hashlib
import hmac

TICK_INTERVAL = 60  # seconds
API_KEY = 'my-api-key'
API_SECRET_KEY = b'my-api-secret-key'


def main():
    print('Starting trader bot, ticking every ' + str(TICK_INTERVAL) + 'seconds')
    

def format_float(f):
    return "%.8f" % f


if __name__ == "__main__":
    main()

Running the program now won't do much. The print statement will execute, and we will see some text in the console, but the program will exit immediately after. Most bots run indefinitely until terminated by the operator. Let's setup our bot to do the same. Update the main() method with the following changes, and also add the new tick() method stub.

def main():
    print('Starting trader bot, ticking every ' + str(TICK_INTERVAL) + 'seconds')

    while True:
        start = time.time()
        tick()
        end = time.time()

        # Sleep the thread if needed
        if end - start < TICK_INTERVAL:
            time.sleep(TICK_INTERVAL - (end - start))
            
def tick():
    pass

Now our bot will run it's tick method every 30 seconds while accounting for any latency in the tick method itself. Next we need to flesh out the tick method. This is where most of the program logic will live.

def tick():
    print('Running routine')

    market_summaries = simple_reqest('https://bittrex.com/api/v1.1/public/getmarketsummaries')
    for summary in market_summaries['result']:
        market = summary['MarketName']
        day_close = summary['PrevDay']
        last = summary['Last']

        percent_chg = ((last / day_close) - 1) * 100
        print(market + ' changed ' + str(percent_chg))
        

def simple_reqest(url):
    r = requests.get(url)
    return r.json()

Now if you run the program you'll see that the bot queries all of the available markets on Bittrex and then prints the percentage the market has changed over the last 24 hours. We've also added the simple_request() method which dispatches an HTTP request and then converts the response to JSON.

Our bot is cool and all, but it doesn't actually trade any crypto yet. Let's flesh out our advanced algorithm to place buy and sell orders. We'll need a few things including a way to make signed requests which the Bittrex API expects when making trades.

def tick():
    print('Running routine')

    market_summaries = simple_reqest('https://bittrex.com/api/v1.1/public/getmarketsummaries')
    for summary in market_summaries['result']:
        market = summary['MarketName']
        day_close = summary['PrevDay']
        last = summary['Last']

        percent_chg = ((last / day_close) - 1) * 100
        print(market + ' changed ' + str(percent_chg))

        if 40 < percent_chg < 60:
            # Fomo strikes! Let's buy some
            print('Purchasing 5 units of ' + market + ' for ' + str(format_float(last)))
            res = buy_limit(market, 5, last)
            print(res)

        if percent_chg < -20:
            # Ship is sinking, get out!
            sell_limit(market, 5, last)
            
def buy_limit(market, quantity, rate):
    url = 'https://bittrex.com/api/v1.1/market/buylimit?apikey=' + API_KEY + '&market=' + market + '&quantity=' + str(quantity) + '&rate=' + format_float(rate)
    return signed_request(url)


def sell_limit(market, quantity, rate):
    url = 'https://bittrex.com/api/v1.1/market/selllimit?apikey=' + API_KEY + '&market=' + market + '&quantity=' + str(quantity) + '&rate=' + format_float(rate)
    return signed_request(url)


def signed_request(url):
    now = time.time()
    url += '&nonce=' + str(now)
    signed = hmac.new(API_SECRET_KEY, url.encode('utf-8'), hashlib.sha512).hexdigest()
    headers = {'apisign': signed}
    r = requests.get(url, headers=headers)
    return r.json()

There's quite a bit going on here. Let's break it down. The new logic in our tick() method includes the meat of our algorithm.

        if 40 < percent_chg < 60:
            # Fomo strikes! Let's buy some
            print('Purchasing 5 units of ' + market + ' for ' + str(format_float(last)))
            res = buy_limit(market, 5, last)
            print(res)

        if percent_chg < -20:
            # Ship is sinking, get out!
            sell_limit(market, 5, last)

As you can see, this algorithm is extremely stupid. This bot trades based only on the 24 hour change of a coin. Despite this silly example, it should serve as a gateway for you to begin fleshing out your own secret algorithm.

We've also added some new methods to handle placing buy and sell orders. These methods require an API key because they modify aspects of your account. The final method we added, signed_request(), is needed to send a valid request to Bittrex. The specifics of this are outlined in the Bittrex developer's guide online.

I hope this guide helps you on your way to riches! Feel free to ask for help in the comments if you get lost or stuck.

Sort:  

Really informative, thank you. I've made my own price bot for steem, it displays the price changed from last, and percent changed. I have it updating every 5 seconds using the CryptoCompare API.

Did you do this using the same script?

Simple and clear!

Cool information.

Hope you found it useful!

Resteemed so i can test it later when i have more time. Thanks for sharing this information

Nice break down! Seems simple enough.

A sample code on github would also be cool, such that one can download and review later :-)

A great suggestion indeed. I've uploaded the final product to https://github.com/tmstieff/BittrexBot

Awesome! Thanks :-)

Can this also apply to Poloniex's API?

I think with little tweaking you could make it work. I don't know exact details, but Bitfinex API requests are very similar. Although keywords in HTTP string are different. For me it seems that they all use same logic.

This will be very helpful.

Can we expect any follow up on this article with more updates?

Yes, I plan on writing a follow up this week.

This is a C language right?

This is written using Python, but you could easily translate it to whatever language you're comfortable with.

Cool. :-)

I keep getting an error saying ModuleNotFoundError: No module named 'requests'

Any idea what I'm doing wrong?

Coin Marketplace

STEEM 0.26
TRX 0.11
JST 0.033
BTC 64006.33
ETH 3077.08
USDT 1.00
SBD 3.87