Ejemplo n.º 1
0
    def __fee(self, exchange):
        nonce = str(int(time.time() * 1e6))
        d = dict()
        if exchange == "trt":
            url = "https://api.therocktrading.com/v1/funds/BTCEUR"
            signature = hmac.new(self.secret_trt.encode(),
                                 msg=(str(nonce) + url).encode(),
                                 digestmod=hashlib.sha512).hexdigest()
            _headers = {
                "Content-Type": "application/json",
                "X-TRT-KEY": self.apikey_trt,
                "X-TRT-SIGN": signature,
                "X-TRT-NONCE": nonce
            }
            resp = requests.get(url, headers=_headers)
            d["feetrttaker"] = json.loads(resp.text)["buy_fee"]
            d["feetrtmaker"] = json.loads(resp.text)["sell_fee"]

            return d
        elif exchange == "krk":
            api = krakenex.API(self.apikey_krk, self.secret_krk)
            k = KrakenAPI(api)
            resp = pd.DataFrame(k.get_trade_volume("BTCEUR")[2])
            d["feekrk"] = resp["XXBTZEUR"][0]
            return d
        elif exchange == "bnb":
            resp = self.client.get_trade_fee(symbol="BNBTRX")
            print(resp)
            d["feebnbtaker"] = resp["tradeFee"][0]["taker"]
            d["feebnbmaker"] = resp["tradeFee"][0]["maker"]
            return d
Ejemplo n.º 2
0
 def __order(self, exchange, order):
     nonce = str(int(time.time() * 1e6))
     d = dict()
     if order == None:
         return d
     if exchange == "TRT":
         url = "https://api.therocktrading.com/v1/funds/" + self.pair + "/orders/" + order
         signature = hmac.new(self.secret_TRT.encode(),
                              msg=(str(nonce) + url).encode(),
                              digestmod=hashlib.sha512).hexdigest()
         _headers = {
             "Content-Type": "application/json",
             "X-TRT-KEY": self.apikey_TRT,
             "X-TRT-SIGN": signature,
             "X-TRT-NONCE": nonce
         }
         resp = requests.get(url, headers=_headers)
         print("TRT", resp)
         d["status_TRT"] = json.loads(resp.text)["status"]
         return d
     elif exchange == "krk":
         print(
             "FUNCTION NOT ENABLED ON KRAKEN EXCHANGE, USE OTHER EXCHANGES FOR THIS FEATURE TO WORK"
         )
         exit(2)
         api = krakenex.API(self.apikey_krk, self.secret_krk)
         k = KrakenAPI(api)
         resp = pd.DataFrame(k.get_trade_volume(self.pair)[2])
         d["feekrk"] = resp["XXBTZEUR"][0]
         return d
     elif exchange == "BNB":
         resp = self.client.get_order(symbol=self.pair, orderId=order)
         print("binance", resp)
         d["status_BNB"] = resp["status"]
         return d
Ejemplo n.º 3
0
 def kraken():
     api = krakenex.API()
     k = KrakenAPI(api)
     x = k.get_ticker_information('XBTUSD')
     for i in x:
         a = x.iloc[0][0][0]
     return a
 def _get_backcast_data(self):
     
     api = krakenex.API()
     k = KrakenAPI(api)
     api.load_key('kraken_keys.py')
     df, last = k.get_ohlc_data(self.pair, interval=self.data_agg, ascending=True)
     df.index = df.index.tz_localize(tz='UTC').tz_convert('US/Central')
     return df
Ejemplo n.º 5
0
    def __init__(self):
        super().__init__()
        args = json.load(open('krakenKey.json'))
        api = krakenex.API(**args)
        self.kraken = KrakenAPI(api)

        accounts = self.kraken.get_account_balance()
        print(accounts)
        return
Ejemplo n.º 6
0
 def __init__(self, interval=1, waitInterval=1, **params):
     self.KAPI = KrakenAPI(krakenex.API())
     self.ohlc, self.since = self.KAPI.get_ohlc_data(
         "BTCUSD",
         interval=interval,
         since=None,
         ascending=True,
     )
     self.interval = interval
     self.waitInterval = waitInterval
     super().__init__(**params)
