-
Notifications
You must be signed in to change notification settings - Fork 346
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
AccountStats Plugin #349
Merged
+263
−6
Merged
AccountStats Plugin #349
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
ecd66da
Adding tools dir and a simple script to analyse lending history
laxdog b70294c
Implement AccountStats plugin - WORK IN PROGRESS
rnevet 6565e57
Fetch all lending history from Poloniex
rnevet 2cd2718
Fix fetch all lending history from Poloniex
rnevet 5cd95a7
Notify every 24Hrs
rnevet 5a1bba1
Updated documentation
rnevet 9da81a5
Removed tools
rnevet e31400c
Strip plugin names from config
3922aba
Removed semicolon
rnevet e3abd2e
removed trailing space
rnevet bee639a
Removed unused imports
rnevet File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
from plugins import * | ||
import plugins.Plugin as Plugin | ||
|
||
config = None | ||
api = None | ||
log = None | ||
notify_conf = None | ||
plugins = [] | ||
|
||
|
||
def init_plugin(plugin_name): | ||
""" | ||
:return: instance of requested class | ||
:rtype: Plugin | ||
""" | ||
klass = globals()[plugin_name] # type: Plugin | ||
instance = klass(config, api, log, notify_conf) | ||
instance.on_bot_init() | ||
return instance | ||
|
||
|
||
def init(cfg, api1, log1, notify_conf1): | ||
""" | ||
@type cfg1: modules.Configuration | ||
@type api1: modules.Poloniex.Poloniex | ||
@type log1: modules.Logger.Logger | ||
""" | ||
global config, api, log, notify_conf | ||
config = cfg | ||
api = api1 | ||
log = log1 | ||
notify_conf = notify_conf1 | ||
|
||
plugin_names = config.get_plugins_config() | ||
for plugin_name in plugin_names: | ||
plugins.append(init_plugin(plugin_name)) | ||
|
||
|
||
def after_lending(): | ||
for plugin in plugins: | ||
plugin.after_lending() | ||
|
||
|
||
def before_lending(): | ||
for plugin in plugins: | ||
plugin.before_lending() | ||
|
||
|
||
def on_bot_exit(): | ||
for plugin in plugins: | ||
plugin.on_bot_exit() |
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,122 @@ | ||
# coding=utf-8 | ||
from plugins.Plugin import Plugin | ||
import modules.Poloniex as Poloniex | ||
import sqlite3 | ||
|
||
BITCOIN_GENESIS_BLOCK_DATE = "2009-01-03 18:15:05" | ||
DAY_IN_SEC = 86400 | ||
DB_DROP = "DROP TABLE IF EXISTS history" | ||
DB_CREATE = "CREATE TABLE IF NOT EXISTS history(" \ | ||
"id INTEGER UNIQUE, open TIMESTAMP, close TIMESTAMP," \ | ||
" duration NUMBER, interest NUMBER, rate NUMBER," \ | ||
" currency TEXT, amount NUMBER, earned NUMBER, fee NUMBER )" | ||
DB_INSERT = "INSERT OR REPLACE INTO 'history'" \ | ||
"('id','open','close','duration','interest','rate','currency','amount','earned','fee')" \ | ||
" VALUES (?,?,?,?,?,?,?,?,?,?);" | ||
DB_GET_LAST_TIMESTAMP = "SELECT max(close) as last_timestamp FROM 'history'" | ||
DB_GET_FIRST_TIMESTAMP = "SELECT min(close) as first_timestamp FROM 'history'" | ||
DB_GET_TOTAL_EARNED = "SELECT sum(earned) as total_earned, currency FROM 'history' GROUP BY currency" | ||
DB_GET_24HR_EARNED = "SELECT sum(earned) as total_earned, currency FROM 'history' " \ | ||
"WHERE close BETWEEN datetime('now','-1 day') AND datetime('now') GROUP BY currency" | ||
|
||
|
||
class AccountStats(Plugin): | ||
last_notification = 0 | ||
|
||
def on_bot_init(self): | ||
super(AccountStats, self).on_bot_init() | ||
self.init_db() | ||
|
||
def after_lending(self): | ||
self.update_history() | ||
self.notify_daily() | ||
|
||
# noinspection PyAttributeOutsideInit | ||
def init_db(self): | ||
self.db = sqlite3.connect(r'market_data\loan_history.sqlite3') | ||
self.db.execute(DB_CREATE) | ||
self.db.commit() | ||
|
||
def update_history(self): | ||
# timestamps are in UTC | ||
last_time_stamp = self.get_last_timestamp() | ||
|
||
if last_time_stamp is None: | ||
# no entries means db is empty and needs initialization | ||
last_time_stamp = BITCOIN_GENESIS_BLOCK_DATE | ||
self.db.execute("PRAGMA user_version = 0") | ||
|
||
self.fetch_history(Poloniex.create_time_stamp(last_time_stamp), sqlite3.time.time()) | ||
|
||
# As Poloniex API return a unspecified number of recent loans, but not all so we need to loop back. | ||
if (self.get_db_version() == 0) and (self.get_first_timestamp() is not None): | ||
last_time_stamp = BITCOIN_GENESIS_BLOCK_DATE | ||
loop = True | ||
while loop: | ||
sqlite3.time.sleep(10) # delay a bit, try not to annoy poloniex | ||
first_time_stamp = self.get_first_timestamp() | ||
count = self.fetch_history(Poloniex.create_time_stamp(last_time_stamp, ) | ||
, Poloniex.create_time_stamp(first_time_stamp)) | ||
loop = count != 0 | ||
# if we reached here without errors means we managed to fetch all the history, db is ready. | ||
self.set_db_version(1) | ||
|
||
def set_db_version(self, version): | ||
self.db.execute("PRAGMA user_version = " + str(version)) | ||
|
||
def get_db_version(self): | ||
return self.db.execute("PRAGMA user_version").fetchone()[0] | ||
|
||
def fetch_history(self, first_time_stamp, last_time_stamp): | ||
history = self.api.return_lending_history(first_time_stamp, last_time_stamp - 1, 50000) | ||
loans = [] | ||
for loan in reversed(history): | ||
loans.append( | ||
[loan['id'], loan['open'], loan['close'], loan['duration'], loan['interest'], | ||
loan['rate'], loan['currency'], loan['amount'], loan['earned'], loan['fee']]) | ||
self.db.executemany(DB_INSERT, loans) | ||
self.db.commit() | ||
count = len(loans) | ||
self.log.log('Downloaded ' + str(count) + ' loans history ' | ||
+ sqlite3.datetime.datetime.utcfromtimestamp(first_time_stamp).strftime('%Y-%m-%d %H:%M:%S') | ||
+ ' to ' + sqlite3.datetime.datetime.utcfromtimestamp(last_time_stamp - 1).strftime( | ||
'%Y-%m-%d %H:%M:%S')) | ||
if count > 0: | ||
self.log.log('Last: ' + history[0]['close'] + ' First:' + history[count - 1]['close']) | ||
return count | ||
|
||
def get_last_timestamp(self): | ||
cursor = self.db.execute(DB_GET_LAST_TIMESTAMP) | ||
row = cursor.fetchone() | ||
cursor.close() | ||
return row[0] | ||
|
||
def get_first_timestamp(self): | ||
cursor = self.db.execute(DB_GET_FIRST_TIMESTAMP) | ||
row = cursor.fetchone() | ||
cursor.close() | ||
return row[0] | ||
|
||
def notify_daily(self): | ||
if self.get_db_version() == 0: | ||
self.log.log_error('AccountStats DB isn\'t ready.') | ||
return | ||
|
||
if self.last_notification != 0 and self.last_notification + DAY_IN_SEC > sqlite3.time.time(): | ||
return | ||
|
||
cursor = self.db.execute(DB_GET_24HR_EARNED) | ||
output = '' | ||
for row in cursor: | ||
output += str(row[0]) + ' ' + str(row[1]) + ' in last 24hrs\n' | ||
cursor.close() | ||
|
||
cursor = self.db.execute(DB_GET_TOTAL_EARNED) | ||
for row in cursor: | ||
output += str(row[0]) + ' ' + str(row[1]) + ' in total\n' | ||
cursor.close() | ||
if output != '': | ||
self.last_notification = sqlite3.time.time() | ||
output = 'Earnings:\n----------\n' + output | ||
self.log.notify(output, self.notify_config) | ||
self.log.log(output) |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
# coding=utf-8 | ||
|
||
|
||
class Plugin(object): | ||
""" | ||
@type cfg1: modules.Configuration | ||
@type api1: modules.Poloniex.Poloniex | ||
@type log1: modules.Logger.Logger | ||
""" | ||
def __init__(self, cfg1, api1, log1, notify_config1): | ||
self.api = api1 | ||
self.config = cfg1 | ||
self.notify_config = notify_config1 | ||
self.log = log1 | ||
|
||
# override this to run plugin init code | ||
def on_bot_init(self): | ||
self.log.log(self.__class__.__name__ + ' plugin started.') | ||
|
||
# override this to run plugin loop code before lending | ||
def before_lending(self): | ||
pass | ||
|
||
# override this to run plugin loop code after lending | ||
def after_lending(self): | ||
pass | ||
|
||
# override this to run plugin stop code | ||
# since the bot can be killed, there is not guarantee this will be called. | ||
def on_bot_stop(self): | ||
pass |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
# coding=utf-8 | ||
__all__ = [] | ||
|
||
import pkgutil | ||
import inspect | ||
|
||
for loader, name, is_pkg in pkgutil.walk_packages(__path__): | ||
module = loader.find_module(name).load_module(name) | ||
|
||
for name, value in inspect.getmembers(module): | ||
if name.startswith('__'): | ||
continue | ||
|
||
globals()[name] = value | ||
__all__.append(name) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That
r
looks like a typo, can't find reference to it in the docs.Unless it means "relative" to current directory?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
it indicates a raw string - so \ don't need to be escaped. :)
https://docs.python.org/2.0/ref/strings.html
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You should use
/
as path separator (work on any system). Oros.path.join()
.