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