def _get_client(cls):
        """
        Get an authenticated GDAX client

        :returns: an authenticated GDAX client
        :raises KeyError: Error raised if environment variables are not set
        """

        try:
            key = os.environ[GDAXTrader.GDAX_KEY_ENV]
            secret = os.environ[GDAXTrader.GDAX_SECRET_ENV]
            passphrase = os.environ[GDAXTrader.GDAX_PASSPHRASE_ENV]
        except KeyError as error:
            raise KeyError(
                'Missing environment variable for GDAX: '.format(error))

        try:
            api_url = os.environ[GDAXTrader.GDAX_API_URL_ENV]
        except KeyError:
            client = gdax.AuthenticatedClient(key, secret, passphrase)
        else:
            client = gdax.AuthenticatedClient(key,
                                              secret,
                                              passphrase,
                                              api_url=api_url)

        return client
Example #2
0
def initialize_gdax(test_bool):
    key, secret, passphrase = load_gdax_auth(test_bool)
    if test_bool == True:
        logger.info("Initialize GDAX Sandbox API")
        bot_db.db.my_db = 'gdax_test'
        bot_db.db.set_engine()
        ac = gdax.AuthenticatedClient(key, secret, passphrase,
                api_url="https://api-public.sandbox.gdax.com")
    if test_bool == False:
        logger.info("Initialize live GDAX API")
        bot_db.db.my_db = 'gdax'
        bot_db.db.set_engine()
        ac = gdax.AuthenticatedClient(key, secret, passphrase)
    return(ac)
Example #3
0
def get_last_fill(total_ventas,
                  total_compras):  #hace falta pasar variables total ventas
    auth_client = gdax.AuthenticatedClient(key, b64secret, passphrase)
    response = auth_client.get_fills()

    for x in response:
        for y in x:
            t = y
            if (t["order_id"] == last_sell_id):
                print(bcolors.CLOSED + "Se ejecuta la orden de venta" +
                      bcolors.ENDC)
                total_operacion_venta = float(t["price"]) * float(t["size"])
                print("Total operacion venta: " + str(total_operacion_venta))
                total_ventas = total_ventas + total_operacion_venta
                ########REVISAR ESTE indicador_ventas=indicador_ventas+1    UnboundLocalError: local variable 'indicador_ventas' referenced before assignment
                return 1  #Valor de indicador

            #ponemos el indicador para que indique que se realizo una venta..
            elif (t["order_id"] == last_buy_id):
                print(bcolors.CLOSED + "Se ejecuta la orden de compra" +
                      bcolors.ENDC)
                total_operacion_compra = float(t["price"]) * float(t["size"])
                print("Total operacion compra: " + str(total_operacion_compra))
                total_compras = total_compras + total_operacion_compra
                #########REVISAR ESTE indicador_compras=indicador_compras+1
                return -1
Example #4
0
    def buy_product(self, price):

        if not self.can_buy():
            return -1

        if price <= 0:
            raise RuntimeError('Cannot buy for a negative price')

        #auth_client = gdax.AuthenticatedClient(SANDBOX_API_KEY, SANDBOX_API_SECRET, SANDBOX_API_PASSPHRASE, api_url="https://api-public.sandbox.gdax.com")
        auth_client = gdax.AuthenticatedClient(API_KEY, API_SECRET, API_PASSPHRASE)

        amount = round(self.period_euro_limit / price, 8)
        price = round(price, 8)

        resp = auth_client.buy(price=price, size=amount, product_id=self.product)

        print(resp)

        if 'id' in resp:
            # Ordine piazzato con successo
            # TODO: Verificare se l'ordine verrà mai completato

            print("[", self.product, "] Buy order placed, id: ",resp['id'] ,", status: ", resp['status'], sep='')

            self.last_buy_time = time()

            try:
                with (open(self.file_path, "wb")) as file:
                    pickle.dump(self.last_buy_time, file)
            except:
                print("[", self.product, "] Error saving file", self.file_path, sep='')

            return True

        return False
Example #5
0
 def _init_client(self):
     url = "https://api.gdax.com"
     if self.sandbox:
          url = "https://api-public.sandbox.gdax.com"
     self.client_public = gdax.PublicClient()
     self.client_private = gdax.AuthenticatedClient(
                           self.api_key,self.api_secret,self.api_pass,url)
Example #6
0
def gdax_transactions():
    transactions = []
    apiclient = gdax.AuthenticatedClient(apikeys.gdax["apiKey"],
                                         apikeys.gdax["secret"],
                                         apikeys.gdax["password"])
    gdax_accounts = apiclient.get_accounts()
    for a in gdax_accounts:
        ah = apiclient.get_account_history(account_id=a["id"])
        for txs in ah:
            for tx in txs:
                created = dp(tx["created_at"])
                if tx["type"] in ["fee", "match"]:
                    transactions.append([
                        created,
                        "gdax",
                        tx["type"],
                        a["currency"],
                        Decimal(tx["amount"]),
                        tx["details"],
                    ])
                else:
                    transactions.append([
                        created,
                        "gdax",
                        tx["type"],
                        a["currency"],
                        Decimal(tx["amount"]),
                        tx["details"],
                    ])
    return transactions
Example #7
0
    def authorize_gdax_account(self,
                               api_key=None,
                               api_secret_key=None,
                               api_passphrase=None):
        """
		Returns an authenticated client given valid api credentials

		Go to https://www.gdax.com/settings/api to create API credentials.
		As far as I can tell, the View, Trade and Manage permissions are necessary.
		(Not 100% sure what Manage does however.)

		Parameters:
			api_key: string
				32 character string representing the account's api key
			api_secret_key: string
				88 character string representing the account's api secret key
			api_passphrase: string
				11 character string representing the account's api passphrase

		Returns:
			authenticated_client: gdax.AuthenticatedClient
				Authenticated client that has access to GDAX account identified
				by the API key, secret key and passphrase.
		"""

        if api_key is None or api_secret_key is None or api_passphrase is None:
            raise ValueError(
                'Must input API credentials into authorize_gdax_account()')

        authenticated_client = gdax.AuthenticatedClient(
            api_key, api_secret_key, api_passphrase)

        return authenticated_client
Example #8
0
 def __init__(self):
     """Initializer."""
     config = utils.read_config()
     self._client = gdax.AuthenticatedClient(
         key=config['key'],
         b64secret=config['secret'],
         passphrase=config['passphrase'])
Example #9
0
def buyAtBestPrice(size='0.01', product_id='LTC-EUR'):

    myInfo = infoPerso.infoPerso()

    auth_client = gdax.AuthenticatedClient(myInfo.gdax_key,
                                           myInfo.gdax_b64secret,
                                           myInfo.gdax_passphrase)

    publicClient = gdax.PublicClient()
    ticker = publicClient.get_product_ticker(product_id)

    price = float(ticker['price']) - 0.5
    keys = {'size': size, 'product_id': product_id, 'price': price}
    order = auth_client.buy(**keys)
    print(order)

    count = 0
    while (count < 60):
        time.sleep(1)
        auth_client.cancel_order(order['id'])
        ticker = publicClient.get_product_ticker(product_id)
        price = float(ticker['price']) - 0.5
        keys = {'size': size, 'product_id': product_id, 'price': price}
        order = auth_client.buy(**keys)
        print(order)
        count = count + 1

    return order
Example #10
0
    def __init__(self,
                 name="Bot",
                 currency="BTC-USD",
                 transition_buffer=0.4,
                 webSocket=None):

        #obtain credentials, authenticate GDAX client and websocket, and then over-write credentials
        self._passphrase = ""
        self._secret = ""
        self._key = ""
        self.get_credentials(credentials_file="../../credentials.txt"
                             )  #fills in passphrase, secret, and key
        self._client = gdax.AuthenticatedClient(self._key, self._secret,
                                                self._passphrase)
        self._socket = webSocket
        self.scramble_credentials(
        )  #over-writes the credentials with new characters

        self._name = name
        self._fsm = FSM(state_usage=[3, 4, 5])
        self._currency = currency
        self._running = False
        self._calibration = False

        # These fields will only be used for fake trading analysis. Each bot will keep a portfolio
        # and at the end of program execution, we'll plot the bots against each other
        self._prices_at_trading = [
        ]  #keeps the price history of the crypto at the trading points
        self._portfolio_at_trading = [
        ]  #keeps the value history of the bot's portfolio
        self._crypto = 0  #set an initial value for fake crypto
        self._cash = float(
            self.client().get_product_ticker(product_id=self.currency())
            ["price"])  #set an initial fake cash value
