Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import sys
- import time
- import config
- import argparse
- import math
- import threading
- import json
- # from multiprocessing.pool import ThreadPool
- from BinanceAPI import *
- # sudo date -s "$(wget -qSO- --max-redirect=0 google.com 2>&1 | grep Date: | cut -d' ' -f5-8)Z"
- # python trader.py --basecoin BTC --cores 30 --percentFall 5
- # TODO: Test ticker with API v3.
- # Binance API
- client = BinanceAPI(config.api_key, config.api_secret)
- # Argument list
- parser = argparse.ArgumentParser()
- parser.add_argument("--basecoin", type=str, help="Market Symbol (Ex: ETH)", default="BTC")
- parser.add_argument("--percentFall", type=float, help="% Percent to which the value has to fluncuate before action is taken.", default=5)
- parser.add_argument("--coin", type=str, help="", default="")
- parser.add_argument("--cores", type=int, help="Number of threads to run", default=10)
- option = parser.parse_args()
- # Global vars
- _basecoin = option.basecoin
- _percentFall = option.percentFall
- _cores = option.cores
- _coin = option.coin.strip().upper()
- _getValueRunning = False
- _cycleAllAskPricesRunning = False
- _getValueTickerReady = False
- _startTime = 0
- _counter = 0
- _AskPrices = []
- _file = _basecoin + 'coins.json'
- # Load list of all coins
- def loadCoinsList():
- global _AskPrices, _file
- # Todo: Check if file exists, if not scrape new.
- with open(_file) as coins_file:
- _AskPrices = json.load(coins_file)
- return True # Done
- # /////////////////////////////////
- # Get new list:
- query = client.get_account()["balances"]
- for index, item in enumerate(query):
- if not item["asset"] == _basecoin:
- _AskPrices.append({"coin":item["asset"], "price":0.00000000})
- with open(_file, 'w') as outfile:
- json.dump(_AskPrices, outfile)
- # Thread: Initial scrape all coins askPrice
- def cycleAllAskPrices(startIndex):
- global _AskPrices
- indexo = startIndex
- while(_cycleAllAskPricesRunning == True):
- for index, item in enumerate(_AskPrices):
- if _cycleAllAskPricesRunning == False:
- break
- if indexo - 1 <= index:
- indexo = 0
- try:
- _AskPrices[index]['price'] = client.get_ticker(item["coin"] + _basecoin)["askPrice"]
- except Exception as e:
- print(_AskPrices[index])
- print(e)
- # del _AskPrices[index]
- # Returns seconds since program started.
- def getTime():
- if _startTime == 0:
- return 0
- else:
- return time.time() - _startTime
- # Returns balance of specified coin.
- def getBalance(coin):
- balance = client.get_account()["balances"]
- for index, item in enumerate(balance):
- if item["asset"] == coin :
- print ("[%0.2f] getBalance(%s): %.8f" % (getTime(), coin, float(item["free"])))
- return float(item["free"])
- # Returns quantity of coin to buy.
- def getBuyQuantity(balance, fetch):
- global _coin, _AskPrices
- if fetch == True:
- askPrice = client.get_ticker(_coin + _basecoin)["askPrice"]
- else:
- askPrice = 0.00000000
- for index, item in enumerate(_AskPrices):
- if item["coin"] == _coin :
- askPrice = item["price"]
- break
- calc = balance / float(askPrice)
- return math.trunc(calc)
- # MARKET BUY - Buy everything! Param: Basecoin balance
- def buy(balance):
- global _coin
- buyQuantity = getBuyQuantity(balance, False)
- while (1):
- print(buyQuantity)
- break # FIX HERE BEFORE RUNNING LIVE!
- # order = client.buy_market(_coin + _basecoin, buyQuantity)
- print ("[%0.2f] __ORDER(buy):" % (getTime()))
- print (order)
- if order['status'] == "FILLED":
- print ("[%0.2f] ____Order(buy) FILLED. Done." % (getTime()))
- print
- break
- else:
- print ("[%0.2f] ____Order(buy) NOT FILLED..." % (getTime()))
- try:
- print( client.cancel(_coin + _basecoin, order['orderId']) )
- except Exception as e:
- print(e)
- buyQuantity = getBuyQuantity(balance, True)
- # MARKET SELL - Sell everything! Param: Quantity to sell (initially)
- def sell():
- global _coin, _sellQuantity
- while (1):
- order = client.sell_market(_coin + _basecoin, _sellQuantity)
- print ("[%0.2f] __ORDER(sell):" % (getTime()))
- print (order)
- if order['status'] == "FILLED":
- print ("[%0.2f] ____Order(sell) FILLED. Done." % (getTime()))
- print
- break
- else:
- print ("[%0.2f] ____Order(sell) NOT FILLED..." % (getTime()))
- try:
- print ( client.cancel(_coin + _basecoin, order['orderId']) )
- except Exception as e:
- print(e)
- _sellQuantity = math.trunc(getBalance(_coin))
- # Thread
- def getValueTicker():
- global _coin, _value, _getValueRunning, _getValueTickerReady
- while(_getValueRunning == True):
- try:
- _value = float(client.get_ticker(_coin + _basecoin)["lastPrice"])
- _getValueTickerReady = True # Replace with Mutex/Conditionals
- except Exception as e:
- print(e)
- time.sleep(2)
- break
- return True
- # Thread
- def setSellQuantityAndSaveFile():
- global _coin, _sellQuantity, _file, _AskPrices
- _sellQuantity = math.trunc(getBalance(_coin)) # Update Sell Quantity
- with open(_file, 'w') as outfile: # Save _AskPrices -> coins.json
- json.dump(_AskPrices, outfile)
- return True
- # 100: 150, 13.34 (CRASHED)
- # 30: 150, 15.22
- # 20: 150, 17.20
- # 15: 150, 17.27 \\ 4 cpu
- # 15: 150, 21.14
- # 10: 150, 25.84
- # 7: 150, 44.53
- # 6: 150, 50.48
- # 5: 150, 56.45
- def StartThreads():
- print ("Start Value Ticker Threads :")
- global _counter
- st = threading.Thread(target=setSellQuantityAndSaveFile)
- st.start()
- print("[%0.2f] %s" % (getTime(), st))
- for x in range(0, _cores):
- t = threading.Thread(target=getValueTicker)
- t.start()
- print("[%0.2f, %s] %s" % (getTime(), _counter, t))
- time.sleep(1.3 / _cores)
- def StartAskPricesThreads():
- print ("Start askPrices Threads :")
- global _coinsList, _counter, _AskPrices
- for x in range(0, _cores):
- startIndex = x * (len(_AskPrices) / _cores)
- t = threading.Thread(target=cycleAllAskPrices, args=(startIndex, ))
- # t.setDaemon(True)
- t.start()
- print("[%0.2f, %s] %s" % (getTime(), _counter, t))
- def testPing():
- sTime = time.time()
- query = client.get_ticker("TRX" + _basecoin)["askPrice"]
- eTime = time.time()
- return eTime - sTime
- def main():
- print ("\n\n---- Welcome to PnDBot by AU overspringshandling ----")
- print ("---- Basecoin: %s" % (_basecoin))
- print ("---- Percent Fall: %s%%" % (_percentFall))
- print ("---- Ticker threads: %i" % (_cores))
- # Setup
- global _coin, _startTime, _value, _sellQuantity, _getValueRunning, _getValueTickerReady, _coinsList, _counter, _cycleAllAskPricesRunning, _AskPrices
- loadCoinsList()
- print("---- Coins on market: %i" % (len(_AskPrices)))
- balance = getBalance(_basecoin)
- preValue = 0.00000001
- _value = 0.00000001
- _sellQuantity = 0
- _getValueRunning = True
- _getValueTickerReady = False
- pingTime = testPing()
- print(pingTime)
- print("\nWait until minimum %s seconds before pump starts. Then press ENTER..." % (len(_AskPrices) / _cores) * 2)
- input()
- test = raw_input()
- _cycleAllAskPricesRunning = True
- StartAskPricesThreads()
- # Waiting for user input
- if len(_coin) < 1:
- print ("\nEnter target coin: ")
- _coin = raw_input().strip().upper()
- # Start the time!
- _startTime = time.time()
- _cycleAllAskPricesRunning = False
- # BUY!
- buy(balance)
- print
- # Starting threads
- StartThreads()
- # Wait for a _value to be ready
- while (_getValueTickerReady == False):
- time.sleep(0.05)
- preValue = _value
- while (1) :
- _counter = _counter + 1
- while (_getValueTickerReady == False):
- time.sleep(0.05)
- _getValueTickerReady = False
- threshhold = preValue - (preValue * _percentFall / 100)
- unitToAction = threshhold - _value
- percentToAction = 100 - _value / threshhold * 100
- print ("[%0.2f, %s] %s: %0.8f ||| Threshh.: %0.8f || To action: %0.8f | %0.5f%%" % (getTime(), _counter, _coin + _basecoin, _value, threshhold, unitToAction, percentToAction))
- if threshhold > _value :
- sell()
- break
- elif _value > (preValue + (preValue * _percentFall/5 / 100)) :
- preValue = _value
- _getValueRunning = False
- print ("\n[%0.2f, %s] Done. Balances:" % (getTime(), _counter))
- getBalance(_basecoin)
- getBalance(_coin)
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement