This repository has been archived by the owner on Apr 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathgemini_api.py
175 lines (137 loc) · 4.64 KB
/
gemini_api.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
"""
Gemini API Bindings
REST API: https://docs.gemini.com/rest-api/#requests
public:
/ticker
private:
/heartbeat
/order/new
/order/status
WebSocket API: https://docs.gemini.com/websocket-api/#websocket-request
private:
/order/events
"""
import os
import base64
import hmac
import json
import requests
from time import sleep
from hashlib import sha384
from symbols import Order, Currency, currency_by_symbol
from settings import (
API_VERSION,
API_URL,
API_WS_URL,
API_KEY,
API_SECRET,
STARTING_NONCE,
DATA_DIR,
)
class RateLimitExceeded(Exception):
pass
def retry_if_exception(func):
def wrapped(*args, **kwargs):
try:
return func(*args, **kwargs)
except RateLimitExceeded:
print(f'Rate limit exceeded! Retrying in 10 seconds...')
sleep(10)
return func(*args, **kwargs)
except Exception as e:
print(f'{func} raised {e}! Retrying one more time in 2 seconds...')
sleep(2)
return func(*args, **kwargs)
return wrapped
def get_nonce(min_nonce: int=STARTING_NONCE) -> int:
"""nonce must always monotonically increase, so we track it in a file"""
last = min_nonce
try:
with open(os.path.join(DATA_DIR, '.last_nonce.txt'), 'r') as f:
last = int(f.read().strip())
except Exception:
pass
last = last if last > min_nonce else min_nonce
with open(os.path.join(DATA_DIR, '.last_nonce.txt'), 'w') as f:
last += 1
f.write(str(last))
return last
### API Base Methods
def base_headers(url: str, request_json: dict=None) -> dict:
"""basic auth & content headers shared by the REST and WS API"""
request_json = request_json or {}
request_json['request'] = f'/v{API_VERSION}{url}'
request_json['nonce'] = get_nonce()
base_64 = base64.b64encode(json.dumps(request_json).encode())
signature = hmac.new(API_SECRET.encode(), base_64, sha384).hexdigest()
return {
'X-GEMINI-APIKEY': API_KEY,
'X-GEMINI-PAYLOAD': base_64,
'X-GEMINI-SIGNATURE': signature,
}
@retry_if_exception
def request(url: str, request_json: dict=None, method='POST', public: bool=False) -> dict:
"""Make an HTTP request to the Gemini API, public=True disables auth headers"""
http_headers = {
'Content-Type': "text/plain",
'Content-Length': "0",
'Cache-Control': "no-cache",
}
response = requests.request(
method,
f'{API_URL}/v{API_VERSION}{url}',
headers={
**http_headers,
**({} if public else base_headers(url, request_json)),
},
)
if response.status_code == 429:
raise RateLimitExceeded
try:
return json.loads(response.text)
except json.decoder.JSONDecodeError:
print(response.text)
raise
@retry_if_exception
def websocket_request(url, request_json: dict=None):
"""Subscribe to websocket messages from a Gemini API endpoint"""
try:
from websocket import create_connection
except ImportError:
print('The package websocket-client is required to use the WS api:')
print(' pip install websocket-client')
raise SystemExit(1)
headers = base_headers(url, request_json)
return create_connection(
f'{API_WS_URL}/v{API_VERSION}{url}',
headers=headers,
)
### API REST Methods
def heartbeat() -> None:
"""send a keep-alive heartbeat ping to the Gemini API"""
response = request('/heartbeat')
if not response['result']:
raise Exception('Heartbeat request failed!')
def ticker(symbol: str) -> dict:
"""fetch the current price and volume for a given symbol"""
return request(f'/pubticker/{symbol}', method='GET', public=True)
def new_order(side: str, symbol: str, amt: Currency, price: Currency) -> dict:
"""create a new buy or sell order for a given symbol, amt, and price"""
return request('/order/new', {
# "client_order_id": client_order_id,
"symbol": symbol,
"amount": str(amt),
"price": str(price),
"side": side,
"type": "exchange limit",
})
def order_status(order_id: str) -> dict:
"""fetch the up-to-date order object for a given order id"""
# https://docs.gemini.com/rest-api/#order-status
return request('/order/status', {'order_id': order_id})
### API WebSocket Methods
def order_events(order_id: str):
"""subscibe to event updates for a given order id"""
ws = websocket_request('/order/events', {'order_id': order_id})
while True:
yield json.loads(ws.recv())