2018-03-02 15:22:00 +00:00
|
|
|
"""
|
|
|
|
This module contains the class to persist trades into SQLite
|
|
|
|
"""
|
|
|
|
|
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
|
2018-07-04 07:31:35 +00:00
|
|
|
from typing import Any, Dict, Optional
|
2017-05-12 17:11:56 +00:00
|
|
|
|
2017-10-31 23:22:38 +00:00
|
|
|
import arrow
|
2018-01-10 07:51:36 +00:00
|
|
|
from sqlalchemy import (Boolean, Column, DateTime, Float, Integer, String,
|
2018-07-04 07:31:35 +00:00
|
|
|
create_engine, inspect)
|
2018-06-07 19:35:57 +00:00
|
|
|
from sqlalchemy.exc import NoSuchModuleError
|
2017-05-12 17:11:56 +00:00
|
|
|
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-11-09 22:45:22 +00:00
|
|
|
from sqlalchemy.pool import StaticPool
|
2017-05-12 17:11:56 +00:00
|
|
|
|
2018-06-07 19:35:57 +00:00
|
|
|
from freqtrade import OperationalException
|
|
|
|
|
2017-10-31 23:22:38 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
2017-09-08 13:51:00 +00:00
|
|
|
|
2018-05-31 19:10:15 +00:00
|
|
|
_DECL_BASE: Any = declarative_base()
|
2018-06-23 13:27:29 +00:00
|
|
|
_SQL_DOCS_URL = 'http://docs.sqlalchemy.org/en/latest/core/engines.html#database-urls'
|
2017-05-12 17:11:56 +00:00
|
|
|
|
|
|
|
|
2018-06-07 03:25:53 +00:00
|
|
|
def init(config: Dict) -> 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
|
|
|
|
:return: None
|
|
|
|
"""
|
2018-06-23 11:50:22 +00:00
|
|
|
db_url = config.get('db_url', None)
|
2018-06-07 03:25:53 +00:00
|
|
|
kwargs = {}
|
|
|
|
|
2018-06-07 17:10:26 +00:00
|
|
|
# Take care of thread ownership if in-memory db
|
|
|
|
if db_url == 'sqlite://':
|
2018-06-07 03:25:53 +00:00
|
|
|
kwargs.update({
|
|
|
|
'connect_args': {'check_same_thread': False},
|
|
|
|
'poolclass': StaticPool,
|
|
|
|
'echo': False,
|
|
|
|
})
|
|
|
|
|
2018-06-07 19:35:57 +00:00
|
|
|
try:
|
|
|
|
engine = create_engine(db_url, **kwargs)
|
|
|
|
except NoSuchModuleError:
|
2018-06-23 13:27:29 +00:00
|
|
|
raise OperationalException(f'Given value for db_url: \'{db_url}\' '
|
|
|
|
f'is no valid database URL! (See {_SQL_DOCS_URL})')
|
2018-06-07 19:35:57 +00:00
|
|
|
|
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)
|
2018-05-06 07:09:53 +00:00
|
|
|
check_migrate(engine)
|
2017-09-08 13:51:00 +00:00
|
|
|
|
2018-06-07 17:10:26 +00:00
|
|
|
# Clean dry_run DB if the db is not in-memory
|
2018-06-23 11:50:22 +00:00
|
|
|
if config.get('dry_run', False) and db_url != 'sqlite://':
|
2018-01-23 07:23:29 +00:00
|
|
|
clean_dry_run_db()
|
|
|
|
|
2017-09-08 13:51:00 +00:00
|
|
|
|
2018-05-06 07:09:53 +00:00
|
|
|
def has_column(columns, searchname: str) -> bool:
|
|
|
|
return len(list(filter(lambda x: x["name"] == searchname, columns))) == 1
|
|
|
|
|
|
|
|
|
2018-06-27 17:49:08 +00:00
|
|
|
def get_column_def(columns, column: str, default: str) -> str:
|
|
|
|
return default if not has_column(columns, column) else column
|
|
|
|
|
|
|
|
|
2018-05-06 07:09:53 +00:00
|
|
|
def check_migrate(engine) -> None:
|
|
|
|
"""
|
|
|
|
Checks if migration is necessary and migrates if necessary
|
|
|
|
"""
|
|
|
|
inspector = inspect(engine)
|
|
|
|
|
|
|
|
cols = inspector.get_columns('trades')
|
2018-06-27 18:15:25 +00:00
|
|
|
tabs = inspector.get_table_names()
|
|
|
|
table_back_name = 'trades_bak'
|
2018-07-01 18:03:07 +00:00
|
|
|
for i, table_back_name in enumerate(tabs):
|
2018-06-27 18:15:25 +00:00
|
|
|
table_back_name = f'trades_bak{i}'
|
|
|
|
logger.info(f'trying {table_back_name}')
|
2018-05-06 07:09:53 +00:00
|
|
|
|
2018-06-27 17:49:08 +00:00
|
|
|
# Check for latest column
|
|
|
|
if not has_column(cols, 'max_rate'):
|
2018-07-23 08:10:37 +00:00
|
|
|
fee_open = get_column_def(cols, 'fee_open', 'fee')
|
|
|
|
fee_close = get_column_def(cols, 'fee_close', 'fee')
|
2018-06-27 17:49:08 +00:00
|
|
|
open_rate_requested = get_column_def(cols, 'open_rate_requested', 'null')
|
|
|
|
close_rate_requested = get_column_def(cols, 'close_rate_requested', 'null')
|
|
|
|
stop_loss = get_column_def(cols, 'stop_loss', '0.0')
|
|
|
|
initial_stop_loss = get_column_def(cols, 'initial_stop_loss', '0.0')
|
|
|
|
max_rate = get_column_def(cols, 'max_rate', '0.0')
|
|
|
|
|
2018-05-06 07:09:53 +00:00
|
|
|
# Schema migration necessary
|
2018-06-27 18:15:25 +00:00
|
|
|
engine.execute(f"alter table trades rename to {table_back_name}")
|
2018-05-06 07:09:53 +00:00
|
|
|
# let SQLAlchemy create the schema as required
|
|
|
|
_DECL_BASE.metadata.create_all(engine)
|
|
|
|
|
|
|
|
# Copy data back - following the correct schema
|
2018-06-27 17:49:08 +00:00
|
|
|
engine.execute(f"""insert into trades
|
2018-05-06 07:09:53 +00:00
|
|
|
(id, exchange, pair, is_open, fee_open, fee_close, open_rate,
|
|
|
|
open_rate_requested, close_rate, close_rate_requested, close_profit,
|
2018-06-27 17:49:08 +00:00
|
|
|
stake_amount, amount, open_date, close_date, open_order_id,
|
|
|
|
stop_loss, initial_stop_loss, max_rate
|
|
|
|
)
|
2018-05-12 11:39:16 +00:00
|
|
|
select id, lower(exchange),
|
2018-05-12 11:37:42 +00:00
|
|
|
case
|
|
|
|
when instr(pair, '_') != 0 then
|
|
|
|
substr(pair, instr(pair, '_') + 1) || '/' ||
|
|
|
|
substr(pair, 1, instr(pair, '_') - 1)
|
|
|
|
else pair
|
|
|
|
end
|
|
|
|
pair,
|
2018-07-23 08:10:37 +00:00
|
|
|
is_open, {fee_open} fee_open, {fee_close} fee_close,
|
2018-06-27 17:49:08 +00:00
|
|
|
open_rate, {open_rate_requested} open_rate_requested, close_rate,
|
|
|
|
{close_rate_requested} close_rate_requested, close_profit,
|
|
|
|
stake_amount, amount, open_date, close_date, open_order_id,
|
|
|
|
{stop_loss} stop_loss, {initial_stop_loss} initial_stop_loss,
|
|
|
|
{max_rate} max_rate
|
2018-06-27 18:15:25 +00:00
|
|
|
from {table_back_name}
|
2018-05-06 07:09:53 +00:00
|
|
|
""")
|
|
|
|
|
2018-05-12 08:04:41 +00:00
|
|
|
# Reread columns - the above recreated the table!
|
|
|
|
inspector = inspect(engine)
|
|
|
|
cols = inspector.get_columns('trades')
|
2018-05-06 07:09:53 +00:00
|
|
|
|
|
|
|
|
2017-10-27 13:52:14 +00:00
|
|
|
def cleanup() -> None:
|
|
|
|
"""
|
|
|
|
Flushes all pending operations to disk.
|
|
|
|
:return: None
|
|
|
|
"""
|
|
|
|
Trade.session.flush()
|
|
|
|
|
|
|
|
|
2018-01-23 07:23:29 +00:00
|
|
|
def clean_dry_run_db() -> None:
|
|
|
|
"""
|
|
|
|
Remove open_order_id from a Dry_run DB
|
|
|
|
:return: None
|
|
|
|
"""
|
|
|
|
for trade in Trade.query.filter(Trade.open_order_id.isnot(None)).all():
|
|
|
|
# Check we are updating only a dry_run order not a prod one
|
|
|
|
if 'dry_run' in trade.open_order_id:
|
|
|
|
trade.open_order_id = None
|
|
|
|
|
|
|
|
|
2017-11-07 19:13:36 +00:00
|
|
|
class Trade(_DECL_BASE):
|
2018-03-02 15:22:00 +00:00
|
|
|
"""
|
|
|
|
Class used to define a trade structure
|
|
|
|
"""
|
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)
|
2018-04-21 17:47:08 +00:00
|
|
|
fee_open = Column(Float, nullable=False, default=0.0)
|
|
|
|
fee_close = Column(Float, nullable=False, default=0.0)
|
2017-10-31 23:22:38 +00:00
|
|
|
open_rate = Column(Float)
|
2018-04-25 18:16:36 +00:00
|
|
|
open_rate_requested = Column(Float)
|
2017-05-12 17:11:56 +00:00
|
|
|
close_rate = Column(Float)
|
2018-04-25 18:16:36 +00:00
|
|
|
close_rate_requested = Column(Float)
|
2017-05-12 17:11:56 +00:00
|
|
|
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)
|
2018-06-26 18:49:07 +00:00
|
|
|
# absolute value of the stop loss
|
|
|
|
stop_loss = Column(Float, nullable=True, default=0.0)
|
|
|
|
# absolute value of the initial stop loss
|
|
|
|
initial_stop_loss = Column(Float, nullable=True, default=0.0)
|
|
|
|
# absolute value of the highest reached price
|
|
|
|
max_rate = Column(Float, nullable=True, default=0.0)
|
2017-05-12 17:11:56 +00:00
|
|
|
|
|
|
|
def __repr__(self):
|
2018-06-23 13:27:29 +00:00
|
|
|
open_since = arrow.get(self.open_date).humanize() if self.is_open else 'closed'
|
|
|
|
|
|
|
|
return (f'Trade(id={self.id}, pair={self.pair}, amount={self.amount:.8f}, '
|
|
|
|
f'open_rate={self.open_rate:.8f}, open_since={open_since})')
|
2017-05-12 22:30:08 +00:00
|
|
|
|
2018-07-01 17:54:26 +00:00
|
|
|
def adjust_stop_loss(self, current_price: float, stoploss: float, initial: bool = False):
|
|
|
|
"""this adjusts the stop loss to it's most recently observed setting"""
|
2018-06-26 18:49:07 +00:00
|
|
|
|
2018-06-27 04:38:49 +00:00
|
|
|
if initial and not (self.stop_loss is None or self.stop_loss == 0):
|
|
|
|
# Don't modify if called with initial and nothing to do
|
|
|
|
return
|
|
|
|
|
2018-06-26 20:41:28 +00:00
|
|
|
new_loss = float(current_price * (1 - abs(stoploss)))
|
2018-06-26 18:49:07 +00:00
|
|
|
|
|
|
|
# keeping track of the highest observed rate for this trade
|
|
|
|
if self.max_rate is None:
|
|
|
|
self.max_rate = current_price
|
|
|
|
else:
|
|
|
|
if current_price > self.max_rate:
|
|
|
|
self.max_rate = current_price
|
|
|
|
|
|
|
|
# no stop loss assigned yet
|
2018-07-01 17:54:26 +00:00
|
|
|
if not self.stop_loss:
|
2018-06-26 18:49:07 +00:00
|
|
|
logger.debug("assigning new stop loss")
|
|
|
|
self.stop_loss = new_loss
|
|
|
|
self.initial_stop_loss = new_loss
|
|
|
|
|
|
|
|
# evaluate if the stop loss needs to be updated
|
|
|
|
else:
|
|
|
|
if new_loss > self.stop_loss: # stop losses only walk up, never down!
|
|
|
|
self.stop_loss = new_loss
|
|
|
|
logger.debug("adjusted stop loss")
|
|
|
|
else:
|
|
|
|
logger.debug("keeping current stop loss")
|
|
|
|
|
|
|
|
logger.debug(
|
2018-06-26 20:41:28 +00:00
|
|
|
f"{self.pair} - current price {current_price:.8f}, "
|
|
|
|
f"bought at {self.open_rate:.8f} and calculated "
|
|
|
|
f"stop loss is at: {self.initial_stop_loss:.8f} initial "
|
|
|
|
f"stop at {self.stop_loss:.8f}. "
|
|
|
|
f"trailing stop loss saved us: "
|
|
|
|
f"{float(self.stop_loss) - float(self.initial_stop_loss):.8f} "
|
|
|
|
f"and max observed rate was {self.max_rate:.8f}")
|
2018-06-26 18:49:07 +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
|
|
|
"""
|
2018-06-23 13:27:29 +00:00
|
|
|
order_type = order['type']
|
2017-12-16 01:36:43 +00:00
|
|
|
# Ignore open and cancelled orders
|
2018-03-25 20:25:26 +00:00
|
|
|
if order['status'] == 'open' or order['price'] is None:
|
2017-10-31 23:22:38 +00:00
|
|
|
return
|
|
|
|
|
2017-11-17 19:17:29 +00:00
|
|
|
logger.info('Updating trade (id=%d) ...', self.id)
|
2017-12-17 21:07:56 +00:00
|
|
|
|
|
|
|
getcontext().prec = 8 # Bittrex do not go above 8 decimal
|
2018-06-23 13:27:29 +00:00
|
|
|
if order_type == 'limit' and order['side'] == 'buy':
|
2017-10-31 23:54:16 +00:00
|
|
|
# Update open rate and actual amount
|
2018-03-25 20:25:26 +00:00
|
|
|
self.open_rate = Decimal(order['price'])
|
2017-12-17 21:07:56 +00:00
|
|
|
self.amount = Decimal(order['amount'])
|
2017-11-17 19:17:29 +00:00
|
|
|
logger.info('LIMIT_BUY has been fulfilled for %s.', self)
|
2017-12-16 00:09:07 +00:00
|
|
|
self.open_order_id = None
|
2018-06-23 13:27:29 +00:00
|
|
|
elif order_type == 'limit' and order['side'] == 'sell':
|
2018-03-25 20:25:26 +00:00
|
|
|
self.close(order['price'])
|
2017-10-31 23:22:38 +00:00
|
|
|
else:
|
2018-06-23 13:27:29 +00:00
|
|
|
raise ValueError(f'Unknown order type: {order_type}')
|
2017-12-27 10:41:11 +00:00
|
|
|
cleanup()
|
2017-06-08 18:01:01 +00:00
|
|
|
|
2017-12-16 00:09:07 +00:00
|
|
|
def close(self, rate: float) -> None:
|
|
|
|
"""
|
|
|
|
Sets close_rate to the given rate, calculates total profit
|
|
|
|
and marks trade as closed
|
|
|
|
"""
|
2017-12-17 21:07:56 +00:00
|
|
|
self.close_rate = Decimal(rate)
|
|
|
|
self.close_profit = self.calc_profit_percent()
|
2017-12-16 00:09:07 +00:00
|
|
|
self.close_date = datetime.utcnow()
|
|
|
|
self.is_open = False
|
2017-10-31 23:22:38 +00:00
|
|
|
self.open_order_id = None
|
2017-12-16 00:09:07 +00:00
|
|
|
logger.info(
|
|
|
|
'Marking %s as closed as the trade is fulfilled and found no open orders for it.',
|
|
|
|
self
|
|
|
|
)
|
2017-09-08 19:17:58 +00:00
|
|
|
|
2017-12-19 05:58:02 +00:00
|
|
|
def calc_open_trade_price(
|
|
|
|
self,
|
|
|
|
fee: Optional[float] = None) -> float:
|
2017-12-17 21:07:56 +00:00
|
|
|
"""
|
|
|
|
Calculate the open_rate in BTC
|
|
|
|
:param fee: fee to use on the open rate (optional).
|
|
|
|
If rate is not set self.fee will be used
|
|
|
|
:return: Price in BTC of the open trade
|
|
|
|
"""
|
|
|
|
getcontext().prec = 8
|
|
|
|
|
|
|
|
buy_trade = (Decimal(self.amount) * Decimal(self.open_rate))
|
2018-04-21 17:47:08 +00:00
|
|
|
fees = buy_trade * Decimal(fee or self.fee_open)
|
2017-12-17 21:07:56 +00:00
|
|
|
return float(buy_trade + fees)
|
|
|
|
|
2017-12-19 05:58:02 +00:00
|
|
|
def calc_close_trade_price(
|
|
|
|
self,
|
|
|
|
rate: Optional[float] = None,
|
|
|
|
fee: Optional[float] = None) -> float:
|
2017-12-17 21:07:56 +00:00
|
|
|
"""
|
|
|
|
Calculate the close_rate in BTC
|
|
|
|
:param fee: fee to use on the close rate (optional).
|
|
|
|
If rate is not set self.fee will be used
|
|
|
|
:param rate: rate to compare with (optional).
|
|
|
|
If rate is not set self.close_rate will be used
|
|
|
|
:return: Price in BTC of the open trade
|
|
|
|
"""
|
|
|
|
getcontext().prec = 8
|
|
|
|
|
|
|
|
if rate is None and not self.close_rate:
|
|
|
|
return 0.0
|
|
|
|
|
|
|
|
sell_trade = (Decimal(self.amount) * Decimal(rate or self.close_rate))
|
2018-04-21 17:47:08 +00:00
|
|
|
fees = sell_trade * Decimal(fee or self.fee_close)
|
2017-12-17 21:07:56 +00:00
|
|
|
return float(sell_trade - fees)
|
|
|
|
|
2017-12-19 05:58:02 +00:00
|
|
|
def calc_profit(
|
|
|
|
self,
|
|
|
|
rate: Optional[float] = None,
|
|
|
|
fee: Optional[float] = None) -> float:
|
2017-12-17 21:07:56 +00:00
|
|
|
"""
|
|
|
|
Calculate the profit in BTC between Close and Open trade
|
|
|
|
:param fee: fee to use on the close rate (optional).
|
|
|
|
If rate is not set self.fee will be used
|
|
|
|
:param rate: close rate to compare with (optional).
|
|
|
|
If rate is not set self.close_rate will be used
|
|
|
|
:return: profit in BTC as float
|
|
|
|
"""
|
|
|
|
open_trade_price = self.calc_open_trade_price()
|
|
|
|
close_trade_price = self.calc_close_trade_price(
|
2018-02-06 17:37:10 +00:00
|
|
|
rate=(rate or self.close_rate),
|
2018-04-21 17:47:08 +00:00
|
|
|
fee=(fee or self.fee_close)
|
2017-12-17 21:07:56 +00:00
|
|
|
)
|
2018-06-23 13:27:29 +00:00
|
|
|
profit = close_trade_price - open_trade_price
|
|
|
|
return float(f"{profit:.8f}")
|
2017-12-17 21:07:56 +00:00
|
|
|
|
2017-12-19 05:58:02 +00:00
|
|
|
def calc_profit_percent(
|
|
|
|
self,
|
|
|
|
rate: Optional[float] = None,
|
|
|
|
fee: 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
|
2018-03-17 21:12:21 +00:00
|
|
|
:param fee: fee to use on the close rate (optional).
|
2017-10-31 23:22:38 +00:00
|
|
|
:return: profit in percentage as float
|
|
|
|
"""
|
2017-11-01 01:51:10 +00:00
|
|
|
getcontext().prec = 8
|
2017-12-17 21:07:56 +00:00
|
|
|
|
|
|
|
open_trade_price = self.calc_open_trade_price()
|
|
|
|
close_trade_price = self.calc_close_trade_price(
|
2018-02-06 17:37:10 +00:00
|
|
|
rate=(rate or self.close_rate),
|
2018-04-21 17:47:08 +00:00
|
|
|
fee=(fee or self.fee_close)
|
2017-12-17 21:07:56 +00:00
|
|
|
)
|
2018-06-23 13:27:29 +00:00
|
|
|
profit_percent = (close_trade_price / open_trade_price) - 1
|
|
|
|
return float(f"{profit_percent:.8f}")
|