stable/freqtrade/persistence.py

111 lines
3.7 KiB
Python
Raw Normal View History

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
from typing import Optional, Dict
2017-05-12 17:11:56 +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
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
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:
"""
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)
: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 19:39:31 +00:00
engine = create_engine(db_url, echo=False)
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)
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)
fee = Column(Float, nullable=False, default=0.0)
open_rate = Column(Float)
2017-05-12 17:11:56 +00:00
close_rate = Column(Float)
close_profit = Column(Float)
stake_amount = Column(Float, nullable=False)
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,
arrow.get(self.open_date).humanize() if self.is_open else 'closed'
2017-05-12 17:11:56 +00:00
)
def update(self, order: Dict) -> None:
2017-06-08 18:01:01 +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']:
return
logger.debug('Updating trade (id=%d) ...', self.id)
if order['type'] == 'LIMIT_BUY':
# Update open rate and actual amount
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()
else:
raise ValueError('Unknown order type: {}'.format(order['type']))
2017-06-08 18:01:01 +00:00
self.open_order_id = None
2017-11-01 02:27:08 +00:00
def calc_profit(self, rate: Optional[float] = None) -> float:
"""
Calculates the profit in percentage (including fee).
: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))