import ccxt from tabulate import tabulate import pandas as pd import datetime import time import sys import os import numpy as np #Function to help calculating days until expiry — currently unused def hours_between(d1, d2): d1 = datetime.datetime.strptime(d1, "%Y-%m-%d") d2 = datetime.datetime.strptime(d2, "%Y-%m-%d") return abs((d2 - d1).hours) ftx = ccxt.ftx({ 'enableRateLimit': True, 'apiKey':'4g7RKt0ZgG1lsga0E57EdG7X5wlWOsdEc3wiJ6B1', 'secret':'shbBCtB-MJC5MIjwgd0lepRhEAPYa_8VKK09vtPN', }) #Collateral amount for optional total PnL columns collateral = 10000.00 #print ('Collateral: $' + str(collateral)) def calc_futures(): #Gets list of dictionaries; each list item is a dictionary of outputs for each future all_futures = ftx.publicGetFutures() all_futures = all_futures['result'] #print ('Number of futures live: ' + str(len(all_futures))) #Separate perpetuals and calendar futures perp_futures_all = [] cal_futures_all = [] for i in all_futures: if i['perpetual'] == True: perp_futures_all.append(i) #Filter out MOVE contracts elif i['perpetual'] == False and 'MOVE' not in i['name']: cal_futures_all.append(i) #Cut down dictionaries into data only necessary for futures perp_futures = [] cal_futures = [] #For perps for i in perp_futures_all: i = {key:val for key, val in i.items() if key == 'last' or key == 'perpetual' or key == 'underlying' or key == 'name' or key == 'bid' or key == 'ask' } perp_futures.append(i) #For calendar expiration futures - some additional variables like Expiry needed for i in cal_futures_all: i = {key:val for key, val in i.items() if key == 'last' or key == 'perpetual' or key == 'underlying' or key == 'name' or key == 'expiry' or key == 'bid' or key == 'ask' } cal_futures.append(i) #Get funding rates, make into a list, for perps for i in perp_futures: #Get funding name + use it to pull funding stats future_name = i['name'] funding = ftx.publicGetFuturesFutureNameStats ({'future_name': future_name}) i["next_funding_rate"] = f'{funding["result"]["nextFundingRate"]:.8f}' i["next_funding_time"] = funding["result"]["nextFundingTime"] #Pandas-ize it perp_df = pd.DataFrame(perp_futures) cal_df = pd.DataFrame(cal_futures) #Rename cal columns #cal_df = cal_df.rename(columns{'last': 'cal_last', }) #Set indexes perp_df.set_index('name') cal_df.set_index('name') #Merge calendar expiry and perp futures combined_df = perp_df.merge(cal_df, left_on='underlying', right_on='underlying') #Get price difference combined_df['price_dif'] = combined_df.last_y - combined_df.last_x combined_df['price_dif_%'] = combined_df.last_y / combined_df.last_x #Get $ needed of collateral per $ profit on futures spread trade combined_df['collateral_spread_trade'] = (combined_df.last_x + combined_df.last_y) / (abs(combined_df.price_dif)) #Funding TODO #Find time left until expiry of calendar contract + estimate funding expenses between now and expiration? #print (ftx.parse8601(combined_df.expiry)) #combined_df['time_remaining'] = hours_between(str(combined_df.next_funding_time), str(combined_df.expiry)) #Lazy funding estimates #combined_df['funding_paid'] = (combined_df.last_x *(combined_df.next_funding_rate)) #Total PnL combined_df['TotalPnL'] = collateral / combined_df.collateral_spread_trade #PnL % from collateral combined_df['PnL%'] = combined_df.TotalPnL / collateral combined_df['PnL%'] = (combined_df['PnL%'] * 100).astype(str) + '%' #Create market buy/sell spread PnL: PnL as if buying market one side and selling market another side #First create new column for if perp greater than cal or not combined_df.loc[combined_df['bid_x'] <= combined_df['bid_y'], 'perp_greater'] = False combined_df.loc[combined_df['bid_x'] >= combined_df['bid_y'], 'perp_greater'] = True #Get price dif per market buys combined_df.loc[combined_df['perp_greater'] == True, 'market_price_dif'] = abs(combined_df['bid_x'] - combined_df['ask_y']) combined_df.loc[combined_df['perp_greater'] == False, 'market_price_dif'] = abs(combined_df['ask_x'] - combined_df['bid_y']) #Get $ needed of collateral per $ profit on market futures spread trade combined_df.loc[combined_df['perp_greater'] == True, 'collateral_spread_market'] = (combined_df.bid_x + combined_df.ask_y) / (abs(combined_df.market_price_dif)) combined_df.loc[combined_df['perp_greater'] == False, 'collateral_spread_market'] = (combined_df.ask_x + combined_df.bid_y) / (abs(combined_df.market_price_dif)) #Total market PnL combined_df['TotalPnLMarket'] = collateral / combined_df.collateral_spread_market #Market PnL % from collateral combined_df['MarketPnL%'] = combined_df.TotalPnLMarket / collateral combined_df['MarketPnL%'] = (combined_df['MarketPnL%'] * 100).astype(str) + '%' #Sorting combined_df = combined_df.sort_values(by=['collateral_spread_market'], ascending=True) #Make new dataframes with less columns of only important info combined_df_pretty = combined_df.loc[:, ['name_x', 'bid_x', 'ask_x', 'last_x', 'name_y', 'bid_y', 'ask_y', 'last_y', 'underlying', 'next_funding_rate', 'collateral_spread_trade', 'TotalPnL', 'PnL%', 'perp_greater', 'market_price_dif']] combined_df_market = combined_df.loc[:, ['name_x', 'bid_x', 'ask_x', 'name_y', 'bid_y', 'ask_y', 'underlying', 'next_funding_rate', 'market_price_dif', 'collateral_spread_market', 'TotalPnLMarket', 'MarketPnL%']] simple_df_market = combined_df.loc[:, ['name_x', 'bid_x', 'ask_x', 'name_y', 'bid_y', 'ask_y', 'underlying', 'next_funding_rate', 'MarketPnL%']] #Clear last readout and print new one os.system('cls' if os.name == 'nt' else "printf '\033c'") #print(tabulate(combined_df, headers='keys', tablefmt='pretty', stralign='left', numalign='right', floatfmt='.8f')) #print(tabulate(combined_df_market, headers='keys', tablefmt='pretty', stralign='left', numalign='right', floatfmt='.8f')) print(tabulate(simple_df_market, headers='keys', tablefmt='pretty', stralign='left', numalign='right', floatfmt='.8f')) #Loop to refresh every 30 seconds while True: calc_futures() time.sleep(30)
Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.
OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.
import sys
name = sys.stdin.readline()
print("Hello "+ name)
Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.
When ever you want to perform a set of operations based on a condition IF-ELSE is used.
if conditional-expression
#code
elif conditional-expression
#code
else:
#code
Indentation is very important in Python, make sure the indentation is followed correctly
For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.
mylist=("Iphone","Pixel","Samsung")
for i in mylist:
print(i)
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while condition
#code
There are four types of collections in Python.
List is a collection which is ordered and can be changed. Lists are specified in square brackets.
mylist=["iPhone","Pixel","Samsung"]
print(mylist)
Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
Below throws an error if you assign another value to tuple again.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)
Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.
myset = {"iPhone","Pixel","Samsung"}
print(myset)
Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.
mydict = {
"brand" :"iPhone",
"model": "iPhone 11"
}
print(mydict)
Following are the libraries supported by OneCompiler's Python compiler
Name | Description |
---|---|
NumPy | NumPy python library helps users to work on arrays with ease |
SciPy | SciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation |
SKLearn/Scikit-learn | Scikit-learn or Scikit-learn is the most useful library for machine learning in Python |
Pandas | Pandas is the most efficient Python library for data manipulation and analysis |
DOcplex | DOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling |