def __init__(self): self.name = 'POLONIEX' self.public_api = poloniex.Poloniex() self.private_api = poloniex.Poloniex(config_key.poloniex_api_key, config_key.poloniex_secret_key) # This is the taker fee for a 30 day volume of <600BTC # in this arbitrage strategy we do not make orders, only fill(take) existing ones thus we apply the taker fee self.trading_fee = 0.25
def test_coach_existance(self): self.polo = poloniex.Poloniex() # coach is created by default self.assertTrue(isinstance(self.polo.coach, poloniex.Coach)) # remove coach self.polo = poloniex.Poloniex(coach=False) self.assertFalse(self.polo.coach) # coach injection myCoach = poloniex.Coach() self.polo = poloniex.Poloniex(coach=myCoach) self.polo2 = poloniex.Poloniex(coach=myCoach) self.assertTrue(self.polo.coach is self.polo2.coach)
def poloUpdate(): usd_eur = CurrencyRates().get_rates('USD')['EUR'] client = poloniex.Poloniex(apikey=apikey, secret=secret) coins = defaultdict(float) for name, amount in client.returnBalances().items(): if amount != .0: coins[name] += amount combinedValue = .0 prices = client.returnTicker() btc_value = prices['USDT_BTC']['last'] * usd_eur data = {} for a in coins: amount = coins[a] if a != 'BTC': price = prices['BTC_' + a]['last'] * btc_value else: price = btc_value value = price * amount data[a] = {'amount': amount, 'price': price, 'value': value} combinedValue += value return { 'marketname': 'Poloniex', 'timestamp': time(), 'value': combinedValue, 'coinData': data }
def main(): # Get currency pairs sorted by 24-hour volume polo = poloniex.Poloniex(timeout=10, coach=True) sorted_tickers = sorted(polo.returnTicker().items(), key=lambda x: float(x[1]['baseVolume']), reverse=True) currency_pairs = [(k, float(v['baseVolume'])) for k, v in sorted_tickers if 'BTC_' in k or k == 'USDT_BTC'] volume_texts = [] for currency_pair, volume_24h in currency_pairs[0:DISPLAY_NUMS]: print("currency_pair={}".format(currency_pair)) volume_texts.append( get_volumes(currency_pair, volume_24h, MINUTES, TICKS)) body = textwrap.dedent(u""" Date : {date} Ticks : {minutes} mins x {ticks} {volume_texts} """).format( date=datetime.now().strftime('%Y/%m/%d %H:%M'), minutes=MINUTES, ticks=TICKS, volume_texts='\n\n'.join(volume_texts), ).strip() print('----------') print(body) print('----------') email_client = EmailClient() # Send an email to myself email_client.send_test_email(u"Poloniex trade volumes", body)
def getExcelData(pair="USDT_BTC", location="", period=day, start=defStart, end=defEnd): polo = poloniex.Poloniex(extend=True) if location == "C:/": print("Saving file to default directory.") btcData = polo.marketChart(pair, day, start, end) print(btcData[0]) outputList = [] for sample in btcData: outStr = sample['high'], sample['low'], sample['open'], sample[ 'close'], sample['volume'] outputList.append(outStr) with open(location + pair + ".csv", 'w') as f: f.write("high, low, open, close, volume, " + str(period) + ", Start: " + unixToDate(start) + ", End: " + unixToDate(end)) f.write("\n") for stringlet in outputList: print(str(stringlet)) outStringlet = str(stringlet).replace("(", "") outStringlet = outStringlet.replace("'", "") outStringlet = outStringlet.replace(")", "") f.write(outStringlet) f.write("\n")
def __init__(self, pair, config): self._client = poloniex.Poloniex() self._pair = pair self._hours_candlestick = config["candlestickhours"] self._period_candlestick = config["candlestickperiod"] self._data_chart = None self._data_ticker = None
def test_method_integrity(self): self.polo = poloniex.Poloniex() for command in poloniex.PUBLIC_COMMANDS: self.assertTrue(hasattr(self.polo, command)) for command in poloniex.PRIVATE_COMMANDS: self.assertTrue(hasattr(self.polo, command)) self.assertTrue(hasattr(self.polo, 'marketTradeHist'))
def return_chart_data(self, pair, period, start_time, end_time): """ retrieve data from poloniex. """ polo = poloniex.Poloniex() chart_data = polo.returnChartData(pair, period=period, start=time.mktime(time.strptime(start_time, "%Y-%m-%d %H:%M")), end=time.mktime(time.strptime(end_time, "%Y-%m-%d %H:%M"))) df = pd.DataFrame(chart_data) df["datetime"] = pd.to_datetime(df["date"].astype(int) , unit="s") df = df.set_index("datetime") fig, ax1 = plt.subplots(figsize=(20, 10)) ax1.plot(df.index, df[self.column].astype(np.float32), label = "Coin Price", color="deeppink") ax2 = ax1.twinx() ax2.plot(df.index, df["quoteVolume"].astype(np.float32), label = "Trading Volume of Coin", color="dodgerblue") ax1.legend(loc=2, fontsize=14) ax2.legend(loc=1, fontsize=14) ax1.tick_params(labelsize=14) ax2.tick_params(labelsize=14) plt.show() self.dataframe = df.loc[:, ["close"]].astype(np.float32)
def setupPoloniex(): file = open("../credentials/james.champ.at.tuta.io.key", "r") key = file.readline()[0:-1] secret = file.readline()[0:-1] file.close() polo = poloniex.Poloniex(key, secret, timeout=10) return polo
def __init__(self, currency, trans_q, holding, configs): super().__init__() self.currency = currency self.trans_q = trans_q self.stoprequest = threading.Event() self.polo = poloniex.Poloniex(configs['poloniex']['key'], configs['poloniex']['secret'], coach=True) self.holding = holding
def gen(coin): import poloniex import api_conf key = str(api_conf.key) secret = str(api_conf.secret) data = poloniex.Poloniex(key, secret) ret = data.generateNewAddress(coin) return ret
def __init__(self, currency, period, hist_length, configs): self.period = period self.hist_length = hist_length self.currency = currency self.deq = None self.polo = poloniex.Poloniex(configs['poloniex']['key'], configs['poloniex']['secret'], coach=True)
def get_open_orders(): api_key, secret = get_key() polo = poloniex.Poloniex(api_key, secret) data = polo.returnOpenOrders() data = filter_open_orders(data) return data
def getDataPoloniex(self): polo = poloniex.Poloniex() polo.timeout = 10 chartUSDT_BTC = polo.returnChartData('USDT_ETH', period=300, start=time.time() - 1440*60 * 500, end=time.time())#1440(min)*60(sec)=DAY tmpDate = [chartUSDT_BTC[i]['date'] for i in range(len(chartUSDT_BTC))] date = [datetime.datetime.fromtimestamp(tmpDate[i]) for i in range(len(tmpDate))] data = [float(chartUSDT_BTC[i]['open']) for i in range(len(chartUSDT_BTC))] return date ,data
def loadChart(price='USDT_BTC', length=365): polo = poloniex.Poloniex() period = polo.DAY # period of data end = time.time() start = end - period * length chart = polo.returnChartData(price, period=period, start=start, end=end) df = DataFrame.from_dict(chart, dtype=float) return df
def __init__(self): self.polo_client = poloniex.Poloniex() data = json.load(open('credentials.json')) self.polo_client.key = data['string sample']['string sample'] self.polo_client.secret = data['string sample']['string sample'] self.binance_api_key = data['string sample']['string sample'] self.binance_api_secret = data['string sample']['string sample'] self.binance_client = Client(self.binance_api_key, self.binance_api_secret)
def __init__(self, mode="BTC"): Market_Adapter.__init__(self, mode) auth = util.get_poloniex_auth() self.client = poloniex.Poloniex(**auth) self.name = "Poloniex" # timeout for buy, sell orders self.timeout = 90 self.retries = 5 self.coin_name_array = util.read_subs_from_file( settings.general["poloniex_file"])
def __init__(self, Key=False, Secret=False, coach=True, timeout=5): self.poloniex = poloniex.Poloniex(Key, Secret, coach, timeout, logging.WARNING, True) # sets extend as true for this script's function choice to work self.MINUTE, self.HOUR, self.DAY, self.WEEK, self.MONTH, self.YEAR = \ 60, 60*60, 60*60*24, 60*60*24*7, 60*60*24*30, 60*60*24*365 if not Key and not Secret: # log print("Key and secret not defined, public commands only.")
def __init__(self, config): if os.path.isfile(config): with open(config) as f: config = json.load(f) self.polo = poloniex.Poloniex(config['key'], config['secret']) self.coins = config['coins'] self.interval = config['interval'] self._running, self._thread = False, None self.openLoanOffers = None self.availBalance = None
def __init__(self): self.exchange = shared.exchange['name'] self.key = shared.api['key'] self.secret = shared.api['secret'] self.output = BotLog() if shared.exchange['name'] == 'poloniex': self.api = poloniex.Poloniex(self.key, self.secret) elif shared.exchange['name'] == 'kraken': self.api = krakenex.API(self.key, self.secret)
def __init__(self, apiKey=None, apiSecret=None): """Init connector.""" self.apiKey = apiKey self.apiSecret = apiSecret myCoach = poloniex.Coach(callLimit=1) self.polo = poloniex.Poloniex(coach=myCoach, key=self.apiKey, secret=self.apiSecret, timeout=180)
def test_PoloniexErrors(self): self.polo = poloniex.Poloniex() # no keys, private command with self.assertRaises(poloniex.PoloniexError): self.polo.returnBalances() # invalid command with self.assertRaises(poloniex.PoloniexError): self.polo('foo') # catch errors returned from poloniex.com with self.assertRaises(poloniex.PoloniexError): self.polo.returnOrderBook(currencyPair='atestfoo')
def __init__(self, APIKey, Secret, dataDir, dataQueue, orderQueue, instructionQueue): self.polo = poloniex.Poloniex(APIKey, Secret) self.dataQueue = dataQueue self.orderQueue = orderQueue self.instructionQueue = instructionQueue self.DATA_DIR = dataDir Thread.__init__(self) self.daemon = True
def get_market_data(candlestick_period = '7200', start = '0', end = time.time()): '''connects to poloniex and gets the chart data ''' polo = poloniex.Poloniex(key,secret,extend=True) market_keys = list(polo.returnOpenOrders('all').keys()) dd={} for x in market_keys: dd[x]=pd.DataFrame(polo.returnChartData(x, period, start, end)).set_index('date') return pd.Panel(dd)
def getMarketDepth(pair="USDT_BTC", printB=False): polo = poloniex.Poloniex(extend=True) orderData = polo.marketOrders(pair, depth=70) # print(orderData) bidArray = np.ndarray([]) for bidOrder in orderData['bids']: price = float(bidOrder[0]) amount = float(bidOrder[1]) print(price, amount) order = np.ndarray([price, amount], shape=(2, 1)) # print(order) assert False np.append(bidArray, order) print(bidArray)
def getCharts(pair): api = poloniex.Poloniex(key,secret,jsonNums=float) raw = api.returnChartData(pair, period=api.DAY, start=time()-api.YEAR*10) #print(raw) df = pd.DataFrame(raw) # adjust dates format and set dates as index df['date'] = pd.to_datetime(df["date"], unit='s') df.set_index('date', inplace=True) # show the end of dataframe print(df.tail())
def gen(): key = str(api_conf.key) secret = str(api_conf.secret) data = poloniex.Poloniex(key, secret) try: x = data.returnAvailableAccountBalances() except: pass else: k = dict.keys(x) for i in k: i = str(i) print(x[i]) #print("\n") return (x)
def construct_random_model(time_period): api = poloniex.Poloniex('', '') test_market = mm.TestMarket(api, 'BTC_ETH', time_period[0].timestamp(), time_period[1].timestamp(), 300) short_window = np.random.randint(1, 20) long_window = np.random.randint(short_window + 1, 100) portfolio = pc.BTC_ETH_MovingAverageCrossover(1000, short_window, long_window, 10, 'weightedAverage') model = em.ExecutionModel(False, test_market, portfolio) return model
def data_extraction(minutes=5, days=100, kind_money='USDT_BCH'): # poloniexのAPI準備 polo = poloniex.Poloniex() # period[分]間隔でdays日分読み込む chart_data = polo.returnChartData(kind_money, period=minutes * 60, start=time.time() - polo.DAY * days, end=time.time()) # pandasにデータの取り込み df = pd.DataFrame(chart_data) return df
def what_to_buy(): polo = poloniex.Poloniex() found = {} for currency_pair in polo.returnTicker(): data = polo.returnChartData(currency_pair, period=300, start=(time.time() - polo.HOUR * 2)) data = convert_to_float(data) found[currency_pair] = find_tree_line_strike(data) if not found[currency_pair]: found[currency_pair] = find_abandoned_baby(data) return found