· 5 years ago · Jun 24, 2020, 11:14 AM
1import hmac
2import hashlib
3import json
4import requests
5import time
6import pandas as pd
7
8base_url = "https://api.crypto.com/v2/"
9
10## Add authentication details
11API_KEY = os.environ['CRYPTO_COM_API_KEY']
12SECRET_KEY = os.environ['CRYPTO_COM_API_SEC']
13
14## Request orders history
15nonce = int(round(time.time() * 1000))
16
17req = {
18 "id": 0,
19 "api_key": API_KEY,
20 "method": "private/get-order-history",
21 "params": {},
22 "nonce": nonce
23}
24
25# This step isn't actially necessary with an empty params entry
26paramString = ""
27
28if "params" in req:
29 for key in req['params']:
30 paramString += key
31 paramString += str(req['params'][key])
32
33
34sigPayload = req['method'] + str(req['id']) + req['api_key'] + paramString + str(req['nonce'])
35
36req['sig'] = hmac.new(
37 bytes(str(SECRET_KEY), 'utf-8'),
38 msg=bytes(sigPayload, 'utf-8'),
39 digestmod=hashlib.sha256
40).hexdigest()
41
42response = requests.post(base_url + "private/get-order-history", json=req)
43
44# Put the results in a table
45orders = pd.DataFrame.from_dict(response.json()['result']['order_list'])
46
47# Turn the millis since epoch into a datetime and format for Cointracking.info
48orders.create_time = pd.to_datetime(orders.create_time, unit='ms')
49orders.update_time = pd.to_datetime(orders.update_time, unit='ms')
50# e.g. 2020-06-23T14:42:44+00
51orders.create_time = orders.create_time.dt.strftime('%Y-%m-%dT%H:%M:%S+00')
52orders.update_time = orders.update_time.dt.strftime('%Y-%m-%dT%H:%M:%S+00')
53
54# Split the instruments into two columns
55orders['left'], orders['right'] = orders['instrument_name'].str.split('_', 1).str
56
57## The fee information does not seem to be included here.
58# Individual trades can be summed (not sure if this is right - do they add up correctly?)
59nonce = int(round(time.time() * 1000))
60
61req = {
62 "id": 2,
63 "method": "private/get-trades",
64 "api_key": API_KEY,
65 "params": {
66 "page": 0,
67 "page_size": 200
68 },
69 "nonce": nonce
70}
71
72paramString = ""
73
74if "params" in req:
75 for key in req['params']:
76 paramString += key
77 paramString += str(req['params'][key])
78
79
80sigPayload = req['method'] + str(req['id']) + req['api_key'] + paramString + str(req['nonce'])
81
82req['sig'] = hmac.new(
83 bytes(str(SECRET_KEY), 'utf-8'),
84 msg=bytes(sigPayload, 'utf-8'),
85 digestmod=hashlib.sha256
86).hexdigest()
87
88response = requests.post(base_url + "private/get-trades", json=req)
89
90# Put the trades into a table
91fees = pd.DataFrame.from_dict(response.json()['result']['trade_list'])
92
93# Aggregate by order_id and fee_currency
94fees = fess.groupby(['order_id', 'fee_currency']).agg({'fee': 'sum', 'traded_price': 'mean', "traded_quantity": 'sum'}).reset_index()
95
96# Merge into the order list
97out = orders.merge(fees, on = ["order_id", "fee_currency"])
98
99# Drop cancelled orders
100out = out.query("status != \"CANCELED\"")
101
102# Write to CSV
103out.to_csv("crypto_com.csv")