Ejemplo n.º 7
0
    def __init__(self, folder, pair, timezone):

        # initiate api
        self.api = krakenex.API()
        self.k = KrakenAPI(self.api, tier=0, retry=.1)

        # set pair
        self.pair = pair
        self.tz = pytz.timezone(timezone)

        # set and create folder
        self.folder = folder
        os.makedirs(self.folder + pair, exist_ok=True)
Ejemplo n.º 8
0
    def trade(self, exchange, fund_id, side, amount, price):
        nonce = str(int(time.time() * 1e6))
        print(amount)
        amount = round(amount, 8)
        if exchange == "trt":
            url = "https://api.therocktrading.com/v1/funds/" + fund_id + "/orders"
            payload_trt = {
                "fund_id": "BTCEUR",
                "side": side,
                "amount": amount,
                "price": 0
            }
            signature = hmac.new(self.secret_trt.encode(),
                                 msg=(str(nonce) + url).encode(),
                                 digestmod=hashlib.sha512).hexdigest()

            _headers = {
                'User-Agent': 'PyRock v1',
                "Content-Type": "application/json",
                "X-TRT-KEY": self.apikey_trt,
                "X-TRT-SIGN": signature,
                "X-TRT-NONCE": nonce
            }
            resp = requests.post(url,
                                 data=json.dumps(payload_trt),
                                 headers=_headers)
            try:
                return json.loads(resp.text)
            except KeyError:
                return "ERROR"
        elif exchange == "krk":
            api = krakenex.API(self.apikey_krk, self.secret_krk)
            k = KrakenAPI(api)
            resp = k.add_standard_order(fund_id, side, "limit", str(amount),
                                        str(price))
            resp = str(resp).replace("\'", "\"")
            return resp
        elif exchange == "bnb":

            if side == "buy":
                order = self.client.order_limit_buy(symbol=fund_id,
                                                    quantity=round(amount, 8),
                                                    price=price)
            elif side == "sell":
                order = self.client.order_limit_sell(symbol=fund_id,
                                                     quantity=round(amount, 8),
                                                     price=price)
            return dict(order)
Ejemplo n.º 9
0
def get_data(monnaie='XXBTZEUR', interval=60, since=None):
    """Renvoie une DataFrame de max 720 valeurs selon :
        - la paire de monnaie (monnaie) choisie sous forme de string. Par
        defaut elle vaut 'XXBTZEUR' et renvoie donc la valeur du Bitcoin en Euros.
        Si la paire pose problème, tenter de rajouter un X devant la cryptomonaie et
        un Z devant la monnaie "classique", comme pour la valeur par défaut. (se référer
        aux monnaies disponibles sur la plateforme Kraken)
        - l'intervalle (interval) en minutes, qui représente l'intervalle temporel
        entre deux entrées de la DataFrame. Par défaut elle vaut 60.
        - la date de début (since). Par défaut la fonction renvoie
        les 720 dernières valeurs selon l'intervalle choisi.
    """
    api = krakenex.API()
    k = KrakenAPI(api)
    ohlc = k.get_ohlc_data(monnaie, interval, since)
    return ohlc[0]
Ejemplo n.º 10
0
def calculate_capital():

    # Connect to API:
    con = krakenex.API()
    con.load_key(kraken_key_filepath)
    api = KrakenAPI(con)

    volume = api.get_account_balance()
    crypto_on_hand = volume.loc[CRYPTO][0]
    open_position = check_openPosition(crypto_on_hand)
    if open_position:
        current_price = float(
            api.get_ticker_information(CRYPTO + FIAT)['c'][0][0])
        return round(current_price * crypto_on_hand, 2)
    else:
        return round(float(volume.loc[FIAT][0]), 2)
