def get_lending_balance(investor, currency=None): p = poloniex(investor.apikey.encode("utf8"), investor.apisecret.encode("utf8")) ret = p.api_query("returnAvailableAccountBalances") if not isinstance(ret, dict): return Decimal(0) if currency: return Decimal(ret.get("lending", {}).get(currency, 0)) return ret.get("lending", {})
def main(argv): period = 10 #pair = "BTC_USDT" #pair = "BTC_XMR" try: opts, args = getopt.getopt(argv, "hp:c:n:s:e:", ["period=", "currency="]) except getopt.GetoptError: print("trading-bot.py -p <period length> -c <currency pair>") sys.exit(2) for opt, arg in opts: if opt == '-h': print("trading-bot.py -p <period length> -c <currency pair>") sys.exit() elif opt in ("-p", "--period"): if (int(arg) in [300, 900, 1800, 7200, 14400, 86400]): period = arg else: print( "Poloniex requires periods in 300,900,1800,7200,14400, or 86400 second increments" ) sys.exit(2) elif opt in ("-c", "--currency"): pair = arg conn = poloniex("key pub to modify", "key private to modify") while True: currentValues = conn.api_query("returnTicker") lastPairPrice = currentValues[pair]["last"] dataDate = datetime.datetime.now() print("{:%Y-%m-%d %H:%M:%S}".format(datetime.datetime.now()) + " Period: %ss %s: %s" % (period, pair, lastPairPrice)) time.sleep(int(period))
def get_lending_history(investor, currency=None): p = poloniex(investor.apikey.encode("utf8"), investor.apisecret.encode("utf8")) ret = p.api_query("returnLendingHistory", {"limit": 500}) if not isinstance(ret, list): return [] if currency: return [l for l in ret if l.get("currency", []) == currency] return ret
def __init__(self, exchange, pair, period, backtest=True): self.pair = pair self.period = period self.startTime = 1491048000 self.endTime = 1491591200 self.data = [] if (exchange == "poloniex"): self.conn = poloniex('key goes here', 'Secret goes here') if backtest: self.data = self.conn.api_query( "returnChartData", { "currencyPair": self.pair, "start": self.startTime, "end": self.endTime, "period": self.period }) if (exchange == "bittrex"): if backtest: url = "https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName=" + self.pair + "&tickInterval=" + self.period + "&_=" + str( self.startTime) response = urllib.urlopen(url) rawdata = json.loads(response.read()) self.data = rawdata["result"]
def get_lending_offers(investor, currency=None): p = poloniex(investor.apikey.encode("utf8"), investor.apisecret.encode("utf8")) ret = p.api_query("returnOpenLoanOffers") if not isinstance(ret, dict): return {} if currency: return [l for l in ret if l.get("currency", []) == currency] return ret
def get_ticker(creds = POLONIEX_CREDENTIALS): """ Returns poloniex ticker dict. """ pol = poloniex(creds) pol_ticker = pol.returnTicker() return pol_ticker
def __init__(self, exchange, pair, period, start_time=False, endTime=False, backtest=True): self.pair = pair self.period = period if backtest: self.start_time = tt.TimetoFloat(start_time) self.endTime = tt.TimetoFloat(endTime) self.compteur = 0 self.data = [] if (exchange == "poloniex"): self.conn = poloniex('key goes here','Secret goes here') if backtest: poloData = self.conn.api_query("returnChartData",{"currencyPair":self.pair,"start":self.start_time,"end":self.endTime,"period":self.period}) for datum in poloData: if (datum['open'] and datum['close'] and datum['high'] and datum['low']): self.data.append(BotCandlestick(self.period,datum['open'],datum['close'],datum['high'],datum['low'],self.start_time+self.compteur*self.period,datum['weightedAverage'])) self.compteur += 1 if (exchange == "bittrex"): if backtest: url = "https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName="+self.pair+"&tickInterval="+str(self.period)+"&_="+str(self.start_time) response = urlopen(url) rawdata = json.loads(response.read()) self.data = rawdata["result"]
def __init__(self, dateOpen, type, pair, currentPrice, amount, stopLoss, targetPrice, backtest, output): self.output = output self.status = "OPEN" self.type = type self.pair = pair self.exitType = "" self.backtest = backtest self.dateOpen = dateOpen self.dateClosed = "" self.entryPrice = currentPrice self.exitPrice = "" self.profit = 0 self.fees = amount * 0.0025 self.quantity = round(amount / currentPrice, 3) if self.backtest == "live": config = configparser.ConfigParser() config.sections() config.read('config.ini') self.conn = poloniex(config['Default']['apikey'], config['Default']['apisecret']) self.output.log("Trade opened " + self.type) orderNumber = self.conn.buy(self.pair, currentPrice*1.0005, self.quantity) self.stopLoss = currentPrice * (1-stopLoss) self.targetPrice = currentPrice * (1+targetPrice)
def __init__(self, pair, period, endTime, startTime, backtest=True): self.pair = pair self.period = period self.endTime = endTime self.startTime = startTime self.data = [] self.conn = poloniex('key goes here', 'Secret goes here') if backtest: poloData = self.conn.api_query( "returnChartData", { "currencyPair": self.pair, "start": self.startTime - 12 * 900, "end": self.endTime, "period": self.period }) for datum in poloData: if datum['open'] and datum['close'] and datum[ 'high'] and datum['low'] and datum['date']: self.data.append( BotCandlestick(self.period, datum['open'], datum['close'], datum['high'], datum['low'], datum['weightedAverage'], datum['date']))
def poloniex_server(): # [email protected] API_KEY = '...' SECRET_KEY = '...' return poloniex(API_KEY, SECRET_KEY)
def selldef(curr, amount_curr, den): rate = json.load(urllib2.urlopen(pt))['BTC_' + curr]['last'] time.sleep(delay) Order = poloniex.sell(poloniex(api, sec), 'BTC_' + curr, str(float(rate) + minVal), str(amount_curr)) time.sleep(delay) wait(Order['orderNumber'], curr, amount_curr, den, False)
def job(): conn = None try: params = config() conn = psycopg2.connect(**params) configs = config_all(filename='api_config.ini') for name in configs: account_id = get_account_id(conn, name) if account_id: if 'key' in configs[name].keys( ) and 'secret' in configs[name].keys(): p = poloniex(configs[name]['key'], configs[name]['secret']) data = p.return_complete_balances() write_json_data(conn, data, account_id) else: raise Exception( 'Error', 'Can not find key or secret for [' + name + '] in api_config.ini') except (Exception) as error: print(error) finally: if conn is not None: conn.close()
def __init__(self, creds = "poloniex_cred.json"): super(Poloniex, self).__init__() self._pol = poloniex.poloniex(creds) try: self._pol_ticker = self._pol.returnTicker() except: raise PriceSourceError("Error getting Poloniex ticker") self._pol_ticker_ts = time.time() self._lock = threading.RLock()
def __init__(self): self.pair = "BTC_REP" self.period = 300 self.endTime = time.time() self.startTime = self.endTime - 3600 * 2 self.data = [] self.prices = [] self.conn = poloniex('key goes here', 'Secret goes here')
def __init__(self, exchange, pair, period): self.conn = poloniex('key goes here','key goes here') self.pair = pair self.period = period self.startTime = 1491048000 self.endTime = 1491591200 self.data = self.conn.api_query("returnChartData",{"currencyPair":self.pair,"start":self.startTime,"end":self.endTime,"period":self.period})
def get_lending_active(investor, currency=None): p = poloniex(investor.apikey.encode("utf8"), investor.apisecret.encode("utf8")) ret = p.api_query("returnActiveLoans") if not isinstance(ret, dict): return [] if currency: return [ l for l in ret.get("provided", []) if l.get("currency") == currency ] return ret.get("provided", [])
def poloniex_server(): # select which account to use, options: # 'account1' aka [email protected] # 'account2' aka [email protected] account = 'account1' data = json.load(open('../../api_keys.json', 'r')) api_key = data[account]['api_key'] secret_key = data[account]['secret_key'] return poloniex(api_key, secret_key)
def buydef(curr, amount_curr, den): print(str(type(curr)) + ' ' + str(curr)) print(str(type(amount_curr)) + ' ' + str(amount_curr)) print(str(type(den)) + ' ' + str(den)) rate = json.load(urllib2.urlopen(pt))['BTC_' + curr]['last'] print(rate) time.sleep(delay) Order = poloniex.buy(poloniex(api, sec), 'BTC_' + curr, str(float(rate) - minVal), str(amount_curr)) time.sleep(delay) print(Order['orderNumber']) time.sleep(delay) wait(Order['orderNumber'], curr, amount_curr, den, True)
def Connection(self): counter = 0 while True: try: print('Trying connection') conn = poloniex(self.username, self.password) return conn except: wait(1) counter += 1 pass if counter == 10: print('fail connection please try again') break
def wait(orderNumber, curr, amount_curr, den, isBuy): tlapse = 0 OpenOrders = poloniex.returnOpenOrders(poloniex(api, sec), 'BTC_' + curr) time.sleep(delay) while OpenOrders != []: # [] if no open orders if tlapse > 30: # cancel order print('cancel') poloniex.cancel(poloniex(api, sec), 'BTC_' + str(curr), orderNumber) if isBuy == True: print('rebuy') buydef(curr, amount_curr, den) else: print('resell') selldef(curr, amount_curr, den) time.sleep(delay) else: print('t:' + str(tlapse)) time.sleep(delay) tlapse += 1 OpenOrders = poloniex.returnOpenOrders(poloniex(api, sec), 'BTC_' + str(curr))
def main(): ''' Main function. Parses command line args and starts a history run or live ticker. ''' variables = init_variables() parser = argparse.ArgumentParser( description="Cryptobot for poloniex, written by Adrian Larkeryd, 2017") parser.add_argument( "-p", "--pair", help="cryptocurrency pair, USDT_BTC, BTC_ETH or BTC_LTC ... etc etc", default="USDT_BTC") parser.add_argument( "--history", help= "run a history test, takes two epoch time stamps as parameters: --history 1501542000 " + str(int(time.time())), nargs=2, type=int) parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() if args.verbose: print args variables['pair'] = args.pair polo = poloniex(adrlar_key, adrlar_secret) if args.history: history_run(args.history[0], args.history[1], polo, variables, model_secondbot) else: print "Setting up with 200 data points in all timeframes..." t_tmp = time.time() variables = live_setup(polo, variables, model_secondbot) print "It took {}s to gather the historical data and crunch the numbers".format( round(time.time() - t_tmp, 2)) print "\nGOING LIVE!" # Start ticker variables['live'] = True #print len(variables[300]['all_dates']), len(variables[300]['all_score']), len(variables[300]['all_candles']), len(variables[300]['all_close_prices']), len(variables[300]['all_rsi']) ticker(polo, variables, model_secondbot)
def __init__(self, exchange, pair, period, backtest, output, startTime=1483228800, endTime=1514764800): self.exchange = exchange self.pair = pair self.period = period self.startTime = startTime # 01 JAN 2017 #self.startTime = 1504224000 # 01 SEP 2017 #self.endTime = 1506729600 # 30 SEP 2017 self.endTime = endTime # 1 Jan 2018 self.data = [] if (self.exchange == "poloniex"): self.conn = poloniex('key goes here', 'Secret goes here') if backtest in ["backtest", "warm"]: data = self.conn.api_query( "returnChartData", { "currencyPair": self.pair, "start": self.startTime, "end": self.endTime, "period": self.period }) #data = json.loads(open("./data/btc-usd-data.json", "r").readline()) for d in data: if (d['open'] and d['close'] and d['high'] and d['low']): self.data.append( BotCandlestick(output, d['date'], self.period, d['open'], d['close'], d['high'], d['low'], d['weightedAverage'])) if (self.exchange == "bittrex"): if backtest == "backtest": url = "https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName=" + self.pair + "&tickInterval=" + self.period + "&_=" + str( self.startTime) response = requests.get(url) rawdata = response.json() self.data = rawdata["result"]
def __init__(self, daemons, credentials): self.daemons=daemons self.out={} self.api={} for i, exch in enumerate(credentials): if (exch=="cryptsy"): self.api[exch]=PyCryptsy(str(credentials[exch]["pubkey"]), str(credentials[exch]["privkey"])) elif (exch=="bittrex"): self.api[exch]=Bittrex.Bittrex(str(credentials[exch]["pubkey"]), str(credentials[exch]["privkey"])) elif (exch=="c-cex"): self.api[exch]=PyCCEX(str(credentials[exch]["key"])) elif (exch=="cryptopia"): self.api[exch]=PyCryptopia() elif (exch=="poloniex"): self.api[exch]=poloniex(str(credentials[exch]["key"]), str(credentials[exch]["secret"])) elif (exch=="bleutrade"): self.api[exch]=bleuBot(str(credentials[exch]["key"]), str(credentials[exch]["secret"])) else: raise ValueError("unknown exchange")
def main(argv): period = 10 ## Run the script once every 10 seconds pair = "BTC_XRP" # # Get the arguments/options from the command line try: opts, args = getopt.getopt(argv, "hp:", ["period="]) except getopt.GetoptError: print('Please try\t\t trading-bot.py -p <period length>') sys.exit(2) # Handle the various options from the command line of the program for opt, arg in opts: # Command for getting the help options if opt == '-h': print('trading-bot.py -p <period length>') sys.exit() # Command for getting the period option elif opt in ("-p", "--period"): if (int(arg) in [300, 900, 1800, 7200, 14400, 86400]): period = arg else: print( 'Poloniex requires periods in 300,900,1800,7200,14400, or 86400 second increments' ) sys.exit(2) elif opt in ("-c", "--currency"): pair = arg conn = poloniex('keys go here', 'keys go here') while True: currVals = conn.api_query("returnTicker") lastPrice = currVals[pair]["last"] print() print("{:%Y-%m-%d %H:%M:%S}".format(datetime.datetime.now()) + " Period:%ss %s: %s" % (period, pair, lastPrice)) time.sleep(int(period))
def __init__(self, exchange, pair, period, backtest=True): self.pair = pair self.period = period # hard coded self.startTime = 1491048000 self.endTime = 1491591200 # where weare going to save the historical data self.data = [] # poloniex if (exchange == "poloniex"): self.conn = poloniex('key goes here', 'Secret goes here') if backtest: poloData = self.conn.api_query( "returnChartData", { "currencyPair": self.pair, "start": self.startTime, "end": self.endTime, "period": self.period }) for datum in poloData: if (datum['open'] and datum['close'] and datum['high'] and datum['low']): #se il dato non c e mette tutto a zero! se uno e zero non lo considero altrimenti lo aggiungo self.data.append( BotCandlestick(self.period, datum['open'], datum['close'], datum['high'], datum['low'], datum['weightedAverage'])) # bittrex if (exchange == "bittrex"): if backtest: url = "https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName=" + self.pair + "&tickInterval=" + self.period + "&_=" + str( self.startTime) response = urllib.urlopen(url) rawdata = json.loads(response.read()) self.data = rawdata["result"]
def make_lending_offer(investor, currency, amount, rate, duration, strategy, autoRenew=1): p = poloniex(investor.apikey.encode("utf8"), investor.apisecret.encode("utf8")) data = { "currency": currency, "amount": amount, "lendingRate": rate, "duration": duration, "autoRenew": autoRenew } print data ret = p.api_query("createLoanOffer", data) print ret if not isinstance(ret, dict): return 0 return ret.get("orderID", 0)
def __init__(self, exchange, pair, period, backtest=True): self.pair = pair self.period = period self.startTime = 1526500085 self.endTime = 1526502085 self.data = [] if (exchange == "poloniex"): self.conn = poloniex( '5NTVQ4P4-AIUEPN28-E57OXVUV-7C19OZCJ', 'b4182fec0b5c578563b6ebe9367c41d6609e06af8ef2960f0159a5338980e426ed3939c9e53f9afbcf3be279f26eb3a800da2c6b785dd2680764be16ee523323' ) if backtest: poloData = self.conn.api_query( "returnChartData", { "currencyPair": self.pair, "start": self.startTime, "end": self.endTime, "period": self.period }) for datum in poloData: if (datum['open'] and datum['close'] and datum['high'] and datum['low']): self.data.append( BotCandlestick(self.period, datum['open'], datum['close'], datum['high'], datum['low'], datum['weightedAverage'])) if (exchange == "bittrex"): if backtest: url = "https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName=" + self.pair + "&tickInterval=" + self.period + "&_=" + str( self.startTime) response = urllib.urlopen(url) rawdata = json.loads(response.read()) self.data = rawdata["result"]
def __init__(self, poloapicreds=['', ''], bittrexapicreds=['', '']): print( "Initializing Crypto Commander, Intelligent and Responsive Crypto-Currency Platform..." ) print( "Disclaimer!! You have launched this via command line, great caution is advised and the developers are NOT responsible for proper usage or lost coins!" ) print( "Notice - :: :: Bitcoin & Crypto-Currencies are largely untested and come with no assurances! Trade with care. :: ::" ) if poloapicreds == ['', '']: print( "No poloniex credentials found, skipping initialization. This may cause instability!" ) else: try: self.poloniexBot = poloniex(poloapicreds[0], poloapicreds[1]) self.btcBalance, self.btsBalance, self.clamBalance, self.dashBalance, self.dogeBalance, self.ethBalance, self.fctBalance, self.ltcBalance, self.maidBalance, self.strBalance, self.xmrBalance, self.xrpBalance, = Decimal( 0.0), Decimal(0.0), Decimal(0.0), Decimal(0.0), Decimal( 0.0), Decimal(0.0), Decimal(0.0), Decimal( 0.0), Decimal(0.0), Decimal(0.0), Decimal( 0.0), Decimal(0.0) except AttributeError: print( "An error occurred trying to initialize Poloniex functionality." ) if bittrexapicreds == ['', '']: print( "No bittrex credentials detected, skipping initialization. This may cause instability!" ) else: try: self.bittrexBot = Bittrex(bittrexapicreds[0], bittrexapicreds[1]) except AttributeError: print( "An error occurred trying to initialized Bittrex functionality." )
def start_apis(): keys = {} with open('keys.csv', 'rb') as csvfile: r = csv.reader(csvfile) i = 0 a = [] for row in r: if i == 0: a = row else: keys[row[0]] = {} dic = keys[row[0]] for col in range(1, len(row)): if col != "": dic[a[col]] = row[col] i += 1 c = keys["cex"] capi = cex.cex(c["username"], c["public key"], c["private key"]) capi.INDEX = 0 if (capi.balance().has_key('username')): print(s.SUCCESS + "Connected to CEX.io") else: print(s.ERROR + "Unable to connected to CEX.io") p = keys["poloniex"] papi = pol.poloniex(p["public key"], p["private key"]) papi.INDEX = 1 if (papi.returnBalances().has_key('BTC')): print(s.SUCCESS + "Connected to Poloniex") else: print(s.ERROR + "Unable to connected to Poloniex") context = (capi, papi) return context
def __init__(self, daemons, credentials): self.daemons = daemons self.out = {} self.api = {} for i, exch in enumerate(credentials): if (exch == "cryptsy"): self.api[exch] = PyCryptsy(str(credentials[exch]["pubkey"]), str(credentials[exch]["privkey"])) elif (exch == "bittrex"): self.api[exch] = Bittrex.Bittrex( str(credentials[exch]["pubkey"]), str(credentials[exch]["privkey"])) elif (exch == "c-cex"): self.api[exch] = PyCCEX(str(credentials[exch]["key"])) elif (exch == "cryptopia"): self.api[exch] = PyCryptopia() elif (exch == "poloniex"): self.api[exch] = poloniex(str(credentials[exch]["key"]), str(credentials[exch]["secret"])) elif (exch == "bleutrade"): self.api[exch] = bleuBot(str(credentials[exch]["key"]), str(credentials[exch]["secret"])) else: raise ValueError("unknown exchange")
def start_apis(): keys = {} with open('keys.csv', 'rb') as csvfile: r = csv.reader(csvfile) i = 0 a = [] for row in r: if i == 0: a = row else: keys[row[0]] = {} dic = keys[row[0]] for col in range(1,len(row)): if col != "": dic[a[col]] = row[col] i += 1 c = keys["cex"] capi = cex.cex(c["username"],c["public key"],c["private key"]) capi.INDEX = 0 if(capi.balance().has_key('username')): print(s.SUCCESS + "Connected to CEX.io") else: print(s.ERROR + "Unable to connected to CEX.io") p = keys["poloniex"] papi = pol.poloniex(p["public key"],p["private key"]) papi.INDEX = 1 if(papi.returnBalances().has_key('BTC')): print(s.SUCCESS + "Connected to Poloniex") else: print(s.ERROR + "Unable to connected to Poloniex") context = (capi,papi) return context
def poloniex_server(): API_KEY = '...' SECRET_KEY = '...' return poloniex(API_KEY, SECRET_KEY)
def main(argv): period = 10 pair = "BTC_XMR" prices = [] currentMovingAverage = 0 lengthOfMA = 0 startTime = False endTime = False historicalData = False tradePlaced = False typeOfTrade = False dataDate = "" orderNumber = "" dataPoints = [] localMax = [] currentResistance = 0.018 try: opts, args = getopt.getopt(argv, "hp:c:n:s:e", ["period=", "currency=", "points="]) except getopt.GetoptError: print("Trading_bot.py -p <period> -c <currency pair> -n <period of moving average>") sys.exit(2) for opt, arg in opts: if opt == "-h": print("Trading_bot.py -p <period> -c <currency pair> -n <period of moving average>") sys.exit() elif opt in ("-p", "--period"): if int(arg) in [10, 300, 900, 1800, 7200, 14400, 86400]: # in seconds period = arg else: print("Poloniex requires periods in 10, 300, 900, 1800, 7200, 14400 or 86400 second increments") sys.exit(2) elif opt in ("-c", "--currency"): pair = arg elif opt in ("-n", "--points"): lengthOfMA = int(arg) elif opt in ("-s"): startTime = arg elif opt in ("-e"): endTime = arg conn = poloniex("keys go here", "keys go here") # get api keys through account output = open("output.html", "w") output.truncate() output.write("""<html><head><script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script><script type="text/javascript">google.charts.load('current', {'packages':['corechart']});google.charts.setOnLoadCallback(drawChart);function drawChart() {var data = new google.visualization.DataTable();data.addColumn('string', 'time');data.addColumn('number', 'value') ;data.addColumn({type: 'string', role:'annotation'});data.addColumn({type: 'string', role:'annotationText'});data.addColumn('number', 'trend');data.addRows([""") if (startTime): historicalData = conn.api_query("returnChartData", {"currencyPair": pair, "start": startTime, "end": endTime, "period": period}) while True: if startTime and historicalData: nextDataPoint = historicalData.pop(0) lastPairPrice = nextDataPoint["weightedAverage"] dataDate = datetime.datetime.fromtimestamp(int(nextDataPoint["Date"])).strftime("%Y-%m-%d %H:%M:%S") elif startTime and not historicalData: for point in dataPoints: output.write(+ point["date"] + ", " + point["price"] + ", " + point["label"] + ", " + point["desc"] + ", " + point["trend"]) output.write("], \n") output.write("""]); var options = { title: "Price Chart", legend: {position: "bottom"} }; var chart = new google.visualization.LineChart(document.getElementById("curve_chart")); chart.draw(data, options);}</script></head><body><div id="curve_chart" style="width: 100%; height: 100%"></div></body></html>""") exit() else: currentValues = conn.api_query("returnTicker") lastPairPrice = currentValues[pair]["last"] dataDate = datetime.datetime.now() dataPoints.append({ "date": datetime, "price": str(lastPairPrice), "trend": str(currentResistance), "label": "null", "desc": "null" }) if len(dataPoints) > 2 and dataPoints[-2]["price"] > dataPoints[-1]["price"] and dataPoints[-2]["price"] > dataPoints[-3]["price"]: dataPoints[-2]["label"] = "'MAX'" dataPoints[-2]["desc"] = "'This is a local maximum'" numberOfSimilarLocalMaxes = 0 for oldMax in localMax: if float(oldMax) > float(dataPoints[-2]["price"]) - 0.0001 and float(oldMax) < float(dataPoints[-2]["price"]) + 0.0001: numberOfSimilarLocalMaxes += 1 if numberOfSimilarLocalMaxes > 2: currentResistance = dataPoints[-2]["price"] dataPoints[-2]["trend"] = dataPoints[-2]["price"] dataPoints[-1]["trend"] = dataPoints[-2]["trend"] localMax.append(dataPoints[-2]["price"]) if len(prices) > 0: currentMovingAverage = sum(prices) / float(len(prices)) previousPrice = prices[-1] if not tradePlaced: if lastPairPrice > currentMovingAverage and lastPairPrice < previousPrice: print("SELL ORDER") orderNumber = conn.sell(pair, lastPairPrice, 0.01) tradePlaced = True typeOfTrade = "short" elif lastPairPrice < currentMovingAverage and lastPairPrice > previousPrice: print("BUY ORDER") orderNumber = conn.buy(pair, lastPairPrice, 0.01) tradePlaced = True typeOfTrade = "long" elif typeOfTrade == "short": if lastPairPrice < currentMovingAverage: print("EXIT TRADE") conn.cancel(pair, orderNumber) tradePlaced = False typeOfTrade = False elif typeOfTrade == "long": if lastPairPrice > currentMovingAverage: print("EXIT TRADE") conn.cancel(pair, orderNumber) tradePlaced = False typeOfTrade = False else: previousPrice = 0 print("%s Period: %ss %s: %s Moving Average: %s" % (dataDate, period, pair, lastPairPrice, currentMovingAverage)) prices.append(float(lastPairPrice)) prices = prices[-lengthOfMA:] if not startTime: time.sleep(int(period))
def __init__(self): self.Poloniex = poloniex("", "") self.Bittrex = bittrex("", "") self.Mintpal = mintpal("", "")
#!/usr/bin/env python import poloniex, sys, json, time p = poloniex.poloniex('put your API key here', 'put your API secret here') def turnOffAutoRenew(): for loan in p.returnActiveLoans()['provided']: if loan['autoRenew']: id = loan['id'] print id, p.toggleAutoRenew(id) def turnOnAutoRenew(): for loan in p.returnActiveLoans()['provided']: if not loan['autoRenew']: id = loan['id'] print id, p.toggleAutoRenew(id) def pp(x): print json.dumps(x, indent = 2) # print p.returnAvailableAccountBalances() # th = p.returnTradeHistory("BTC_CLAM", 1455482888, 1455569288) # pp(th) def usage(): print "on off bal hist newaddr wd" if len(sys.argv) < 2: usage() elif sys.argv[1] == 'on':
def __init__(self): self.Poloniex = poloniex("","") self.Bittrex = bittrex("", "") self.Mintpal = mintpal("", "")
apiKeysIndex = int(sys.argv[1]) if sys.argv[2] == 'tunning' : market = sys.argv[3] if sys.argv[4] == 'auto': getBestParams(market=market, shortFrom=50, shortTo=280, shortDelta=5, longTo=5000, longDelta=8) else: shortFrom = int(sys.argv[4]) shortTo = int(sys.argv[5]) shortDelta = int(sys.argv[6]) longTo = int(sys.argv[6]) longDelta = int(sys.argv[7]) getBestParams(market=market, shortFrom=shortFrom, shortTo=shortTo, shortDelta=shortDelta, longTo=longTo, longDelta=longDelta) else: market = sys.argv[2] shortEMALength = int(sys.argv[3]) longEMALength = int(sys.argv[4]) # print sys.argv pol = poloniex.poloniex(credentials.credentials.apikeys[apiKeysIndex],credentials.credentials.secrets[apiKeysIndex]) tradeLoop(market=market, shortEMALength=shortEMALength, longEMALength=longEMALength) # tradeLoop(market='BTC_IOC', shortEMALength=265, longEMALength=1781) # getBestParams('BTC_ETH') # getBestParams(market='BTC_IOC', shortFrom=50, shortTo=280, shortDelta=5, longTo=2000, longDelta=8) # tradeLoop(market='BTC_ETH', shortEMALength=159, longEMALength=1156)