def __init__(self, coin_id, product_id, auth_client):
        print "Initializing GDAX Bot PRODUCT: {}".format(product_id)

        self.auth_client = auth_client
        self.pc = gdax.PublicClient()
        self.coin_id = coin_id
        self.product_id = product_id
        self.orderbook = gdax.OrderBook(product_id=[self.product_id])
        self.init_orderbook()

        self.min_amount, self.quote_increment, self.min_market_funds = self.get_product_info(
        )
        self.last_buy_price = None

        self.short_max_profit = Decimal(settings.SHORT_MAX_PROFIT)
        self.long_max_profit = Decimal(settings.LONG_MAX_PROFIT)
        self.short_max_loss = Decimal(settings.SHORT_MAX_LOSS)
        self.long_max_loss = Decimal(settings.LONG_MAX_LOSS)
        self.max_slippage = settings.MAX_SLIPPAGE

        self.equivalent_fiat = None

        self.long_flag = False
        self.short_flag = False

        self.open_orders = []
        self.order_thread = None
        self.pending_order = False
        self.order_exp = 10  #sec Time until bot should cancel limit order and create new one
        self.get_orders()

        print self.get_balances()
 def orderbook_conn(self):
     if self.orderbook.stop:
         print self.orderbook.error
         print "Reset Connection for {}".format(self.coin_id)
         self.orderbook.close()
         self.orderbook = gdax.OrderBook(product_id=[self.product_id])
         self.init_orderbook()
Beispiel #3
0
def download_csv(filename, num_files=10):
    total_start_time = time.time()
    curr_file = 0
    order_book = gdax.OrderBook(product_id="BTC-USD")
    order_book.start()
    while curr_file < num_files:
        file_dir = "/Users/Jeff/Desktop/Novumind/test_csv/" + filename + str(
            curr_file) + ".csv"
        csv = open(file_dir, "w")
        csv.truncate(0)

        t1 = time.time()
        while True:
            book = order_book.get_current_book()
            book_timestamp = time.time()
            if len(book["asks"]) > 0 and len(book["bids"]) > 0:
                break
        if curr_file == 0:
            print("Time taken to obtain non-null order book: " +
                  str(time.time() - t1))
        csv.write("side, price, size, timestamp of order book: " +
                  str(book_timestamp) + "\n")
        t2 = time.time()
        write_helper("asks", book, csv)
        write_helper("bids", book, csv)
        csv.close()
        write_time = time.time() - t2
        print("Time taken to read order book & write file " + str(curr_file) +
              ": " + str(write_time))
        curr_file += 1
        time.sleep(float(1 - write_time))
    print("Time taken to write " + str(num_files) + " files: " +
          str(time.time() - total_start_time))
Beispiel #4
0
def download_csv2(filename, num_display=200, num_files=10):
    total_start_time = time.time()
    curr_file = 0
    order_book = gdax.OrderBook(product_id="BTC-USD")
    order_book.start()

    threading.Timer(1, get_order_book())
Beispiel #5
0
def get_order_book():
    order_book = gdax.OrderBook(product_id="BTC-USD")
    while True:
        book = order_book.get_current_book()
        book_timestamp = time.time()
        if len(book["asks"]) > 0 and len(book["bids"]) > 0:
            break
    csv.write("side, price, size, timestamp of order book: " +
              str(book_timestamp) + "\n")
    t2 = time.time()
    write_helper("asks", book)
    write_helper("bids", book)
    csv.close()
Beispiel #6
0
 def __init__(self):
     self.books = dict()
     for p in PRODUCTS:
         order_book = gdax.OrderBook(product_id=p)
         order_book.start()
         self.books[p] = order_book
         time.sleep(1)
     # Wait for all books to be initialized
     for p, order_book in self.books.items():
         book = order_book.get_current_book()
         while book['sequence'] == -1:
             book = order_book.get_current_book()
             time.sleep(1)
         print('{} book initialized, sequence {}'.format(
             p, book['sequence']))
