Added adding and removing trades to/from maintenance_margin in freqtradebot

This commit is contained in:
Sam Germain 2021-08-08 16:32:44 -06:00
parent 82917e2705
commit ff63c792b2
2 changed files with 24 additions and 4 deletions

View File

@ -16,7 +16,7 @@ from freqtrade.configuration import validate_config_consistency
from freqtrade.data.converter import order_book_to_dataframe
from freqtrade.data.dataprovider import DataProvider
from freqtrade.edge import Edge
from freqtrade.enums import RPCMessageType, SellType, State, TradingMode
from freqtrade.enums import Collateral, RPCMessageType, SellType, State, TradingMode
from freqtrade.exceptions import (DependencyException, ExchangeError, InsufficientFundsError,
InvalidOrderException, PricingError)
from freqtrade.exchange import timeframe_to_minutes, timeframe_to_seconds
@ -42,6 +42,9 @@ class FreqtradeBot(LoggingMixin):
This is from here the bot start its logic.
"""
collateral: Optional[Collateral] = None
trading_mode: TradingMode = TradingMode.SPOT
def __init__(self, config: Dict[str, Any]) -> None:
"""
Init all variables and objects the bot needs to work
@ -106,13 +109,18 @@ class FreqtradeBot(LoggingMixin):
if self.config.get("trading_mode"):
self.trading_mode = TradingMode(self.config.get("trading_mode"))
if self.config.get('collateral'):
self.collateral = Collateral(self.config.get('collateral'))
# Start calculating maintenance margin if on cross margin
# TODO: Add margin_mode to freqtrade.configuration?
if self.config.get('collateral') == "cross":
if self.collateral == Collateral.CROSS:
self.maintenance_margin = MaintenanceMargin(
exchange_name=self.exchange.name,
trading_mode=self.trading_mode)
self.maintenance_margin.run
self.maintenance_margin.run()
def notify_status(self, msg: str) -> None:
"""
@ -590,6 +598,9 @@ class FreqtradeBot(LoggingMixin):
if order_status == 'closed':
self.update_trade_state(trade, order_id, order)
if self.collateral == Collateral.CROSS:
self.maintenance_margin.add_new_trade(trade)
Trade.query.session.add(trade)
Trade.commit()
@ -1146,9 +1157,18 @@ class FreqtradeBot(LoggingMixin):
reason='Auto lock')
self._notify_sell(trade, order_type)
self._remove_maintenance_trade(trade)
return True
def _remove_maintenance_trade(self, trade: Trade):
"""
Removes a trade from the maintenance margin object
:param trade: The trade to remove from the maintenance margin
"""
if self.collateral == Collateral.CROSS:
self.maintenance_margin.remove_trade(trade)
def _notify_sell(self, trade: Trade, order_type: str, fill: bool = False) -> None:
"""
Sends rpc notification when a sell occurred.

View File

@ -15,7 +15,7 @@ class MaintenanceMargin:
def margin_level(self):
# This is the current value of all assets,
# and if you pass below liq_level, you are liquidated
# TODO: Add args to formula
# TODO-lev: Add args to formula
return liquidation_price(
trading_mode=self.trading_mode,
exchange_name=self.exchange_name