Skip to content

Commit

Permalink
Logs data in any fiat currency available on Kraken & clean code
Browse files Browse the repository at this point in the history
  • Loading branch information
smechaab committed Sep 11, 2018
1 parent b66f942 commit 09f8b69
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 36 deletions.
50 changes: 22 additions & 28 deletions CurrencyViewer.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
And please, don't hesitate to feedback !
v0.2.0
v0.2.1
Extracts data and store them in "data.csv"
1. Displays the different amount of crypto currencies you own on your Kraken wallet.
Expand Down Expand Up @@ -49,7 +49,7 @@ def __init__(self):

#%% Main purpose of this script
# It calls every function in order, it allows to get the full data for user
def processCViewer(self,log=True, currency = "USD", time="rfc1123"):
def processCViewer(self, log=True, currency="USD", time="rfc1123"):

data, c, f = self.collectData()
price = self.getMarketPrice(c)
Expand Down Expand Up @@ -117,9 +117,8 @@ def collectData(self):
#(e.g : XXBT -> XBT, ZEUR -> EUR)
return data, crypto_index, fiat_index

#%% Get XBT to FIAT price
#%% Get XBT to FIAT price
def getXBTtoFiatPrice(self, fiat):
#We prepare our list of markets exchange we are interested in
data_price = self.k.query_public('Ticker',{'pair': "XBT"+fiat,})
print("XBT"+fiat)
#Error ?
Expand All @@ -137,7 +136,7 @@ def getXBTtoFiatPrice(self, fiat):
index=list(data_price['result'].keys())[0]
return data_price['result'][index]['c'][0]

#%%
#%% getMarketPrice
def getMarketPrice(self, crypto_index):
#We prepare our list of markets exchange we are interested in

Expand Down Expand Up @@ -178,16 +177,21 @@ def getMarketPrice(self, crypto_index):
#price is a list of str -> cast to float
return price

#%% updateFiatInTotal
def updateFiatInTotal(self, fiat):
xbtfiat = self.getXBTtoFiatPrice(fiat)
self.fiatbtc_pair.update({fiat: xbtfiat})
self.total[fiat] = self.btc_total * float(xbtfiat)

#%%
#%% processingConversion
def processingConversion(self, price, crypto_index, fiat_index):
#Finally multiplying balance of crypto of user wallet BY actual real-time price of market
# price of coin in FIAT * amount of coin = Estimated value of currencies in FIAT MONEY
self.values = {}
self.total = {}
self.fiatbtc_pair = {}
btc_total = 0

self.btc_total = 0
self.totals = []
for i in fiat_index:
self.total.update({i : ''})
Expand All @@ -208,39 +212,26 @@ def processingConversion(self, price, crypto_index, fiat_index):
crypto_tmp = 'X'+self.market[i][0:3]

self.values.update({self.market[i] : self.balance[self.currencies.index(crypto_tmp)] * price[i]})
#We find the index of the crypto in crypto_tmp and extract its balance
print(self.market[i], self.balance[self.currencies.index(crypto_tmp)], price[i])

if(self.market[i][0]=='D'): fiat_tmp = self.market[i][4:7]
else: fiat_tmp = self.market[i][3:6]

btc_total += self.values[self.market[i]]
print("btc_total =",btc_total)
self.btc_total += self.values[self.market[i]]
print("btc_total =",self.btc_total)

for i in fiat_index:
xbtfiat = self.getXBTtoFiatPrice(i)
self.fiatbtc_pair.update({i : xbtfiat})
self.total[i] = btc_total * float(xbtfiat)

self.updateFiatInTotal(i)

for n in range(len(fiat_index)):
self.values.update({self.currencies[len(crypto_index)+n] : self.balance[len(crypto_index)+n]})
#For each market, we calculate the price for each fiat money involved in
#One exception : when i-n < 0, we need to fix balance index because
#len(price) and len(market) is not equal to len(balance)

#self.totals[n] += self.balance[len(crypto_index)+n]

# for f_curr in fiat_index:
# data_price = self.k.query_public('Ticker',{'pair': "XBT"+f_curr,})
# self.totals.append(data_price)#debug

#%% Displaying
def displayResults(self):
print(self.values)
print(self.total)

#%% Log file writer
#%% Log file writer
def createLogFile(self, filename, assets, writeFiat):
log_file = open(filename, 'w', newline='')
wr = csv.writer(log_file)
Expand All @@ -263,7 +254,7 @@ def createLogFile(self, filename, assets, writeFiat):
wr.writerow(header)
log_file.close()

#%% writing log
#%% writing log
def writeLog(self, data, filename="data.csv", writeFiat=False, currency="USD", time='rfc1123'):
assets = self.k.query_public('Assets')
if(os.path.exists(os.path.join(os.getcwd(),filename)) == False):
Expand All @@ -275,7 +266,10 @@ def writeLog(self, data, filename="data.csv", writeFiat=False, currency="USD", t
for row in reversed(list(csv.reader(f))):
lastLine = row
break


if currency not in self.total: self.updateFiatInTotal(currency)
#If user wants a fiat conversion not in his kraken wallet

if(lastLine[-1] == currency):
lastTotal = float(lastLine[-3])
var = float((self.total[currency] - lastTotal) / lastTotal)*100
Expand Down Expand Up @@ -306,7 +300,7 @@ def writeLog(self, data, filename="data.csv", writeFiat=False, currency="USD", t
row.append("{0:.5f}".format(assertValue))
else:
row.append("0")

row.append("{0:.2f}".format(self.total[currency]))
row.append("{0:.2f}".format(var))
row.append(currency)
Expand Down
55 changes: 48 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,32 @@ krakenex-CurrencyViewer
=======================
This is a short python3 program that dynamically displays and converts the cryptocurrencies in your Kraken wallet into equivalents fiat money.


If this script helped you or if you have any feedback, please don't hesitate to contact me.

Author : smechaab
Author : smechaab
Contact : [email protected]

Credits
-------
This code is based on Krakenex Python3 API by veox: https://github.com/veox/python3-krakenex

* v0.2.0
* v0.2.1

This is a tiny program I personally use it daily.
It allows me to check my currencies without logging every 10 minutes on Kraken website.
This is also very useful for developers on the Krakenex API thanks to dynamically extracted data.

Please note that you need to fill your kraken.key file with your API keys. You can easily generate a pair of keys on the Kraken website, see the API documentation : https://www.kraken.com/help/api

v0.2.0 Changes
v0.2.1 Changes
----------------
Adding CSV log writing feature.
Providing more object-oriented code and more library-oriented.
Adding CSV log writing feature. Your data are now stored in data.csv by default which is located in the same directory.
Providing more object-oriented code, thus more library-oriented.

TODO :
It is also planned to add other exchanges than Kraken.

Your data logs are now stored by default in data.csv and is located in the same directory.


I wish you a good ‘back-to-school’ !

Expand All @@ -49,6 +49,47 @@ Program features
NOTE: Some bugs need to be fixed with fiat currencies other than EUR or USD,
it will be patched in the next one.

Example
-------

See `example.py`
```
import CurrencyViewer as cv
a = cv.CurrencyViewer()
a.processCViewer(log=True, currency="USD", time="rfc1123")
```

This is aimed to be very easy to use.

It is also possible to call some intermediate functions :

* ```processCViewer(self, log=True, currency="USD", time="rfc1123")```:
Main function to call, implies to call : collectData(), getMarketPrice(), processingConversion(), displayResults() and writeLog().
Returns nothing


* ```collectData(self)```:
Uses krakenex library get data from Kraken API in Json.
Returns raw data, list of crypto in user's wallet, list of fiat in user's wallet


* ```getXBTtoFiatPrice(self, fiat)```:
Return XBT price for "fiat" input currency


* ```getMarketPrice(self, crypto_index)```:
Returns crypto price in XBT


* ```updateFiatInTotal(self, fiat)```:
Updates "total" dict table to add { Fiat_currency : Total_Wallet_Value }.
Returns nothing


* ```displayResults(self)```:
* ``values`` (dict), total value of all crypto in XBT
* ``total`` (dict), total value in fiat currencies


Interesting variables
Expand Down
2 changes: 1 addition & 1 deletion example.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@
import CurrencyViewer as cv

a = cv.CurrencyViewer()
a.processCViewer(log=True, currency="USD", time="rfc1123") #time format: unixtime or rfc1123
a.processCViewer(log=True, currency="JPY", time="rfc1123") #time format: unixtime or rfc1123

0 comments on commit 09f8b69

Please sign in to comment.