Advertisement
Guest User

Untitled

a guest
Jan 16th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.04 KB | None | 0 0
  1. import os
  2. import sys
  3. import time
  4. import config
  5. import argparse
  6. import math
  7. import threading
  8. import json
  9. # from multiprocessing.pool import ThreadPool
  10. from BinanceAPI import *
  11.  
  12.  
  13. # sudo date -s "$(wget -qSO- --max-redirect=0 google.com 2>&1 | grep Date: | cut -d' ' -f5-8)Z"
  14.  
  15. # python trader.py --basecoin BTC --cores 30 --percentFall 5
  16.  
  17. # TODO: Test ticker with API v3.
  18.  
  19.  
  20. # Binance API
  21. client = BinanceAPI(config.api_key, config.api_secret)
  22.  
  23. # Argument list
  24. parser = argparse.ArgumentParser()
  25. parser.add_argument("--basecoin", type=str, help="Market Symbol (Ex: ETH)", default="BTC")
  26. parser.add_argument("--percentFall", type=float, help="% Percent to which the value has to fluncuate before action is taken.", default=5)
  27. parser.add_argument("--coin", type=str, help="", default="")
  28. parser.add_argument("--cores", type=int, help="Number of threads to run", default=10)
  29. option = parser.parse_args()
  30.  
  31. # Global vars
  32. _basecoin = option.basecoin
  33. _percentFall = option.percentFall
  34. _cores = option.cores
  35. _coin = option.coin.strip().upper()
  36. _getValueRunning = False
  37. _cycleAllAskPricesRunning = False
  38. _getValueTickerReady = False
  39. _startTime = 0
  40. _counter = 0
  41. _AskPrices = []
  42. _file = _basecoin + 'coins.json'
  43.  
  44. # Load list of all coins
  45. def loadCoinsList():
  46. global _AskPrices, _file
  47.  
  48. # Todo: Check if file exists, if not scrape new.
  49.  
  50. with open(_file) as coins_file:
  51. _AskPrices = json.load(coins_file)
  52. return True # Done
  53.  
  54. # /////////////////////////////////
  55. # Get new list:
  56. query = client.get_account()["balances"]
  57. for index, item in enumerate(query):
  58. if not item["asset"] == _basecoin:
  59. _AskPrices.append({"coin":item["asset"], "price":0.00000000})
  60. with open(_file, 'w') as outfile:
  61. json.dump(_AskPrices, outfile)
  62.  
  63. # Thread: Initial scrape all coins askPrice
  64. def cycleAllAskPrices(startIndex):
  65. global _AskPrices
  66. indexo = startIndex
  67. while(_cycleAllAskPricesRunning == True):
  68. for index, item in enumerate(_AskPrices):
  69. if _cycleAllAskPricesRunning == False:
  70. break
  71. if indexo - 1 <= index:
  72. indexo = 0
  73. try:
  74. _AskPrices[index]['price'] = client.get_ticker(item["coin"] + _basecoin)["askPrice"]
  75. except Exception as e:
  76. print(_AskPrices[index])
  77. print(e)
  78. # del _AskPrices[index]
  79.  
  80. # Returns seconds since program started.
  81. def getTime():
  82. if _startTime == 0:
  83. return 0
  84. else:
  85. return time.time() - _startTime
  86.  
  87. # Returns balance of specified coin.
  88. def getBalance(coin):
  89. balance = client.get_account()["balances"]
  90. for index, item in enumerate(balance):
  91. if item["asset"] == coin :
  92. print ("[%0.2f] getBalance(%s): %.8f" % (getTime(), coin, float(item["free"])))
  93. return float(item["free"])
  94.  
  95.  
  96. # Returns quantity of coin to buy.
  97. def getBuyQuantity(balance, fetch):
  98. global _coin, _AskPrices
  99. if fetch == True:
  100. askPrice = client.get_ticker(_coin + _basecoin)["askPrice"]
  101. else:
  102. askPrice = 0.00000000
  103. for index, item in enumerate(_AskPrices):
  104. if item["coin"] == _coin :
  105. askPrice = item["price"]
  106. break
  107. calc = balance / float(askPrice)
  108. return math.trunc(calc)
  109.  
  110. # MARKET BUY - Buy everything! Param: Basecoin balance
  111. def buy(balance):
  112. global _coin
  113. buyQuantity = getBuyQuantity(balance, False)
  114. while (1):
  115. print(buyQuantity)
  116. break # FIX HERE BEFORE RUNNING LIVE!
  117. # order = client.buy_market(_coin + _basecoin, buyQuantity)
  118.  
  119. print ("[%0.2f] __ORDER(buy):" % (getTime()))
  120. print (order)
  121.  
  122. if order['status'] == "FILLED":
  123. print ("[%0.2f] ____Order(buy) FILLED. Done." % (getTime()))
  124. print
  125. break
  126. else:
  127. print ("[%0.2f] ____Order(buy) NOT FILLED..." % (getTime()))
  128. try:
  129. print( client.cancel(_coin + _basecoin, order['orderId']) )
  130. except Exception as e:
  131. print(e)
  132. buyQuantity = getBuyQuantity(balance, True)
  133.  
  134. # MARKET SELL - Sell everything! Param: Quantity to sell (initially)
  135. def sell():
  136. global _coin, _sellQuantity
  137. while (1):
  138. order = client.sell_market(_coin + _basecoin, _sellQuantity)
  139. print ("[%0.2f] __ORDER(sell):" % (getTime()))
  140. print (order)
  141.  
  142. if order['status'] == "FILLED":
  143. print ("[%0.2f] ____Order(sell) FILLED. Done." % (getTime()))
  144. print
  145. break
  146. else:
  147. print ("[%0.2f] ____Order(sell) NOT FILLED..." % (getTime()))
  148. try:
  149. print ( client.cancel(_coin + _basecoin, order['orderId']) )
  150. except Exception as e:
  151. print(e)
  152. _sellQuantity = math.trunc(getBalance(_coin))
  153.  
  154. # Thread
  155. def getValueTicker():
  156. global _coin, _value, _getValueRunning, _getValueTickerReady
  157. while(_getValueRunning == True):
  158. try:
  159. _value = float(client.get_ticker(_coin + _basecoin)["lastPrice"])
  160. _getValueTickerReady = True # Replace with Mutex/Conditionals
  161. except Exception as e:
  162. print(e)
  163. time.sleep(2)
  164. break
  165. return True
  166.  
  167. # Thread
  168. def setSellQuantityAndSaveFile():
  169. global _coin, _sellQuantity, _file, _AskPrices
  170. _sellQuantity = math.trunc(getBalance(_coin)) # Update Sell Quantity
  171.  
  172. with open(_file, 'w') as outfile: # Save _AskPrices -> coins.json
  173. json.dump(_AskPrices, outfile)
  174.  
  175. return True
  176.  
  177. # 100: 150, 13.34 (CRASHED)
  178. # 30: 150, 15.22
  179. # 20: 150, 17.20
  180. # 15: 150, 17.27 \\ 4 cpu
  181. # 15: 150, 21.14
  182. # 10: 150, 25.84
  183. # 7: 150, 44.53
  184. # 6: 150, 50.48
  185. # 5: 150, 56.45
  186. def StartThreads():
  187. print ("Start Value Ticker Threads :")
  188. global _counter
  189.  
  190. st = threading.Thread(target=setSellQuantityAndSaveFile)
  191. st.start()
  192. print("[%0.2f] %s" % (getTime(), st))
  193.  
  194. for x in range(0, _cores):
  195. t = threading.Thread(target=getValueTicker)
  196. t.start()
  197. print("[%0.2f, %s] %s" % (getTime(), _counter, t))
  198. time.sleep(1.3 / _cores)
  199.  
  200. def StartAskPricesThreads():
  201. print ("Start askPrices Threads :")
  202. global _coinsList, _counter, _AskPrices
  203. for x in range(0, _cores):
  204. startIndex = x * (len(_AskPrices) / _cores)
  205. t = threading.Thread(target=cycleAllAskPrices, args=(startIndex, ))
  206. # t.setDaemon(True)
  207. t.start()
  208. print("[%0.2f, %s] %s" % (getTime(), _counter, t))
  209.  
  210. def testPing():
  211. sTime = time.time()
  212. query = client.get_ticker("TRX" + _basecoin)["askPrice"]
  213. eTime = time.time()
  214. return eTime - sTime
  215.  
  216. def main():
  217. print ("\n\n---- Welcome to PnDBot by AU overspringshandling ----")
  218. print ("---- Basecoin: %s" % (_basecoin))
  219. print ("---- Percent Fall: %s%%" % (_percentFall))
  220. print ("---- Ticker threads: %i" % (_cores))
  221.  
  222. # Setup
  223. global _coin, _startTime, _value, _sellQuantity, _getValueRunning, _getValueTickerReady, _coinsList, _counter, _cycleAllAskPricesRunning, _AskPrices
  224. loadCoinsList()
  225. print("---- Coins on market: %i" % (len(_AskPrices)))
  226. balance = getBalance(_basecoin)
  227. preValue = 0.00000001
  228. _value = 0.00000001
  229. _sellQuantity = 0
  230. _getValueRunning = True
  231. _getValueTickerReady = False
  232.  
  233. pingTime = testPing()
  234. print(pingTime)
  235. print("\nWait until minimum %s seconds before pump starts. Then press ENTER..." % (len(_AskPrices) / _cores) * 2)
  236. input()
  237. test = raw_input()
  238.  
  239. _cycleAllAskPricesRunning = True
  240. StartAskPricesThreads()
  241.  
  242. # Waiting for user input
  243. if len(_coin) < 1:
  244. print ("\nEnter target coin: ")
  245. _coin = raw_input().strip().upper()
  246.  
  247. # Start the time!
  248. _startTime = time.time()
  249.  
  250. _cycleAllAskPricesRunning = False
  251.  
  252. # BUY!
  253. buy(balance)
  254. print
  255.  
  256. # Starting threads
  257. StartThreads()
  258.  
  259. # Wait for a _value to be ready
  260. while (_getValueTickerReady == False):
  261. time.sleep(0.05)
  262. preValue = _value
  263.  
  264. while (1) :
  265. _counter = _counter + 1
  266. while (_getValueTickerReady == False):
  267. time.sleep(0.05)
  268. _getValueTickerReady = False
  269.  
  270. threshhold = preValue - (preValue * _percentFall / 100)
  271. unitToAction = threshhold - _value
  272. percentToAction = 100 - _value / threshhold * 100
  273.  
  274. print ("[%0.2f, %s] %s: %0.8f ||| Threshh.: %0.8f || To action: %0.8f | %0.5f%%" % (getTime(), _counter, _coin + _basecoin, _value, threshhold, unitToAction, percentToAction))
  275.  
  276. if threshhold > _value :
  277. sell()
  278. break
  279. elif _value > (preValue + (preValue * _percentFall/5 / 100)) :
  280. preValue = _value
  281. _getValueRunning = False
  282.  
  283. print ("\n[%0.2f, %s] Done. Balances:" % (getTime(), _counter))
  284.  
  285. getBalance(_basecoin)
  286. getBalance(_coin)
  287.  
  288.  
  289.  
  290. if __name__ == "__main__":
  291. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement