def getPrices(): prices = {} # get cny usd prices['cnyusd'] = huobi_main_monitor.Huobi_Main_Monitor( ).get_cnyusd_bid_price()['rates']['CNY'] # get huobi market prices: sell eth, sell ltc, buy btc. prices['btccny-huobi'] = float( huobi_main_monitor.Huobi_Main_Monitor().get_btccny_ask_price()) prices['ltccny-huobi'] = float( huobi_main_monitor.Huobi_Main_Monitor().get_ltccny_bid_price()) prices['ethcny-huobi'] = float( huobi_eth_monitor.Huobi_ETH_Monitor().getAverageBidsGivenSize(10)[1]) prices['ethbtc-huobi'] = prices['ethcny-huobi'] / prices['btccny-huobi'] prices['ltcbtc-huobi'] = prices['ltccny-huobi'] / prices['btccny-huobi'] # get Poloniex market prices: prices['ethbtc-poloniex'] = float( Poloniex().returnTicker()['BTC_ETH']['lowestAsk']) prices['ltcbtc-poloniex'] = float( Poloniex().returnTicker()['BTC_LTC']['lowestAsk']) # get Coinbase market prices: return prices
def poloniex(market='BTC_STR'): polo = Poloniex() ticket_poloniex = polo.returnTicker()[market] print("Ask : " + FORMAT.format(ticket_poloniex['lowestAsk']) + " Bid : " + FORMAT.format(ticket_poloniex['highestBid'])) return float(ticket_poloniex['lowestAsk']), float( ticket_poloniex['highestBid'])
def __init__(self, coin_code, buy_price, sell_price, stop_loss): self.coin_code = coin_code self.buy_price = buy_price self.sell_price = sell_price self.stop_loss = stop_loss self.polo = Poloniex()
def poloniex_linear_regression(polo_model, lr_model): polo = Poloniex() data_points = polo_model.get_data_points() x = np.asarray([point['date'] for point in data_points]).astype(np.float) y = np.asarray([point['weightedAverage'] for point in data_points]).astype(np.float) x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=1) polo_class = hc.PoloniexData( polo.returnChartData('BTC_ETH', 300, time.time() - 86400, time.time() + 300)) polo_x_test = np.asarray([point['date'] for point in polo_class.get_data_points()]).astype(np.float)\ .reshape((-1, 1)) np.append(polo_x_test, np.add(time.time(), 1800)) polo_y_test = np.asarray([point['weightedAverage'] for point in polo_class.get_data_points()]).astype(np.float)\ .reshape((-1, 1)) x_train = x_train.reshape((-1, 1)) y_train = y_train.reshape((-1, 1)) lr_model.fit(x_train, y_train) predict = lr_model.predict(polo_x_test) return { 'model': lr_model, 'predict': predict, 'x_test': polo_x_test, 'y_test': polo_y_test }
def __init__(self, ex_ev): self.ex_ev = ex_ev self.log = None self.loop = asyncio.new_event_loop() self.polo = Poloniex() self.tickers = [] self.bulk_size = 100
def load_cryptopair(pair, from_dt, to_dt, period=Period.D1): """Load OHLC data on a cryptocurrency pair from Poloniex exchange""" polo = Poloniex() t = timer() if isinstance(period, Period): period = period.value chart_data = polo.returnChartData(pair, period=period, start=dt_to_ts(from_dt), end=dt_to_ts(to_dt)) print("done. %.2fs" % (timer() - t)) chart_df = pd.DataFrame(chart_data) chart_df.set_index('date', drop=True, inplace=True) chart_df.index = pd.to_datetime(chart_df.index, unit='s') chart_df.fillna(method='ffill', inplace=True) # fill gaps forwards chart_df.fillna(method='bfill', inplace=True) # fill gaps backwards chart_df = chart_df.astype(float) chart_df.rename(columns={ 'open': 'O', 'high': 'H', 'low': 'L', 'close': 'C', 'volume': 'V' }, inplace=True) return chart_df[['O', 'H', 'L', 'C', 'V']]
def get_tick(coin): polo = Poloniex() intermediate_data = polo('returnTicker')[coin] date = datetime.now().strftime("%Y-%m-%d %H:%M:%S") last = intermediate_data['last'] tickers.insert_tickers(date, coin, last, 0) return last, date
def index(request): polo = Poloniex() records = polo.returnTicker() return render(request, 'bc_api/home.html', { 'latest_usdt_btc': records['USDT_BTC'], 'records': records })
def pull_polo(self): polo = Poloniex() coins = polo.returnTicker() tickLen = '7200' start = datetime.today() - timedelta(self.look_back) start = str(int(start.timestamp())) for coin in coins: if coin[:3] == 'BTC': hist = requests.get( 'https://poloniex.com/public?command=returnChartData¤cyPair=' + coin + '&start=' + start + '&end=9999999999&period=' + tickLen) #print(hist.json()) try: h_frame = pd.DataFrame(hist.json()) print(h_frame.head()) frame = h_frame.copy() frame['avg_vol_3'] = frame['volume'].rolling(3).mean() frame['avg_vol_13'] = frame['volume'].rolling(13).mean() frame['avg_vol_34'] = frame['volume'].rolling(34).mean() frame['avg_close_3'] = frame['close'].rolling(3).mean() frame['avg_close_13'] = frame['close'].rolling(13).mean() frame['avg_close_34'] = frame['close'].rolling(34).mean() frame.fillna(value=-99999, inplace=True) frame.to_csv("./histories/" + coin + "_hist.txt", encoding="utf-8") except: print("error_retrieving data")
def __init__(self): """ Costructor method. """ ExchangeBaseClass.__init__(self) self.polo = Poloniex()
def __init__(self, ticker_len, start_amount, histdepth): self.in_shapes = [] self.out_shapes = [] self.trade_hist = {} self.polo = Poloniex() self.hist_depth = histdepth self.ticker_len = ticker_len self.end_ts = datetime.now()+timedelta(seconds=(ticker_len*24)) self.start_amount = start_amount self.hs = HistWorker() self.refresh_data() self.inputs = self.hs.hist_shaped.shape[0]*(self.hs.hist_shaped[0].shape[1]) self.outputs = self.hs.hist_shaped.shape[0] #self.make_shapes() self.folio = CryptoFolio(start_amount, list(self.hs.currentHists.keys())) self.leaf_names = [] for ix in range(1,self.inputs+1): sign = sign *-1 self.in_shapes.append((0.0-(sign*.005*ix), -1.0, 0.0+(sign*.005*ix))) self.out_shapes.append((0.0, 1.0, 0.0)) self.subStrate = Substrate(self.in_shapes, self.out_shapes) for l in range(len(self.in_shapes[0])): self.leaf_names.append('leaf_one_'+str(l)) self.leaf_names.append('leaf_two_'+str(l)) self.load_net() print(self.hs.coin_dict) self.poloTrader()
def handle(self, *args, **options): email = options.get('email') exchange = options.get('exchange') if not email: raise CommandError( "Please provide --account_email. See details --help") accounts = Account.objects.filter(user__email=email, exchange__name=exchange, is_active=True) if not accounts.exists(): raise CommandError( f"Could not find account for {exchange} with {email} email") for account in accounts: api_key = account.api_key api_secret = account.api_secret polo = Poloniex(api_key, api_secret) try: # history = polo.returnTradeHistory(start=1000, end=1000000000) history = polo.returnTradeHistory() except PoloniexCommandException as e: self.stdout.write(f'Poloniex connection problem. {e}') return for pair in list(history): orders = history[pair] pair = '-'.join(pair.split('_')) self.save_orders(account, orders, pair) self.stdout.write('Done.')
def dataFrame(self, size=0, window=120): # get data from db data = self.__call__(size) # make dataframe df = pd.DataFrame(data) # format dates df['date'] = [pd.to_datetime(c['_id'], unit='s') for c in data] # del '_id' del df['_id'] # set 'date' col as index df.set_index('date', inplace=True) if not self.polo: self.polo = Poloniex(prop.apikey, prop.apiSecret) # Variables SMA, EMA, RSI valorvela smaperiod = 50 ema20 = 20 ema30 = 30 self.valorVela = df['close'].size - 1 # calculate/add sma and bbands df = bbands(df, smaperiod, self.valorVela) # add slow ema #df = ema(df, ema30, colname='emaslow') # add fast ema #df = ema(df, ema20, colname='emafast') # add macd # df = macd(df) # add rsi # df = rsi(df, window // 5) # add candle body and shadow size # df['bodysize'] = df['open'] - df['close'] # df['shadowsize'] = df['high'] - df['low'] # add percent change df['percentChange'] = df['close'].pct_change() return df
def get_poloniex_data(cryptocurrency, period, start_time): polo = Poloniex() data = polo.returnChartData(cryptocurrency, period=period, start=start_time) dataframe = pd.DataFrame(data) return dataframe
def init(config: dict) -> None: """ Initializes this module with the given config, it does basic validation whether the specified exchange and pairs are valid. :param config: config to use :return: None """ global _API, EXCHANGE _CONF.update(config) if config['dry_run']: logger.info('Instance is running with dry_run enabled') use_poloniex = config.get('poloniex', {}).get('enabled', False) use_bittrex = config.get('bittrex', {}).get('enabled', False) if use_poloniex: EXCHANGE = Exchange.POLONIEX _API = Poloniex(key=config['poloniex']['key'], secret=config['poloniex']['secret']) elif use_bittrex: EXCHANGE = Exchange.BITTREX _API = Bittrex(api_key=config['bittrex']['key'], api_secret=config['bittrex']['secret']) else: raise RuntimeError('No exchange specified. Aborting!') # Check if all pairs are available markets = get_markets() for pair in config[EXCHANGE.name.lower()]['pair_whitelist']: if pair not in markets: raise RuntimeError( 'Pair {} is not available at Poloniex'.format(pair))
def __init__(self, config: dict): """ Initializes the ApiWrapper with the given config, it does basic validation whether the specified exchange and pairs are valid. :param config: dict """ self.dry_run = config['dry_run'] if self.dry_run: logger.info('Instance is running with dry_run enabled') use_poloniex = config.get('poloniex', {}).get('enabled', False) use_bittrex = config.get('bittrex', {}).get('enabled', False) if use_poloniex: self.exchange = Exchange.POLONIEX self.api = Poloniex(key=config['poloniex']['key'], secret=config['poloniex']['secret']) elif use_bittrex: self.exchange = Exchange.BITTREX self.api = Bittrex(api_key=config['bittrex']['key'], api_secret=config['bittrex']['secret']) else: self.api = None raise RuntimeError('No exchange specified. Aborting!') # Check if all pairs are available markets = self.get_markets() for pair in config[self.exchange.name.lower()]['pair_whitelist']: if pair not in markets: raise RuntimeError( 'Pair {} is not available at Poloniex'.format(pair))
def getSearchTerms(): import json from poloniex import Poloniex polo = Poloniex() eventNames = [ "upgrade", "updates", "releas", "testing", "aplha", "beta", "announce", "interview", "major", "launch", "add", "improve", "v1" ] coinMarketList = [ market[market.index("_") + 1:] for market in polo.return24hVolume().keys() if "BTC_" in market ] coinList = polo.returnCurrencies() coinNames = [] ignoredCoins = [ "burst", "clams", "counterparty", "expanse", "dash", "horizon", "magi", "nem", "nexium", "nxt", "omni", "radium", "ripple", "shadow", "stellar", "tether" ] for coin in coinList: if not coinList[coin]["name"].lower( ) in ignoredCoins and coin in coinMarketList: coinNames.append(coinList[coin]["name"].lower()) return [coinNames, eventNames]
def get_target(coin_name, time_chosen): # download actual trading data of the test time polo = Poloniex() args = {} args["currencyPair"] = "BTC_" + coin_name command = "returnTradeHistory" args["start"] = time_chosen args["end"] = time_chosen + 1800 js = polo.api(command, args) df = pd.DataFrame(js) df["rate"] = df["rate"].apply(float) df = df[np.isfinite(df['rate'])] delta = df["rate"].iloc[0] / df["rate"].iloc[-1] - 1 # sigmoid function with an multiply factor to magnify delta ############################### # need to make the multiply factor an argument ############################### target = 1 / (1 + math.e**(-150 * delta)) return target
def get_polo_data(self): polo = Poloniex.Poloniex() self.start = d_to_t(self.start) self.end = d_to_t(self.end) oracle_main = {} for tick in self.tickers: oracle = {} data = polo.returnChartData(tick, self.period, self.start, self.end) cols = list(data[0].keys()) for col in cols: oracle[col] = [] for entry in data: for col in cols: if col == 'date': oracle[col].append(t_to_d(entry[col])) else: oracle[col].append(entry[col]) df = pd.DataFrame(oracle, index=oracle['date']) df.index = df['date'] del df['date'] df.index.name = 'date' oracle_main[tick] = df return (oracle_main)
def connect_api(ticker): '''Easiest way to connect to Poloniex API.''' api_key = 'TSOM80FK-VIYJV705-6E27F6P3-IL92VWCF' secret = '6bd7cf3f563edded66f6f73782fed44d0e9cc0b345d5a290a4abf60f7c9713e32a718f94a665237bc2d444320bb33bf98e3911dd547d2c7acdf7a464bc37ae53' polo = Poloniex(api_key, secret) # connects to API with key return polo
def __init__(self, ticker_len, start_amount, histdepth, base_sym): self.trade_hist = {} self.polo = Poloniex() self.hd = histdepth self.ticker_len = ticker_len self.end_ts = datetime.now() + timedelta(seconds=(ticker_len * 24)) self.start_amount = start_amount self.hs = HistWorker() self.hs.combine_live_usd_frames() print(self.hs.currentHists.keys()) self.end_idx = len(self.hs.hist_shaped[0]) - 1 self.but_target = .1 self.inputs = self.hs.hist_shaped.shape[0] * ( self.hs.hist_shaped[0].shape[1]) self.outputs = self.hs.hist_shaped.shape[0] self.folio = CryptoFolio(start_amount, list(self.hs.currentHists.keys()), base_sym) self.base_sym = base_sym sign = 1 for ix in range(1, self.outputs + 1): sign = sign * -1 self.out_shapes.append((0.0 - (sign * .005 * ix), 0.0, -1.0)) for ix2 in range(1, (self.inputs // self.outputs) + 1): self.in_shapes.append( (0.0 + (sign * .01 * ix2), 0.0 - (sign * .01 * ix2), 0.0)) self.subStrate = Substrate(self.in_shapes, self.out_shapes) self.load_net() print(self.hs.coin_dict) self.poloTrader()
def __init__(self, *args, **kwargs): self._polo = Poloniex(*args, **kwargs) self.ticker_update_freq = 1 self.ticker_updated = datetime(1970, 1, 1) self._ticker = {} self.ticker = None self.ticker_active = False self._ticker_thread = None self.charts_update_freq = 60 self.charts_updated = datetime(1970, 1, 1) self.charts = {} self.charts_active = False self._charts_thread = None self.chart_path = None self._new_chart = False self.balances_update_freq = 1 self.balances_updated = datetime(1970, 1, 1) self.balances = None self.balances_active = False self._balances_thread = None self.markets = self._get_markets()
def get_poloniex_close_tickers(tickers, period=86400, start_ohlc=days_ago(days=365), end_ohlc=now()): main_df = pd.DataFrame() for count, ticker in enumerate(tickers): df = pd.DataFrame( Poloniex().returnChartData(currencyPair=ticker, period=period, start=start_ohlc, end=end_ohlc)).astype(float) df.index = timestamp_to_UTC(df['date']) df.rename(columns={'close': ticker}, inplace=True) df = pd.DataFrame(df[ticker]) if main_df.empty: main_df = df else: main_df = main_df.join(df, how='outer') main_df.fillna(value=0.0, inplace=True) return main_df.copy()
def __init__(self, name, period, pmult, start, smult): Series.__init__(self) self.api = Poloniex() self.name = name self.period = t[period] * pmult self.start = time() - t[start] * smult self.data = self.update()
def get_poloniex_tickers(coin='BTC'): returnTicker = Poloniex().returnTicker() tickers = np.array(list(returnTicker.keys())) coin_ = re.compile(coin) coin_tickers = np.array(list(filter(coin_.search, tickers))) return coin_tickers
def get_data_until_success(command, args): """ Due to Poloniex's limit an api call to 50000 trading records get_data_utill_success() send api calls until reaching the end time """ polo = Poloniex() js0 = polo.api(command, args) df0 = pd.DataFrame(js0) # !!! timezone conversion fix -18000 unix_time_convert = lambda x: int(time.mktime(datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S").timetuple())-18000) df0["date"] = df0["date"].apply(unix_time_convert) if len(df0) == 50000: while (df0["date"].iloc[-1] > args["start"]): args["end"] = df0["date"].iloc[-1] + 1 print(args) js = polo.api(command, args) df = pd.DataFrame(js) if not df.empty: df["date"] = df["date"].apply(unix_time_convert) df0 = df0.append(df, ignore_index=True) if len(df) < 50000: df0.loc[-1,"date"] = args["start"] df0["rate"] = df0["rate"].apply(float) df0["total"] = df0["total"].apply(float) return df0
def main(): parser = argparse.ArgumentParser() parser.add_argument('-c', '--currency', required=True) parser.add_argument('-p', '--period', type=int, required=True, choices=[60, 300, 600]) args = parser.parse_args() poloniex = Poloniex(args.currency, args.period) count = 0 while(True): date = datetime.now() open = poloniex.get_field('last') close = poloniex.get_field('last') high = poloniex.get_field('high24hr') low = poloniex.get_field('low24hr') db = Database() db.create(currency=args.currency, period=args.period, date_initial=date, open_candle=open, close_candle=close, high=high, low=low) count = count + 1 print('Salvo com sucesso! Data/Hora: {}' .format(date.strftime('%d/%m/%Y %H:%M:%S'))) print('NÂș de candles salvos: ', count) time.sleep(args.period)
def __init__(self, key=False, secret=False): self.pw = PoloniexWrap(key, secret) self.al = dataModel.myAsyncLoans() self.poloSend = Poloniex(key, secret) self.key = self.pw.key self.secret = self.pw.secret self.activeOffers = {}
def onJoin(self, details): db().drop() initTick = Poloniex().returnTicker() for market in initTick: initTick[market]['_id'] = market db().insert_one(initTick[market]) yield self.subscribe(self.onTick, 'ticker') print('Subscribed to Ticker')
def setUp(self): apiKey = os.environ.get('API_KEY', False) apiSecret = os.environ.get('API_SECRET', False) if not apiKey or not apiSecret: self.skipTest('private keys not provided') self.poloniex = Poloniex(apiKey, apiSecret)