2017-10-31 23:22:38 +00:00
|
|
|
import logging
|
2017-05-12 17:11:56 +00:00
|
|
|
from datetime import datetime
|
2017-11-01 02:27:08 +00:00
|
|
|
from decimal import Decimal, getcontext
|
2017-10-31 23:22:38 +00:00
|
|
|
from typing import Optional, Dict
|
2017-05-12 17:11:56 +00:00
|
|
|
|
2017-10-31 23:22:38 +00:00
|
|
|
import arrow
|
2017-05-12 17:11:56 +00:00
|
|
|
from sqlalchemy import Boolean, Column, DateTime, Float, Integer, String, create_engine
|
|
|
|
from sqlalchemy.ext.declarative import declarative_base
|
2017-09-03 06:50:48 +00:00
|
|
|
from sqlalchemy.orm.scoping import scoped_session
|
|
|
|
from sqlalchemy.orm.session import sessionmaker
|
2017-05-12 17:11:56 +00:00
|
|
|
|
2017-10-31 23:22:38 +00:00
|
|
|
logging.basicConfig(level=logging.DEBUG,
|
|
|
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
|
|
|
logger = logging.getLogger(__name__)
|
2017-09-08 13:51:00 +00:00
|
|
|
|
2017-09-08 21:10:22 +00:00
|
|
|
_CONF = {}
|
2017-11-07 19:13:36 +00:00
|
|
|
_DECL_BASE = declarative_base()
|
2017-05-12 17:11:56 +00:00
|
|
|
|
|
|
|
|
2017-09-08 21:10:22 +00:00
|
|
|
def init(config: dict, db_url: Optional[str] = None) -> None:
|
2017-09-08 13:51:00 +00:00
|
|
|
"""
|
|
|
|
Initializes this module with the given config,
|
|
|
|
registers all known command handlers
|
|
|
|
and starts polling for message updates
|
|
|
|
:param config: config to use
|
2017-09-08 19:39:31 +00:00
|
|
|
:param db_url: database connector string for sqlalchemy (Optional)
|
2017-09-08 13:51:00 +00:00
|
|
|
:return: None
|
|
|
|
"""
|
2017-09-08 21:10:22 +00:00
|
|
|
_CONF.update(config)
|
2017-09-08 19:39:31 +00:00
|
|
|
if not db_url:
|
2017-09-08 21:10:22 +00:00
|
|
|
if _CONF.get('dry_run', False):
|
2017-10-31 23:26:21 +00:00
|
|
|
db_url = 'sqlite:///tradesv3.dry_run.sqlite'
|
2017-09-08 19:39:31 +00:00
|
|
|
else:
|
2017-10-31 23:26:21 +00:00
|
|
|
db_url = 'sqlite:///tradesv3.sqlite'
|
2017-09-08 13:51:00 +00:00
|
|
|
|
2017-09-08 19:39:31 +00:00
|
|
|
engine = create_engine(db_url, echo=False)
|
2017-09-08 19:17:58 +00:00
|
|
|
session = scoped_session(sessionmaker(bind=engine, autoflush=True, autocommit=True))
|
|
|
|
Trade.session = session()
|
|
|
|
Trade.query = session.query_property()
|
2017-11-07 19:13:36 +00:00
|
|
|
_DECL_BASE.metadata.create_all(engine)
|
2017-09-08 13:51:00 +00:00
|
|
|
|
|
|
|
|
2017-10-27 13:52:14 +00:00
|
|
|
def cleanup() -> None:
|
|
|
|
"""
|
|
|
|
Flushes all pending operations to disk.
|
|
|
|
:return: None
|
|
|
|
"""
|
|
|
|
Trade.session.flush()
|
|
|
|
|
|
|
|
|
2017-11-07 19:13:36 +00:00
|
|
|
class Trade(_DECL_BASE):
|
2017-05-12 17:11:56 +00:00
|
|
|
__tablename__ = 'trades'
|
|
|
|
|
|
|
|
id = Column(Integer, primary_key=True)
|
2017-10-06 10:22:04 +00:00
|
|
|
exchange = Column(String, nullable=False)
|
2017-05-12 17:11:56 +00:00
|
|
|
pair = Column(String, nullable=False)
|
|
|
|
is_open = Column(Boolean, nullable=False, default=True)
|
2017-11-01 01:20:55 +00:00
|
|
|
fee = Column(Float, nullable=False, default=0.0)
|
2017-10-31 23:22:38 +00:00
|
|
|
open_rate = Column(Float)
|
2017-05-12 17:11:56 +00:00
|
|
|
close_rate = Column(Float)
|
|
|
|
close_profit = Column(Float)
|
2017-11-01 01:20:55 +00:00
|
|
|
stake_amount = Column(Float, nullable=False)
|
2017-10-31 23:22:38 +00:00
|
|
|
amount = Column(Float)
|
2017-05-12 17:11:56 +00:00
|
|
|
open_date = Column(DateTime, nullable=False, default=datetime.utcnow)
|
|
|
|
close_date = Column(DateTime)
|
2017-05-14 12:14:16 +00:00
|
|
|
open_order_id = Column(String)
|
2017-05-12 17:11:56 +00:00
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return 'Trade(id={}, pair={}, amount={}, open_rate={}, open_since={})'.format(
|
|
|
|
self.id,
|
|
|
|
self.pair,
|
|
|
|
self.amount,
|
|
|
|
self.open_rate,
|
2017-10-31 23:22:38 +00:00
|
|
|
arrow.get(self.open_date).humanize() if self.is_open else 'closed'
|
2017-05-12 17:11:56 +00:00
|
|
|
)
|
2017-05-12 22:30:08 +00:00
|
|
|
|
2017-10-31 23:22:38 +00:00
|
|
|
def update(self, order: Dict) -> None:
|
2017-06-08 18:01:01 +00:00
|
|
|
"""
|
2017-10-31 23:22:38 +00:00
|
|
|
Updates this entity with amount and actual open/close rates.
|
|
|
|
:param order: order retrieved by exchange.get_order()
|
|
|
|
:return: None
|
2017-06-08 18:01:01 +00:00
|
|
|
"""
|
2017-11-01 00:12:16 +00:00
|
|
|
if not order['closed']:
|
2017-10-31 23:22:38 +00:00
|
|
|
return
|
|
|
|
|
|
|
|
logger.debug('Updating trade (id=%d) ...', self.id)
|
|
|
|
if order['type'] == 'LIMIT_BUY':
|
2017-10-31 23:54:16 +00:00
|
|
|
# Update open rate and actual amount
|
2017-10-31 23:22:38 +00:00
|
|
|
self.open_rate = order['rate']
|
|
|
|
self.amount = order['amount']
|
|
|
|
elif order['type'] == 'LIMIT_SELL':
|
|
|
|
# Set close rate and set actual profit
|
|
|
|
self.close_rate = order['rate']
|
|
|
|
self.close_profit = self.calc_profit()
|
2017-11-07 21:26:44 +00:00
|
|
|
self.close_date = datetime.utcnow()
|
2017-10-31 23:22:38 +00:00
|
|
|
else:
|
|
|
|
raise ValueError('Unknown order type: {}'.format(order['type']))
|
2017-06-08 18:01:01 +00:00
|
|
|
|
2017-10-31 23:22:38 +00:00
|
|
|
self.open_order_id = None
|
2017-09-08 19:17:58 +00:00
|
|
|
|
2017-11-01 02:27:08 +00:00
|
|
|
def calc_profit(self, rate: Optional[float] = None) -> float:
|
2017-10-31 23:22:38 +00:00
|
|
|
"""
|
2017-11-01 01:20:55 +00:00
|
|
|
Calculates the profit in percentage (including fee).
|
2017-10-31 23:22:38 +00:00
|
|
|
:param rate: rate to compare with (optional).
|
|
|
|
If rate is not set self.close_rate will be used
|
|
|
|
:return: profit in percentage as float
|
|
|
|
"""
|
2017-11-01 01:51:10 +00:00
|
|
|
getcontext().prec = 8
|
|
|
|
return float((Decimal(rate or self.close_rate) - Decimal(self.open_rate))
|
|
|
|
/ Decimal(self.open_rate) - Decimal(self.fee))
|