This repository was archived by the owner on Mar 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathbtc
More file actions
executable file
·286 lines (235 loc) · 9.11 KB
/
Copy pathbtc
File metadata and controls
executable file
·286 lines (235 loc) · 9.11 KB
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
#!/usr/bin/env python
"""
btc
~~~
Buy, sell, and transfer bitcoin instantly in your terminal! (Powered by
Coinbase: https://coinbase.com/).
Usage:
btc init
btc address
btc balance
btc request <btc> <email> [<note>]
btc send <btc> (<email> | <address>) [<note>]
btc test
btc logs
btc rates
btc buy <btc>
btc sell <btc>
btc (-h | --help)
btc --version
Options:
-h --help Show this screen.
--version Show version.
Written by Randall Degges <http://www.rdegges.com/>. Like the software? Send a
tip to Randall: 14m3gaa3TvEgN7Ltc4377v3MVCPnyunuqS
"""
from json import dumps
from os import chmod
from os.path import exists, expanduser
from sys import exit
from textwrap import wrap
from docopt import docopt
from requests import get, post
##### GLOBALS
API_URI = 'https://coinbase.com/api/v1'
CONFIG_FILE = expanduser('~/.btc')
VERSION = 'btc 0.3'
class BTC(object):
def get_api_key(self):
"""Get the API key, or quit with an error."""
if exists(CONFIG_FILE):
return open(CONFIG_FILE).read()
else:
print 'No API key found! Please run `btc init` to initialize.'
exit(1)
def make_request(self, path, data={}, method='GET'):
"""Make the specified API request, and return the JSON data, or quit
with an error.
"""
params = {
'api_key': self.get_api_key(),
}
if method.lower() == 'post':
resp = post('%s/%s' % (API_URI, path), params=params,
data=dumps(data), headers={'Content-Type':
'application/json'})
else:
params = dict(params.items() + data.items())
resp = get('%s/%s' % (API_URI, path), params=params)
if resp.status_code != 200:
print 'Error connecting to Coinbase API. Please try again.'
print 'If the problem persists, please check your API key.'
exit(1)
return resp.json()
def address(self):
"""Return the user's current bitcoin receive address."""
json = self.make_request('account/receive_address')
print 'Your bitcoin receive address is:', json['address']
def balance(self):
"""Return the amount of bitcoin in this user's account."""
json = self.make_request('account/balance')
print 'You have a total of %s %s in your account.' % (json['amount'],
json['currency'])
def request(self, amount, email, note):
"""Request bitcoin payment by email address."""
json = self.make_request('transactions/request_money', data={
'transaction': {
'from': email,
'amount': amount,
'notes': note
}
}, method='POST')
if not json['success']:
print 'There Were Error(s) Requesting Bitcoin'
print '======================================'
for error in json['errors']:
print '- %s' % '\n '.join(wrap(error, 77))
print '======================================'
return
print 'Request successful!'
def send(self, amount, address, note):
"""Send bitcoin payment by email address or bitcoin address."""
json = self.make_request('transactions/send_money', data={
'transaction': {
'to': address,
'amount': amount,
'notes': note
}
}, method='POST')
if not json['success']:
print 'There Were Error(s) Sending Bitcoin'
print '==================================='
for error in json['errors']:
print '- %s' % '\n '.join(wrap(error, 77))
print '==================================='
return
print 'Sending Bitcoin Successful'
print '=========================='
print dumps(json['transaction'], sort_keys=True, indent=2,
separators=(',', ': '))
print '=========================='
def logs(self):
"""List a user's recent Coinbase transactions."""
json = self.make_request('transactions')
print 'Transaction Logs'
print '================'
print dumps(json['transactions'], sort_keys=True, indent=2,
separators=(',', ': '))
print '================'
def sell(self, amount):
"""Sell bitcoin."""
bjson = self.make_request('prices/sell', data={'qty': amount})
api_key = raw_input("Are you sure you'd like to sell %f BTC? This will give you ~%s %s (y/n) " % (amount, bjson['amount'], bjson['currency'])).strip().lower()
if api_key != 'y':
return
json = self.make_request('sells', method='POST', data={
'qty': amount,
})
if not json['success']:
print 'There Were Error(s) Selling Your Bitcoin'
print '========================================'
for error in json['errors']:
print '- %s' % '\n '.join(wrap(error, 77))
print '========================================'
return
print 'Sell Successful'
print '==============='
print dumps(json['transfer'], sort_keys=True, indent=2,
separators=(',', ': '))
print '==============='
def test(self):
"""Test the API key to make sure it's working."""
resp = get('%s/users?api_key=%s' % (API_URI, self.get_api_key()))
if resp.status_code == 200:
print 'Your API key is working!'
else:
print 'Your API is NOT working. Please check your API key.'
print 'To update your API key, re-run `btc init`.'
def rates(self):
"""List current exchange rates."""
bjson = self.make_request('prices/buy')
sjson = self.make_request('prices/sell')
print 'Bitcoin Exchange Rates'
print '======================'
print 'Buy: 1 BTC for %s %s' % (bjson['amount'], bjson['currency'])
print 'Sell: 1 BTC for %s %s' % (sjson['amount'], sjson['currency'])
print '======================'
def buy(self, amount):
"""Purchase bitcoin."""
bjson = self.make_request('prices/buy', data={'qty': amount})
api_key = raw_input("Are you sure you'd like to purchase %f BTC? This will cost ~%s %s (y/n) " % (amount, bjson['amount'], bjson['currency'])).strip().lower()
if api_key != 'y':
return
json = self.make_request('buys', method='POST', data={
'qty': amount,
'agree_btc_amount_varies': True,
})
if not json['success']:
print 'There Were Error(s) Making Your Purchase'
print '========================================'
for error in json['errors']:
print '- %s' % '\n '.join(wrap(error, 77))
print '========================================'
return
print 'Purchase Successful'
print '==================='
print dumps(json['transfer'], sort_keys=True, indent=2,
separators=(',', ': '))
print '==================='
def init():
"""Initialize `btc`.
This will store the user's API key in their home directory: ~/.btc, and
ensure the API key specified actually works.
"""
print 'Initializing `btc`...\n'
finished = False
while not finished:
api_key = raw_input('Enter your Coinbase API key here: ').strip()
if not api_key:
print '\nNot sure how to find your Coinbase API key?'
print 'You can get one here: ' \
'https://coinbase.com/account/integrations\n'
continue
# Validate the API key.
resp = get('%s/users?api_key=%s' % (API_URI, api_key))
if resp.status_code == 200:
f = open(CONFIG_FILE, 'wb')
f.write(api_key)
f.close()
chmod(CONFIG_FILE, 0600)
print '\nSuccessfully initialized `btc`!'
print 'Your API key is stored here:', CONFIG_FILE, '\n'
print 'Run `btc` for usage information.'
finished = True
else:
print '\nYour API key is not working, please verify it is ' \
'correct, and try again.\n'
def main():
"""Handle user input, and do stuff accordingly."""
arguments = docopt(__doc__, version=VERSION)
btc = BTC()
if arguments['init']:
init()
elif arguments['address']:
btc.address()
elif arguments['balance']:
btc.balance()
elif arguments['request']:
btc.request(float(arguments['<btc>']), arguments['<email>'],
arguments['<note>'])
elif arguments['send']:
address = (arguments['<email>'] if arguments['<email>'] else
arguments['<address>'])
btc.send(float(arguments['<btc>']), address, arguments['<note>'])
elif arguments['logs']:
btc.logs()
elif arguments['sell']:
btc.sell(float(arguments['<btc>']))
elif arguments['test']:
btc.test()
elif arguments['rates']:
btc.rates()
elif arguments['buy']:
btc.buy(float(arguments['<btc>']))
if __name__ == '__main__':
main()