· 5 years ago · Jun 24, 2020, 11:24 AM
1import hmac
2import hashlib
3import json
4import requests
5import time
6import os
7import pandas as pd
8
9base_url = "https://api.crypto.com/v2/"
10
11## Add authentication details
12API_KEY = os.environ['CRYPTO_COM_API_KEY']
13SECRET_KEY = os.environ['CRYPTO_COM_API_SEC']
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.create_time = pd.to_datetime(orders.create_time, unit='ms')
50orders.update_time = pd.to_datetime(orders.update_time, unit='ms')
51# e.g. 2020-06-23T14:42:44+00
52orders.create_time = orders.create_time.dt.strftime('%Y-%m-%dT%H:%M:%S+00')
53orders.update_time = orders.update_time.dt.strftime('%Y-%m-%dT%H:%M:%S+00')
54
55# Split the instruments into two columns
56orders['left'], orders['right'] = orders['instrument_name'].str.split('_', 1).str
57
58## The fee information does not seem to be included here.
59# Individual trades can be summed (not sure if this is right - do they add up correctly?)
60nonce = int(round(time.time() * 1000))
61
62req = {
63 "id": 2,
64 "method": "private/get-trades",
65 "api_key": API_KEY,
66 "params": {
67 "page": 0,
68 "page_size": 200
69 },
70 "nonce": nonce
71}
72
73paramString = ""
74
75if "params" in req:
76 for key in req['params']:
77 paramString += key
78 paramString += str(req['params'][key])
79
80
81sigPayload = req['method'] + str(req['id']) + req['api_key'] + paramString + str(req['nonce'])
82
83req['sig'] = hmac.new(
84 bytes(str(SECRET_KEY), 'utf-8'),
85 msg=bytes(sigPayload, 'utf-8'),
86 digestmod=hashlib.sha256
87).hexdigest()
88
89response = requests.post(base_url + "private/get-trades", json=req)
90
91# Put the trades into a table
92fees = pd.DataFrame.from_dict(response.json()['result']['trade_list'])
93
94# Aggregate by order_id and fee_currency
95fees = fees.groupby(['order_id', 'fee_currency']).agg({'fee': 'sum', 'traded_price': 'mean', "traded_quantity": 'sum'}).reset_index()
96
97# Merge into the order list
98out = orders.merge(fees, on = ["order_id", "fee_currency"])
99
100# Drop cancelled orders
101out = out.query("status != \"CANCELED\"")
102
103# Write to CSV
104out.to_csv("crypto_com.csv")