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!

25 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. شركة مكافحة حشرات
    تهتم شركة قمم التميز باعمال الرش والقضاء على الحشرات المنزلية فمهما كانت المعاناة ومهما كانت كمية الحشرات التى تعانى منها فتعاون مع افضل شركة تهتم بهذه الخدمة الان شركة مكافحة حشرات بخميس مشيط
    الحشرات المنزلية من المشكلات التى تعانى منها البيوت ، وخصوص فى المناطق المرتفعة فيها الحرارة ، وحيث تنشر الحشرات فى المنزل وقد تسبب متاعب كثيرة وأمراض خطيرة .
    وللحماية منزلك من الحشرات ومنع دخولها ويمكن ان نطرح بعض النصائح :
    *الحرص على النظافة الدائمة للمنزل ،
    *التهوية الجيدة لغرف المنزل ودخول أشعة الشمس لقتل الحشرات التى لا ترى إلا بالعين المجردة .
    *التخلص من القمامة أول بأول حتى لا تكون عرضه للأنتشار الحشرات .
    نتظيف خزانات الطعام وتهويتها جيدة، والتخلص من الفضلات ، وغلق المحكم للبرطمانات للطعام التى تواجد فى خزانة حتى لا تكون مصدر لتسرب الحشرات .
    *وضع سلك شبكة صغير الحجم على النوافذ والأبواب ، وسد الثقوب والشقوق بالأسمنت اوجبس ،لكى لا تتسرب الحشرات منها .
    *تنظيف الأطباق وأوانى الطعام بعد استعمالها مباشرة ، لأنها قد تسبب فى خروج الحشرات من المكان التى تعيش فيه .
    *عدم ترك فضلات الطعام على مائدة الطعام ، وتنظيف بصفة دورية تمنع من أنتشار الحشرات والوقاية منها .
    وهناك حشرات متعددة قد تسبب للأنسان أزعاج دائم ومنها : النمل والصراصير والبق والذباب والناموس والفئران .
    النمل نوعان * النمل عادى مصدر غذائه فضلات الطعام ويعيش فى ثقوب وشقوق المنزل . شركة مكافحة النمل الابيض بخميس مشيط
    والنمل الأبيض يسمى ( العتة) وهو يحتاج إلى طعام الدائم لكى يبقى على قيد الحياة ، مصدر غذائه السكر (الجلكوز) الموجود فى الخشب ، و المتواجد فى الأبواب والنوافذ والأثاث ، وقد يسبب خطر كبير على منزلك فالنمل الأبيض يعمل ممرات ويقوم بتأسيس بيت له أسفل المنزل ، ويكون دمار بمرور الوقت وأضرار فادحة لايمكن اصلاحها إلا بعد فوات الآوان .
    ويمكن التخلص من النمل الأبيض برش مبيدات كيمائية مخصص لها أثناء بناء الأثاث فى الأرض ، وعند تركيب الأبواب التأكيد من أغلاق جميع الفتحات فى جوانب الباب وألأفضل تركيب الأبواب بالمفاصل وليس بالمواد اللزقة ، وعند شراء الأثاث الضغط على الخشب وتأكد مدى قوتها وعدم أصابتها بالنمل الأبيض . شركة نقل عفش بخميس مشيط
    أما النمل العادى التى يتواجد المطبخ يمكن التخلص منه بقليل من الصودا المخلوطة بالسكر وضعها فى الثقوب والفتحات التى تخرج منها فالنمل يموت فى الحال .
    فى خزانة الطعام نضع فيها قليل من القهوة المرة أو الفلفل غير المطحون فهو يخلصك من النمل نهائيا وكذلك الحشرات الأخرى .
    والصراصير لمنعها من أنتشارها فى المنزل يمكن سد البالوعات والمراحيض فى الليل ، صب المحاليل السامة أو مشتقات البترول القتلة فى فتحات المراحيض والبالوعات ثم صب ماء عليها فى الصباح.

    ReplyDelete
  5. 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
  6. 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
  7. 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
  8. 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
  9. In the first place, auto title advances might be viewed as a secured advance since it requires a vow. In getting such advances, a borrower is required to give the title of his or her auto as guarantee. online car title loans chicago

    ReplyDelete
  10. It is just in crises that payday credits prove to be useful. Payday credits likewise safeguard you out of circumstances of ricocheted checks and late installment punishments by influencing the fitting money to progress accessible. Payday Loans Chicago

    ReplyDelete
  11. I like to read your article because it really helps me. Thank you for sharing this post with us.
    Togel Online

    ReplyDelete
  12. pasaran bola dan prediksi bola parlay lengkap terbaik

    bursa sepakbola
    pasaran bola
    prediksi bola

    https://tajenonline.com/berikut-bolavita-live-chat-agen-sabung-ayam-yang-terpercaya/

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

    www.freesitemaker.net

    ReplyDelete
  14. 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
  15. 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
  16. 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
  17. 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
  18. 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
  19. 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
  20. 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