stable/persistence.py

69 lines
2.3 KiB
Python
Raw Normal View History

2017-05-12 17:11:56 +00:00
from datetime import datetime
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
from sqlalchemy.types import Enum
2017-06-08 18:01:01 +00:00
from exchange import Exchange, get_exchange_api
2017-05-21 15:58:54 +00:00
from utils import get_conf
2017-05-12 17:11:56 +00:00
2017-06-08 18:01:01 +00:00
conf = get_conf()
if conf.get('dry_run', False):
2017-05-21 15:58:54 +00:00
db_handle = 'sqlite:///tradesv2.dry_run.sqlite'
else:
db_handle = 'sqlite:///tradesv2.sqlite'
2017-05-12 17:11:56 +00:00
2017-05-21 15:58:54 +00:00
engine = create_engine(db_handle, echo=False)
session = scoped_session(sessionmaker(bind=engine, autoflush=True, autocommit=True))
Session = session()
2017-05-21 15:58:54 +00:00
Base = declarative_base()
2017-05-12 17:11:56 +00:00
class Trade(Base):
__tablename__ = 'trades'
query = session.query_property()
2017-05-12 17:11:56 +00:00
id = Column(Integer, primary_key=True)
exchange = Column(Enum(Exchange), nullable=False)
pair = Column(String, nullable=False)
is_open = Column(Boolean, nullable=False, default=True)
open_rate = Column(Float, nullable=False)
close_rate = Column(Float)
close_profit = Column(Float)
btc_amount = Column(Float, nullable=False)
amount = Column(Float, nullable=False)
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,
'closed' if not self.is_open else round((datetime.utcnow() - self.open_date).total_seconds() / 60, 2)
)
2017-09-01 19:11:46 +00:00
def exec_sell_order(self, rate: float, amount: float) -> float:
2017-06-08 18:01:01 +00:00
"""
Executes a sell for the given trade and updated the entity.
:param rate: rate to sell for
:param amount: amount to sell
:return: current profit as percentage
"""
profit = 100 * ((rate - self.open_rate) / self.open_rate)
# Execute sell and update trade record
order_id = get_exchange_api(conf).sell(self.pair, rate, amount)
self.close_rate = rate
self.close_profit = profit
self.close_date = datetime.utcnow()
self.open_order_id = order_id
Session.flush()
2017-06-08 18:01:01 +00:00
return profit
Base.metadata.create_all(engine)