-
Notifications
You must be signed in to change notification settings - Fork 0
/
PseudoAPI_buy_sell.py
184 lines (146 loc) · 6.19 KB
/
PseudoAPI_buy_sell.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
176
177
178
179
180
181
182
183
184
# Copyright (c) 2018 A&D
# facilitates all buy/sell requests by the different files
import hmac
import hashlib
from math import floor
from urllib.parse import urlencode
from PrivateData import secret_key, api_key
from Generics import PARAMETERS
from time import time
from requests import get
# decimal precision allowed for trading each crypto
stepsizes = {}
# get the binance step sizes of each crypto (the step size is the minimum significant digits allowed by binance for crypto to be traded in)
def binStepSize():
"""
:return:
"""
# getting the dictionary of a lot of aggregate data for all symbols
stepsizeinfo = get("https://api.binance.com/api/v1/exchangeInfo")
bigdata = stepsizeinfo.json()["symbols"]
# iterating through the dictionary and adding just the stepsizes into our own dictionary
for i in bigdata:
symbol = i["symbol"]
stepsize = i["filters"][1]["stepSize"]
temp = {symbol: stepsize}
stepsizes.update(temp)
# buy the specified crypto currency
# returns the new currencytotrade and pricebought in case it is used
def buyBin(symbol, stepsize, currencyToTrade, percenttospend=PARAMETERS['PERCENT_TO_SPEND'], percentquantitytospend=PARAMETERS['PERCENT_QUANTITY_TO_SPEND']):
"""
:param symbol:
:param stepsize:
:param currencyToTrade:
:param percenttospend:
:param percentquantitytospend:
:return:
"""
timestamp = int(time.time() * 1000)
balance = getBalance('BTC')
# multiply balance by constant ratio of how much we want to spend
# and then convert quantity from BTC price to amount of coin
balancetospend = float(balance) * percenttospend
ratio = getbinanceprice(symbol)
# store the price the crypto was a bought at for cumulative percent change calculations
priceBought = ratio
# mark item as the current crypto being traded and save the buy price at for failure condition
entry = {symbol: {'buyPrice': ratio, 'timestamp': timestamp}}
currencyToTrade.clear()
currencyToTrade.update(entry)
quantity = balancetospend / float(ratio) * float(percentquantitytospend)
# making the quantity to buy
quantity = float(quantity)
# based on the stepsize of the currency round the quantity to that amount
if (float(stepsize) == float(1)):
quantity = int(quantity)
if (float(stepsize) == 0.1):
quantity = floor(quantity * 10) / 10
if (float(stepsize) == 0.01):
quantity = floor(quantity * 100) / 100
if (float(stepsize) == 0.001):
quantity = floor(quantity * 1000) / 1000
# building the query string for buying(signed)
headers = {'X-MBX-APIKEY': api_key}
buyParameters = {'symbol': symbol, 'side': 'buy', 'type': 'market', 'timestamp': timestamp, 'quantity': quantity}
query = urlencode(sorted(buyParameters.items()))
signature = hmac.new(secret_key.encode('utf-8'), query.encode('utf-8'), hashlib.sha256).hexdigest()
query += "&signature=" + signature
# testBuy = requests.post("https://api.binance.com/api/v3/order?" + query, headers=headers)
return currencyToTrade, priceBought
# sell the specified crypto
def sellBin(symbol, stepsize):
"""
:param symbol:
:param stepsize:
:return:
"""
# current time in ms
timestamp = int(time.time() * 1000) - 1000
# building the request query url plus other parameters(signed)
headers = {'X-MBX-APIKEY': api_key}
infoParameter = {'timestamp': timestamp}
query = urlencode(sorted(infoParameter.items()))
signature = hmac.new(secret_key.encode('utf-8'), query.encode('utf-8'), hashlib.sha256).hexdigest()
query += "&signature=" + signature
# getting the account info
accountInfo = get("https://api.binance.com/api/v3/account?" + query, headers=headers)
# getting rid of the 'BTC' part of the crypto asset name
if (symbol == 'BTCUSDT'):
asset = 'BTC'
else:
asset = symbol.split('BTC', 1)[0]
# iterating through the account info to find the balance of the coin we're selling
for i in accountInfo.json()["balances"]:
if (i["asset"] == asset):
balance = i["free"]
# making the quantity to sell
quantity = float(balance)
# based on the stepsize of the currency round the quantity to that amount
if (float(stepsize) == float(1)):
quantity = int(quantity)
if (float(stepsize) == 0.1):
quantity = floor(quantity * 10) / 10
if (float(stepsize) == 0.01):
quantity = floor(quantity * 100) / 100
if (float(stepsize) == 0.001):
quantity = floor(quantity * 1000) / 1000
# building the sell query string
sellParameters = {'symbol': symbol, 'side': 'sell', 'type': 'market', 'timestamp': timestamp, 'quantity': quantity}
query = urlencode(sorted(sellParameters.items()))
signature = hmac.new(secret_key.encode('utf-8'), query.encode('utf-8'), hashlib.sha256).hexdigest()
query += "&signature=" + signature
# actually selling
# testSell = requests.post("https://api.binance.com/api/v3/order?" + query, headers=headers)
# get the balance in bitcoins
def getBalance(symbol):
"""
:param symbol:
:return:
"""
timestamp = int(time.time() * 1000)
# building the request query url plus other parameters(signed)
headers = {'X-MBX-APIKEY': api_key}
infoParameter = {'timestamp': timestamp}
query = urlencode(sorted(infoParameter.items()))
signature = hmac.new(secret_key.encode('utf-8'), query.encode('utf-8'), hashlib.sha256).hexdigest()
query += "&signature=" + signature
# requesting account info to get the balance
accountInfo = get("https://api.binance.com/api/v3/account?" + query, headers=headers)
accountInfo = accountInfo.json()["balances"]
balance = 0
for val in accountInfo:
if(val["asset"] == symbol):
balance = val["free"]
return balance
# get the binance price of the specified currency
def getbinanceprice(currency):
"""
:param currency:
:return:
"""
# getting the aggregate trade data and finding one price to return
parameters = {'symbol': currency}
binData = get("https://api.binance.com/api/v3/ticker/price", params=parameters)
binData = binData.json()
binPrice = binData['price']
return binPrice