Skip to content

Commit

Permalink
fix maxme#3 - pep8 cleaning using 'autopep8 --max-line-length=119'
Browse files Browse the repository at this point in the history
  • Loading branch information
maxme committed Mar 19, 2013
1 parent b66d8c1 commit 0cb27c5
Show file tree
Hide file tree
Showing 19 changed files with 61 additions and 57 deletions.
12 changes: 7 additions & 5 deletions src/arbitrage.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import logging
import json


class Arbitrer(object):
def __init__(self):
self.markets = []
Expand All @@ -17,14 +18,14 @@ def init_markets(self, markets):
self.market_names = markets
for market_name in markets:
exec('import public_markets.' + market_name.lower())
market = eval('public_markets.' + market_name.lower() + '.' + market_name + '()')
market = eval('public_markets.' + market_name.lower() + '.' + market_name + '()')
self.markets.append(market)

def init_observers(self, observers):
self.observer_names = observers
for observer_name in observers:
exec('import observers.' + observer_name.lower())
observer = eval('observers.' + observer_name.lower() + '.' + observer_name + '()')
observer = eval('observers.' + observer_name.lower() + '.' + observer_name + '()')
self.observers.append(observer)

def get_profit_for(self, mi, mj, kask, kbid):
Expand Down Expand Up @@ -98,12 +99,12 @@ def arbitrage_depth_opportunity(self, kask, kbid):
best_i, best_j = (i, j)
best_w_buyprice, best_w_sellprice = (w_buyprice, w_sellprice)
return best_profit, best_volume, self.depths[kask]["asks"][best_i]["price"],\
self.depths[kbid]["bids"][best_j]["price"], best_w_buyprice, best_w_sellprice
self.depths[kbid]["bids"][best_j]["price"], best_w_buyprice, best_w_sellprice

def arbitrage_opportunity(self, kask, ask, kbid, bid):
perc = (bid["price"] - ask["price"]) / bid["price"] * 100
profit, volume, buyprice, sellprice, weighted_buyprice,\
weighted_sellprice = self.arbitrage_depth_opportunity(kask, kbid)
weighted_sellprice = self.arbitrage_depth_opportunity(kask, kbid)
if volume == 0 or buyprice == 0:
return
perc2 = (1 - (volume - (profit / buyprice)) / volume) * 100
Expand Down Expand Up @@ -141,7 +142,7 @@ def tick(self):

for kmarket1 in self.depths:
for kmarket2 in self.depths:
if kmarket1 == kmarket2: # same market
if kmarket1 == kmarket2: # same market
continue
market1 = self.depths[kmarket1]
market2 = self.depths[kmarket2]
Expand All @@ -158,6 +159,7 @@ def loop(self):
self.tick()
time.sleep(30)


def main():
import argparse
parser = argparse.ArgumentParser()
Expand Down
3 changes: 1 addition & 2 deletions src/config.py-example
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ markets = ["MtGoxEUR", "BitcoinCentralEUR", "IntersangoEUR"]
# ["Logger", "TraderBot", "TraderBotSim", "HistoryDumper", "Emailer"]
observers = ["Logger"]

market_expiration_time = 120 # in seconds: 2 minutes
market_expiration_time = 120 # in seconds: 2 minutes

#### Trader Bot Config
# Access to Private APIs
Expand All @@ -28,4 +28,3 @@ smtp_login = 'FIXME'
smtp_passwd = 'FIXME'
smtp_from = 'FIXME'
smtp_to = 'FIXME'

2 changes: 1 addition & 1 deletion src/observers/historydumper.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import time
import os


class HistoryDumper(Observer):
out_dir = 'history/'

Expand All @@ -22,4 +23,3 @@ def end_opportunity_finder(self):

def opportunity(self, profit, volume, buyprice, kask, sellprice, kbid, perc, weighted_buyprice, weighted_sellprice):
pass

4 changes: 2 additions & 2 deletions src/observers/logger.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import logging
from observer import Observer


