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!

21 comments:

  1. Thanks for sharing this blog http://www.iessaywriter.com/ its very informative and useful for us .

    ReplyDelete
  2. Fantastic post it is you are share here.This post is good informative and you've got posted such invaluable and informative article which gave me lot of knowledge. I hope that you are going to preserve it up and we will be able to have extra informative and helping news from you.Outdoor Media Agencies in Surat

    ReplyDelete
  3. nice information read it must.thank you for share it
    Law Exams

    ReplyDelete
  4. 2D Free Column Agen Bandar Togel The purpose of this term is not much different from the term free colok above, it's just a 2D free plug you have to choose 2 numbers to be placed bets. Bandar Togel Suppose you place a bet 6 and 1, and the outcome is 7168. Then you've been declared win,Agen Bandar Togel and is entitled to get paid a bet on you. Very easy and not too risky.

    Drag Dragon Just like a free plug and 2D free plug, the dragon plug requires you to select 3 togel numbers at random Bandar Agen Togel. Suppose you choose the number 367 and the outcome is 6973. Then you are legitimate as the winner, and get paid according to the big that is bet Bandar Togel.

    Colok Jitu The purpose of this term is you have to guess one of the four numbers that will come out, Which in the 4 digits is divided into 4 parts, namely the As, the Kop,Bandar Agen Togel the Head and the Tail. Just like a free plug, but the plug is more specific in choosing the part number Agen Bandar Togel.

    ReplyDelete
  5. Ayoo Main di Pelangi Togel
    TOTAL HADIAH RATUSAN JUTAAN UNTUK DIBAGIKAN

    KEPADA MEMBER PERMAINAN TOGEL
    - Semua Pasti Menang Dan dapat ^_^ , No Zonk

    bandar Togel online terpercaya di indonesia

    ReplyDelete
  6. bandar togel online terbaik dan terpecaya
    minimal deposit hanya 20.000
    info lebih jelas bisa hubungi CS kami
    Telp : +85581569708
    BBM : D8E23B5C
    Line : togelpelangi
    Link:bandar togel

    ReplyDelete
  7. yuk bergabung bersama kami
    di permainan tebak angka
    info lebih jelas silakan kunjugi kami...
    Telp : +85581569708
    BBM : D8E23B5C
    Line : togelpelangi
    Link:Bandar togel singapore terbaik indonesia

    ReplyDelete
  8. You have brought up a very fantastic details , appreciate it for the post.

    www.freesitemaker.net

    ReplyDelete
  9. This article is out of the roof. Wow! Wonderful. Great Post!
    https://www.aarinkaur.com/
    https://www.aarinkaur.com/Contact-Mumbai-Escorts-Aarin.html
    https://www.aarinkaur.com/Mumbai-Escorts-Rate-Card.html
    https://www.aarinkaur.com/Mumbai-Escorts-Location.html
    https://www.aarinkaur.com/Mumbai-Escorts-Location.html

    ReplyDelete
  10. It's very nice of you to share your knowledge through posts. I love to read stories about your experiences. hire someone to write a paper They're very useful and interesting.

    ReplyDelete
  11. Only for kicks, I chose to compose a tradebot a few days ago, and figured it very well may be intriguing so that others might see custom assignment writing exactly that it is so easy to get an essential bot rolling. As a speedy disclaimer, the bot that we end up with is the bot that I am running at present, however it presumably make you lose the entirety of your cash. I'm expecting that you have git introduced, a functioning python establishment, and a sensibly all around subsidized mtgox account.

    ReplyDelete
  12. In case you are stressed over the breaks on your home relax .We are here to get it fix. In case Edmonton foundation repair you are stressed over snow on your rooftop, we can eliminate it. We are here to clean you drain.

    ReplyDelete
  13. We have a solutions-focused organization where we approach each Client with an initial consultation to gather information regarding their current systems to provide them high quality oil in water services to satisfy them.

    ReplyDelete
  14. We have a solutions-focused organization where we approach each Client with an initial consultation to gather information regarding their current systems to provide them high quality luxury kitchen design services to satisfy them.

    ReplyDelete
  15. I have been striked your site. when I read your blog. you shared informative post. but I have to connect with a vpn I got it from VPN for Raspberry Pi. because I wants some information about mtgox auto trading bot in python. I worked in other professional.

    ReplyDelete
  16. ماكينة تعبئة سكر اصابع للفنادق والمطاعم تُعتبر أداة ضرورية في فنادق ومطاعم الضيافة حيث يتم استخدامها بشكل يومي لتلبية احتياجات الضيوف. تأتي هذه الماكينات بتصميمات متطورة تتيح للمستخدمين تعبئة كميات دقيقة من السكر بسرعة وسهولة. بفضل آلياتها الدقيقة، تقدم هذه الماكينات سهولة في الاستخدام وضمان جودة التعبئة، مما يساهم في توفير الوقت والجهد في تنظيم الخدمة للضيوف. تعتبر استخداماتها متعددة، حيث يمكن استخدامها أيضًا في المنازل والمكاتب لتوفير وقت التعبئة والمحافظة على التنظيم في المساحات الصغيرة.

    ReplyDelete
  17. تغليف المواد الغذائية برولات شرنك POF له العديد من الأهميات، ومنها ؛ حماية الطعام: تغليف المواد الغذائية بشريط POF المصنع بمصنع الوليد افضل مصنع أكياس بولي ايثيلين فيمصر ساعد في حمايتها من التلوث الخارجي والتأثيرات البيئية الضارة مثل الرطوبة والأتربة والجراثيم. يمكن أن يؤدي التلوث الميكروبي إلى تدهور الطعام وتلفه، مما يؤدي إلى فقدان قيمته الغذائية ورائحته وطعمه. وبالتالي، فإن تغليف المنتجات الغذائية بشريط POF يحميها ويحافظ على جودتها العالية.

    ReplyDelete
  18. UPVC pipes are much lighter than metal pipes, making them easier to handle, transport, and install. fittings factories in Egypt can be easily joined using solvent cement, which simplifies the installation process and reduces labor costs. UPVC is recyclable, which helps reduce environmental impact and supports sustainable practices.

    ReplyDelete
  19. خطوات طباعة الاستيكر الشفاف:
    اختيار نوع الطابعة:

    يتم استخدام نوعين رئيسيين من الطابعات لطباعة الاستيكرات الشفافة:
    طابعات الليزر: تتميز بجودة الطباعة العالية وسرعتها، وهي مثالية للاستخدام الاحترافي.
    طابعات نفث الحبر: توفر نتائج ممتازة للأعمال الصغيرة والشخصية، ولكن يجب استخدام حبر مقاوم للماء في حال استخدام طباعة استيكر لاصقفي أماكن معرضة للرطوبة.
    إعداد الطابعة:

    التأكد من إعدادات الطابعة لتتناسب مع نوع الورق المستخدم. غالبًا ما توجد إعدادات خاصة للطباعة على الورق الشفاف.

    ReplyDelete