示例#1
0
 def __init__(self,
              api_key=os.getenv("GEMINI_AUDITOR_API_KEY"),
              api_secret=os.getenv("GEMINI_AUDITOR_API_SECRET"),
              sandbox=False):
     self._auditor_api_key = api_key
     self._auditor_api_secret = api_secret
     self.public_client = gemini.PublicClient()
     self.private_client = gemini.PrivateClient(self._auditor_api_key,
                                                self._auditor_api_secret)
import gemini
# Gemini API request
import requests
import json
# Custom package
import telegram as tel

# Telegram chat id
chatid = 000000

# Gemini API credentials
key = '****'
secret = '****'

# Initialize Gemini API client
r = gemini.PrivateClient(key, secret)


def round_down(n, decimals=0):
    multiplier = 10**decimals
    return math.floor(n * multiplier) / multiplier


def getCurrPrice():
    price = float(r.get_ticker('BTCUSD')['last'])
    return price


def getBal():
    # Get Balances
    usdbal = 0
示例#3
0
def backfill_gemini(gemini_api_key: str, gemini_api_secret: str):
    conn = connect_serenity_db()
    cur = conn.cursor()
    type_code_cache = TypeCodeCache(cur)
    instrument_cache = InstrumentCache(cur, type_code_cache)
    exch_service = ExchangeEntityService(cur, type_code_cache,
                                         instrument_cache)
    client = gemini.PrivateClient(gemini_api_key, gemini_api_secret)

    for exchange_symbol in ('BTCUSD', 'ETHBTC', 'ZECBTC'):
        instrument_symbol = exchange_symbol[0:3] + '-' + exchange_symbol[3:]
        instrument_type = type_code_cache.get_by_code(InstrumentType,
                                                      'CurrencyPair')
        instrument = instrument_cache.get_or_create_instrument(
            instrument_symbol, instrument_type)
        exchange_instrument = instrument_cache.get_or_create_exchange_instrument(
            exchange_symbol.lower(), instrument, 'Gemini')

        conn.commit()

        exchange = type_code_cache.get_by_code(Exchange, 'Gemini')

        for trade in client.get_past_trades(exchange_symbol):
            fill_price = trade['price']
            quantity = trade['amount']
            fees = trade['fee_amount']
            side = type_code_cache.get_by_code(Side, trade['type'])
            trade_id = trade['tid']
            order_uuid = trade['order_id']
            create_time_ms = trade['timestampms']
            create_time = datetime.utcfromtimestamp(create_time_ms // 1000).\
                replace(microsecond=create_time_ms % 1000 * 1000)

            # because we cannot get historical exchange orders past 7 days, we need to synthesize limit orders
            exchange_account = ExchangeAccount(0, exchange, 'default')
            exchange_account = exch_service.get_or_create_account(
                exchange_account)
            order_type = type_code_cache.get_by_code(OrderType, 'Limit')
            tif = type_code_cache.get_by_code(TimeInForce, 'GTC')
            order = ExchangeOrder(0, exchange, exchange_instrument, order_type,
                                  exchange_account, side, tif, order_uuid,
                                  fill_price, quantity, create_time)
            order = exch_service.get_or_create_exchange_order(order)
            conn.commit()

            # create the fills and insert, linking back to the synthetic order
            fill = ExchangeFill(0, fill_price, quantity, fees, trade_id,
                                create_time)
            fill.set_order(order)
            exch_service.get_or_create_exchange_fill(fill)
            conn.commit()

    for transfer in client.api_query('/v1/transfers', {}):
        transfer_type = type_code_cache.get_by_code(ExchangeTransferType,
                                                    transfer['type'])
        transfer_method = type_code_cache.get_by_code(ExchangeTransferMethod,
                                                      "Blockchain")
        currency = instrument_cache.get_or_create_currency(
            transfer['currency'])
        quantity = transfer['amount']
        transfer_ref = transfer['txHash']
        transfer_time_ms = transfer['timestampms']
        transfer_time = datetime.utcfromtimestamp(transfer_time_ms // 1000). \
            replace(microsecond=transfer_time_ms % 1000 * 1000)

        transfer = ExchangeTransfer(0, exchange, transfer_type,
                                    transfer_method, currency, quantity,
                                    transfer_ref, transfer_time)
        exch_service.get_or_create_exchange_transfer(transfer)

    conn.commit()
示例#4
0
def main(argv):
    period = 10
    pair = "BTCUSD"
    prices = []
    currentMovingAverage = 0
    lengthOfMA = 0
    startTime = False
    endTime = False
    historicalData = False
    tradePlaced = False
    typeOfTrade = False
    dataDate = ""
    orderNumber = ""
    net = []
    total = 100000
    bitcoin = 10
    '''
    Following code is for command line arguments. opts and args represents options
    such as -h, -p, -c etc. Those options with a colon following require an argument.
    -h for help
    -p, --period for period length
    -c, --currency for currency pair
    -n, --points for number of points for moving average
    -s is starttime for historical backtesting
    -e is endtime for historical backtesting
    '''
    try:
        opts, args = getopt.getopt(argv, "hp:c:n:s:e:",
                                   ["period=", "currency=", "points="])
    except getopt.GetoptError:
        print(
            'trading-bot.py -p <period length> -c <currency pair> -n <period of moving average>'
        )
        sys.exit(2)

    for opt, arg in opts:
        if opt == '-h':
            print(
                'trading-bot.py -p <period length> -c <currency pair> -n <period of moving average>'
            )
            sys.exit()
        elif opt in ("-p", "--period"):
            if (int(arg) in [10, 300, 900, 1800, 7200, 14400, 86400]):
                period = arg
            else:
                print(
                    'Poloniex requires periods in 300,900,1800,7200,14400, or 86400 second increments'
                )
                sys.exit(2)
        elif opt in ("-c", "--currency"):
            pair = arg
        elif opt in ("-n", "--points"):
            lengthOfMA = int(arg)
        elif opt in ("-s"):
            startTime = arg
        elif opt in ("-e"):
            endTime = arg

    # establish connection to gemini exchange, sandbox=True indicates sandbox
    r = gemini.PrivateClient("JBCBbwEmXfD6IwS6Q4WN",
                             "2YzrK8cq5jCRs8r8QKLKUtDDJxqV",
                             sandbox=True)

    conn = poloniex(
        'OICTWNLZ-NG2ATAQN-S3DYCUWH-QGWMPXD3',
        '0348b3b5932f49b1e84feeacbec88a8b9eb0770d11fe553515f6a946b8b23eb2abe9748ee06417f1fd27310759e3b6535782c03de75c3499f42c714b0b6530a5'
    )

    if (startTime):
        historicalData = r.get_trade_history("BTCUSD", since="17/06/2017")

    while True:

        #if we are doing a historical backtest
        if (startTime and historicalData):
            nextDataPoint = historicalData.pop(0)
            lastPairPrice = nextDataPoint['weightedAverage']
            dataDate = datetime.datetime.fromtimestamp(
                int(nextDataPoint['date'])).strftime('%Y-%m-%d %H:%M:%S')
        elif (startTime and not historicalData):
            exit()

        #if we are doing live trading
        else:
            currentValues = r.get_ticker(pair)
            lastPairPrice = float(currentValues["last"])
            dataDate = datetime.datetime.now()
        """
        This is the code that will actually execute the trades
        """
        if (len(prices) > 0):
            currentMovingAverage = sum(prices) / float(len(prices))
            previousPrice = prices[-1]
            if ((not tradePlaced) and (total > 0)):
                # if (not tradePlaced):
                if ((lastPairPrice > currentMovingAverage)
                        and (lastPairPrice < previousPrice) and (bitcoin > 0)):
                    orderNumber = r.new_order(pair, "1", str(lastPairPrice),
                                              "sell")
                    print("SELL 1 BTC AT " + str(lastPairPrice * 1))
                    tradePlaced = True
                    typeOfTrade = "short"
                    priceSoldAt = lastPairPrice
                    total = total + (priceSoldAt * 1)
                    bitcoin = bitcoin - 1
                    print("total: " + str(total))

                elif ((lastPairPrice < currentMovingAverage)
                      and (lastPairPrice > previousPrice)):
                    print("BUY 1 BTC AT " + str(lastPairPrice * 1))
                    orderNumber = r.new_order(pair, "1", str(lastPairPrice),
                                              "buy")
                    tradePlaced = True
                    typeOfTrade = "long"
                    priceBoughtAt = lastPairPrice
                    total = total - (priceBoughtAt * 1)
                    bitcoin = bitcoin + 1
                    print("total: " + str(total))

            elif (typeOfTrade == "short"):
                if (lastPairPrice < currentMovingAverage):
                    print("EXIT TRADE")
                    # conn.cancel(pair,orderNumber)
                    tradePlaced = False
                    typeOfTrade = False
            elif (typeOfTrade == "long"):
                if (lastPairPrice > currentMovingAverage):
                    print("EXIT TRADE")
                    # conn.cancel(pair,orderNumber)
                    tradePlaced = False
                    typeOfTrade = False
        else:
            previousPrice = 0

        print("%s Period: %ss %s: %s Moving Average: %s" %
              (dataDate, period, pair, lastPairPrice, currentMovingAverage))

        prices.append(float(lastPairPrice))
        prices = prices[-lengthOfMA:]
        if (not startTime):
            time.sleep(int(period))

        if (bitcoin > 0):
            print("bitcoin:", bitcoin)
示例#5
0
 def __init__(self):
     self.api_key = getenv("API_KEY", None)
     self.private_key = getenv("API_SECRET", None)
     self.private_client = gemini.PrivateClient(
         self.api_key, self.private_key,
         sandbox=False) if self.api_key and self.private_key else None
示例#6
0
import gemini

p = gemini.PublicClient()
r = gemini.PrivateClient("bXVM9YaofU9ply00F9aO",
                         "352ks5RLMzntpfJYgJceBge71cgq",
                         sandbox=True)

lists = []

lists = p.symbols()

for list in lists:

    print(p.get_ticker(list))
    print(list)
import math, urllib2, json, re


def download():
    graph = {}
    page = urllib2.urlopen(
        "https://bittrex.com/api/v1.1/public/getmarketsummaries")
    data = page.read()
    jsrates = json.loads(data)

    result_list = jsrates["result"]
    for result_index, result in enumerate(result_list):
        ask = result["Ask"]
        bid = result["Bid"]
        market = result["MarketName"]
        pattern = re.compile("([A-Z0-9]*)-([A-Z0-9]*)")
示例#7
0
#Importing libraries
import gemini
import ccxt
import pandas as pd
import time
import datetime
from datetime import timedelta

r = gemini.PrivateClient("PUBLICACCOUNT", "SECRETKEY")

##Get live BTC price
#while True:
#  price = cryptocompare.get_price('BTC', currency = 'USD')
#  print (price)
#  time.sleep(0.2)

#Fetching data from Gemini
gemini = ccxt.gemini()
ticker = "BTC/USD"
btc_ohlcv = gemini.fetch_ohlcv(ticker, timeframe='1d')
k = 0.68


def get_target_price(ticker):
    df = pd.DataFrame(
        btc_ohlcv, columns=['date', 'open', 'high', 'low', 'close', 'volume'])
    df['date'] = pd.to_datetime(df['date'], unit='ms')
    df.set_index('date', inplace=True)

    yesterday = df.iloc[-2]
示例#8
0
# Ensure responses aren't cached
@app.after_request
def after_request(response):
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Expires"] = 0
    response.headers["Pragma"] = "no-cache"
    return response


# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///finance.db")

#provide public and private API keys for websocket connection
r = gemini.PrivateClient("Vk5HgHCe3RD3RQLI4ngj",
                         "4HiK4Hc4HKsdSWc7LpJd47LqGxYF",
                         sandbox=True)

#Sandbox url. Change to live url for live envt
base_url = "https://api.sandbox.gemini.com/v1"


#Function to get latest price from exchange & compare to stop loss positions in db. Comparison is combined in this function due to rate limiting of API.
#Return price for display in index page
def btc_price():

    #Get BTC Price and parse json
    response = urllib.request.urlopen(base_url + "/pubticker/btcusd")
    a = (response.read())
    b = json.loads(a)