Esempio n. 1
0
    def get(self, request):

        # Generate Deribit client
        client = RestClient(settings.DERIBIT_KEY, settings.DERIBIT_SECRET)

        print("Getting this thing")
        print(Instrument.objects.first().instrumentName)

        # Get instruments
        instruments = client.getinstruments()
        trade_list = client.getlasttrades(instruments[1]['instrumentName'])

        instruments_model = Instrument(**instruments[1])
        instruments_model.save()

        #trade_list = client.getlasttrades(Instrument.objects.get(id=827).instrumentName)

        print(trade_list)

        # Create instruments
        # TODO: Make use of bulk_create here
        for trade in trade_list:
            try:
                trade_model = Trade(**trade)
                trade_model.instrument = instrument_model
                trade_model.save()
            except Exception as e:
                # TODO: Integrate logger here
                print("Error while saving model")
                print(e)

        context = {'trade_list': Trade.objects.all()}
        return render(request, 'table_trade.html', context)
Esempio n. 2
0
class myDERIBIT:
    Access_key = "no"
    Access_secret = "no"
    client = 0
    frontMfuture = 0
    lastInfo = 'nothing yet'
    killDeribitThread = False
    contractCount = str(1)
    timeLeft = 500 * 60
    emailSentTime = 5

    def __init__(self):
        self.Access_key = os.environ.get('Access_key', 'no')
        self.Access_secret = os.environ.get('Access_secret', 'no')
        self.contractCount = os.environ.get('count', 'no')
        self.client = RestClient(self.Access_key, self.Access_secret)
        self.frontMfuture = self.getFronFutureName()
        timestampim = self.getLastTradetimeToDate()

    def ClosePosition(self, posParams, direction):
        closeDirection = 0
        if direction == 'buy':
            closeDirection = 'sell'
        elif direction == 'sell':
            closeDirection = 'buy'
        self.BuyOrSellMarket(posParams, closeDirection)

    def BuyOrSellMarket(self, posParams, direction):
        response = 0
        posParams['type'] = 'market'
        posParams['price'] = ''

        if direction == 'buy':
            try:
                response = self.client.buy(posParams['instrument'],
                                           posParams['quantity'],
                                           posParams['price'])
            except Exception:
                nonce = int(time.time() * 1000)
                signature = self.deribit_signature(nonce,
                                                   '/api/v1/private/buy',
                                                   posParams, self.Access_key,
                                                   self.Access_secret)
                response = self.client.session.post(
                    'https://www.deribit.com' + '/api/v1/private/buy',
                    data=posParams,
                    headers={'x-deribit-sig': signature},
                    verify=True)
        elif direction == 'sell':
            try:
                self.client.sell(posParams['instrument'],
                                 posParams['quantity'], posParams['price'])
            except Exception:
                nonce = int(time.time() * 1000)
                signature = self.deribit_signature(nonce,
                                                   '/api/v1/private/sell',
                                                   posParams, self.Access_key,
                                                   self.Access_secret)
                response = self.client.session.post(
                    'https://www.deribit.com' + '/api/v1/private/sell',
                    data=posParams,
                    headers={'x-deribit-sig': signature},
                    verify=True)

    def getPositionsWithSlippage(self):
        posParams = {}
        posJson = 0
        direction = 0
        try:
            posJson = self.value(self.client.positions())
        except Exception:
            nonce = int(time.time() * 1000)
            signature = self.deribit_signature(nonce,
                                               '/api/v1/private/positions',
                                               posParams, self.Access_key,
                                               self.Access_secret)
            response = self.client.session.post(
                'https://www.deribit.com' + '/api/v1/private/positions',
                data=posParams,
                headers={'x-deribit-sig': signature},
                verify=True)
            posJson = self.value(response.json())['result']

        if posJson.empty:
            direction = 0
        else:
            posParams['instrument'] = str(posJson['instrument'][0])
            direction = str(posJson['direction'][0])
            posParams['quantity'] = str(abs(posJson['size'][0]))
            if direction == 'buy':
                posParams['price'] = str(posJson['markPrice'][0] - 5)
            elif direction == 'sell':
                posParams['price'] = str(posJson['markPrice'][0] + 5)
        return posParams, direction

    def deribit_signature(self, nonce, uri, params, access_key, access_secret):
        sign = '_=%s&_ackey=%s&_acsec=%s&_action=%s' % (nonce, access_key,
                                                        access_secret, uri)
        for key in sorted(params.keys()):
            sign += '&' + key + '=' + "".join(params[key])
        return '%s.%s.%s' % (access_key, nonce,
                             base64.b64encode(hashlib.sha256(sign).digest()))

    def value(self, df):
        return json_normalize(df)

    def getFronFutureName(self):
        instruments = self.client.getinstruments()
        instruments0 = json_normalize(instruments)
        instruments0 = pd.DataFrame.from_dict(instruments)
        futures = instruments0[instruments0['kind'].str.contains("uture")]
        frontMfuture = futures.iloc[0]['instrumentName']
        now = datetime.datetime.now()
        for i in xrange(len(futures)):
            notPERPETUAL = 'PERPETUAL' not in futures.iloc[i]['instrumentName']
            yearDif = int(futures.iloc[i]['expiration'][0:4]) - int(now.year)
            monthDif = int(futures.iloc[i]['expiration'][5:7]) - int(now.month)
            dayDif = int(futures.iloc[i]['expiration'][8:10]) - int(now.day)
            if notPERPETUAL and yearDif == 1:
                frontMfuture = futures.iloc[i]['instrumentName']
                break
            if notPERPETUAL and yearDif == 0 and monthDif > 0:
                frontMfuture = futures.iloc[i]['instrumentName']
                break
            if notPERPETUAL and monthDif == 0 and dayDif > 4:
                frontMfuture = futures.iloc[i]['instrumentName']
                break
        return frontMfuture

    def getLastTradetimeToDate(self, instrument=None):
        if instrument == None:
            instrument = self.frontMfuture
        timestampim = (self.value(
            self.client.getlasttrades(instrument))['timeStamp'][0])
        timestampim = time.strftime("%a %d %b %Y %H:%M:%S GMT",
                                    time.gmtime(timestampim / 1000.0))
        return timestampim

    def getBestBidAsk(self, instrument=None):
        if instrument == None:
            instrument = self.frontMfuture
        ask = self.value(self.client.getorderbook(instrument)['asks'][0])[
            'price']  # satmaq isdiyenner
        bid = self.value(self.client.getorderbook(instrument)['bids'][0])[
            'price']  #almaq istiyenner
        return ask, bid
Esempio n. 3
0
from deribit_api import RestClient
from localsettings import *


client = RestClient(DERIBIT_KEY, DERIBIT_SECRET)
client.index()
client.account()

# Get instruments
instruments = client.getinstruments()

print(instruments[1])

# Get Last trades
lastrades = client.getlasttrades(instruments[1]['instrumentName'])

print(lastrades[0])