Ejemplo n.º 11
0
    def __init__(self,
                 pair='XXBTZUSD',
                 timezone='America/New_York',
                 folder='data'):

        # initiate api
        api = krakenex.API()
        self.k = KrakenAPI(api, tier=0, retry=.1)

        # set pair
        self.pair = pair
        self.tz = pytz.timezone(timezone)

        # set and create folder
        self.folder = folder
        os.makedirs(os.path.join(self.folder, pair), exist_ok=True)
Ejemplo n.º 12
0
def get_api():
    """Get krakenx API object"""

    log.debug("Getting kraken API object")

    kx_api = krakenex.API(get_secret("KRAKEN_KEY"),
                          get_secret("KRAKEN_SECRET"))
    return KrakenAPI(kx_api)
Ejemplo n.º 13
0
    def __balance(self, exchange):
        nonce = str(int(time.time() * 1e6))
        d = dict()
        if exchange == "trt":

            url = "https://api.therocktrading.com/v1/balances"
            signature = hmac.new(self.secret_trt.encode(),
                                 msg=(str(nonce) + url).encode(),
                                 digestmod=hashlib.sha512).hexdigest()
            _headers = {
                "Content-Type": "application/json",
                "X-TRT-KEY": self.apikey_trt,
                "X-TRT-SIGN": signature,
                "X-TRT-NONCE": nonce
            }
            resp = requests.get(url, headers=_headers)
            d["trtbtc"] = json.loads(resp.text)["balances"][0]["balance"]
            d["trteur"] = json.loads(resp.text)["balances"][8]["balance"]
            return d
        elif exchange == "krk":
            api = krakenex.API(self.apikey_krk, self.secret_krk)
            k = KrakenAPI(api)
            resp = k.get_account_balance()
            d["krkbtc"] = resp["vol"]["XXBT"]
            d["krkbch"] = resp["vol"]["BCH"]
            return d
        elif exchange == "bnb":
            is_fine = True
            while is_fine:
                try:
                    is_fine = False
                except ConnectionError:
                    print(
                        f"{Fore.RED}[ERR] CHECK INTERNET CONNECTION{Style.RESET_ALL}"
                    )
            try:
                d["bnbtrx"] = float(
                    self.client.get_asset_balance(asset="TRX")["free"])
                d["bnbbnb"] = float(
                    self.client.get_asset_balance(asset="BNB")["free"])
            except Exception:
                d["bnbtrx"] = float(
                    self.client.get_asset_balance(asset="TRX")["free"])
                d["bnbbnb"] = float(
                    self.client.get_asset_balance(asset="BNB")["free"])
            return d
Ejemplo n.º 14
0
class KrakenData(Data):
    def __init__(self, interval=1, waitInterval=1, **params):
        self.KAPI = KrakenAPI(krakenex.API())
        self.ohlc, self.since = self.KAPI.get_ohlc_data(
            "BTCUSD",
            interval=interval,
            since=None,
            ascending=True,
        )
        self.interval = interval
        self.waitInterval = waitInterval
        super().__init__(**params)

    async def dataGenerator(self):
        wait = 60
        maxRows = 2880
        blockSize = 1440
        retry = 0
        timer = None
        while retry < 10:
            if timer is not None:
                await timer
            try:
                ohlcnew, self.since = self.KAPI.get_ohlc_data(
                    "BTCUSD",
                    interval=self.interval,
                    since=self.since,
                    ascending=True,
                )
            except Exception:
                await asyncio.sleep(wait)
                retry += 1
                continue
            # Remove the last enty as it is unconfirmed
            retry = 0
            self.ohlc.drop(self.ohlc.tail(1).index, inplace=True)
            self.ohlc = self.ohlc.append(ohlcnew)
            if len(self.ohlc) >= maxRows:
                self.ohlc.drop(self.ohlc.head(blockSize).index, inplace=True)
            timer = asyncio.create_task(asyncio.sleep(self.waitInterval *
                                                      wait))
            yield self.ohlc
        raise ConnectionError("Retry Exceeded 10")
