-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathFTX_Class.py
75 lines (61 loc) · 2.89 KB
/
FTX_Class.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
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import time
import urllib.parse
from typing import Optional, Dict, Any, List
from requests import Request, Session, Response
import hmac
class FtxClient:
_ENDPOINT = 'https://ftx.com/api/'
def __init__(self, api_key=None, api_secret=None, subaccount_name=None) -> None:
self._session = Session()
self._api_key = api_key
self._api_secret = api_secret
self._subaccount_name = subaccount_name
def _get(self, path: str, params: Optional[Dict[str, Any]] = None) -> Any:
return self._request('GET', path, params=params)
def _post(self, path: str, params: Optional[Dict[str, Any]] = None) -> Any:
return self._request('POST', path, json=params)
def _request(self, method: str, path: str, **kwargs) -> Any:
request = Request(method, self._ENDPOINT + path, **kwargs)
self._sign_request(request)
response = self._session.send(request.prepare())
return self._process_response(response)
def _sign_request(self, request: Request) -> None:
ts = int(time.time() * 1000)
prepared = request.prepare()
signature_payload = f'{ts}{prepared.method}{prepared.path_url}'.encode()
if prepared.body:
signature_payload += prepared.body
signature = hmac.new(self._api_secret.encode(), signature_payload, 'sha256').hexdigest()
request.headers['FTX-KEY'] = self._api_key
request.headers['FTX-SIGN'] = signature
request.headers['FTX-TS'] = str(ts)
if self._subaccount_name:
request.headers['FTX-SUBACCOUNT'] = urllib.parse.quote(self._subaccount_name)
def _process_response(self, response: Response) -> Any:
try:
data = response.json()
except ValueError:
response.raise_for_status()
raise
else:
if not data['success']:
raise Exception(data['error'])
return data['result']
def place_order(self, market: str, side: str, price: float, size: float, client_id: str,
type: str = 'limit', reduce_only: bool = False, ioc: bool = False, post_only: bool = False,
) -> dict:
return self._post('orders', {'market': market,
'side': side,
'price': price,
'size': size,
'type': type,
'reduceOnly': reduce_only,
'ioc': ioc,
'postOnly': post_only,
'clientId': client_id,
})
def get_open_orders(self, order_id: int, market: str = None) -> List[dict]:
return self._get(f'orders', {'market': market, 'order_id':order_id})