Example #11
0
def login():
    """
    Prompts the user for their GDAX API key, secret, and passphrase before
    logging into the trading system.

    @return: authenticated GDAX Client object
    """

    # TODO: Add a helper message with GDAX instructions and a security disclaimer

    while True:
        print("Enter your GDAX API key: ")
        api_key = input()

        print("Enter your secret: ")
        secret = input()

        print("Enter your passphrase: ")
        passphrase = input()

        print("\nAuthenticating...")
        gdax_client = gdax.AuthenticatedClient(api_key, secret, passphrase)

        if True: # TODO: Check if authentication was successful
            config["STATE"]["LOGGED_IN"] = True
            config["CREDENTIALS"]["API_KEY"] = api_key
            config["CREDENTIALS"]["SECRET"] = secret
            config["CREDENTIALS"]["PASSPHRASE"] = passphrase

            return gdax_client
        else:
            print("\nInvalid credentials. Please try again.\n")
Example #12
0
def main():
    logging.basicConfig(format="%(asctime)s - %(message)s",
                        datefmt="%m/%d/%Y %I:%M:%S %p",
                        filename="../ctrade.log",
                        level=logging.DEBUG)
    logging.info("CryptoTrade has started successfully.")

    auth_client = gdax.AuthenticatedClient("", "", "", api_url="")
    accounts = auth_client.get_accounts()
    for i in accounts:
        if i["currency"] == "BTC":
            wallet = i

    base = 3600.0

    for _ in range(100):
        ticker = auth_client.get_product_ticker(product_id="BTC-USD")
        price = float(ticker["price"])
        print(price)
        if price >= base:
            newPrice = str(round(price * 1.1, 2))
            newSize = str(round(float(wallet["available"]) / 2, 10))
            auth_client.sell(price=newPrice,
                             size=newSize,
                             product_id="BTC-USD")
            print("SELL: {0} BTC at ${1} per".format(newSize, newPrice))
        time.sleep(5)
        accounts = auth_client.get_accounts()
        for i in accounts:
            if i["currency"] == "BTC":
                wallet = i

    exit(0)
 def __init__(self, exchangeName):
     if exchangeName == "GDAX":
         self.exchangeName = "GDAX"
         exchange.auth_client = gdax.AuthenticatedClient(
             exchange.loginData['key'], exchange.loginData['b64secret'],
             exchange.loginData['passphrase'],
             exchange.loginData['api_url'])
Example #14
0
    def __init__(self, name="Bot", currency="BTC-USD", webSocket=None):

        #obtain credentials, authenticate GDAX client and websocket, and then over-write credentials
        self._passphrase = ""
        self._secret = ""
        self._key = ""
        self.get_credentials(credentials_file="../../credentials.txt"
                             )  #fills in passphrase, secret, and key

        #main body parts
        self._data_center = DataCenter(self)
        self._client = gdax.AuthenticatedClient(self._key, self._secret,
                                                self._passphrase)
        self._socket = webSocket
        self._trade_hands = TradeHands(self)

        #other bot stuff
        self._name = name
        self._currency = currency
        self._running = False
        self._fake_crypto = 0  #set an initial value for fake crypto
        self._fake_cash = 1000  #set an initial fake cash value

        self._socket.set_data_center(self._data_center)
        self._socket.set_bot(self)

        self.scramble_credentials()
Example #15
0
def gdax_price(market, ts):
    if os.path.exists("gdax_price.pickle"):
        with open("gdax_price.pickle", "rb") as f:
            p = pickle.load(f)
    else:
        p = {}
    if (market, ts) in p:
        amt = p[market, ts]
    else:
        c = gdax.AuthenticatedClient(apikeys.gdax["apiKey"],
                                     apikeys.gdax["secret"],
                                     apikeys.gdax["password"])
        data = c.get_product_historic_rates(
            market,
            start=ts.isoformat(),
            end=(ts + timedelta(minutes=1)).isoformat())
        sleep(0.5)
        try:
            amt = Decimal(data[0][1])
        except IndexError:
            print(market, ts, data)
            raise
        with open("gdax_price.pickle", "wb") as f:
            p[market, ts] = amt
            pickle.dump(p, f)
    # print(f"gdax price {market} {amt:0.2f}")
    return amt
