Skip to content

Instantly share code, notes, and snippets.

@eezis
Last active November 13, 2022 04:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eezis/8914e29b1f2a65b3affb0363662129b7 to your computer and use it in GitHub Desktop.
Save eezis/8914e29b1f2a65b3affb0363662129b7 to your computer and use it in GitHub Desktop.
Get your Phemex Positions and Balance using CCXT -- in jupyter notebook
# -*- coding: utf-8 -*-
import os
import sys
from pprint import pprint
import ccxt
import pandas as pd
PHEMEX_API_KEY = os.getenv('PHEMEX_API_KEY')
PHEMEX_API_SECRET = os.getenv('PHEMEX_API_SECRET')
phemex = ccxt.phemex(
{
"apiKey": PHEMEX_API_KEY,
"secret": PHEMEX_API_SECRET,
"verbose": False, # switch it to False if you don't want the HTTP log
}
)
def get_price(exchange, curr: str) -> float:
"""
Takes 'BTC' and returns the ticker price for 'BTC/USDT', if 'USDT' is passed in it
returns 1.0. In this example pass the phemex exchange object in
"""
if curr == 'USDT':
return 1.0
else:
tick = exchange.fetchTicker(curr+'/USDT')
mid_point = tick['bid']
return mid_point
def get_phemex_balances():
"""
Returns a dataframe with current positions and values
NOTE: we do not care about the locked/free for the balance calculation
all tokens are presumed to be available.
"""
# to see what we are working with
# pprint(phemex.fetch_balance())
# print()
phemexBalance = phemex.fetch_balance()
# print(phemexBalance['total'])
# print()
# print(phemexBalance['free'])
balances = []
for symbol, value in phemexBalance['total'].items():
if value > 0.0:
# get the bid price from the ticker price
bid_price = get_price(phemex, symbol);
# load a list of dictionary entries for easy dataframe creation
datum = {}
datum['asset'] = symbol
datum['free'] = value
datum['locked'] = 0.0
datum['total'] = value
datum['price'] = bid_price
datum['balance'] = round(bid_price * datum['total'],2)
datum['platform'] = 'Phemex'
balances.append(datum)
# print(balances)
df = pd.DataFrame(balances)
return df
df = get_phemex_balances()
print(f'Phemex Balance: {df.balance.sum():,.2f}')
df
@eezis
Copy link
Author

eezis commented Jan 14, 2021

Presumes that you you are loading your keys as environmental variables and returns a handy Pandas DataFrame.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment