Rename _session to sessoin

This commit is contained in:
Matthias 2023-03-15 21:12:06 +01:00
parent 8073989c98
commit aa54b77702
7 changed files with 33 additions and 33 deletions

View File

@ -20,7 +20,7 @@ def start_convert_db(args: Dict[str, Any]) -> None:
config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE) config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE)
init_db(config['db_url']) init_db(config['db_url'])
session_target = Trade._session session_target = Trade.session
init_db(config['db_url_from']) init_db(config['db_url_from'])
logger.info("Starting db migration.") logger.info("Starting db migration.")

View File

@ -819,7 +819,7 @@ class FreqtradeBot(LoggingMixin):
trade.orders.append(order_obj) trade.orders.append(order_obj)
trade.recalc_trade_from_orders() trade.recalc_trade_from_orders()
Trade._session.add(trade) Trade.session.add(trade)
Trade.commit() Trade.commit()
# Updating wallets # Updating wallets

View File

@ -54,12 +54,12 @@ def init_db(db_url: str) -> None:
# https://docs.sqlalchemy.org/en/13/orm/contextual.html#thread-local-scope # https://docs.sqlalchemy.org/en/13/orm/contextual.html#thread-local-scope
# Scoped sessions proxy requests to the appropriate thread-local session. # Scoped sessions proxy requests to the appropriate thread-local session.
# We should use the scoped_session object - not a seperately initialized version # We should use the scoped_session object - not a seperately initialized version
Trade._session = scoped_session(sessionmaker(bind=engine, autoflush=False)) Trade.session = scoped_session(sessionmaker(bind=engine, autoflush=False))
Order._session = Trade._session Order.session = Trade.session
PairLock._session = Trade._session PairLock.session = Trade.session
Trade.query = Trade._session.query_property() Trade.query = Trade.session.query_property()
Order.query = Trade._session.query_property() Order.query = Trade.session.query_property()
PairLock.query = Trade._session.query_property() PairLock.query = Trade.session.query_property()
previous_tables = inspect(engine).get_table_names() previous_tables = inspect(engine).get_table_names()
ModelBase.metadata.create_all(engine) ModelBase.metadata.create_all(engine)

View File

@ -14,7 +14,7 @@ class PairLock(ModelBase):
""" """
__tablename__ = 'pairlocks' __tablename__ = 'pairlocks'
query: ClassVar[QueryPropertyDescriptor] query: ClassVar[QueryPropertyDescriptor]
_session: ClassVar[SessionType] session: ClassVar[SessionType]
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)

View File

@ -51,8 +51,8 @@ class PairLocks():
active=True active=True
) )
if PairLocks.use_db: if PairLocks.use_db:
PairLock._session.add(lock) PairLock.session.add(lock)
PairLock._session.commit() PairLock.session.commit()
else: else:
PairLocks.locks.append(lock) PairLocks.locks.append(lock)
return lock return lock
@ -106,7 +106,7 @@ class PairLocks():
for lock in locks: for lock in locks:
lock.active = False lock.active = False
if PairLocks.use_db: if PairLocks.use_db:
PairLock._session.commit() PairLock.session.commit()
@staticmethod @staticmethod
def unlock_reason(reason: str, now: Optional[datetime] = None) -> None: def unlock_reason(reason: str, now: Optional[datetime] = None) -> None:
@ -130,7 +130,7 @@ class PairLocks():
for lock in locks: for lock in locks:
logger.info(f"Releasing lock for {lock.pair} with reason '{reason}'.") logger.info(f"Releasing lock for {lock.pair} with reason '{reason}'.")
lock.active = False lock.active = False
PairLock._session.commit() PairLock.session.commit()
else: else:
# used in backtesting mode; don't show log messages for speed # used in backtesting mode; don't show log messages for speed
locksb = PairLocks.get_pair_locks(None) locksb = PairLocks.get_pair_locks(None)

View File

@ -37,7 +37,7 @@ class Order(ModelBase):
""" """
__tablename__ = 'orders' __tablename__ = 'orders'
query: ClassVar[QueryPropertyDescriptor] query: ClassVar[QueryPropertyDescriptor]
_session: ClassVar[SessionType] session: ClassVar[SessionType]
# Uniqueness should be ensured over pair, order_id # Uniqueness should be ensured over pair, order_id
# its likely that order_id is unique per Pair on some exchanges. # its likely that order_id is unique per Pair on some exchanges.
@ -1153,7 +1153,7 @@ class LocalTrade():
get open trade count get open trade count
""" """
if Trade.use_db: if Trade.use_db:
return Trade._session.execute( return Trade.session.execute(
select(func.count(Trade.id)).filter(Trade.is_open.is_(True)) select(func.count(Trade.id)).filter(Trade.is_open.is_(True))
).scalar_one() ).scalar_one()
else: else:
@ -1189,7 +1189,7 @@ class Trade(ModelBase, LocalTrade):
""" """
__tablename__ = 'trades' __tablename__ = 'trades'
query: ClassVar[QueryPropertyDescriptor] query: ClassVar[QueryPropertyDescriptor]
_session: ClassVar[SessionType] session: ClassVar[SessionType]
use_db: bool = True use_db: bool = True
@ -1289,18 +1289,18 @@ class Trade(ModelBase, LocalTrade):
def delete(self) -> None: def delete(self) -> None:
for order in self.orders: for order in self.orders:
Order._session.delete(order) Order.session.delete(order)
Trade._session.delete(self) Trade.session.delete(self)
Trade.commit() Trade.commit()
@staticmethod @staticmethod
def commit(): def commit():
Trade._session.commit() Trade.session.commit()
@staticmethod @staticmethod
def rollback(): def rollback():
Trade._session.rollback() Trade.session.rollback()
@staticmethod @staticmethod
def get_trades_proxy(*, pair: Optional[str] = None, is_open: Optional[bool] = None, def get_trades_proxy(*, pair: Optional[str] = None, is_open: Optional[bool] = None,
@ -1369,7 +1369,7 @@ class Trade(ModelBase, LocalTrade):
e.g. `(trade_filter=Trade.id == trade_id)` e.g. `(trade_filter=Trade.id == trade_id)`
:return: unsorted query object :return: unsorted query object
""" """
return Trade._session.scalars(Trade.get_trades_query(trade_filter, include_orders)) return Trade.session.scalars(Trade.get_trades_query(trade_filter, include_orders))
@staticmethod @staticmethod
def get_open_order_trades() -> List['Trade']: def get_open_order_trades() -> List['Trade']:
@ -1407,7 +1407,7 @@ class Trade(ModelBase, LocalTrade):
Retrieves total realized profit Retrieves total realized profit
""" """
if Trade.use_db: if Trade.use_db:
total_profit: float = Trade._session.execute( total_profit: float = Trade.session.execute(
select(func.sum(Trade.close_profit_abs)).filter(Trade.is_open.is_(False)) select(func.sum(Trade.close_profit_abs)).filter(Trade.is_open.is_(False))
).scalar_one() ).scalar_one()
else: else:
@ -1422,7 +1422,7 @@ class Trade(ModelBase, LocalTrade):
in stake currency in stake currency
""" """
if Trade.use_db: if Trade.use_db:
total_open_stake_amount = Trade._session.scalar( total_open_stake_amount = Trade.session.scalar(
select(func.sum(Trade.stake_amount)).filter(Trade.is_open.is_(True)) select(func.sum(Trade.stake_amount)).filter(Trade.is_open.is_(True))
) )
else: else:
@ -1441,7 +1441,7 @@ class Trade(ModelBase, LocalTrade):
start_date = datetime.now(timezone.utc) - timedelta(minutes=minutes) start_date = datetime.now(timezone.utc) - timedelta(minutes=minutes)
filters.append(Trade.close_date >= start_date) filters.append(Trade.close_date >= start_date)
pair_rates = Trade._session.execute( pair_rates = Trade.session.execute(
select( select(
Trade.pair, Trade.pair,
func.sum(Trade.close_profit).label('profit_sum'), func.sum(Trade.close_profit).label('profit_sum'),
@ -1476,7 +1476,7 @@ class Trade(ModelBase, LocalTrade):
if (pair is not None): if (pair is not None):
filters.append(Trade.pair == pair) filters.append(Trade.pair == pair)
enter_tag_perf = Trade._session.execute( enter_tag_perf = Trade.session.execute(
select( select(
Trade.enter_tag, Trade.enter_tag,
func.sum(Trade.close_profit).label('profit_sum'), func.sum(Trade.close_profit).label('profit_sum'),
@ -1509,7 +1509,7 @@ class Trade(ModelBase, LocalTrade):
filters: List = [Trade.is_open.is_(False)] filters: List = [Trade.is_open.is_(False)]
if (pair is not None): if (pair is not None):
filters.append(Trade.pair == pair) filters.append(Trade.pair == pair)
sell_tag_perf = Trade._session.execute( sell_tag_perf = Trade.session.execute(
select( select(
Trade.exit_reason, Trade.exit_reason,
func.sum(Trade.close_profit).label('profit_sum'), func.sum(Trade.close_profit).label('profit_sum'),
@ -1542,7 +1542,7 @@ class Trade(ModelBase, LocalTrade):
filters: List = [Trade.is_open.is_(False)] filters: List = [Trade.is_open.is_(False)]
if (pair is not None): if (pair is not None):
filters.append(Trade.pair == pair) filters.append(Trade.pair == pair)
mix_tag_perf = Trade._session.execute( mix_tag_perf = Trade.session.execute(
select( select(
Trade.id, Trade.id,
Trade.enter_tag, Trade.enter_tag,
@ -1589,7 +1589,7 @@ class Trade(ModelBase, LocalTrade):
NOTE: Not supported in Backtesting. NOTE: Not supported in Backtesting.
:returns: Tuple containing (pair, profit_sum) :returns: Tuple containing (pair, profit_sum)
""" """
best_pair = Trade._session.execute( best_pair = Trade.session.execute(
select( select(
Trade.pair, Trade.pair,
func.sum(Trade.close_profit).label('profit_sum') func.sum(Trade.close_profit).label('profit_sum')

View File

@ -340,7 +340,7 @@ class RPC:
for day in range(0, timescale): for day in range(0, timescale):
profitday = start_date - time_offset(day) profitday = start_date - time_offset(day)
# Only query for necessary columns for performance reasons. # Only query for necessary columns for performance reasons.
trades = Trade._session.execute( trades = Trade.session.execute(
select(Trade.close_profit_abs) select(Trade.close_profit_abs)
.filter(Trade.is_open.is_(False), .filter(Trade.is_open.is_(False),
Trade.close_date >= profitday, Trade.close_date >= profitday,
@ -384,18 +384,18 @@ class RPC:
""" Returns the X last trades """ """ Returns the X last trades """
order_by: Any = Trade.id if order_by_id else Trade.close_date.desc() order_by: Any = Trade.id if order_by_id else Trade.close_date.desc()
if limit: if limit:
trades = Trade._session.execute( trades = Trade.session.execute(
Trade.get_trades_query([Trade.is_open.is_(False)]) Trade.get_trades_query([Trade.is_open.is_(False)])
.order_by(order_by) .order_by(order_by)
.limit(limit) .limit(limit)
.offset(offset)) .offset(offset))
else: else:
trades = Trade._session.execute( trades = Trade.session.execute(
Trade.get_trades_query([Trade.is_open.is_(False)]) Trade.get_trades_query([Trade.is_open.is_(False)])
.order_by(Trade.close_date.desc())) .order_by(Trade.close_date.desc()))
output = [trade.to_json() for trade in trades] output = [trade.to_json() for trade in trades]
total_trades = Trade._session.scalar( total_trades = Trade.session.scalar(
select(func.count(Trade.id)).filter(Trade.is_open.is_(False))) select(func.count(Trade.id)).filter(Trade.is_open.is_(False)))
return { return {
@ -444,7 +444,7 @@ class RPC:
""" Returns cumulative profit statistics """ """ Returns cumulative profit statistics """
trade_filter = ((Trade.is_open.is_(False) & (Trade.close_date >= start_date)) | trade_filter = ((Trade.is_open.is_(False) & (Trade.close_date >= start_date)) |
Trade.is_open.is_(True)) Trade.is_open.is_(True))
trades: Sequence[Trade] = Trade._session.scalars(Trade.get_trades_query( trades: Sequence[Trade] = Trade.session.scalars(Trade.get_trades_query(
trade_filter, include_orders=False).order_by(Trade.id)).all() trade_filter, include_orders=False).order_by(Trade.id)).all()
profit_all_coin = [] profit_all_coin = []