Ejemplo n.º 15
0
def create_client_from_config(config):
    retry = config["API"].get("retry", 0)
    crl_sleep = config["API"].get("crl_sleep", 5)
    tier = config["API"].get("tier", "Intermediate")
    api_key = config["API"].get("key", None)
    secret = config["API"].get("secret", None)
    client = krakenex.API(key=api_key, secret=secret)
    client = KrakenAPI(client,
                       retry=float(retry),
                       crl_sleep=float(crl_sleep),
                       tier=tier)
    return client
Ejemplo n.º 16
0
class CryptoTracker(object):
    def __init__(self, config):
        api = krakenex.API()
        self.k = KrakenAPI(api)
        self.config = config

    def get_exchange_rate(self, crypto, fiat):
        pair = "X{}Z{}".format(crypto, fiat)
        ticker = self.k.get_ticker_information(pair)
        return ticker

    def get_currencies(self):
        return {
            'XRP': XrpHandler(self.config),
            'ETH': EthHandler(self.config),
            'XBT': XbtHandler(self.config),
            'LTC': LtcHandler(self.config),
        }

    def get_local_currency(self):
        return self.config.local_currency

    def get_fiat_currency(self):
        return self.config.fiat_currency

    def get_exchange_rates(self, base=None):
        url = 'https://api.fixer.io/latest'
        if base is not None:
            url += '?base={}'.format(base)
        req = requests.get(url)

        rates = json.loads(req.text)
        return rates['rates']

    def update_currencies(self):
        accounts = self.config.accounts

        balances = defaultdict(float)
        rates = defaultdict(float)
        crypto_currencies = self.get_currencies()

        for curr in accounts.keys():
            ohlc = self.get_exchange_rate(
                curr, crypto_currencies[curr].fiat_currency())
            if ohlc is not None and len(ohlc) > 0:
                rates[curr] = float(ohlc.iloc[0]['c'][0])
            balances[curr] += crypto_currencies[curr].update(accounts[curr])
        positions = {
            curr: balances[curr] * rates[curr]
            for curr in balances if curr in rates and curr in balances
        }
        return balances, positions
Ejemplo n.º 17
0
    def __init__(self, instance, data={}, parent=None):
        JSConfigClient.__init__(self,
                                instance=instance,
                                data=data,
                                parent=parent,
                                template=TEMPLATE)
        import krakenex
        from pykrakenapi import KrakenAPI

        kraken_api = krakenex.API()
        kraken_api.key = self.config.data["api_key_"]
        kraken_api.secret = self.config.data["private_key_"]
        self.api = KrakenAPI(kraken_api)
    def __init__(self, exchanges):
        '''exchanges = comma separated list of exchanges you want to monitor'''
        self.exchanges = [e.lower() for e in exchanges]

        # Depending on which exchanges got included, connect to APIs
        if 'kraken' in self.exchanges:
            self.kraken_api = krakenex.API()
            self.kraken = KrakenAPI(self.kraken_api)
        if 'gdax' in self.exchanges:
            self.gdax = gdax_api.PublicClient()
        if 'bittrex' in self.exchanges:
            self.bittrex = Bittrex(None, None)
        if 'coinmarketcap' in self.exchanges:
            self.coinmarketcap = Market()
Ejemplo n.º 19
0
    def connect_account(self, kraken_key_filepath):
        '''Connects to a private Kraken account.

        kraken_key_filepath : str
            kraken_key_filepath must be a Python file in the format:

            <API_KEY>
            <API_SECRET_KEY>

            On the first two lines.

        pair : ticker pair that you are trading
        interval : aggregation of the historical data
        '''

        # Connect to API:
        con = krakenex.API()
        con.load_key(kraken_key_filepath)
        api = KrakenAPI(con)
        return api, con
Ejemplo n.º 20
0
    def __init__(self,market=None):

        #Make sure the intialised values are set for the Connections
        if market==None:
            raise NameError("No market pair defined. Add pair=xxx to the Controller initialization")


        #Make the connections once for better practice
        #without storing keys
        #Try make a connection to the Kracken API
        try:
            api = krakenex.API()
            #Use the kraken wapper for better functionality
            self.client = KrakenAPI(api)
        except:
            print("Couldn't make a connection to the Kraken API")
            print("exit")
            sys.exit(1)
        
        #
        self.market = market
