Add method to update fees on closed trades

This commit is contained in:
Matthias 2020-08-22 08:39:10 +02:00
parent fc42d552ab
commit 39beb5c837
2 changed files with 44 additions and 2 deletions

View File

@ -138,6 +138,8 @@ class FreqtradeBot:
# This will update the database after the initial migration # This will update the database after the initial migration
self.update_open_orders() self.update_open_orders()
self.update_closed_trades_without_assigned_fees()
def process(self) -> None: def process(self) -> None:
""" """
Queries the persistence layer for open trades and handles them, Queries the persistence layer for open trades and handles them,
@ -148,6 +150,8 @@ class FreqtradeBot:
# Check whether markets have to be reloaded and reload them when it's needed # Check whether markets have to be reloaded and reload them when it's needed
self.exchange.reload_markets() self.exchange.reload_markets()
self.update_closed_trades_without_assigned_fees()
# Query trades from persistence layer # Query trades from persistence layer
trades = Trade.get_open_trades() trades = Trade.get_open_trades()
@ -233,7 +237,8 @@ class FreqtradeBot:
def update_open_orders(self): def update_open_orders(self):
""" """
Updates open orders based on order list kept in the database Updates open orders based on order list kept in the database.
Mainly updates the state of orders - but may also close trades
""" """
orders = Order.get_open_orders() orders = Order.get_open_orders()
logger.info(f"Updating {len(orders)} open orders.") logger.info(f"Updating {len(orders)} open orders.")
@ -249,6 +254,21 @@ class FreqtradeBot:
except ExchangeError: except ExchangeError:
logger.warning(f"Error updating {order.order_id}") logger.warning(f"Error updating {order.order_id}")
def update_closed_trades_without_assigned_fees(self):
"""
Update closed trades without close fees assigned.
Only works when Orders are in the database, otherwise the last orderid is unknown.
"""
trades: List[Trade] = Trade.get_sold_trades_without_assigned_fees()
for trade in trades:
if not trade.is_open and not trade.fee_updated('sell'):
# Get sell fee
order = trade.select_order('sell', 'closed')
if order:
logger.info(f"Updating sell-fee on trade {trade} for order {order.order_id}.")
self.update_trade_state(trade, order.order_id)
def refind_lost_order(self, trade): def refind_lost_order(self, trade):
""" """
Try refinding a lost trade. Try refinding a lost trade.

View File

@ -8,7 +8,7 @@ from typing import Any, Dict, List, Optional
import arrow import arrow
from sqlalchemy import (Boolean, Column, DateTime, Float, ForeignKey, Integer, from sqlalchemy import (Boolean, Column, DateTime, Float, ForeignKey, Integer,
String, create_engine, desc, func, inspect) String, create_engine, desc, func, inspect, or_)
from sqlalchemy.exc import NoSuchModuleError from sqlalchemy.exc import NoSuchModuleError
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Query, relationship from sqlalchemy.orm import Query, relationship
@ -508,6 +508,17 @@ class Trade(_DECL_BASE):
profit_ratio = (close_trade_price / self.open_trade_price) - 1 profit_ratio = (close_trade_price / self.open_trade_price) - 1
return float(f"{profit_ratio:.8f}") return float(f"{profit_ratio:.8f}")
def select_order(self, order_side: str, status: str):
"""
Returns latest order for this orderside and status
Returns None if nothing is found
"""
orders = [o for o in self.orders if o.side == order_side and o.status == status]
if len(orders) > 0:
return orders[-1]
else:
return None
@staticmethod @staticmethod
def get_trades(trade_filter=None) -> Query: def get_trades(trade_filter=None) -> Query:
""" """
@ -539,6 +550,17 @@ class Trade(_DECL_BASE):
""" """
return Trade.get_trades(Trade.open_order_id.isnot(None)).all() return Trade.get_trades(Trade.open_order_id.isnot(None)).all()
@staticmethod
def get_sold_trades_without_assigned_fees():
"""
Returns all closed trades which don't have fees set correctly
"""
return Trade.get_trades([Trade.fee_close_currency.is_(None),
Trade.id == 100,
Trade.orders.any(),
Trade.is_open.is_(False),
]).all()
@staticmethod @staticmethod
def total_open_trades_stakes() -> float: def total_open_trades_stakes() -> float:
""" """