forked from fj317/PumpBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPumpBot.py
273 lines (241 loc) · 9 KB
/
PumpBot.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
from binance.client import Client
from binance.enums import *
from binance.exceptions import *
import sys
import math
import json
import requests
import webbrowser
import time
import urllib
import os
import ssl
import time
# UTILS
def float_to_string(number, precision=10):
return '{0:.{prec}f}'.format(
number, prec=precision,
).rstrip('0').rstrip('.') or '0'
def log(information):
currentTime = time.strftime("%H:%M:%S", time.localtime())
logfile.writelines(str(currentTime) + " --- " + str(information) + "\n")
def marketSell(amountSell):
order = client.order_market_sell(
symbol=tradingPair,
quantity=amountSell)
log("Sold at market price")
print("Sold at market price")
# make log file
logfile = open("log.txt", "w+")
# read json file
try:
f = open('keys.json', )
except FileNotFoundError:
log("Keys.json not found")
sys.exit("Error. Keys.json not found. \nRemember to rename your keys.json.example to keys.json.")
data = json.load(f)
apiKey = data['apiKey']
apiSecret = data['apiSecret']
if (apiKey == "") or (apiSecret == ""):
log("API Keys Missing")
sys.exit("One or Both of you API Keys are missing.\n"
"Please open the keys.json to include them.")
f = open('config.json', )
data = json.load(f)
# loading config settings
quotedCoin = data['quotedCoin'].upper()
buyLimit = data['buyLimit']
percentOfWallet = float(data['percentOfWallet']) / 100
manualQuoted = float(data['manualQuoted'])
profitMargin = float(data['profitMargin']) / 100
stopLoss = float(data['stopLoss'])
currentVersion = float(data['currentVersion'])
endpoint = data['endpoint']
# check we have the latest version
ssl._create_default_https_context = ssl._create_unverified_context
url = 'https://raw.githubusercontent.com/fj317/PumpBot/master/config.json'
urllib.request.urlretrieve(url, 'version.json')
try:
f = open('version.json', )
except FileNotFoundError:
log("version.json not found")
print("Fatal error checking versions. Please try again\n")
quit()
data = json.load(f)
f.close()
latestVersion = data['currentVersion']
os.remove("version.json")
if latestVersion > currentVersion:
log("Current version {}. New version {}".format(currentVersion, latestVersion))
print("\nNew version of the script found. Please download the new version...\n")
time.sleep(3)
endpoints = {
'default': 'https://api.binance.{}/api',
'api1': 'https://api1.binance.{}/api',
'api2': 'https://api2.binance.{}/api',
'api3': 'https://api3.binance.{}/api'
}
try:
Client.API_URL = endpoints[endpoint]
except Exception as d:
print("Endpoint error. Using default endpoint instead")
log("Endpoint error. Using default endpoint instead")
# create binance Client
client = Client(apiKey, apiSecret)
# get all symbols with coinPair as quote
tickers = client.get_all_tickers()
symbols = []
for ticker in tickers:
if quotedCoin in ticker["symbol"]: symbols.append(ticker["symbol"])
# cache average prices
print("Caching all {} pairs average prices...\nThis can take a while. Please, be patient...\n".format(quotedCoin))
tickers = client.get_ticker()
averagePrices = []
for ticker in tickers:
if quotedCoin in ticker['symbol']:
averagePrices.append(dict(symbol=ticker['symbol'], wAvgPrice=ticker["weightedAvgPrice"]))
# getting btc conversion
response = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
data = response.json()
in_USD = float((data['bpi']['USD']['rate_float']))
print("Sucessfully cached BTC pairs!")
# find amount of bitcoin to use
try:
QuotedBalance = float(client.get_asset_balance(asset=quotedCoin)['free'])
except (BinanceRequestException, BinanceAPIException):
log("Error with getting balance")
sys.exit("Error with getting balance.")
# decide if use percentage or manual amount
if manualQuoted <= 0:
AmountToSell = QuotedBalance * percentOfWallet
else:
AmountToSell = manualQuoted
# nice user message
print('''
___ ___ _
( _`\ ( _`\ ( )_
| |_) ) _ _ ___ ___ _ _ | (_) ) _ | ,_)
| ,__/'( ) ( )/' _ ` _ `\( '_`\ | _ <' /'_`\ | |
| | | (_) || ( ) ( ) || (_) ) | (_) )( (_) )| |_
(_) `\___/'(_) (_) (_)| ,__/' (____/'`\___/'`\__)
| |
(_) ''')
# wait until coin input
print("\nInvesting amount for {}: {}".format(quotedCoin, float_to_string(AmountToSell)))
print("Investing amount in USD: {}".format(float_to_string((in_USD * AmountToSell), 2)))
tradingPair = input("\nCoin pair: ").upper() + quotedCoin
# get trading pair price
try:
price = float(client.get_avg_price(symbol=tradingPair)['price'])
except BinanceAPIException as e:
if e.code == -1121:
print(
"Invalid trading pair given. Check your input is correct as well as config.json's 'coinPair' value to "
"fix the error.")
log("Invalid trading pair given.")
else:
print("A BinanceAPI error has occurred. Code = " + str(e.code))
print(
e.message + ". Please use https://github.com/binance/binance-spot-api-docs/blob/master/errors.md to find "
"greater details on error codes before raising an issue.")
log("Binannce API error occured on getting price for trading pair.")
quit()
except Exception as d:
print(d)
print("An unknown error has occurred.")
log("Unlnown error has occured on getting price for trading pair.")
quit()
# calculate amount of coin to buy
amountOfCoin = AmountToSell / price
# ensure buy limit is setup correctly
averagePrice = 0
for ticker in averagePrices:
if ticker["symbol"] == tradingPair:
averagePrice = ticker["wAvgPrice"]
if averagePrice == 0: averagePrice = price
# rounding the coin amount to the specified lot size
info = client.get_symbol_info(tradingPair)
minQty = float(info['filters'][2]['stepSize'])
amountOfCoin = float_to_string(amountOfCoin, int(- math.log10(minQty)))
# rounding price to correct dp
minPrice = minQty = float(info['filters'][0]['tickSize'])
averagePrice = float(averagePrice) * buyLimit
averagePrice = float_to_string(averagePrice, int(- math.log10(minPrice)))
try:
# buy order
order = client.order_limit_buy(
symbol=tradingPair,
quantity=amountOfCoin,
price=averagePrice)
print('Buy order has been made!')
except BinanceAPIException as e:
print("A BinanceAPI error has occurred. Code = " + str(e.code))
print(
e.message + ". Please use https://github.com/binance/binance-spot-api-docs/blob/master/errors.md to find "
"greater details on error codes before raising an issue.")
log("Binance API error has occured on buy order")
quit()
except Exception as d:
print(d)
print("An unknown error has occurred.")
log("Unknown error has occured on buy order")
quit()
# waits until the buy order has been confirmed
while order['status'] != "FILLED":
print("Waiting for coin to buy...")
# once finished waiting for buy order we can process the sell order
print('Processing sell order.')
# once bought we can get info of order
coinOrderInfo = order["fills"][0]
coinPriceBought = float(coinOrderInfo['price'])
coinOrderQty = float(coinOrderInfo['qty'])
# find price to sell coins at
priceToSell = coinPriceBought * profitMargin
# rounding sell price to correct dp
roundedPriceToSell = float_to_string(priceToSell, int(- math.log10(minPrice)))
# get stop price
stopPrice = float_to_string(stopLoss * coinPriceBought, int(- math.log10(minPrice)))
try:
# oco order (with stop loss)
order = client.create_oco_order(
symbol=tradingPair,
quantity=coinOrderQty,
side=SIDE_SELL,
price=roundedPriceToSell,
stopPrice=stopPrice,
stopLimitPrice=stopPrice,
stopLimitTimeInForce=TIME_IN_FORCE_GTC
)
except BinanceAPIException as e:
print("A BinanceAPI error has occurred. Code = " + str(e.code))
print(
e.message + " Please use https://github.com/binance/binance-spot-api-docs/blob/master/errors.md to find "
"greater details "
"on error codes before raising an issue.")
log(e)
log("Binance API error has occured on sell order")
print("Attempting to market sell.")
marketSell(coinOrderQty)
quit()
except Exception as d:
print("An unknown error has occurred.")
log(d)
log("Unknown error has occured on sell order")
print("Attempting to market sell.")
marketSell(coinOrderQty)
quit()
print('Sell order has been made!')
# open binance page to trading pair
webbrowser.open('https://www.binance.com/en/trade/' + tradingPair)
print("Waiting for sell order to be completed.")
while order['listOrderStatus'] != "ALL_DONE":
pass
print("Sell order sold!")
newQuotedBalance = float(client.get_asset_balance(asset=quotedCoin)['free'])
profit = newQuotedBalance - QuotedBalance
print("Profit made: " + str(profit))
# wait for Enter to close
input("\nPress Enter to Exit...")
# close Log file and exit
logfile.close()
sys.exit()