[Layer.zip generated from Docker allows you to use FTX US Python library when uploaded as a Layer in AWS - instructions for how to generate your own here: https://dev.to/mmascioni/using-external-python-packages-with-aws-lambda-layers-526o](https://s3-us-west-2.amazonaws.com/secure.notion-static.com/37f54b36-9571-4521-89a2-1e280574b793/Untitled.zip)

Layer.zip generated from Docker allows you to use FTX US Python library when uploaded as a Layer in AWS - instructions for how to generate your own here: https://dev.to/mmascioni/using-external-python-packages-with-aws-lambda-layers-526o

[Layer.zip generated from Docker allows you to use FTX (International) Python library when uploaded as a Layer in AWS - instructions for how to generate your own here: https://dev.to/mmascioni/using-external-python-packages-with-aws-lambda-layers-526o](https://s3-us-west-2.amazonaws.com/secure.notion-static.com/91b14c6d-8fcd-4848-8673-26d442dd19db/ftx-layer.zip)

Layer.zip generated from Docker allows you to use FTX (International) Python library when uploaded as a Layer in AWS - instructions for how to generate your own here: https://dev.to/mmascioni/using-external-python-packages-with-aws-lambda-layers-526o

🤔 Use Case

Dollar cost averaging and trading on the FTX US platform, taking advantage of their excellent fee structure: https://help.ftx.us/hc/en-us/articles/360043579273-Fees

FTX API Documentation: https://docs.ftx.us/#rest-api

👷🏻‍♂️ Architecture

Language: Python 3.8

Infrastructure: AWS Lambda Functions and EventBridge for Automation

👨🏻‍💻 For Developers

I edited the FTX Python package by changing FTX to FTX US in a few places in api.py. Edited code is in the ftx-layer.zip, feel free to unzip to inspect.

line 13 - base_url: str = "https://ftx.us/api/",

line 52 - request.headers[f'FTXUS-KEY'] = self._api_key line 53 - request.headers['FTXUS-SIGN'] = signature line 54 - request.headers['FTXUS-TS'] = str(ts)

Original code package here:

https://github.com/quan-digital/ftx/tree/v1.2

Buy/Sell Bitcoin/Crypto:

import ftx
import json 

YOUR_API_KEY = ""
YOUR_API_SECRET = ""
#change SYMBOL to 'ETH/USD' for ETH (etc)
SYMBOL = 'BTC/USD'
#Change USD_AMOUNT to dollar/fiat amount you want to buy/sell
USD_AMOUNT = 20
#change ORDER_TYPE to 'sell' for sells or 'buy' for buys
ORDER_TYPE = 'buy'

def lambda_handler(event, context):
    client = ftx.FtxClient(api_key=YOUR_API_KEY, api_secret=YOUR_API_SECRET)
    bid_price = client.get_orderbook(SYMBOL, 1)['bids'][0][0]
    order_size = round(USD_AMOUNT/bid_price,4)
    print(f"Bid Price: {bid_price}")
    print(f"Order Size: {order_size}")
    client.place_order(SYMBOL, ORDER_TYPE, bid_price, order_size)
    return {
        'statusCode': 200,
        'body': json.dumps('Order sent!')
    }

Withdraw Crypto to External Wallet

import ftx
import json 
import random

YOUR_API_KEY = ""
YOUR_API_SECRET = ""
#Fill in your FTX API Keys above

coin = 'BTC'
#change COIN to 'ETH' for Ethereum, 'ADA' for Cardano (etc)

size = 0.01
#Change size to crypto amount you want to withdrawal
withdrawAllAvailable = True
#Set withdrawAllAvailable to True to override the size and withdraw everything. Set to False to use the size variable

btcAddress1 = ""
withdrawal_addresses = [btcAddress1]
#add one address to always withdraw to that single address: ["btcaddress1"]
#add multiples to randomly withdraw to one of many addresses (better privacy): ["btcaddress1","btcaddress2","btcaddress3"]
address = random.choice(withdrawal_addresses)
tag = None
method = None
#Method optional; blockchain to use for withdrawal see documentation
password = None
#Password optional; withdrawal password if it is required for your account
code = None
#Code optional; 2fa code if it is required for your account you would need to integrate with Authy/Google Authenticator for this to work
client = ftx.FtxClient(api_key=YOUR_API_KEY, api_secret=YOUR_API_SECRET)

#EX: coin = 'BTC' or coin = 'USD' or coin = 'ETH'
def getCoinAvailableForWithdrawalBalance(coin):
    balances = client.get_balances()
    availableForWithdrawal = list(filter(lambda balance: balance['coin'] == coin,balances))[0]['availableForWithdrawal']
    print(availableForWithdrawal)
    return availableForWithdrawal

def withdrawCoin():
    if(withdrawAllAvailable):
        size = getCoinAvailableForWithdrawalBalance(coin)
    withdrawal = client.request_withdrawal(coin, size, address, tag, method, password, code)
    print(withdrawal)

def lambda_handler(event, context):
    withdrawCoin()
    return {
        'statusCode': 200,
        'body': json.dumps('Withdrawal sent!')
    }

InvestAnswers DCA Steroids ATH Script

import json
import ftx
import requests

# FTX VARS
FTX_PUBLIC_KEY = ""  
FTX_SECRET_KEY = ""

# GLASSNODE VARS
GLASSNODE_API_KEY = ''
GLASSNODE_TOKEN = "BTC"

# SCRIPT VARS
symbol = "BTC/USD"
order_type = 'buy'
buy_amount = 100
tick_size = 4
quote_currency_price_increment = 2

resp = requests.get('<https://api.glassnode.com/v1/metrics/market/price_drawdown_relative>',
    params={'a': GLASSNODE_TOKEN, 'api_key': GLASSNODE_API_KEY})
distance_from_ath = round(resp.json()[-1]['v']*-1,3)

def _setBuyFactor(dist_ath):
    print(f"Distance from ATH: {dist_ath}")
    if dist_ath >= .35 and dist_ath < .4:
        buy_factor = 1.66
    elif dist_ath >= .4 and dist_ath < .45:
        buy_factor = 2.64
    elif dist_ath >= .45 and dist_ath <.5:
        buy_factor = 4.26
    elif dist_ath >= .5 and dist_ath < 1:
        buy_factor = 2
    else:
        buy_factor = 0
    print(f"Buy Factor: {buy_factor}")
    return buy_factor

def _buyCrypto(pub_key, priv_key):
    buy_factor = _setBuyFactor(distance_from_ath)
    print(buy_factor)
    if buy_factor > 0:
        
        #establish connection with FTX
        client = ftx.FtxClient(api_key=pub_key, api_secret=priv_key)
        
        #get BTC spot price
        symbol_spot_price = client.get_orderbook(symbol, 1)['bids'][0][0]
        
        #factor for getting quick fill on limit order
        factor = 0.999
        
        #calculate execution price
        execution_price = str(round(symbol_spot_price*factor,quote_currency_price_increment))
        
        #calculate amount using the buy factor
        amount = round((buy_amount*buy_factor*0.998)/float(execution_price),tick_size)
        
        #place limit buy order for 0.999x ask price 
        buy = client.place_order(symbol, order_type, execution_price, amount)
        print(f'Maker Buy: {buy}')       
    else:
        print("No buy because buy factor was 0.")
        
def lambda_handler(event, context):
    _buyCrypto(FTX_PUBLIC_KEY, FTX_SECRET_KEY)
    return {
        'statusCode': 200,
        'body': json.dumps('End of script')
    }