Last active
January 22, 2023 11:19
-
-
Save inthestatic/1f374102878d184a7c56b0d7de36b7f4 to your computer and use it in GitHub Desktop.
Minimalist delta hedging script for Deribit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import json | |
from time import sleep | |
from datetime import datetime | |
#settings | |
delta_band = .1 # how far can account delta drift from 0 either up or down | |
repeat_seconds = 5 # how often should the script loop to check for delta | |
delta_bias = 1 # 0=no bias, >0 positive price bias ok with additional BTC exposure | |
db_client_id = "" | |
db_client_secret = "" | |
db_api_url = "https://test.deribit.com/api/v2/" | |
db_access_token = "" | |
# help functions | |
def p(item): | |
print(json.dumps(item, indent=4, sort_keys=True)) | |
def db(url_fragment, json=""): | |
resp = requests.get(db_api_url + url_fragment, json=json, headers={'Authorization': db_access_token}).json() | |
try: | |
return resp["result"] | |
except: | |
p(resp) | |
return "ERRORx" | |
# hedging loop | |
while(True): | |
sleep(repeat_seconds) | |
auth = db("public/auth?client_id=" + db_client_id + "&client_secret=" + db_client_secret + "&grant_type=client_credentials") | |
db_access_token = "Bearer " + auth["access_token"] | |
summary = db("/private/get_account_summary?currency=BTC&extended=true") | |
btc_price = db("/public/get_index?currency=BTC")["BTC"] | |
account_delta = summary["delta_total"] | |
account_delta_with_bias = account_delta - delta_bias | |
delta_hedge = round(abs(btc_price * account_delta_with_bias), -1) | |
print("%s - Price: %s Account Delta: %s USD hedge amount: %s" % (datetime.now(), btc_price, account_delta, delta_hedge)) | |
# skip hedging if the amount is too small | |
if delta_hedge < 10 or abs(account_delta_with_bias) < delta_band: | |
continue | |
# hedge the delta by buying or selling | |
p(db("/private/" + ( "buy" if account_delta_with_bias < 0 else "sell" ) + "?amount=" + str(delta_hedge) + "&instrument_name=BTC-PERPETUAL&type=market")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment