Wednesday, December 28, 2011

A simple mtgox auto trading bot in python

Just for kicks, I decided to write a tradebot the other day, and thought it might be interesting for others to see just how simple it is to get a basic bot going.  As a quick disclaimer, the bot that we end up with is the bot that I am running right now, but it probably cause you to lose all of your money.  I am assuming that you have git installed, a working python installation, and a reasonably well funded mtgox account.

step 1 : download a good trading API

git clone https://github.com/viorels/mtgox-trader.git

This code is dead simple to use, and makes writing your bot take no time at all, so you can focus more on trading strategies rather than worrying about your POST variables getting to mtgox alright.

step 2 : move defaultsettings.py to settings.py and fill in credentials

step 3 : test out a hello world app

Create a file like hellomtgox.py, and put in these 4 lines of code


from settings import *
balance = exchange.get_balance()
btc_balance = balance['btcs']
print "you have %s bitcoins in mtgox!" % btc_balance


You should then be able to run   python hellomtgox.py   If successful, you know that your connection with mtgox is working correctly, if not, there might be a problem with your settings.py (wrong username/password?)

step 4 : read some example code

Almost all of the code in the directory, other than the settings and the api.py, is example code.  You can read that to get a feel for which methods are available to you, and how you can effectively use them.

step 5 : think of a good trading strategy

This is definitely the hard part, and you are likely going to be modifying your strategy regularly as the market fluctuates.  The strategy that I am using now is pretty simple.  If the market looks pretty volatile  and is very close to the daily high, sell some coins and buy them back when they are 1% cheaper.  If the price is close to the daily low, buy some coins, and sell them back when the market goes up by 1%.  This is a pretty conservative strategy, and mtgox is taking almost half of each win.  This also only works when

  1. the market is volatile, swinging by 4% or so per day
  2. the market is stable around a single point

If the market is trending up or down, this strategy will bet that the market is going to go back to where it was, and if it doesn't, you lose out more and more as the market drifts away from you.

step 6 : write some damn code

The general structure should look like this

import time
from settings import *


while True:
  # gather data
  # analyze data
  # act on data
  time.sleep(10)


And so, without further ado, here is the code that I am currently using to trade with on the strategy as described above.



import time
from settings import *


while True:
  try:
    balance = exchange.get_balance()
    btc_balance = balance['btcs']
    usd_balance = balance['usds']
    print btc_balance+" btc"
    print usd_balance+" usd"


    ticker = exchange.get_ticker()
    last = ticker['last']
    high = ticker['high']
    low  = ticker['low']


    width = high - low
    girth = 1 - (low / high)
    high_scrape = ( high - last ) / width
    low_scrape  = ( last - low ) / width


    print "width: "+str(width)
    print "girth: "+str(girth)
    print "[ %f %f ( %f ) %f %f ]" % (high,high_scrape,last,low_scrape,low)


    orders = exchange.get_orders()
    print str(len(orders))+" orders open"


    if girth < 0.1:
      print "market seems pretty stable, waiting"
      time.sleep(10)
      continue



    if len(orders) > 0:
      print "there is already a pending order"
      time.sleep(10)
      continue


    if high_scrape < 0.1:
      print "high scrape detected!"
      exchange.sell_btc(amount=btc_balance, price=last)
      exchange.buy_btc(amount=btc_balance, price=float(last)*0.991)


    if low_scrape < 0.1:
      print "low scrape detected!"
      exchange.buy_btc(amount=float(usd_balance)*last, price=last)
      exchange.sell_btc(amount=float(usd_balance)*last, price=float(last)*1.0099)


  except:
    print "oh no!!"


  time.sleep(10)

For testing, I put in 100 coins, and have 50 trading at the high end, and 50 trading at the low end (kept as USD by default).  It has been working pretty well as the market was floating around 4, but today I have an order stuck back down at 4.05, so I am hoping that this upward trend comes back down for a bit so I can get that back :-)

Now, you might notice that the only data that I am pulling from to make my decisions is mtgox high, low, and last.  Yes, this is pretty insane.  Any decent bot really should be analyzing a wide range of data sources, like maybe some historical data, market depth (which the mtgox api here give really easy access to), blockchain data, and even data coming out of the blogotwittisphere could prove extremely useful for successful trading.

Good luck, and be careful not to shoot your foot off!