class Logger(Observer):
def opportunity(self, profit, volume, buyprice, kask, sellprice, kbid, perc, weighted_buyprice, weighted_sellprice):
logging.info("profit: %f EUR with volume: %f BTC - buy at %.4f (%s) sell at %.4f (%s) ~%.2f%%" % \
logging.info("profit: %f EUR with volume: %f BTC - buy at %.4f (%s) sell at %.4f (%s) ~%.2f%%" %
(profit, volume, buyprice, kask, sellprice, kbid, perc))

2 changes: 1 addition & 1 deletion src/observers/observer.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import abc


class Observer(object):
__metaclass__ = abc.ABCMeta

Expand All @@ -13,4 +14,3 @@ def end_opportunity_finder(self):
@abc.abstractmethod
def opportunity(self, profit, volume, buyprice, kask, sellprice, kbid, perc, weighted_buyprice, weighted_sellprice):
pass

22 changes: 9 additions & 13 deletions src/observers/traderbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from private_markets import mtgox
from private_markets import bitcoincentral


class TraderBot(Observer):
def __init__(self):
self.mtgox = mtgox.PrivateMtGox()
Expand All @@ -14,10 +15,10 @@ def __init__(self):
"MtGoxUSD": self.mtgox,
"BitcoinCentralEUR": self.btcentral,
"BitcoinCentralUSD": self.btcentral
}
self.profit_thresh = 5 # in EUR
self.perc_thresh = 2 # in %
self.trade_wait = 120 # in seconds
}
self.profit_thresh = 5 # in EUR
self.perc_thresh = 2 # in %
self.trade_wait = 120 # in seconds
self.last_trade = 0
self.potential_trades = []

Expand All @@ -44,33 +45,28 @@ def opportunity(self, profit, volume, buyprice, kask, sellprice, kbid, perc, wei

# Check balances
if (volume * buyprice) * (1 + config.balance_margin) > self.clients[kask].eur_balance:
logging.warn("Can't automate this trade, not enough money on: %s - need %f got %f" \
logging.warn("Can't automate this trade, not enough money on: %s - need %f got %f"
% (kask, (volume * buyprice) * (1 + config.balance_margin),
self.clients[kask].eur_balance))
return
if volume * (1 + config.balance_margin) > self.clients[kbid].btc_balance:
logging.warn("Can't automate this trade, not enough money on: %s - need %f got %f" \
logging.warn("Can't automate this trade, not enough money on: %s - need %f got %f"
% (kbid, volume * (1 + config.balance_margin),
self.clients[kbid].btc_balance))
return

current_time = time.time()
if current_time - self.last_trade < self.trade_wait:
logging.warn("Can't automate this trade, last trade occured %s seconds ago" % (current_time - self.last_trade))
logging.warn("Can't automate this trade, last trade occured %s seconds ago" % (
current_time - self.last_trade))
return

self.potential_trades.append([profit, volume, kask, kbid, weighted_buyprice, weighted_sellprice])


def watch_balances(self):
pass

def execute_trade(self, volume, kask, kbid, weighted_buyprice, weighted_sellprice):
self.last_trade = time.time()
self.clients[kask].buy(volume)
self.clients[kbid].sell(volume)





13 changes: 7 additions & 6 deletions src/observers/traderbotsim.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from traderbot import TraderBot
import json


class MockMarket(object):
def __init__(self, name, fee=0, eur_balance=500., btc_balance=15., persistent=True):
self.name = name
Expand Down Expand Up @@ -49,23 +50,24 @@ def save(self):
def balance_total(self, price):
return self.eur_balance + self.btc_balance * price


class TraderBotSim(TraderBot):
def __init__(self):
self.mtgox = MockMarket("mtgox", 0.006) # 0.6% fee
self.mtgox = MockMarket("mtgox", 0.006) # 0.6% fee
self.btcentral = MockMarket("bitcoin-central")
self.intersango = MockMarket("intersango")
self.bitcoin24 = MockMarket("bitcoin24")
self.bitstamp = MockMarket("bitstamp", 0.005) # 0.5% fee
self.bitstamp = MockMarket("bitstamp", 0.005) # 0.5% fee
self.clients = {
"MtGoxEUR": self.mtgox,
"MtGoxUSD": self.mtgox,
"BitcoinCentralEUR": self.btcentral,
"Bitcoin24EUR": self.bitcoin24,
"IntersangoEUR": self.intersango,
"BitstampEUR": self.bitstamp,
}
self.profit_thresh = 1 # in EUR
self.perc_thresh = 0.1 # in %
}
self.profit_thresh = 1 # in EUR
self.perc_thresh = 0.1 # in %
self.trade_wait = 120
self.last_trade = 0

Expand All @@ -80,4 +82,3 @@ def execute_trade(self, volume, kask, kbid, weighted_buyprice, weighted_sellpric
if __name__ == "__main__":
t = TraderBotSim()
print t.total_balance(33)

8 changes: 4 additions & 4 deletions src/private_markets/bitcoincentral.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import config
from decimal import Decimal


class PrivateBitcoinCentral(Market):
balance_url = "https://bitcoin-central.net/api/v1/balances/"
trade_url = "https://bitcoin-central.net/api/v1/trade_orders/"
Expand All @@ -31,7 +32,7 @@ def _send_request(self, url, params=[], extra_headers=None):
'Content-type': 'application/json',
'Accept': 'application/json, text/javascript, */*; q=0.01',
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
}
}
if extra_headers is not None:
for k, v in extra_headers.iteritems():
headers[k] = v
Expand All @@ -54,9 +55,8 @@ def _send_request(self, url, params=[], extra_headers=None):
return json.loads(jsonstr)
return None


def trade(self, amount, ttype, price=None):
#params = [("amount", amount), ("currency", self.currency), ("type", ttype)]
# params = [("amount", amount), ("currency", self.currency), ("type", ttype)]
params = {"amount": amount, "currency": self.currency, "type": ttype}
if price:
params["price"] = price
Expand All @@ -78,7 +78,7 @@ def get_info(self):
self.eur_balance = Decimal(response["EUR"])

def __str__(self):
return str({ "btc_balance": self.btc_balance, "eur_balance": self.eur_balance })
return str({"btc_balance": self.btc_balance, "eur_balance": self.eur_balance})


if __name__ == "__main__":
Expand Down
30 changes: 15 additions & 15 deletions src/private_markets/mtgox.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,14 @@
import re
from decimal import Decimal


class PrivateMtGox(Market):
ticker_url = { "method": "GET", "url": "https://mtgox.com/api/1/BTCUSD/public/ticker" }
buy_url = { "method": "POST", "url": "https://mtgox.com/api/1/BTCUSD/private/order/add" }
sell_url = { "method": "POST", "url": "https://mtgox.com/api/1/BTCUSD/private/order/add" }
order_url = { "method": "POST", "url": "https://mtgox.com/api/1/generic/private/order/result" }
open_orders_url = { "method": "POST", "url": "https://mtgox.com/api/1/generic/private/orders" }
info_url = { "method": "POST", "url": "https://mtgox.com/api/1/generic/private/info" }
ticker_url = {"method": "GET", "url": "https://mtgox.com/api/1/BTCUSD/public/ticker"}
buy_url = {"method": "POST", "url": "https://mtgox.com/api/1/BTCUSD/private/order/add"}
sell_url = {"method": "POST", "url": "https://mtgox.com/api/1/BTCUSD/private/order/add"}
order_url = {"method": "POST", "url": "https://mtgox.com/api/1/generic/private/order/result"}
open_orders_url = {"method": "POST", "url": "https://mtgox.com/api/1/generic/private/orders"}
info_url = {"method": "POST", "url": "https://mtgox.com/api/1/generic/private/info"}

def __init__(self):
super(Market, self).__init__()
Expand Down Expand Up @@ -64,7 +65,7 @@ def _send_request(self, url, params, extra_headers=None):
'Content-type': 'application/x-www-form-urlencoded',
'Accept': 'application/json, text/javascript, */*; q=0.01',
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
}
}
if extra_headers is not None:
for k, v in extra_headers.iteritems():
headers[k] = v
Expand All @@ -83,9 +84,9 @@ def trade(self, amount, ttype, price=None):

