Gemini

gemini-layer.zip

Layer.zip generated from Docker allows you to use gemini Python library when uploaded as a Layer in AWS

Buy Bitcoin from Gemini

import json
import gemini

public_key = ""  
private_key = ""
symbol = "BTCUSD"
tick_size = 8
#update symbol based on what crypto/fiat pair you want to buy. Default is BTCUSD, change to BTCEUR for Euros or ETHUSD for Ethereum (for example) - see all possibilities down in symbols and minimums link
#update tick size based on what crypto-pair you are buying. BTC is 8. Check out the API link below to see what you need for your pair
#<https://docs.gemini.com/rest-api/#symbols-and-minimums>

def _buyBitcoin(buy_size,pub_key, priv_key):
    # Set up a buy for 0.999 times the current price add more decimals for a higher price and faster fill. Lower factor makes the order cheaper but fills quickly (0.5 would set an order for half the price and so your order could take months/years to fill)
    trader = gemini.PrivateClient(pub_key, priv_key)
    factor = 0.999
    price = str(round(float(trader.get_ticker(symbol)['ask'])*factor,2))

    #set amount to the most precise rounding (tick_size) and multiply by 0.999 for fee inclusion - if you make an order for $20.00 there should be $19.98 coin bought and $0.02 (0.10% fee)
    amount = round((buy_size*.999)/float(price),tick_size)
		
    #execute maker buy with the appropriate symbol, amount, and calculated price
    buy = trader.new_order(symbol, str(amount), price, "buy", ["maker-or-cancel"])
    print(f'Maker Buy: {buy}')

def lambda_handler(event, context):
    _buyBitcoin(20, public_key, private_key)
    return {
        'statusCode': 200,
        'body': json.dumps('End of script')
    }

Buy ETH from Gemini

import json
import gemini

public_key = ""  
private_key = ""
symbol = "ETHUSD"
tick_size = 6
#update symbol based on what crypto/fiat pair you want to buy. Default is BTCUSD, change to BTCEUR for Euros or ETHUSD for Ethereum (for example) - see all possibilities down in symbols and minimums link
#update tick size based on what crypto-pair you are buying. ETH is 6. Check out the API link below to see what you need for your pair
#<https://docs.gemini.com/rest-api/#symbols-and-minimums>

def _buyEtherium(buy_size,pub_key, priv_key):
    # Set up a buy for the current price
    trader = gemini.PrivateClient(pub_key, priv_key)
    price = str(round(float(trader.get_ticker(symbol)['ask'])*.999,2))

    #most precise rounding + *.999 for fee inclusion
    eth_amount = round((buy_size*.999)/float(price),tick_size)

    #execute maker buy, round to 8 decimal places for precision, multiply price by 2 so your limit order always gets fully filled
    buy = trader.new_order(symbol, str(eth_amount), price, "buy", ["maker-or-cancel"])
    print(f'Maker Buy: {buy}')

def lambda_handler(event, context):
    _buyEtherium(10, public_key, private_key)
    return {
        'statusCode': 200,
        'body': json.dumps('End of script')
    }

Withdraw From Gemini

import json
import gemini
import random

public_key = ""  
private_key = ""
trader = gemini.PrivateClient(public_key, private_key)

#withdraws full available balance of specified coin to given address
def _withdrawFullCoinBalance(coin, address):
    amount = "0"
    for currency in trader.get_balance():
        if(currency['currency'] == coin):
            amount = currency['availableForWithdrawal']
            print(f'Amount Available for Withdrawal: {amount}')
    
    #Replace the amount variable below with ".001" to withdraw .001 BTC - change the amount if you want to withdraw some static amount
    withdraw = trader.withdraw_to_address(coin, address, amount)

def lambda_handler(event, context):
    #Add btc_address/eth_address below 
    #JUST MAKE SURE THAT YOUR WALLET ADDRESS IS THE SAME TOKEN AS THE WITHDRAWAL SYMBOL (ie. btc_address is a bitcoin address)
    bitcoin_withdrawal_symbol = "BTC"
    ethereum_withdrawal_symbol = "ETH"
    btc_address = ''
    eth_address = ''
    _withdrawFullCoinBalance(bitcoin_withdrawal_symbol, btc_address)
    _withdrawFullCoinBalance(ethereum_withdrawal_symbol, eth_address)

    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

Sell Bitcoin - Gemini

import json
import gemini

public_key = ""  
private_key = ""

def _sellBitcoin(sell_size,pub_key, priv_key):
    # Set up a sell for just above the current price
    trader = gemini.PrivateClient(pub_key, priv_key)
    price = str(round(float(trader.get_ticker("BTCUSD")['ask'])*1.001,2))

    #most precise rounding + *.999 for fee inclusion
    btc_amount = round((sell_size*.999)/float(price),8)

    #execute maker sell, round to 8 decimal places for precision, multiply price by 2 so your limit order always gets fully filled
    sell = trader.new_order("BTCUSD", str(btc_amount), price, "sell", ["maker-or-cancel"])
    print(f'Maker Sell: {sell}')
    return [btc_amount, price]

def lambda_handler(event, context):
    message = _sellBitcoin(20, public_key, private_key)
    return {
        'statusCode': 200,
        'body': json.dumps(f'You sold {message[0]} Bitcoin for {message[1]}. You monster.')
    }

Update Bitcoin GSheet - Gemini

import json
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from datetime import datetime
import gemini

public_key = ""  
private_key = ""

def _addTransaction(transaction):
    #populate transaction details
    transaction_date = str(datetime.fromtimestamp(transaction['timestamp']).date())
    transaction_id = float(transaction['tid'])
    provider = "Gemini"
    quantity = float(transaction['amount'])
    btc_price = float(transaction['price'])
    fee = float(transaction['fee_amount'])
    usd_amount = quantity * btc_price + fee

    #populate with new row
    return [transaction_date, transaction_id, provider, quantity, btc_price, usd_amount, fee]
    
def _authenticateSpreadsheet():
    #Set up access to the spreadsheet
    scope = ["<https://spreadsheets.google.com/feeds>",
            '<https://www.googleapis.com/auth/spreadsheets>',
            "<https://www.googleapis.com/auth/drive.file>",
            "<https://www.googleapis.com/auth/drive>"]
    creds = ServiceAccountCredentials.from_json_keyfile_name("sheets_creds.json", scope)
    client = gspread.authorize(creds)
    return client.open("The Public Definitive Bitcoin Sheet").worksheet("BTC Buy Audit File")

def populateBTC(pub_key, priv_key):
    audit_file = _authenticateSpreadsheet()
    num_rows_added = 0
    trader = gemini.PrivateClient(pub_key, private_key)
    buys = trader.get_past_trades("BTCUSD")[::-1]
    last_gemini_transaction = (list(filter(lambda gemini: gemini['Provider'] == 'Gemini', audit_file.get_all_records()[-50:]))[-1]['Transaction ID'])
    for buy in buys:
        if(buy['tid'] > last_gemini_transaction):
            audit_file.append_row(_addTransaction(buy), value_input_option="USER_ENTERED")
            num_rows_added += 1
    return num_rows_added
    
def lambda_handler(event, context):
    num = populateBTC(public_key, private_key)
    # TODO implement
    return {
        'statusCode': 200,
        'body': json.dumps(f'{num} transactions added!')
    }