-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbtc.py
executable file
·240 lines (196 loc) · 9.74 KB
/
btc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
#!/usr/bin/python
import json, sys, argparse, threading, os
import urllib.request, urllib.parse
import requests
from subprocess import check_output
import config
from time import sleep
if os.name == "posix":
import curses, termios
DEBUG = True
exchangeURLs = { 'CoinBase Sell': ['http://coinbase.com/api/v1/prices/sell', 'subtotal/amount', ''],
'CoinBase Buy': ['https://coinbase.com/api/v1/prices/buy', 'subtotal/amount', ''],
'CampBX Buy': ['https://campbx.com/api/xticker.php', 'Best Ask', ''],
'Coinsetter Buy': ['https://api.coinsetter.com/v1/marketdata/ticker', 'bid/price', ''],
'Coinsetter Sell': ['https://api.coinsetter.com/v1/marketdata/ticker', 'ask/price', ''],
#'Bitfloor Bid': ['https://api.bitfloor.com/book/L1/1', 'bid', ''], # Bitfloor shut down 2013-Apr-17
#'Bitfloor Ask': ['https://api.bitfloor.com/book/L1/1', 'ask', '']
#'Mt Gox Last': ['https://data.mtgox.com/api/2/BTCUSD/money/ticker', 'data/last_local/display', ''],
}
exchanges = list(exchangeURLs.keys())
highlightXch = 'CampBX Buy' # highlight this exchange
# Fees
"""
Coinbase - 1% + $0.15/transaction
Bitfloor - 0.4% for buying BTC, -0.1% for selling BTC (you earn money)
Mt Gox - 0.6% or lower depending on volume + Dwolla ($0.25/transaction)
"""
#coinbaseBuyURL = 'https://coinbase.com/api/v1/account/balance'
btcQty = 1
btcVary = True
DEFAULT_REALTIME_SECONDS = 300 # default number of seconds for realtime ticker
HIGHLIGHT_COLOR = '\x1b[96;1m'
HIGHLIGHT_END = '\x1b[0m'
# use ANSI ESC codes for realtime option
# http://en.wikipedia.org/wiki/ANSI_escape_code
PREVIOUS_LINE = '\x1b[1F' # go to beginning of previous line
ERASE_LINE = '\x1b[2K' # clears entire line in terminal
CURSOR_UP = '\x1b[1A' # go up one line
CURSOR_DOWN = '\x1b[1B'
CURSOR_FORWARD = '\x1b[1C'
CURSOR_BACK = '\x1b[1D'
SAVE_CURSOR = '\x1b[s'
RESTORE_CURSOR = '\x1b[u'
def buyBTC(btcQty=1, btcVary=True, dryRun=True, verbose=False, confirm=True):
coinbaseBuyURL = "https://coinbase.com/api/v1/buys"
print('WARNING: This feature is untested as of the Python3 conversion and may have byte/string errors')
print("Getting current price...")
rate = getRate('CoinBase Buy')
print("Current price is $" + rate + "/BTC")
print("Your order total will be about $" + str(float(rate)*float(btcQty)), "(not incl. fees)\n")
if confirm:
c = input("Would you like to continue? Type yes to confirm: ")
if c != "yes":
print("Did not buy any BTC.")
return
print("Attempting to buy {0} BTC".format(btcQty))
payload = { 'qty': btcQty, 'agree_btc_amount_varies': btcVary }
payload = urllib.parse.urlencode(payload)
coinbaseBuyURL = coinbaseBuyURL + '?api_key=' + config.api_key
if dryRun:
print('url: ' + coinbaseBuyURL + '\npayload: ' + payload)
print("Exiting dry run.")
elif not dryRun:
r = urllib.request.urlopen(url=coinbaseBuyURL, data=payload)
buyData = json.load(r)
print("Your purchase has been SUCCESSFULLY COMPLETED" if buyData['success'] else "Purchase failed due to the following error:\n=====\n{0}\n=====".format(json.dumps(buyData['errors'])))
print(json.dumps(buyData['transfer']) if buyData['success'] else json.dumps(buyData))
return 0
def getRate(xch):
"""Return the price at a certain Exchange specified in exchangeURLs"""
if not xch:
print("Error: no exchange name given to getRate()");
# Spoof browser to allow retrieval from sites that disallow bots (like Coinbase)
headers = {'user-agent': 'Mozilla/5.0'}
try:
data = requests.get(exchangeURLs[xch][0], headers=headers).json()
except Exception as e:
return str(e)
keys = exchangeURLs[xch][1].split('/')
data_old = data
for i in range(len(keys)): # drill down the json based on forward slash separated keys
try:
data = data[keys[i]]
except KeyError as e:
return str(data_old) + "| ERR: " + str(e) + " key does not exist"
except Exception as e:
return str(data_old) + "| ERR: " + str(e) + " key does not exist"
if isinstance(data, list): # if we're left with a list, get the first element (for Bitfloor?)
data = data[0]
data = float(str(data).replace('$', '').replace(',', '')) # temporarily remove dollar signs
return str('{:>9,.2f}'.format(data)) # format to 2 decimal places and convert back to string
def formatRate(xch, data):
return '{xch}: {data}'.format(xch=xch, data=data)
def showRate(xch, lock=None, async=False, verbose=False, realtime=0):
"""Outputs nicely formatted prices for specified exchanges asynchronously"""
if not xch:
print("Error: no exchange name given to showRate()")
if not lock and not realtime:
print("Error: no lock given to showRate()")
data = getRate(xch)
#data = "test"
if data.find('$') == -1: # add dollar sign
data = '$' + data
if config.use_colors and xch == highlightXch: # highlight the most important one
data = HIGHLIGHT_COLOR + data + HIGHLIGHT_END
xch = xch.ljust(15) # align it left and pad up to 15 spaces
#if lock.acquire():
if lock and realtime <= 0:
lock.acquire()
try:
#print "lock acquired by: " + xch
print(formatRate(xch, data))
finally:
lock.release()
#print "lock released by: " + xch
return formatRate(xch, data)
#lock.release()
if realtime > 0:
return formatRate(xch, data)
#print CURSOR_UP * 1 + CURSOR_FORWARD * 17 + data
def showRates(verbose=False, async=True, realtime=0):
"""Outputs nicely formatted prices for the exchanges listed in exchangeURLs"""
if realtime > 0: # realtime mode (*NIX only)
if not os.name == "posix":
print("Error: realtime option is only supported on *NIX systems")
return
# TODO
# make exchanges ordered - n-dim array - name, url, json
# have exchange use ANSI ESC codes based on index
# do we need to implement locks for stdout? or make them return values?? (extend Thread class??)
# how to implement waiting interval before updates
#print SAVE_CURSOR + CURSOR_UP
# show initial table - has to be in order the same way to make sure
# all prices are displayed
# if displayImmediately is True, start every cycle showing nothing
# and then revealing prices one by one - good for long refresh periods
# if displayImmediately is False, buffer up all exchanges and display at once (thereby, after the firstRun
# all exchanges are always visible) - good for very slow Internet connections
ERASE_LAST_LINES = (ERASE_LINE + PREVIOUS_LINE) * 6
displayImmediately = False
firstRun = True
while True:
try:
bufferStr = ['=== ' + (check_output(['date'])[:-1]).decode() + ' ==='] # timestamp
if displayImmediately: print(bufferStr[-1])
for xch in exchangeURLs:
bufferStr.append( showRate(xch, realtime=realtime) )
if displayImmediately: print(bufferStr[-1])
if not displayImmediately:
if not firstRun: print(ERASE_LAST_LINES)
firstRun = False
print('\n'.join(bufferStr))
sleep(realtime)
if displayImmediately: print(ERASE_LAST_LINES)
except KeyboardInterrupt as e:
print("\nExiting.")
if DEBUG and str(e): print("ERR: " + str(e))
sys.exit()
except Exception as e:
if str(e): print("ERR: " + str(e))
sys.exit()
return
if async: # 2 threads can print to stdout (haven't implement locks yet)
print("Getting prices (fast version, formatting may be off)...")
print('===', check_output(['date'])[:-1], '===') # timestamp
for xch in exchanges:
lock = threading.RLock()
t = threading.Thread(target=showRate, args=[xch, lock]);
t.start()
sys.exit()
print('===', check_output(['date'])[:-1], '===') # timestamp
print("Getting prices...")
for xch in exchangeURLs:
data = getRate(xch)
if data.find('$') == -1: # add dollar sign
data = '$' + data
if config.use_colors and xch == highlightXch: # highlight the most important one
data = HIGHLIGHT_COLOR + data + HIGHLIGHT_END
xch = xch.ljust(15) # align it left and pad up to 15 spaces
print('{xch}: {data}'.format(xch=xch, data=data))
def main():
parser = argparse.ArgumentParser(description='Buy BTC or Show BTC:USD rates')
parser.add_argument('--buy', nargs='?', const=1, help="Buy BTC" )
parser.add_argument('--dry-run', action='store_const', default=False, const=True, help="Simulate buying BTC but do not actually buy anything")
parser.add_argument('--verbose', action='store_const', default=False, const=True)
parser.add_argument('--no-async', action='store_const', default=False, const=True, help="Get prices one by one (slower but formatting is correct)")
parser.add_argument('--realtime', nargs='?', type=int, const=DEFAULT_REALTIME_SECONDS, help="Show realtime ticker refreshing every REALTIME seconds (Only on UNIX)")
args = parser.parse_args()
if args.verbose: print('args =', args)
#print 'args.buy =', args.buy
if args.buy:
buyBTC(btcQty=args.buy, dryRun=args.dry_run, verbose=args.verbose)
else:
showRates(verbose=args.verbose, async=not args.no_async, realtime=args.realtime);
if __name__ == "__main__":
sys.exit(main())