Ejemplo n.º 21
0
class GetTradeData(object):
    def __init__(self,
                 pair='XXBTZUSD',
                 timezone='America/New_York',
                 folder='data'):

        # initiate api
        api = krakenex.API()
        self.k = KrakenAPI(api, tier=0, retry=.1)

        # set pair
        self.pair = pair
        self.tz = pytz.timezone(timezone)

        # set and create folder
        self.folder = folder
        os.makedirs(os.path.join(self.folder, pair), exist_ok=True)

    def download_trade_data(self, since):

        folder = os.path.join(self.folder, self.pair)

        # update or new download
        if since is 0:
            fs = os.listdir(folder)
            if len(fs) > 0:
                fs.sort()
                last = int(fs[-1].split('.')[0])
            else:
                last = 0
        else:
            last = since

        # get data
        while True:
            try:
                time.sleep(0.75)
                fname = os.path.join(folder,
                                     '{}.pickle'.format(str(last).zfill(19)))
                trades, last = self.k.get_recent_trades(pair=self.pair,
                                                        since=last)

                # set timezone
                index = trades.index.tz_localize(pytz.utc).tz_convert(self.tz)
                trades.index = index

                # store
                print('Data Downloader: storing', fname)
                trades.to_pickle(fname)

            except AttributeError:  # can't tz_localize on empty (last) trades
                print('Data Downloader: download/update finished!')
                break

    def agg_ohlc(self, since, interval=[0]):

        folder = os.path.join(self.folder, self.pair)
        if interval == [0]:
            from config import INTERVALS
            interval = INTERVALS

        # fetch files and convert to dataframe
        fs = os.listdir(folder)
        fs.sort(reverse=True)
        if since > 0:
            fs = [f for f in fs if int(f.split('.')[0]) >= since * 1e9]

        trades = []
        for f in fs:
            print(f)
            if f[0] == '.':
                continue
            trades.append(pd.read_pickle(os.path.join(folder, f)))
        trades = pd.concat(trades, axis=0)
        trades.loc[:, 'cost'] = trades.price * trades.volume

        # store on disc
        # fname = self.folder + self.pair + '_trades.pickle'
        # print('\nData Downloader: storing', fname)
        # trades.to_pickle(fname)

        for i in interval:
            # resample
            gtrades = trades.resample('{}min'.format(i))
            if i == 1:
                fname = os.path.join(self.folder, 'OHLC',
                                     self.pair + '.pickle')
            else:
                fname = os.path.join(self.folder, 'OHLC',
                                     self.pair + '_{}.pickle'.format(i))

            # ohlc, volume
            ohlc = gtrades.price.ohlc()
            ohlc.loc[:, 'volume'] = gtrades.volume.sum()
            ohlc.volume.fillna(0, inplace=True)
            closes = ohlc.close.fillna(method='pad')
            ohlc = ohlc.apply(lambda x: x.fillna(closes))

            # vwap
            ohlc.loc[:, 'vwap'] = gtrades.cost.sum() / ohlc.volume
            ohlc.vwap.fillna(ohlc.close, inplace=True)

            # count
            ohlc.loc[:, 'count'] = gtrades.size()

            # store on disc

            print('\nData Downloader: storing', fname)
            ohlc.to_pickle(fname)
Ejemplo n.º 22
0
import krakenex
from pykrakenapi import KrakenAPI
api = krakenex.API()
k = KrakenAPI(api)
ohlc, last = k.get_ohlc_data(pair="BCHUSD", interval=30)
print('Fetching from Kraken API:\n', ohlc.head(1), '\n')

import numpy as np
import talib

