Repository navigation
Expand file tree
/
Copy pathcore.py
More file actions
323 lines (256 loc) · 11.2 KB
/
Copy pathcore.py
File metadata and controls
323 lines (256 loc) · 11.2 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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# -*- coding: utf-8 -*-
import base64
import hashlib
import hmac
import json
import time
import requests
from geminipy.utils import _get_params
class Client:
"""Gemini API wrapper.
Make public or authenticated requests according to the API documentation:
https://docs.gemini.com/
"""
def __init__(self,
apikey=None,
secret=None,
live=True,
nonce_mult=1000.0,
api_version=1,
timeout=15,
proxy=None):
"""Initialize the class.
:param str apikey: your Gemini API key.
:param str secret: your Gemini API secret key for signatures.
:param float nonce_mult: a custom multiplier for nonce value.
"""
# self._api_version = api_version
if live:
self._url = f'https://api.gemini.com'
else:
self._url = f'https://api.sandbox.gemini.com'
self._proxy = {'http': proxy} if proxy else None
self._timeout = timeout
self._url = f'{self._url}/v{api_version}'
self._apikey = apikey
self._nonce_mult = nonce_mult
self._secret = secret.encode()
self._headers = {'X-GEMINI-APIKEY': self._apikey}
# ================ Class private methods ================
def _request(self, end_point, method=None, params=None):
method = str(method or 'get').lower()
request_args = {
'url': f'{self._url}/{end_point}',
'method': method,
'timeout': self._timeout,
'headers': self._headers
}
if params:
if method in ('post',):
params.update(
request=end_point,
nonce=self._nonce
)
json_params = json.dumps(params or {}).encode()
payload = base64.b64encode(json_params)
signature = hmac.new(self._secret, payload, hashlib.sha384)
request_args.update(headers={
'X-GEMINI-PAYLOAD': payload,
'X-GEMINI-SIGNATURE': signature.hexdigest(),
})
else:
request_args.update(params=params)
if self._proxy:
request_args.update(proxies=self._proxy)
response = requests.request(**request_args)
if response:
if response.ok:
return response.json()
else:
# elif any('json' in h for h in response.headers):
try:
data = response.json()
return {'error': data}
except json.JSONDecodeError:
return {
'error': {
'code': response.status_code,
'reason': response.reason,
'content': response.text
}
}
except (requests.RequestException, requests.ConnectionError):
response.raise_for_status()
@property
def _nonce(self):
"""Return the current millisecond timestamp as the nonce.
:return: current millisecond timestamp as the nonce
"""
return f'{time.time() * self._nonce_mult:.0f}'
class GeminiPublic(Client):
# ================ PUBLIC END POINTS ================
def get_symbols(self):
"""Send a request to get trading symbols info."""
return self._request('symbols')
def get_ticker(self, symbol):
"""Send a request to get a trading symbol ticker info.
:param symbol: symbol id to query (example: "btcusd")
:return: trading symbol ticker info supplied by server.
"""
return self._request(f'pubticker/{symbol}')
def get_orderbook(self, symbol, limit_bids=0, limit_asks=0):
"""Send a request to get a symbol order book data.
:param symbol: symbol id to query (example: "btcusd")
:param limit_bids: limit the number of bids returned (default 0)
:param limit_asks: limit the number of asks returned (default 0)
:return: symbol order book info supplied by server.
"""
params = _get_params(locals(), 'symbol')
return self._request(f'book/{symbol}', params=params)
def get_trades(self, symbol, since=0, limit_trades=50, include_breaks=0):
"""Send a request to get a symbol public trades.
:param str symbol: symbol id to query (example: "btcusd")
:param int since: return trades after this unix epoch (default 0)
:param limit_trades: max number of trades to return (default 50).
:param int include_breaks: whether to display broken trades (default 0)
:return: supplied symbol public trades info supplied by server.
"""
params = _get_params(locals(), 'symbol')
return self._request(f'trades/{symbol}', params=params)
def get_auction(self, symbol):
"""Send a request to get a symbol latest auction info.
:param str symbol: symbol id to query (example: "btcusd")
:return: supplied symbol latest auction supplied by server.
"""
return self._request(f'auction/{symbol}')
def get_auction_history(self, symbol, since=0, limit_auction_results=50, include_indicative=1):
"""Send a request to get a symbol auction history.
:param str symbol: symbol id to query (example: "btcusd")
:param since: only return auction events after this timestamp.
:param limit_auction_results: max number of auction events to return.
:param include_indicative: set to 0 to not include publication of indicative info.
:return:
"""
params = _get_params(locals(), 'symbol')
return self._request(f'auction/{symbol}/history', params)
class Geminipy(GeminiPublic):
"""Gemini API wrapper.
Make public or authenticated requests according to the API documentation:
https://docs.gemini.com/
"""
# ================ AUTHENTICATED ENDPOINTS ================
def place_order(self, side, symbol, amount, price=None, client_order_id=None, type=None, options=None):
"""Send a request to place an order.
:param str side: 'buy' or 'sell'
:param str symbol: symbol id to query (example: "btcusd")
:param float amount: symbol amount to order.
:param float price: order price.
:param client_order_id: an optional custom order indetifier.
:param type: order type (default 'exchange limit')
:param options:
return:
"""
params = _get_params(locals(), 'amount', 'price')
params.update(amount=f'{amount}')
return self._request('order/new', 'post', params)
def cancel_order(self, order_id):
"""Send a request to cancel an order.
:param str order_id: order id to cancel.
:return:
"""
params = _get_params(locals())
return self._request('order/cancel', 'post', params)
def cancel_session(self):
"""Send a request to cancel all session orders.
:return:
"""
return self._request('order/cancel/session', 'post')
def cancel_all(self):
"""Send a request to cancel all orders.
:return:
"""
return self._request('order/cancel/all', 'post')
def get_order_status(self, order_id):
"""Send a request to get an order current status.
:param str order_id: the order id to get information on.
:return:
"""
params = _get_params(locals())
return self._request('order/status', 'post', params)
def get_active_orders(self):
"""Send a request to get active orders.
:return:
"""
return self._request('orders', 'post')
def get_past_trades(self, symbol, limit_trades=50, timestamp=0):
"""Send a symbol trades history request.
:param str symbol: symbol id to query (example: "btcusd")
:param limit_trades: max number of trades to return (default 50)
:param timestamp: return trades after supplied unix epoch (default 0)
:return:
"""
params = _get_params(locals())
return self._request('mytrades', 'post', params)
def get_trade_volume(self):
"""Send a request to get your trade volume."""
return self._request('tradevolume', 'post')
def get_balances(self):
"""Send an account balance request.
:return:
"""
return self._request('balances', 'post')
def new_deposit_address(self, currency, label=None):
"""Send a request to generate a new cryptocurrency deposit address.
:param str currency: crypto currency ID (example: btc)
:param str label: optional label for the deposit address
:return:
"""
params = _get_params(locals(), 'currency')
return self._request(f'deposit/{currency}/newAddress', 'post', params)
def get_notional_balances(self, currency, account=None):
"""Get approved addresses for supplied network and account (if supplied)
:param str currency: currency to get balance for.
:param str account: account name (example: primary)
:return:
"""
params = _get_params(locals(), 'currency')
return self._request(f'notionalbalances/{currency}', 'post', params)
def remove_approved_address(self, network, address, account=None):
"""Get approved addresses for supplied network and account (if supplied)
:param str network: accepted values: bitcoin, ethereum, bitcoincash, litecoin, zcash, filecoin, dogecoin, tezos
:param str address: address to remove.
:param str account: account name (example: primary)
:return:
"""
params = _get_params(locals(), 'network')
return self._request(f'approvedAddresses/account/{network}/remove', 'post', params)
def request_approved_address(self, network, address, label=None, account=None):
"""Get approved addresses for supplied network and account (if supplied)
:param str network: accepted values: bitcoin, ethereum, bitcoincash, litecoin, zcash, filecoin, dogecoin, tezos
:param str address: address to remove.
:param str label: a label to identify the supplied address.
:param str account: account name (example: primary)
:return:
"""
params = _get_params(locals(), 'network')
return self._request(f'approvedAddresses/{network}/request', 'post', params)
def get_fees(self):
"""Send a request to get fees and notional volume."""
self._request('notionalvolume', 'post')
def get_earn_balance(self, account=None):
"""Send an account earn balance request.
:param str account: account name (example: primary)
:return:
"""
params = _get_params(locals())
return self._request('balances/earn', 'post', params)
def get_account_details(self):
"""Send a request to get account details related to supplied API keys.
:return:
"""
return self._request('account', 'post')
def get_heartbeat(self):
"""Send a heartbeat message.
:return:
"""
return self._request('heartbeat', 'post')