Example #16
0
def main(argv):
    if len(argv) < 2:
        raise IOError("No config file provided. Usage: " + argv[0] +
                      " CONFIG_FILE")

    config_file = os.path.expanduser(argv[1])
    config_parser = ConfigParser()
    config_parser.read([config_file])

    key = config_parser.get("GDAXKeys", "key")
    secret = config_parser.get("GDAXKeys", "secret")
    passphrase = config_parser.get("GDAXKeys", "passphrase")

    auth_client = gdax.AuthenticatedClient(key,
                                           secret,
                                           passphrase,
                                           api_url="https://api.gdax.com")
    print auth_client.get_accounts()
    print auth_client.get_product_24hr_stats("BTC-USD")
    prev_price = -1.0
    while True:
        ticker = auth_client.get_product_ticker("BTC-USD")
        print(ticker)
        current_price = float(ticker["price"])
        if current_price < (0.95 * prev_price):
            print "BUY BUY BUY at", current_price
        prev_price = current_price
        time.sleep(5)
Example #17
0
 def get_auth_client():
     config = json.loads(open('priv/cred.json').read())
     key = config["key"]
     pf = config["pf"]
     se = config["se"]
     api_url = config["api_url"]
     return gdax.AuthenticatedClient(key, se, pf, api_url=api_url)
Example #18
0
 def __init__(self):
     if settings.USE_AUTH_CLIENT:
         self.client = gdax.AuthenticatedClient(settings.API_KEY,
                                                settings.API_SECRET,
                                                settings.API_KEY_PASSPHRASE)
     else:
         self.client = gdax.PublicClient()
Example #19
0
def vende(precio, cantidad):
    auth_client = gdax.AuthenticatedClient(key, b64secret, passphrase)
    r = auth_client.sell(price=precio, size=cantidad, product_id=producto)
    if 'message' in r:
        print(r['message'])
        return None
    else:
        return r
Example #20
0
    def __init__(self):
        with open('../TradingAlgo/secrets.txt') as f:
            gdax_info = f.readlines()

        passphrase = (gdax_info[0].split(':'))[1].strip()
        key = (gdax_info[1].split(':'))[1].strip()
        secret = (gdax_info[2].split(':'))[1].strip()
        self.auth_client = gdax.AuthenticatedClient(key, secret.encode('ascii'), passphrase)
Example #21
0
    def __init__(self, options: ExchangeConfig) -> None:
        super(GDAXExchange, self).__init__(options)
        self._type = ExchangeType.GDAX
        self._last = None
        self._orders = {}

        if options.trading_type == TradingType.LIVE:
            self._key, self._secret, self._passphrase = get_keys_from_environment(
                'GDAX')
            self._client = gdax.AuthenticatedClient(self._key, self._secret,
                                                    self._passphrase)

        elif options.trading_type == TradingType.SANDBOX:
            self._key, self._secret, self._passphrase = get_keys_from_environment(
                'GDAX_SANDBOX')
            self._client = gdax.AuthenticatedClient(
                self._key,
                self._secret,
                self._passphrase,
                api_url=EXCHANGE_ORDER_ENDPOINT(ExchangeType.GDAX,
                                                TradingType.SANDBOX))

        val = self._client.get_accounts() if hasattr(self, '_client') else []

        print(val)
        if isinstance(val, dict) and val.get('message') == 'Invalid API Key':
            raise Exception('Something went wrong with the API Key')

        self._accounts = []
        for jsn in val:
            currency = str_to_currency_type(jsn.get('currency'))
            balance = float(jsn.get('balance', 'inf'))
            id = jsn.get('id', 'id')
            account = Account(id=id, currency=currency, balance=balance)
            self._accounts.append(account)

        self._subscription = [
            json.dumps({
                "type": "subscribe",
                "product_id": GDAXExchange.currency_pair_to_string(x)
            }) for x in options.currency_pairs
        ]
        self._heartbeat = json.dumps({"type": "heartbeat", "on": True})

        self._seqnum_enabled = False  # FIXME?
