-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBittrexMarketBuys.py
294 lines (253 loc) · 11 KB
/
BittrexMarketBuys.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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import codecs
import datetime
import time
import hmac
import hashlib
import json
import requests
import sqlite3
import json
import collections
import subprocess
import configparser
import sys
from datetime import datetime
from pushover import init, Client
# Enable Push notifications
PushoverEnabled = 1
# SET IMPORTANT VARIABLES
testMode = True # Set to false when you're ready for real transactions
target = 'DCR' # Ticker for the ultimate cryptocurrency you are buying
source = 'USD' # What you're using to buy the cryptocurrency
targetMarket = target + '-' + source # The market to trade source for target on Bittrex e.g DCR-USD
fundsToSpend = 5 # Number of units of source to spend to trade each time this script runs
exchangeWithdrawalsEnabled = False # Enable to automatically withdraw from the exchange once you reach the limit - NYKNYC!
exchangeHoldingsLimit = 10 # Amount of target to keep on the exchange before initiating a withdrawal if enabled
buyOnBTCMarket = True # This will place a spot market buy trade for BTC with source before purchasing the target asset with BTC
btcMarket = 'BTC' + '-' + source # The market to trade source for BTC if enabled as an intermediary step.
if (buyOnBTCMarket == True):
targetMarket = target + '-' + 'BTC'
# Get config values
config = configparser.ConfigParser()
config.read("config.ini")
BittrexKey = config["DEFAULT"]["BittrexKey"]
BittrexSecret = config["DEFAULT"]["BittrexSecret"]
Address = config["DEFAULT"]["Address"]
# Initialize Pushover for notifications
if (PushoverEnabled):
PushoverToken = config["DEFAULT"]["PushoverToken"]
PushoverUserKey = config["DEFAULT"]["PushoverUserKey"]
init(PushoverToken)
# Variables
headers = {'content-type': 'application/json'}
def signMessage(message):
"Function to sign an API call"
global BittrexSecret
signature = hmac.new(codecs.encode(BittrexSecret),
codecs.encode(message), hashlib.sha512).hexdigest()
return signature
def generateHash(message):
"Function to generate a hash of a message"
hash = hashlib.sha512(str(message).encode("utf-8")).hexdigest()
return hash
def now_milliseconds():
"Function to return timestamp in milliseconds"
return int(time.time() * 1000)
######################################################################
# Bittrex API v3
def getMarket(market):
"GET /markets/{marketSymbol}/ticker"
timestamp = str(now_milliseconds())
uri = 'https://api.bittrex.com/v3/markets/' + market + '/ticker'
method = "GET"
contentHash = generateHash("")
subaccountId = ""
preSign = timestamp + uri + method + contentHash + subaccountId
signature = signMessage(preSign)
headers = {
'content-type': 'application/json',
'Api-Key': BittrexKey,
'Api-Timestamp': timestamp,
'Api-Content-Hash': generateHash(""),
'Api-Signature': signature
}
response = requests.get(uri, headers=headers)
# print(response.text)
jsonStr = json.loads(response.text)
return jsonStr
def getAvailableHoldings(ticker):
"GET /balances/{currencySymbol}"
timestamp = str(now_milliseconds())
uri = 'https://api.bittrex.com/v3/balances/' + ticker
method = "GET"
contentHash = generateHash("")
subaccountId = ""
preSign = timestamp + uri + method + contentHash + subaccountId
signature = signMessage(preSign)
headers = {
'content-type': 'application/json',
'Api-Key': BittrexKey,
'Api-Timestamp': timestamp,
'Api-Content-Hash': generateHash(""),
'Api-Signature': signature
}
response = requests.get(uri, headers=headers)
# print(response.text)
jsonStr = json.loads(response.text)
availableFunds = jsonStr["available"]
return availableFunds
def postOrder(market, direction, type, timeInForce, quantity):
"POST /orders"
timestamp = str(now_milliseconds())
uri = ('https://api.bittrex.com/v3/orders')
method = "POST"
orderRequest = {
"marketSymbol": market,
"direction": direction,
"type": type,
"quantity": quantity,
"timeInForce": timeInForce
}
orderRequestJson = json.dumps(orderRequest)
contentHash = generateHash(orderRequestJson)
subaccountId = ""
preSign = timestamp + uri + method + contentHash + subaccountId
signature = signMessage(preSign)
headers = {
'content-type': 'application/json',
'Api-Key': BittrexKey,
'Api-Timestamp': timestamp,
'Api-Content-Hash': contentHash,
'Api-Signature': signature
}
response = requests.post(uri, data=orderRequestJson, headers=headers)
print(response.text)
jsonStr = json.loads(response.text)
return jsonStr
def postWithdrawal(currency, quantity):
"POST /withdrawals"
timestamp = str(now_milliseconds())
uri = ('https://api.bittrex.com/v3/withdrawals')
method = "POST"
withdrawalRequest = {
"currencySymbol": currency,
"quantity": quantity,
"cryptoAddress": Address
}
withdrawalRequestJson = json.dumps(withdrawalRequest)
contentHash = generateHash(withdrawalRequestJson)
subaccountId = ""
preSign = timestamp + uri + method + contentHash + subaccountId
signature = signMessage(preSign)
headers = {
'content-type': 'application/json',
'Api-Key': BittrexKey,
'Api-Timestamp': timestamp,
'Api-Content-Hash': contentHash,
'Api-Signature': signature
}
response = requests.post(uri, data=withdrawalRequestJson, headers=headers)
print(response.text)
jsonStr = json.loads(response.text)
return jsonStr
######################################################################
# Methods to take advantage of Bittrex API methods
def placeOrder(orderAmount, askPrice, market):
"Generate market buy at asking price"
quantity = orderAmount / askPrice
quantity = round(quantity, 8)
total = round(quantity * askPrice, 8)
assets = market.split('-')
target = assets[0]
source = assets[1]
if (source == 'USD'):
roundPlace = 2
else:
roundPlace = 8
print('Buying ' + str(quantity) + ' ' + target + ' for a total of '
+ '{:.{roundPlace}f}'.format(total, roundPlace = roundPlace) + ' ' + source + ' at '
+ '{:.{roundPlace}f}'.format(askPrice, roundPlace = roundPlace) + ' ' + source + ' each.')
if (testMode == False):
response = postOrder(market, 'BUY', 'MARKET',
'IMMEDIATE_OR_CANCEL', quantity)
if response.get("id"):
saveTrade('Bought', quantity, askPrice, total)
if (PushoverEnabled):
Client(PushoverUserKey).send_message('Bought ' + str(quantity) + ' ' + str(target)
+ ' for a total of ' + '{:.{roundPlace}f}'.format(total, roundPlace = roundPlace) + ' ' + source + ' at '
+ '{:.{roundPlace}f}'.format(askPrice, roundPlace = roundPlace) + ' ' + source + ' each.', title=target + ' Purchase')
else:
if (PushoverEnabled):
Client(PushoverUserKey).send_message('Buy order failed. Reason: ' + str(response),
title=target + ' Purchase Failed')
print('Buy order failed. Reason: ' + response["code"])
else:
saveTrade('Bought', quantity, askPrice, total, testMode)
if (PushoverEnabled):
Client(PushoverUserKey).send_message('**TEST MODE**: Bought ' + str(quantity) + ' ' + str(target)
+ ' for a total of ' + '{:.{roundPlace}f}'.format(total, roundPlace = roundPlace) + ' ' + source + ' at '
+ '{:.{roundPlace}f}'.format(askPrice, roundPlace = roundPlace) + ' ' + source + ' each.', title=target + ' Purchase')
return quantity
def saveTrade(action, quantity, price, total, testMode=False):
"Save trade details to a file called 'lasttrade.txt'"
data = {}
data['data'] = []
data['data'].append({
'action': action,
'quantity': quantity,
'price': price,
'totalPrice': total,
'tradeTime': str(datetime.now()),
'testMode': testMode
})
with open('lasttrade.txt', 'w') as outfile:
json.dump(data, outfile)
print('-------------------------------------------------')
if (testMode == True):
print('**TEST MODE**')
print('Time: ' + str(datetime.now()))
# Get available funds
availableFunds = float(getAvailableHoldings(source))
availableCryptocurrency = float(getAvailableHoldings(target))
print('Available '+ source +': $' + str(availableFunds))
print('Available ' + str(target) + ': ' + str(availableCryptocurrency))
# Get latest target ask price
jsonStr = getMarket(targetMarket)
lastTargetAsk = float(jsonStr['askRate'])
print('Last ' + targetMarket + ' Ask: ' + str(lastTargetAsk))
# Get latest BTC ask price
jsonStr = getMarket(btcMarket)
lastBTCAsk = float(jsonStr['askRate'])
print('Last ' + btcMarket + ' Ask: ' + str(lastBTCAsk))
# Check for available funds and initiate purchase if enough funds are available
if (availableFunds > fundsToSpend):
if (buyOnBTCMarket):
btcToSpend = placeOrder(fundsToSpend, lastBTCAsk, btcMarket)
# Ensure order has had some time to be fulfilled
time.sleep(10)
placeOrder(btcToSpend, lastTargetAsk, targetMarket)
else:
placeOrder(fundsToSpend, lastTargetAsk, targetMarket)
if ((availableFunds - fundsToSpend) < fundsToSpend):
if (PushoverEnabled):
Client(PushoverUserKey).send_message('There will not be enough funds to complete another market purchase on the next run. Deposit more ' + str(source)
+ ' to Bittrex Wallet.', title='Deposit more ' + source + ' to Bittrex Wallet')
print('There will not be enough funds to complete another market purchase on the next run. Deposit more ' + source + ' to Bittrex Wallet.')
else:
if (PushoverEnabled):
Client(PushoverUserKey).send_message('Not enough available funds for ' + str(target)
+ ' purchase!', title='Not Enough Funds')
print("Not enough available funds for order.")
print('-------------------------------------------------')
if (exchangeWithdrawalsEnabled and Address):
# Initiate Withdraw if current holdings on exchange exceed user defined limit.
availableCryptocurrency = float(getAvailableHoldings(target))
if (availableCryptocurrency > exchangeHoldingsLimit):
# Ensure most recent order has had time to be fulfilled
time.sleep(10)
response = postWithdrawal(target, availableCryptocurrency)
if response.get("id"):
if (PushoverEnabled):
Client(PushoverUserKey).send_message(str(availableCryptocurrency) + str(target) + ' was withdrawn to your wallet.\n'
+ str(response), title=str(target) + ' Withdrawn From Exchange')
print(str(availableCryptocurrency) + str(target) + ' was withdrawn to your wallet.')