close = np.array(ohlc.close.to_list())
high = np.array(ohlc.high.to_list())
low = np.array(ohlc.low.to_list())
print("Candlestick information:")
print("Candle Close\n", close[-10:], "\n")
print("Candle High\n", high[-10:], "\n")
print("Candle Low\n", low[-10:], "\n")

simple_moving_average = talib.SMA(close)
print("simple_moving_average:\n", simple_moving_average[-10:], "\n")

macd, macdsignal, macdhist = talib.MACD(close,
                                        fastperiod=12,
                                        slowperiod=26,
                                        signalperiod=9)
print("MACD:\n", macd[-10:], "\n")

parbolic_sar = talib.SAR(high, low, acceleration=1, maximum=1)
print("parbolic_sar:\n", parbolic_sar[-10:], "\n")
import pandas as pd
import matplotlib.pyplot as plt
import boto
import schedule
import time
from logger import logging
import requests
session = requests.Session()
session.verify = False

import krakenex
from pykrakenapi import KrakenAPI
api = krakenex.API()
k = KrakenAPI(api)
api.load_key('kraken_keys.py')

df = k.get_trades_history(start=1558587601)[0]
df.index = df.index.tz_localize(tz='UTC').tz_convert('US/Central')

cols = ['ordertxid','cost', 'fee', 'margin', 'price', 'vol', 'type', 'ordertype']
df2 = df[cols].reset_index().groupby('ordertxid', as_index=False).agg({'dtime':'first', 'cost':'sum', 'fee':'sum', 'margin':'sum', 'price':'sum','vol':'sum', 'type':'first', 'ordertype':'first' })
df3 = df2.set_index('dtime').sort_values('dtime')
df3['is_closing'] = ['open' if x=='limit' else 'close' for x in df3['ordertype']]

def is_long(row):
    order_type = row[0]
    is_closing = row[1]
    if ((order_type=='buy') & (is_closing=='open')) | ((order_type=='sell') & (is_closing=='close')):
        return 'long'
    else:
        return 'short'
Ejemplo n.º 24
0
class GetTradeData(object):
    def __init__(self, folder, pair, timezone):

        # initiate api
        self.api = krakenex.API()
        self.k = KrakenAPI(self.api, tier=0, retry=.1)

        # set pair
        self.pair = pair
        self.tz = pytz.timezone(timezone)

        # set and create folder
        self.folder = folder
        os.makedirs(self.folder + pair, exist_ok=True)

    def download_trade_data(self, since):

        folder = self.folder + self.pair + '/'

        # update or new download?
        if since is 0:
            fs = os.listdir(folder)
            if len(fs) > 0:
                fs.sort()
                last = int(fs[-1].split('.')[0])
            else:
                last = 0
        else:
            last = since

        # get data
        while True:
            try:
                fname = folder + '{}.pickle'.format(str(last).zfill(19))
                trades, last = self.k.get_recent_trades(pair=self.pair,
                                                        since=last)

                # set timezone
                index = trades.index.tz_localize(pytz.utc).tz_convert(self.tz)
                trades.index = index

                # store
                print('storing', fname)
                trades.to_pickle(fname)

            except CallRateLimitError:
                print('\n this should not happen. please report an issue on '
                      'github! thanks. \n')
                raise

            except ValueError:
                print('download/update finished!')
                break

    def agg_ohlc(self, interval):

        folder = self.folder + self.pair + '/'

        # fetch files and convert to dataframe
        fs = os.listdir(folder)
        fs.sort(reverse=True)
        trades = []
        for f in fs:
            trades.append(pd.read_pickle(folder + f))
        trades = pd.concat(trades, axis=0)
        trades.loc[:, 'cost'] = trades.price * trades.volume

        # resample
        gtrades = trades.resample('{}min'.format(interval))

        # ohlc, volume
        ohlc = gtrades.price.ohlc()
        ohlc.loc[:, 'vol'] = gtrades.volume.sum()
        ohlc.vol.fillna(0, inplace=True)
        closes = ohlc.close.fillna(method='pad')
        ohlc = ohlc.apply(lambda x: x.fillna(closes))

        # vwap
        ohlc.loc[:, 'vwap'] = gtrades.cost.sum() / ohlc.vol
        ohlc.vwap.fillna(ohlc.close, inplace=True)

        # count
        ohlc.loc[:, 'count'] = gtrades.size()

        # store on disc
        fname = self.folder + self.pair + '_{}.pickle'.format(interval)
        print('storing', fname)
        ohlc.to_pickle(fname)
