class TestPoloniexPrivateWithoutToken(unittest.TestCase):

    def setUp(self):
        self.poloniex = Poloniex('', '')

    def test_exception(self):
        with self.assertRaises(HTTPError):
            self.poloniex.returnBalances()
    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)
Esempio n. 3
0
class CoinList(object):

    def __init__(self):
        self._polo = Poloniex()
        #connect the internet to accees volumes
        vol = self._polo.marketVolume()
        pairs = []
        coins = []
        volumes = []

        for k, v in vol.iteritems():
            if k.startswith("BTC_") or k.endswith("_BTC"):
        	pairs.append(k)
                for c, val in v.iteritems():
                    if c != 'BTC':
    		        coins.append(c)
	            else:
		        volumes.append(float(val))

        self._df = pd.DataFrame({'coin': coins, 'pair': pairs, 'volume': volumes})
	self._df = self._df.set_index('coin')

    @property
    def allActiveCoins(self):
        return self._df

    @property
    def allCoins(self):
	return self._polo.marketStatus().keys()

    @property
    def polo(self):
	return self._polo

    def topNVolume(self, n = 5, order = False, minVolume = 0):
	if minVolume == 0:
	    r = self._df.sort_values(by='volume', ascending=False)[:n]
            if order:
		return r
            else:
		return r.sort_index()
	else:
	    return self._df[self._df.volume >= minVolume]
Esempio n. 4
0
def main():
    """
    Algorithm:

    If unused BTC:
        get min big loan offer
        Offer unused BTC at (min loan offer - 0.0001%)
    """
    global DEBUG
    args = docopt(__doc__)
    if args['--debug']:
        DEBUG = True

    api_key = os.environ.get('POLONIEX_API_KEY')
    secret = os.environ.get('POLONIEX_SECRET')

    poloniex = Poloniex(api_key=api_key, secret=secret)
    unused_btc = poloniex.get_unused()

    if DEBUG:
        print "Unused BTC:", unused_btc

    if unused_btc:
        min_big_offer = poloniex.get_min_offer_rate(BTC_PER_BIG_OFFER)

        # Get 0.0001% below
        my_rate = min_big_offer - (0.0001 / 100)

        if DEBUG:
            print "poloniex.offer_btc_loan({}, {}, {})".format(
                my_rate, unused_btc, LOAN_DURATION)
        else:
            # Place the actual order
            order_id = poloniex.offer_btc_loan(my_rate,
                                               unused_btc,
                                               LOAN_DURATION)

            # Order status
            if order_id:
                print "Order placed ({})".format(order_id),
            else:
                print "Order failed",
            print "(Rate:", my_rate * 100, "%, Amount:", unused_btc, "BTC)"
Esempio n. 5
0
class TestPoloniex(object):

    def setup(self):
        self.poloniex = Poloniex('', '')

    def test_ticker(self):
        res = self.poloniex.returnTicker()

        assert 'BTC_ETH' in res.keys()
        assert 'lowestAsk' in res['BTC_ETH'].keys()
        
    def test_volume(self):
        res = self.poloniex.return24hVolume()
        
        assert 'BTC_ETH' in res.keys()
        assert 'BTC' in res['BTC_ETH'].keys()
        
    def test_orderbook(self):
        res = self.poloniex.returnOrderBook('BTC_ETH')
        assert 'bids' in res.keys()
        assert 'asks' in res.keys()
        
    def test_tradehistory(self):
        start = datetime.now() - timedelta(hours=1)
        res = self.poloniex.returnTradeHistory('BTC_ETH', start)

        assert len(res)
        assert 'date' in res[0].keys()
        assert 'type' in res[0].keys()
        assert 'amount' in res[0].keys()
        assert 'rate' in res[0].keys()

    def test_chartdata(self):
        start = datetime.now() - timedelta(hours=1)
        res = self.poloniex.returnChartData('BTC_ETH', 300, start)

        assert len(res)
        assert 'date' in res[0].keys()
        assert 'volume' in res[0].keys()
        assert 'high' in res[0].keys()
        assert 'low' in res[0].keys()
        assert 'close' in res[0].keys()
 def __init__(self, api=None):
     self.api = api
     if not self.api:
         self.api = Poloniex(jsonNums=float)
     self.db = MongoClient().poloniex['ticker']
     self.db.drop()
     self.ws = websocket.WebSocketApp("wss://api2.poloniex.com/",
                                      on_message=self.on_message,
                                      on_error=self.on_error,
                                      on_close=self.on_close)
     self.ws.on_open = self.on_open
Esempio n. 7
0
def main():
    global DEBUG
    args = docopt(__doc__)
    if args['--debug']:
        DEBUG = True

    poloniex = Poloniex()
    max_demand = poloniex.get_max_demand_rate()
    min_offer = poloniex.get_min_offer_rate()
    min_big_offer = poloniex.get_min_offer_rate(BTC_PER_BIG_OFFER)

    print "max_demand:", max_demand,
    print "min_offer:", min_offer,
    print "min_big_offer:", min_big_offer

    if not DEBUG:
        keen.add_event("lending-rates", {
            "max-demand": max_demand,
            "min-offer": min_offer,
            "min-big-offer": min_big_offer
        })
	def __init__(self, Key, Secret, interval=60*2, ageLimit=60*5, offset=2):
		"""
		- <Key> - Polo Api key
		- <Secret> - Polo Api secret
		- Loaner.INTERVAL = time in sec to wait between updates [default= 2min]
		- Loaner.AGELIMIT = max age (in sec) for an open loan offer [default= 5min]
		- Loaner.OFFSET = offset from the top loan offer rate (offset*0.000001) [default= 2]
		- Loaner.CHECKINT = number of times to check Loaner.RUNNING between intervals (could be hard on cpu if set too high and INTERVAL set too low!) [default= 20]
		- Loaner.MINAMOUNT = Minimum amount for creating loan offers [default= 0.01]
		"""
		self.POLO = Poloniex(Key, Secret)
		self.INTERVAL, self.AGELIMIT, self.OFFSET, self.CHECKINT, self.MINAMOUNT, self._running, self._thread = [interval, ageLimit, offset, 20, 0.01, False, None]
class TestPoloniexPrivate(unittest.TestCase):

    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)

    def test_balances(self):
        res = self.poloniex.returnBalances()

        assert 'BTC' in res
        assert 'ETH' in res
Esempio n. 10
0
File: FX.py Progetto: zmasz/ltp-bot
	def __init__(self,base,quote):
		self.base = base
		self.quote = quote
		self.pair = self.base + '_' + self.quote
		self.price = Poloniex.getPrice(self,self.pair)

		Data.__init__(self)
		Charter.__init__(self)
		#Backtester.__init__(self)


#xmr = FX("BTC","XMR")
#xmr.saveChartData()


#xmr.chartCandles('7D')
#xmr.showChart()
Esempio n. 11
0
    def __init__(self):
        self.polo = Poloniex()
        vol = self.polo.marketVolume()
        pairs = []
        coins = []
        volumes = []

        for k, v in vol.iteritems():
            if k.startswith("BTC_") or k.endswith("_BTC"):
        	pairs.append(k)
                for c, val in v.iteritems():
                    if c != 'BTC':
    		        coins.append(c) 
	            else:
		        volumes.append(float(val))

        self._df = pd.DataFrame({'coin': coins, 'pair': pairs, 'volume': volumes})
	self._df = self._df.set_index('coin')
Esempio n. 12
0
def getTickers():
    from poloniex import Poloniex
    polo = Poloniex()
    ticker = polo.returnTicker()
    return ticker
Esempio n. 13
0
#!/usr/bin/python3
from poloniex import Poloniex
import operator
import os
import time
import sys
import secret
import math
p = Poloniex(*secret.token)
delta = 0

priceMap = p.returnTicker()
bar = ''
res = 150
low = 0
rows = []

def point(num, char):
    point = int(res * (num - low) / delta)
    bar[point] = char

for k, v in priceMap.items():
    if k[0:3] == 'BTC':
        for i in  ['low24hr', 'lowestAsk', 'last', 'highestBid', 'high24hr', 'baseVolume']:
            v[i] = float(v[i])
        """
        print("{:6} {} {} {} {} {} {}".format( k[4:], 
            v['low24hr'], v['lowestAsk'], v['last'], v['highestBid'], v['high24hr'], v['baseVolume']
        ))
        """ 
Esempio n. 14
0
        """

        url = 'https://api.blockcypher.com/v1/eth/main/addrs/' + eth_address + '/balance'
        resp = requests.get(url)

        if resp.status_code != 200:
            print('Oops, something went wrong')

        data = resp.json()

        return (data['final_balance'])

#initializing the classes
nano = nano(eth_mining_address)
bittrex = bittrex(bittrex_api_key["key"], bittrex_api_key["secret"])
polo = Poloniex()
krak = krakenex.API()
bc = bitchain()
ec = ethchain()

def calc_ETH_yields(hashrateMH):
    netHash = 6807  # network hash rate in GH/s
    blocktime = 12  # in seconds
    BlockReward = 5  # ETH

    userRatio = (hashrateMH * 1e6) / (netHash * 1e9)
    blocksPerMin = 60 / blocktime
    ETHPerMin = blocksPerMin * BlockReward  # input or pulled off a website

    ETHPerMin = ETHPerMin * userRatio
    ETHPerHour = ETHPerMin * 60
Esempio n. 15
0
class PoloniexExchange(ExchangeBaseClass):
    """
    Class that manages Poloniex metadata.
    Inherits from alchemist_lib.exchange.exchange.ExchangeBaseClass.
    
    Website: https://poloniex.com/

    Api documentation: https://poloniex.com/support/api/

    Api wrapper: https://github.com/s4w3d0ff/python-poloniex

    Attributes:
        polo (poloniex.Poloniex): Communication object.
    
    """
    def __init__(self):
        """
        Costructor method.
        """

        ExchangeBaseClass.__init__(self)
        self.polo = Poloniex()

    def get_min_order_size(self, asset):
        """
        This method would return the minimum order size for a specific market, but It's not specified in the Poloniex documentation.
        https://poloniex.com/support/api/

        Args:
            asset (alchemist_lib.database.asset.Asset): The asset traded again BTC.
            
        Return:
            size (decimal.Decimal): Minimum order size. Default is 0.
        """

        return Decimal(0)

    def are_tradable(self, assets):
        """
        Filters tradable assets.
        
        Args:
            assets (alchemist_lib.database.asset.Asset, list[Asset]): List of assets to check.
                
        Return:
            tradable (list[Asset]): Returns all tradable asset (remove not tradable assets from the arg).
                
        Note:
            Checks just pairs with BTC as base currency.
        """

        assets = utils.to_list(assets)

        pairs = self.polo.returnTicker()

        tradable = []
        for asset in assets:
            pair = "BTC_{}".format(asset.ticker)
            if pair in list(pairs.keys()):
                if pairs[pair]["isFrozen"] == "0":
                    tradable.append(asset)
                else:
                    logging.debug("{} is not tradable.".format(asset.ticker))

        return tradable
Esempio n. 16
0
class Polo(Base):
    """
    Poloniex interface
    """
    arg_parser = configargparse.get_argument_parser()
    arg_parser.add('--polo_api_key', help='Poloniex API key')
    arg_parser.add("--polo_secret", help='Poloniex secret key')
    arg_parser.add("--polo_txn_fee", help='Poloniex txn. fee')
    arg_parser.add("--polo_buy_order", help='Poloniex buy order type')
    arg_parser.add("--polo_sell_order", help='Poloniex sell order type')
    valid_candle_intervals = [300, 900, 1800, 7200, 14400, 86400]

    def __init__(self):
        super(Polo, self).__init__()
        args = self.arg_parser.parse_known_args()[0]
        api_key = args.polo_api_key
        secret = args.polo_secret
        self.transaction_fee = float(args.polo_txn_fee)
        self.polo = Poloniex(api_key, secret)
        self.buy_order_type = args.polo_buy_order
        self.sell_order_type = args.polo_sell_order
        self.pair_delimiter = '_'
        self.tickers_cache_refresh_interval = 50  # If the ticker request is within the interval, get data from cache
        self.last_tickers_fetch_epoch = 0
        self.last_tickers_cache = None  # Cache for storing immediate tickers

    def get_balances(self):
        """
        Return available account balances (function returns ONLY currencies > 0)
        """
        try:
            balances = self.polo.returnBalances()
            only_non_zeros = {k: float(v) for k, v in balances.items() if float(v) > 0.0}
        except PoloniexError as e:
            print(colored('!!! Got exception (polo.get_balances): ' + str(e), 'red'))
            only_non_zeros = dict()

        return only_non_zeros

    def get_symbol_ticker(self, symbol, candle_size=5):
        """
        Returns real-time ticker Data-Frame for given symbol/pair
        Info: Currently Poloniex returns tickers for ALL pairs. To speed the queries and avoid
              unnecessary API calls, this method implements temporary cache
        """
        epoch_now = int(time.time())
        if epoch_now < (self.last_tickers_fetch_epoch + self.tickers_cache_refresh_interval):
            # If the ticker request is within cache_fetch_interval, try to get data from cache
            pair_ticker = self.last_tickers_cache[symbol].copy()
        else:
            # If cache is too old fetch data from Poloniex API
            try:
                ticker = self.polo.returnTicker()
                pair_ticker = ticker[symbol]
                self.last_tickers_fetch_epoch = int(time.time())
                self.last_tickers_cache = ticker.copy()
            except (PoloniexError, JSONDecodeError) as e:
                print(colored('!!! Got exception in get_symbol_ticker. Details: ' + str(e), 'red'))
                pair_ticker = self.last_tickers_cache[symbol].copy()
                pair_ticker = dict.fromkeys(pair_ticker, None)

        df = pd.DataFrame.from_dict(pair_ticker, orient="index")
        df = df.T
        # We will use 'last' price as closing one
        df = df.rename(columns={'last': 'close', 'baseVolume': 'volume'})
        df['close'] = df['close'].astype(float)
        df['volume'] = df['volume'].astype(float)
        df['pair'] = symbol
        df['date'] = int(datetime.datetime.utcnow().timestamp())
        return df

    def return_ticker(self):
        """
        Returns ticker for all currencies
        """
        return self.polo.returnTicker()

    def cancel_order(self, order_number):
        """
        Cancels order for given order number
        """
        return self.polo.cancelOrder(order_number)

    def get_open_orders(self, currency_pair='all'):
        """
        Returns your open orders
        """
        return self.polo.returnOpenOrders(currency_pair)

    def get_pairs(self):
        """
        Returns ticker pairs for all currencies
        """
        ticker = self.polo.returnTicker()
        return list(ticker)

    def get_candles_df(self, currency_pair, epoch_start, epoch_end, period=False):
        """
        Returns candlestick chart data in pandas dataframe
        """
        try:
            data = self.get_candles(currency_pair, epoch_start, epoch_end, period)
            df = pd.DataFrame(data)
            df = df.tail(1)
            df['close'] = df['close'].astype(float)
            df['volume'] = df['volume'].astype(float)
            df['pair'] = currency_pair
            return df
        except (PoloniexError, JSONDecodeError) as e:
            print()
            print(colored('!!! Got exception while retrieving polo data:' + str(e) + ', pair: ' + currency_pair, 'red'))
        return pd.DataFrame()

    def get_candles(self, currency_pair, epoch_start, epoch_end, interval_in_sec=300):
        """
        Returns candlestick chart data
        """
        candle_interval = self.get_valid_candle_interval(interval_in_sec)
        data = []
        try:
            data = self.polo.returnChartData(currency_pair, candle_interval, epoch_start, epoch_end)
        except (PoloniexError, JSONDecodeError) as e:
            print()
            print(colored('!!! Got exception while retrieving polo data: ' + str(e) + ', pair: ' + currency_pair, 'red'))
        return data

    def get_market_history(self, start, end, currency_pair='all'):
        """
        Returns market trade history
        """
        data = []
        try:
            data = self.polo.marketTradeHist(currencyPair=currency_pair,
                                             start=start,
                                             end=end)
        except (PoloniexError, JSONDecodeError) as e:
            logger = logging.getLogger(__name__)
            logger.error('Got exception while retrieving polo data:' + str(e) + ', pair: ' + currency_pair, e)
        return data

    def get_valid_candle_interval(self, period_in_sec):
        """
        Returns closest value from valid candle intervals
        """
        if not period_in_sec:
            return period_in_sec

        if period_in_sec in self.valid_candle_intervals:
            return period_in_sec
        # Find the closest valid interval
        return min(self.valid_candle_intervals, key=lambda x: abs(x - period_in_sec))

    def trade(self, actions, wallet, trade_mode):
        if trade_mode == TradeMode.backtest:
            return Base.trade(actions, wallet, trade_mode)
        else:
            actions = self.life_trade(actions)
            return actions

    def life_trade(self, actions):
        """
        Places orders and returns order number
        !!! For now we are NOT handling postOnly type of orders !!!
        """
        for action in actions:

            if action.action == TradeState.none:
                actions.remove(action)
                continue

            # Handle buy_sell mode
            wallet = self.get_balances()
            if action.buy_sell_mode == BuySellMode.all:
                action.amount = self.get_buy_sell_all_amount(wallet, action)
            elif action.buy_sell_mode == BuySellMode.fixed:
                action.amount = self.get_fixed_trade_amount(wallet, action)

            print('Processing live-action: ' + str(action.action) +
                  ', amount:', str(action.amount) +
                  ', pair:', action.pair +
                  ', rate:', str(action.rate) +
                  ', buy_sell_mode:', action.buy_sell_mode)

            # If we don't have enough assets, just skip/remove the action
            if action.amount == 0.0:
                print(colored('No assets to buy/sell, ...skipping: ' + str(action.amount) + ' ' + action.pair, 'green'))
                actions.remove(action)
                continue

            # ** Buy Action **
            if action.action == TradeState.buy:
                try:
                    print(colored('Setting buy order: ' + str(action.amount) + '' + action.pair, 'green'))
                    action.order_number = self.polo.buy(action.pair, action.rate, action.amount, self.buy_order_type)
                except PoloniexError as e:
                    print(colored('Got exception: ' + str(e) + ' Txn: buy-' + action.pair, 'red'))
                    continue
                amount_unfilled = action.order_number.get('amountUnfilled')
                if float(amount_unfilled) == 0.0:
                    actions.remove(action)
                    print(colored('Bought: ' + str(action.amount) + '' + action.pair, 'green'))
                else:
                    action.amount = amount_unfilled
                    print(colored('Not filled 100% buy txn. Unfilled amount: ' + str(amount_unfilled) + '' + action.pair, 'red'))

            # ** Sell Action **
            elif action.action == TradeState.sell:
                try:
                    print(colored('Setting sell order: ' + str(action.amount) + '' + action.pair, 'yellow'))
                    action.order_number = self.polo.sell(action.pair, action.rate,  action.amount, self.buy_order_type)
                except PoloniexError as e:
                    print(colored('Got exception: ' + str(e) + ' Txn: sell-' + action.pair, 'red'))
                    continue
                amount_unfilled = action.order_number.get('amountUnfilled')
                if float(amount_unfilled) == 0.0:
                    actions.remove(action)
                    print(colored('Sold: ' + str(action.amount) + '' + action.pair, 'yellow'))
                else:
                    action.amount = amount_unfilled
                    print(colored('Not filled 100% sell txn. Unfilled amount: ' + str(amount_unfilled) + '' + action.pair, 'red'))
        return actions
class wsTicker(object):

    def __init__(self, api=None):
        self.api = api
        if not self.api:
            self.api = Poloniex(jsonNums=float)
        self.db = MongoClient().poloniex['ticker']
        self.db.drop()
        self.ws = websocket.WebSocketApp("wss://api2.poloniex.com/",
                                         on_message=self.on_message,
                                         on_error=self.on_error,
                                         on_close=self.on_close)
        self.ws.on_open = self.on_open

    def __call__(self, market=None):
        """ returns ticker from mongodb """
        if market:
            return self.db.find_one({'_id': market})
        return list(self.db.find())

    def on_message(self, ws, message):
        message = json.loads(message)
        if 'error' in message:
            print(message['error'])
            return

        if message[0] == 1002:
            if message[1] == 1:
                print('Subscribed to ticker')
                return

            if message[1] == 0:
                print('Unsubscribed to ticker')
                return

            data = message[2]

            self.db.update_one(
                {"id": float(data[0])},
                {"$set": {'last': data[1],
                          'lowestAsk': data[2],
                          'highestBid': data[3],
                          'percentChange': data[4],
                          'baseVolume': data[5],
                          'quoteVolume': data[6],
                          'isFrozen': data[7],
                          'high24hr': data[8],
                          'low24hr': data[9]
                          }},
                upsert=True)

    def on_error(self, ws, error):
        print(error)

    def on_close(self, ws):
        print("Websocket closed!")

    def on_open(self, ws):
        tick = self.api.returnTicker()
        for market in tick:
            self.db.update_one(
                {'_id': market},
                {'$set': tick[market]},
                upsert=True)
        print('Populated markets database with ticker data')
        self.ws.send(json.dumps({'command': 'subscribe',
                                 'channel': 1002}))

    def start(self):
        self.t = Thread(target=self.ws.run_forever)
        self.t.daemon = True
        self.t.start()
        print('Thread started')

    def stop(self):
        self.ws.close()
        self.t.join()
        print('Thread joined')
Esempio n. 18
0
class PoloniexClientWrapper:
    MAX_TRIES = 3
    SLEEP_TRIES = 1
    API_KEY = EXCHANGE_DATA["poloniex"]["api_key"]
    API_SECRET = EXCHANGE_DATA["poloniex"]["api_secret"]

    def __init__(self):
        self._client = Client(self.API_KEY, self.API_SECRET)
        self._cache = dict()

    def get_orderbook(self, symbol="BTC_USDT", limit=4612):
        operation = PoloniexOperation.GET_ORDERBOOK
        params = {"symbol": self._invert_symbol(symbol), "limit": limit}
        return self._request(operation, params)

    def get_orderbook_ticker(self, symbol="BTC_USDT"):
        operation = PoloniexOperation.GET_ORDERBOOK_TICKER
        params = {"symbol": self._invert_symbol(symbol)}
        return self._request(operation, params)

    def get_orderbook_tickers(self):
        operation = PoloniexOperation.GET_ORDERBOOK_TICKERS
        return self._request(operation)

    def get_recent_trades(self, symbol="BTC_USDT", limit=200):
        operation = PoloniexOperation.GET_RECENT_TRADES
        params = {"symbol": self._invert_symbol(symbol), "limit": limit}
        return self._request(operation, params)

    def get_coins(self):
        operation = PoloniexOperation.GET_COINS
        return self._request(operation)

    def _invert_symbol(self, symbol):
        coin_1, coin_2 = symbol.split("_")
        symbol = coin_2 + "_" + coin_1
        return symbol

    def _request(self, operation, params=dict()):
        current_time = time.time()

        # Create cache key.
        key = str(operation)
        for p in params:
            key += str(params[p])

        if key in self._cache and \
                abs(current_time - self._cache[key]["time"]) < 60:
            return self._cache[key]["database"]
        else:
            i = 0
            while i < self.MAX_TRIES:
                try:
                    if operation == PoloniexOperation.GET_ORDERBOOK:
                        response = self._client.returnOrderBook(
                            currencyPair=params["symbol"],
                            depth=params["limit"])
                    elif operation == PoloniexOperation.GET_ORDERBOOK_TICKER:
                        response = self._client.returnOrderBook(
                            currencyPair=params["symbol"], depth=1)
                    elif operation == PoloniexOperation.GET_ORDERBOOK_TICKERS:
                        response = self._client.returnOrderBook(
                            currencyPair="all", depth=1)
                    elif operation == PoloniexOperation.GET_RECENT_TRADES:
                        response = self._client.returnTradeHistoryPublic(
                            currencyPair=params["symbol"])[:params["limit"]]
                    elif operation == PoloniexOperation.GET_COINS:
                        response = self._client._private('returnBalances')
                    break
                except Exception as e:
                    print(e)
                    if i < self.MAX_TRIES:
                        time.sleep(self.SLEEP_TRIES)
                        self._client = Client(self.API_KEY, self.API_SECRET)
                        current_time = time.time()
                        i += 1
                    else:
                        return None

        if key not in self._cache:
            self._cache[key] = dict()

        # Update cache.
        self._cache[key]["time"] = current_time
        self._cache[key]["database"] = response

        return response
Esempio n. 19
0
 def __init__(self, api_key, secret):
     api_p=''
     key_p=''
     self.api=Poloniex(api_key, secret)
     pass
Esempio n. 20
0
import gdax
from poloniex import Poloniex
import pandas as pd

#### Polo Data
polo = Poloniex()
orders = polo.returnOrderBook()['BTC_ETH']

poloAsks = pd.DataFrame(orders['asks'])
poloAsks.columns = ['price', 'volume']
poloAsks = poloAsks.astype(float)

poloBids = pd.DataFrame(orders['bids'])
poloBids.columns = ['price', 'volume']
poloBids = poloBids.astype(float)

#### GDAX Data
public_client = gdax.PublicClient()
wsClient = gdax.WebsocketClient(url="wss://ws-feed.gdax.com",
                                products="ETH-BTC")

gdaxEthBtcOrderBook = public_client.get_product_order_book('ETH-BTC', level=2)

bids = dict.get(gdaxEthBtcOrderBook, 'bids')
asks = dict.get(gdaxEthBtcOrderBook, 'asks')
wsClient.close()

gdaxBids = pd.DataFrame(bids)
gdaxBids.columns = ["price", "volume", "orders"]
gdaxBids = gdaxBids.astype(float)
Esempio n. 21
0
# Import Standard Library Modules
import time
import sys
# Import the External Poloniex Library (python-poloniex-master folder + PIP install poloniex)
import poloniex
from poloniex import Poloniex

try:  # First check for user BTC Value input
    budget = str(sys.argv[1])  #.format('0.001')
except:  # Print an Exeption (error) if there is no input
    print("put Budget in as python AllCoinsInBTC.py 0.001")
    exit(1)

while True:  # Setup to connect to Poloniex API
    try:
        polo = Poloniex()
        polo.key = 'Your_Poloniex_Key_Here'
        polo.secret = 'Your_Poloniex_Secret_Here'
        print(" ")
        print("---!Connected to Poloniex.com!---")
        break
    except:
        backoff("Can not connect to Poloniex API")
        exit(1)


def backoff(msg):  # Function for the Error Message later in script
    print(msg)
    time.sleep(0.1)

Esempio n. 22
0
from ConfigParser import SafeConfigParser

# get config
config = SafeConfigParser()
config_location = 'default.cfg'
loadedFiles = config.read([config_location])
duration = float(config.get("BOT", "duration"))
frequency = int(config.get("BOT", "frequency"))
total_amount_to_spend = float(config.get("BOT", "totalAmountToSpend"))
api_key = config.get("API","apikey")
api_secret = config.get("API","secret")

currency_pair = "BTC_XMR"

# initiate bot
bot = Poloniex(api_key, api_secret)

# variables
btc_volume_each_trade = total_amount_to_spend/(duration*3600/frequency)
amount_traded_in_btc = 0.0
amount_xmr_bought = 0.0

# see how far we have to go into the order book to fill the order
def get_buy_price():
    order_book = bot.returnOrderBook(currency_pair)
    asks = order_book["asks"]
    btc_ask_volume = 0.0
    for i, val in enumerate(asks):
        btc_ask_volume += (float(val[0]) * val[1])
        if btc_ask_volume >= btc_volume_each_trade:
            return float(val[0])
Esempio n. 23
0
 def setUp(self):
     self.poloniex = Poloniex('BTC_BTS', 60)
Esempio n. 24
0
 def test_invalid_currency(self):
     self.instance = Poloniex('TC_DASH', 800)
     self.assertNotIn(self.instance.currency_pair,
                      self.instance._list_currencies())
Esempio n. 25
0
from poloniex import Poloniex
from sklearn.linear_model import LinearRegression
import helper_functions as hf
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split

# define the currency pair we will be performing with
currency_pair = ['BTC_ETH']

# retrieve the crypto-currency chart data
chart_data = hf.glueCurrencies(currency_pair, Poloniex())

# create a Poloniex api model according to the given currency pairs
polo_model = hf.create_poloniex_model(chart_data)

# create the needed parameters for the linear regression model and its prediction methods
processed_model, predict, x_test, y_test = hf.poloniex_linear_regression(
    polo_model, LinearRegression()).values()

# draw the linear regression prediction line and print the next estimated price for the mentioned unix time period
hf.draw_prediction(predict, processed_model, x_test, y_test)
Esempio n. 26
0
 def __init__(self):
     self._client = Client(self.API_KEY, self.API_SECRET)
     self._cache = dict()
Esempio n. 27
0
 def setup(self):
     self.poloniex = Poloniex('', '')
import pandas as pd
from bokeh.plotting import figure, output_file, show
import numpy as np
from sklearn import linear_model
from bokeh.models import HoverTool, BoxSelectTool
import matplotlib.pyplot as plt
import datetime as dt
from pandas_datareader import data
#change the number to move the left bound left and right if needed
numOfDaysToGet = 17000
numOfCandleSticksToPredict = 1
currencyToGet = 'USDT_BTC'
windowLength = 14

#api call with poloniex
api = Poloniex(timeout=None, jsonNums=float)

#change the number to move the right bound left and right if needed
NumOfDaysToMoveBackFromToday = time() - api.DAY*0

#period of candlesticks to recieve: 24, 4, 2, 0.5, 0.25, or  0.083
period = api.HOUR * 24

#api call
raw = api.returnChartData(currencyToGet, period=period, start=time() - api.DAY*numOfDaysToGet, end= NumOfDaysToMoveBackFromToday)

#load dataframe with infrom from api call
df = pd.DataFrame(raw)


#create date column and convert epoch time from api call to date
Esempio n. 29
0
from poloniex import Poloniex
from decimal import Decimal
import time
import datetime
from config import *

polo = Poloniex(API_KEY, SECRET)


def main():
    # for each coin, create a specific coin seller
    global polo
    coin_sellers = [CoinSeller(config) for config in sell_coin_configs]

    while True:
        for coin_seller in coin_sellers:
            try:
                coin_seller.sell()
            except Exception as e:
                print(e)
                print(
                    '\033[91m{}  error when selling {}. recreate polo.\033[0m'.
                    format(
                        datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                        coin_seller.coin))
                polo = Poloniex(API_KEY, SECRET)

        time.sleep(SLEEP_TIME)


class CoinSeller:
Esempio n. 30
0
    def run(self, transaction=True):
        agent = Poloniex(self.apikey, self.secret)
        BTC2USD = Price().price('BTC', 'USD')['USD']
        balance = agent.returnBalances()
        portfolio = {}
        for coin in self.coins:
            c_balance = balance[coin]
            if coin == 'BTC':
                portfolio[coin] = (BTC2USD, c_balance)
            else:
                portfolio[coin] = (
                    BTC2USD *
                    agent.returnTicker()['BTC_{}'.format(coin)]['last'],
                    c_balance)

        df = pd.DataFrame(portfolio, index=range(2))
        df = df.append(df.ix[0] * df.ix[1], ignore_index=True)
        df = df.join(
            pd.Series(['/', '/', round(df.ix[2].sum(), 2)], name='total'))
        df = df.append(df.ix[2] / df.ix[2, -1], ignore_index=True)
        df.index = ['price', 'balance', 'value', 'weight']
        df_str = df.round(2).replace(
            0, '/').astype(str).apply(lambda s: s.str.rjust(8))
        nbars = len(self.coins) * 10 + 17
        print('#' * nbars)
        print('{:-^{width}}'.format(' CURRENT PORTFOLIO ({}) '.format(
            strftime('%Y-%m-%d %H:%M:%S', gmtime())),
                                    width=nbars))
        print(df_str)

        self.train()
        print('{:-^{width}}'.format(
            ' SUGGESTED PORTFOLIO (EXP. SHARPE = {:.8f}) '.format(self.sharpe),
            width=nbars))
        order = pd.DataFrame(
            [self.portfolio * df.ix[-2, -1] / df.ix[0, :-1], df.ix[1, :-1]],
            index=range(2))
        order = order.append(order.ix[0, :] - order.ix[1, :],
                             ignore_index=True)
        order.index = ['target', 'current', 'order']
        print(
            order.round(3).replace(
                0, '/').astype(str).apply(lambda s: s.str.rjust(8)))

        if transaction:
            print('{:-^{width}}'.format(' TRANSACTIONS ', width=nbars))

            def mkt_order(coin, amount, slippage=.1):
                currencyPair = 'BTC_{}'.format(coin)
                ticker = agent.returnTicker()
                if amount:
                    if amount > 0:
                        rate = float(ticker[currencyPair]['lowestAsk']) * (
                            1 + slippage)  # in btc
                        fee = rate * amount * 0.0025  # in btc
                        print(
                            '{} buy {:.3f} {} at {:.3f} USD/{}, fee = {:.6f} USD'
                            .format(strftime('%Y-%m-%d %H:%M:%S',
                                             gmtime()), amount, coin,
                                    rate * BTC2USD, coin, fee * BTC2USD),
                            end='')
                        agent.buy(currencyPair=currencyPair,
                                  rate=rate,
                                  amount=amount,
                                  fillOrKill=1)
                    elif amount < 0:
                        rate = float(ticker[currencyPair]['highestBid']) * (
                            1 - slippage)  # in btc
                        fee = -rate * amount * 0.0025  # in btc
                        print(
                            '{} sell {:.3f} {} at {:.3f} USD/{}, fee = {:.6f} USD'
                            .format(strftime('%Y-%m-%d %H:%M:%S',
                                             gmtime()), -amount, coin,
                                    rate * BTC2USD, coin, fee * BTC2USD),
                            end='')
                        agent.sell(currencyPair=currencyPair,
                                   rate=rate,
                                   amount=-amount,
                                   fillOrKill=1)

            unset = order.ix[-1,
                             np.setdiff1d(self.coins, ['BTC'])].sort_values()
            fail = 0
            for coin in unset.index:
                try:
                    amount = unset[coin]
                    mkt_order(coin, amount)
                    if amount:
                        print('... succeed')
                except PoloniexCommandException:
                    print('... fail (not enough fund)')
                    fail += 1
            fail += sum([
                len(agent.returnOpenOrders(currencyPair='BTC_{}'.format(coin)))
                for coin in self.coins if not coin == 'BTC'
            ])
            if fail:
                print('note: {} order(s) not successfully set'.format(fail))

        balance = agent.returnBalances()
        portfolio = {}
        for coin in self.coins:
            c_balance = balance[coin]
            if coin == 'BTC':
                portfolio[coin] = (BTC2USD, c_balance)
            else:
                portfolio[coin] = (
                    BTC2USD *
                    agent.returnTicker()['BTC_{}'.format(coin)]['last'],
                    c_balance)

        df = pd.DataFrame(portfolio, index=range(2))
        df = df.append(df.ix[0] * df.ix[1], ignore_index=True)
        df = df.join(
            pd.Series(['/', '/', round(df.ix[2].sum(), 2)], name='total'))
        df = df.append(df.ix[2] / df.ix[2, -1], ignore_index=True)
        df.index = ['price', 'balance', 'value', 'weight']
        df_str = df.round(2).replace(
            0, '/').astype(str).apply(lambda s: s.str.rjust(8))
        print('{:-^{width}}'.format(' UPDATED PORTFOLIO ({}) '.format(
            strftime('%Y-%m-%d %H:%M:%S', gmtime())),
                                    width=nbars))
        print(df_str)

        print('#' * nbars)
Esempio n. 31
0
def stringMaker(inpair): #returns a tuple --> (text, colour)
    polo=Poloniex()
    ticker = polo.returnTicker()[inpair]
    print "~~~Running stringMaker(string_pair) function~~~"
    last_val = ticker['last']
    disp_last_val = last_val
    prefix = ""

    # For BTC pairs, this makes things more readable
    if inpair[0:3] == "BTC":
        pair1_disp = (inpair[0:3] + "/" +inpair[4:])
        #print inpair,"--> is a BTC Pair"
        if last_val < 0.001:
            disp_last_val = str(last_val/(1e-6))
            prefix = u"\u00B5\u20BF "
            #print "uB" + disp_last_val
        elif last_val < 0.01:
            disp_last_val = str(int(last_val/(1e-6)))
            prefix = u"\u00B5\u20BF "
            #print "uB " + disp_last_val
        elif last_val < 1:
            disp_last_val = str(round(last_val,5))
            prefix = u"\u20BF "
            #print "B" + disp_last_val

    # For USDT pairs, this makes thigs more readable
    if inpair[0:4] == "USDT":
        pair1_disp = (inpair[0:4] + "/" +inpair[5:])
        prefix = "$"
        #print inpair,"--> is a USDT Pair"
        count = 0
        number = last_val
        while (number > 0):
            number = number//10
            count = count + 1

        if last_val < 1:
            disp_last_val = "Less than $1"
            #print disp_last_val
        elif count > 3:
            disp_last_val = str(int(round(last_val)))
            #print "$" + disp_last_val
        elif count >= 1:
            disp_last_val = '%.2f'%last_val
            #print "$" + '%.2f'%last_val

    #print inpair

    #print"Last Value:", last_val
    percent_change = ticker['percentChange']
    percent_change = percent_change*100
    #print "Percent Change:", round(percent_change,2), "%"
    neg = 1 #change this to something orange
    if percent_change < 0:
        colour = "255,0,0"
        neg = (255,0,0) #red
    else:
        colour = "0,255,0"
        neg = (0,255,0) #green

    pc = str(round(percent_change,1))
    coin_display_string = pair1_disp + "  " + prefix + str(disp_last_val) + "  " + pc + "%   "
    print coin_display_string
    return (coin_display_string, neg)
Esempio n. 32
0
class Loaner(object):
	""" Object for control of threaded Loaner loop"""
	def __init__(self, Key, Secret, interval=60*2, ageLimit=60*5, offset=2):
		"""
		- <Key> - Polo Api key
		- <Secret> - Polo Api secret
		- Loaner.INTERVAL = time in sec to wait between updates [default= 2min]
		- Loaner.AGELIMIT = max age (in sec) for an open loan offer [default= 5min]
		- Loaner.OFFSET = offset from the top loan offer rate (offset*0.000001) [default= 2]
		- Loaner.CHECKINT = number of times to check Loaner.RUNNING between intervals (could be hard on cpu if set too high and INTERVAL set too low!) [default= 20]
		- Loaner.MINAMOUNT = Minimum amount for creating loan offers [default= 0.01]
		"""
		self.POLO = Poloniex(Key, Secret)
		self.INTERVAL, self.AGELIMIT, self.OFFSET, self.CHECKINT, self.MINAMOUNT, self._running, self._thread = [interval, ageLimit, offset, 20, 0.01, False, None]
	
	def _run(self):
		""" Main loop that is threaded (set Loaner.RUNNING to 'False' to stop loop)"""
		while self._running:
			try:
				self.cancelOldLoans(self.POLO.myOpenLoanOrders(), self.AGELIMIT)
				self.createLoans(self.POLO.myAvailBalances(), self.OFFSET)
				for i in range(self.CHECKINT):
					if not self._running: break
					time.sleep(self.INTERVAL/self.CHECKINT)
			except Exception as e:
				logging.info(e);time.sleep(self.INTERVAL/self.CHECKINT)
	
	def start(self):
		""" Start Loaner.thread"""
		self._thread = Thread(target=self._run);self._thread.daemon = True
		self._running = True;self._thread.start()
		logging.info('LOANER: started')
	
	def stop(self):
		""" Stop Loaner.thread"""
		self._running = False;self._thread.join()
		logging.info('LOANER: stopped')
	
	def cancelOldLoans(self, orderList, ageLimit):
		""" Cancel loans in <orderList> that are older than <ageLimit>
			- orderList = JSON object received from poloniex (open loan orders)
			- ageLimit = max age to allow an order to sit still before canceling (in seconds)""" 
		logging.info('LOANER: Checking for stale offers')
		for market in orderList:
			for order in orderList[market]:
				logging.info('LOANER: %s order %s has been open %f2 mins' % (market, str(order['id']), round((time.time()-self.POLO.UTCstr2epoch(order['date']))/60, 2)))
				if time.time()-self.POLO.UTCstr2epoch(order['date']) > ageLimit:
					result = self.POLO.cancelLoanOrder(order['id'])
					if not 'error' in result: logging.info('LOANER: %s %s [%s]' % (market, result["message"].lower(), str(order['id'])))
					else: logging.info('LOANER: %s' % result['error'])
	
	def createLoans(self, balances, offset):
		""" Create loans for all markets in <balances> at the <offset> from the top rate
			- balances = JSON object received from poloniex (available balances)
			- offset = number of 'loanToshis' to offset from the top loan order (offset*0.000001)""" 
		if 'lending' in balances:
			logging.info('LOANER: Checking for coins in lending account')
			for market in balances['lending']:
				if float(balances['lending'][market]) > self.MINAMOUNT:
					result = self.POLO.createLoanOrder(market, balances['lending'][market], float(self.POLO.marketLoans(market)['offers'][0]['rate'])+(offset*0.000001))
					if not 'error' in result: logging.info('LOANER: %s %s %s' % (balances['lending'][market], market, result["message"].lower()))
					else: logging.info('LOANER: %s' % result['error'])