self.buy_url["url"] = self._change_currency_url(self.buy_url["url"], self.currency)

params = [ ("nonce", self._create_nonce()),
("amount_int", str(amount)),
("type", ttype) ]
params = [("nonce", self._create_nonce()),
("amount_int", str(amount)),
("type", ttype)]
if price:
params.append(("price_int", str(price)))

Expand All @@ -101,22 +102,21 @@ def sell(self, amount, price=None):
return self.trade(amount, "ask", price)

def get_info(self):
params = [ ("nonce", self._create_nonce()) ]
params = [("nonce", self._create_nonce())]
response = self._send_request(self.info_url, params)
if response and "result" in response and response["result"] == "success":
self.btc_balance = self._from_int_amount(int(response["return"]["Wallets"]["BTC"]["Balance"]["value_int"]))
self.eur_balance = self._from_int_price(int(response["return"]["Wallets"]["EUR"]["Balance"]["value_int"]))
return 1
return None


def __str__(self):
return str({ "btc_balance": self.btc_balance, "eur_balance": self.eur_balance })
return str({"btc_balance": self.btc_balance, "eur_balance": self.eur_balance})


if __name__ == "__main__":
mtgox = PrivateMtGox()
mtgox.get_info()
#mtgox.buy(0.01, "EUR")
#mtgox.sell(0.01, "EUR")
# mtgox.buy(0.01, "EUR")
# mtgox.sell(0.01, "EUR")
print mtgox
2 changes: 1 addition & 1 deletion src/public_markets/bitcoin24eur.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import json
from market import Market


class Bitcoin24EUR(Market):
def __init__(self):
super(Bitcoin24EUR, self).__init__("EUR")
Expand All @@ -27,4 +28,3 @@ def format_depth(self, depth):
if __name__ == "__main__":
market = Bitcoin24EUR()
print json.dumps(market.get_ticker())

2 changes: 1 addition & 1 deletion src/public_markets/bitcoincentraleur.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import json
from market import Market


class BitcoinCentralEUR(Market):
def __init__(self):
super(BitcoinCentralEUR, self).__init__("EUR")
Expand Down Expand Up @@ -29,4 +30,3 @@ def format_depth(self, depth):
if __name__ == "__main__":
market = BitcoinCentralEUR()
print market.get_ticker()

2 changes: 1 addition & 1 deletion src/public_markets/bitstampeur.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import sys
from market import Market


class BitstampEUR(Market):
def __init__(self):
super(BitstampEUR, self).__init__("EUR")
Expand Down Expand Up @@ -32,4 +33,3 @@ def format_depth(self, depth):
if __name__ == "__main__":
market = BitstampEUR()
print market.get_ticker()

1 change: 1 addition & 0 deletions src/public_markets/btceusd.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import json
from market import Market


class BtceUSD(Market):
def __init__(self):
super(BtceUSD, self).__init__("USD")
Expand Down
2 changes: 1 addition & 1 deletion src/public_markets/intersangoeur.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import json
from market import Market


class IntersangoEUR(Market):
def __init__(self):
super(IntersangoEUR, self).__init__("EUR")
Expand All @@ -27,4 +28,3 @@ def format_depth(self, depth):
if __name__ == "__main__":
market = IntersangoEUR()
print json.dumps(market.get_ticker())

2 changes: 1 addition & 1 deletion src/public_markets/market.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import config
import logging


class Market(object):
def __init__(self, currency):
self.name = self.__class__.__name__
Expand Down Expand Up @@ -45,4 +46,3 @@ def buy(self, price, amount):

def sell(self, price, amount):
pass

Loading

0 comments on commit 0cb27c5

Please sign in to comment.