Ejemplo n.º 25
0
 def __init__(self, config):
     api = krakenex.API()
     self.k = KrakenAPI(api)
     self.config = config
Ejemplo n.º 26
0
Created on Mon Dec 18 13:03:45 2017

@author: austin
"""

import krakenex
from pykrakenapi import KrakenAPI
#import os

api = krakenex.API()
key = "ignored/new_key.key"
api.load_key(key)

api.query_private(method="Balance")

k = KrakenAPI(api)

k.get_account_balance()
k.get_trades_history()

ohlc, last = k.get_ohlc_data("BCHUSD")
print(ohlc)
print(last)

# open trade
descr = k.add_standard_order(pair="XBTEUR",
                             type="buy",
                             ordertype="market",
                             volume=0.002)
descr
k.get_open_orders(trades=True)
Ejemplo n.º 27
0
class Kraken(ExchangeBase, ABC):
    def __init__(self):
        super().__init__()
        args = json.load(open('krakenKey.json'))
        api = krakenex.API(**args)
        self.kraken = KrakenAPI(api)

        accounts = self.kraken.get_account_balance()
        print(accounts)
        return
        # for account in accounts:
        #     currency = account['currency']
        #     balance = float(account['available'])
        #     self.wallets[currency] = Wallet(currency, balance)
        #     print(currency, balance)
        #     if balance > self.valueWallet.amount:
        #         self.valueWallet = self.wallets[currency]

        # self.fee = 0.0025

    def get_last_trade_price(self, symbol):
        ticker = self.kraken.get_product_ticker(symbol)
        return float(ticker['price'])

    def buy(self, key):
        buy_symbol = (key + "-" + self.arbitrar.currency).replace(
            "BTC", "XBT").replace("-", "")
        amount = str(self.arbitrar.amount // 0.01 / 100)
        order = self.kraken.buy(product_id=buy_symbol,
                                type='market',
                                funds=amount)
        if 'message' in order.keys():
            raise InsufficientFundsError(order['message'])

        settled = order['settled']
        while not settled:
            order = self.kraken.get_order(order['id'])
            settled = order['settled']
            time.sleep(0.12)

        self.wallets[key].amount = float(order['filled_size'])
        self.arbitrar.amount = 0
        self.valueWallet = self.wallets[key]

        # NOTE: This includes the fee!
        rate = float(order['executed_value']) / float(order['filled_size'])

        return buy_symbol, rate

    def sell(self):
        sell_symbol = (self.valueWallet.currency + "-" +
                       self.arbitrar.currency).replace("BTC",
                                                       "XBT").replace("-", "")
        amount = str(self.valueWallet.amount)
        order = self.kraken.sell(product_id=sell_symbol,
                                 type='market',
                                 size=amount)
        if 'message' in order.keys():
            raise InsufficientFundsError(order['message'])

        settled = order['settled']
        while not settled:
            order = self.kraken.get_order(order['id'])
            settled = order['settled']
            time.sleep(0.12)

        self.arbitrar.amount = float(order['executed_value'])
        self.valueWallet.amount = 0
        self.valueWallet = self.arbitrar

        # NOTE: This includes the fee!
        rate = float(order['executed_value']) / float(order['filled_size'])

        return sell_symbol, rate

    def get_name(self):
        return "kraken"
Ejemplo n.º 28
0
def get_price_from_kraken(kraken_token):
    krakenApi = KrakenAPI(krakenex.API());
    krakenprice = krakenApi.get_ticker_information(kraken_token).loc[kraken_token]['a'][0]
    return float(krakenprice)
import sys, json, numpy as np
import krakenex
from pykrakenapi import KrakenAPI
import decimal
import time
import nltk
import numpy as np
import random
import string
from sklearn.linear_model import LinearRegression

#connection to the kraken api
api = krakenex.API()
k = KrakenAPI(api)

#user message treatement
greeting_input = (
    "hello",
    "hi",
    "greetings",
    "what's up",
    "hey",
)
greeting_responses = ["hi !", "hey !", "hi there !", "hello !"]
farewell_input = ("bye", "goodbye")
simple_question_input = ("open", "close", "high", "low", "vwap", "volume")
possible_pairs = ("bcheur", "bchusd", "bchxbt", "xxbtzeur", "xbtzusd",
                  "xethxxbt", "xethzusd", "xethzeur")
predictions_input = ("short", "long", "short-term", "long-term")
sample_input = ("yesterday", "week", "weeks")
Ejemplo n.º 30
0
    def __init__(self, key=[''], secret=[''], sftppassword='', settings=None):
        """
        Constructor of the Kraken Core Class
        
        This sets up the connection to Kraken and sets the global
        variables. 
        
        Parameters
        ----------
        key : list of str, optional
        -The keys to a kraken account
        secret : list of str, optional
        -The secrets to a kraken account
        sftppassword : str, optional
        -The password to the sftpserver
        settings : dict, optional
        - A dictionary of the settings to be used
        Returns
        -------
        Class 
        - A kraken core class
        """

        #Check if market specified in settings file and
        #Figure out what market we are interested in
        if not "Ex_Market1" in settings.keys():
            print(
                "Need a Kraken Exchange market specified in the settings file")
            print("Specify Ex_Market1 keyword in settings file")
            raise
        if not "Ex_Market2" in settings.keys():
            print(
                "Need a Kraken Excahnge market 2 specified in the settings file"
            )
            print("Specify Ex_Market2 keyword in settings file")
            raise

        else:
            market = settings["Ex_Market1"] + settings["Ex_Market2"]

        #
        #Do Trivial checks
        if market == "":
            raise NameError(
                "No market pair defined. Add pair=xxx to the Controller initialization"
            )
        if key == ['']:
            print(
                "No Kraken Key defined. No key=xxx given to the Controller initialization"
            )
        if secret == ['']:
            print(
                "No Kraken secret defined. No secret=xxx given to the Controller initialization"
            )

        #Make the connections once for better practice
        #without storing keys
        #Try make all connection to the Kracken API
        try:

            print("Using Keys from input")
            print("*****MAKE SURE KEYS/SECRETS IN RIGHT ORDER")
            #Loop over all keys/secrets
            self.clients = []
            for keyj, secretj in zip(key, secret):

                #Make the connection
                api_j = krakenex.API(key=keyj, secret=secretj)
                #Use the kraken wapper for better functionality
                self.clients.append(KrakenAPI(api_j))

            #Make a way to cycle through the keys
            self.client_cycler = cycle(self.clients)
        except:
            traceback.print_exc()
            print("Couldn't make a connection to the Kraken API")
            print("exit")
            raise

        #Setup FileBot if there is any
        self.Setup_FileBot(settings, sftppassword)

        #Save for later
        self.market = market
        self.min_price = settings["min_increment"]  #This is not bp
        self.bp = 0.0001  #This is bp
        self.acct_mrkt1 = self.Kraken_Lookup_Acct_Market(
            settings["Ex_Market1"])
        self.acct_mrkt2 = self.Kraken_Lookup_Acct_Market(
            settings["Ex_Market2"])

        #Find the number of significant digits so we can round
        #the price later
        digits = format(self.min_price, ".16f")
        #Seperate based on dot
        digits = digits.partition(".")[2]
        self.min_price_digit = len(digits) - len(digits.lstrip("0")) + 1

        #Setup stuff
        if "dust" in settings.keys():
            self.dust = settings["dust"]

        if "volume" in settings.keys():
            self.tot_vol = settings["volume"]

        if "odepth" in settings.keys():
            self.odepth = settings["odepth"]