def run():

    auth_client = gdax.AuthenticatedClient(*get_api_credentials())
    public_client = gdax.PublicClient()
    # products = public_client.get_products()

    coin_increments = {
        'USD': 0.01,
        'BTC': 0.0001,
        'ETH': 0.001,
        'LTC': 0.01
    }

    # coin_increments = public_client.get_product_increments() # TODO: this call doesn't exist, but I'd like to do it programmatically

    order_book_map = {k:gdax.OrderBook(product_id=k) for k in product_list}
    for obm_entry in order_book_map.values():
        obm_entry.start()

    volume_map = make_volume_map(order_book_map, public_client)

    while True:
        # account_dict = {account['currency']:float(account['available']) for account in auth_client.get_accounts()}
        account_dict = {'ETH': 1.0, 'BTC': 1.0, 'USD': 2.4, 'LTC': 1.0, 'BCH': 1.0} # Test
        print("Account: {}".format(account_dict))

        next_trades = []

        for coin, number in account_dict.items():
            next_step = next_move(coin, number, order_book_map, volume_map, product_list)
            if next_step:
                next_trades.append((coin, number, next_step[0], next_step[1]))

        for entry in next_trades:
            make_trade(entry, _, number) # TODO: need to pipe price out of path evalutation so we can set trade price

        time.sleep(1)
        auth_client.cancel_all_trades() # TODO: this doesn't exist
    def init_market(self, market, secondary_markets, socket=""):
        self.loggerList[0].info('Launching public markets ...')
        self.market = []
        try:
            self.loggerList[0].info("Starting public socket")
            self.market.append(gdax.WebsocketClient(url="wss://ws-feed.gdax.com", products="BTC-EUR"))
            self.market.append(gdax.OrderBook("BTC-EUR"))
            return
            
            exec('import public_markets.' + market.lower() + ', public_markets.cryptowatch')

            # import market
            main = eval('public_markets.' + market.lower() + '.' + market + '(self.loggerList)')
            self.market.append(main)
            self.loggerList[0].info('Finished importing public market: {}'.format(market))

            # import secondary market sources
            for site in secondary_markets:
                secondary = eval('public_markets.' + site.lower() + '.' + site + '(self.loggerList)')
                self.market.append(secondary)
                self.loggerList[0].info('Finished importing public market: {}'.format(site))
        except(ImportError, AttributeError) as e:
            self.loggerList[0].error('Failed to import public market.')
            self.loggerList[0].error('Error: {}'.format(e))
Beispiel #9
0
import gdax, time

import numpy as np
import matplotlib.pyplot as plt

plt.ion()

window = 100

order_book = gdax.OrderBook(product_id='BTC-USD')
order_book.start()

time.sleep(10)

try:
    while (True):

        cur_book = order_book.get_current_book()

        bids = np.array(cur_book['bids'])
        bids = bids[:, 0:2].astype(np.float)

        asks = np.array(cur_book['asks'])
        asks = asks[:, 0:2].astype(np.float)

        price = (bids[-1][0] + asks[0][0]) / 2
        print(price)

        b_x = bids[:, 0]
        b_y = bids[:, 1]
        b_i = np.where(b_x > (price - window))
Beispiel #10
0
    def start_orderbooks(self):
        for market in self.products:
            self.orderbooks.update({market: gdax.OrderBook(market)})

        for market in self.orderbooks:
            self.orderbooks[market].start()
Beispiel #11
0
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 17 18:55:31 2017

@author: Boaz
"""

import gdax

book = gdax.OrderBook(
    'BTC-USD'
)  # each orderbook variable can only register to one product at a time
book.start()
asks = book.get_ask()
asks
asks = book.get_asks()  # give the first order on the book
asks = book.get_asks(19410.01)  # return order or None if doesnt exist
asks = [book.get_asks(i) for i in np.linspace(19409, 19411, 200)]
price_availabe = book.get_asks(19410.35) == None

bids = book.get_bids()  # the same for bids
Beispiel #12
0
ticker = Ticker('ETH-USD')
wsClient = gdax.WebsocketClient(url="wss://ws-feed.gdax.com",
                                products="ETH-USD")

f = open("D:/MEW/SapkGDX.txt")
lines = f.readlines()
b64secret = lines[0]

f = open("D:/MEW/apk.txt")
lines = f.readlines()
key = lines[0].strip()
passphrase = lines[1].strip()

auth_client = gdax.AuthenticatedClient(key, b64secret, passphrase)

order_book = gdax.OrderBook(product_id='ETH-USD')
order_book.start()

time.sleep(2)
prevbook = order_book.get_current_book()
file = open("C:/Users/Tim/Desktop/testfile.txt", "w+")

i = 0
while i < 1000:
    i += 1

    book = order_book.get_current_book()
    #print(prevbook == book)
    prevbook = book

    file.write("ASKS__________\n")
Beispiel #13
0
import gdax, time
order_book = gdax.OrderBook(product_id='BTC-EUR')
order_book.start()
time.sleep(10)
order_book.close()