Example #22
0
def initialize_gdax():
    global joker
    joker = False
    gdax_auth = json.load(open('/home/bitnami/auth/gdax'))
    secret = gdax_auth['secret']
    key = gdax_auth['key']
    passphrase = gdax_auth['passphrase']
    ac = gdax.AuthenticatedClient(key, secret, passphrase)
    return (ac)
Example #23
0
def readKeys():
    with open("keys.txt") as key:
        keyList = list(map(str, key))
    API_KEY = keyList[0][keyList[0].find(":") + 1:keyList[0].find("\\")]
    API_SECRET = keyList[1][keyList[1].find(":") + 1:keyList[1].find("\\")]
    PASSPHRASE = keyList[2][keyList[2].find(":") + 1:keyList[2].find("\\")]
    ID = keyList[3][keyList[3].find(":") + 1:]
    client = gdax.AuthenticatedClient(API_KEY, API_SECRET, PASSPHRASE)
    return client, ID
Example #24
0
def get_order_list():
    auth_client = gdax.AuthenticatedClient(key, b64secret, passphrase)
    response = auth_client.get_orders()
    try:
        #json.loads(response[0])
        print(response)  #comprobamos si puede decodificarlo como json
    except ValueError, e:  #Si no puede lanzará un error y
        resp = auth_client.get_orders()  #volvemos a invocar a la función.
        return resp  #y devolvemos la respuesta
Example #25
0
def get_current_price():
    auth_client = gdax.AuthenticatedClient(key, b64secret, passphrase)
    result = auth_client.get_product_ticker(product_id=producto)
    if 'price' in result:
        print(result)
        return (float(result['price']))
    else:
        response = get_current_price()
        return response
    def initialize_auth_client(self, *args, **kwargs):
        """
        Initialize authorized client for API calls.

        :param sandbox: boolean, if true then use sandbox mode for API
        :return: auth_client object
        """
        super().initialize_auth_client(*args, **kwargs)

        if kwargs.get("sandbox", False):
            return gdax.AuthenticatedClient(
                settings.GDAX_SANDBOX_API_KEY,
                settings.GDAX_SANDBOX_API_SECRET,
                settings.GDAX_SANDBOX_PASSPHRASE,
                api_url="https://api-public.sandbox.gdax.com")

        return gdax.AuthenticatedClient(settings.GDAX_API_KEY,
                                        settings.GDAX_API_SECRET,
                                        settings.GDAX_PASSPHRASE)
Example #27
0
    def __init__(self, name):

        self.name = name
        self.login = pd.read_csv(r'C:\dev\gdax\login.txt')
        self.auth_client = gdax.AuthenticatedClient(
            self.login["BLANK LINE"][1], self.login["BLANK LINE"][2],
            self.login["BLANK LINE"][0])

        self.public_client = gdax.PublicClient()
        self.acc_db = self.get_all_acc()
Example #28
0
    def __init__(self, gdax_key, gdax_b64secret, gdax_pass):
        if len(gdax_key) < 30 or len(gdax_b64secret) < 60 or len(
                gdax_pass) < 5:
            raise ValueError(
                'Error: Currently only the GDAX API is supported, please provide GDAX credentials'
            )

        self.gdax_ws = gdax_ws.gdaxWS()
        self.gdax_pub = gdax.PublicClient()
        self.gdax_auth = gdax.AuthenticatedClient(gdax_key, gdax_b64secret,
                                                  gdax_pass)
        logging.debug("Connected to GDAX!")
Example #29
0
def cancelOrder(order_id):
    myInfo = infoPerso.infoPerso()

    auth_client = gdax.AuthenticatedClient(myInfo.gdax_key,
                                           myInfo.gdax_b64secret,
                                           myInfo.gdax_passphrase)

    if order_id:
        orders = auth_client.cancel_order(order_id)
        print(orders)
    else:
        print('no order to cancel')
Example #30
0
    def __init__(self, pair, period):
        config = ConfigParser.ConfigParser()
        config.read("zeus.ini")
        locale.setlocale(locale.LC_ALL, 'pt_PT.utf8')

        self.conn = gdax.AuthenticatedClient(config.get("auth", "key"),
                                             config.get("auth", "secret"),
                                             config.get("auth", "passphrase"))
        self.pair = pair
        self.period = period

        self.data = []