From bc102d57c91ff225c9ca3cd1745d7b8460efcce0 Mon Sep 17 00:00:00 2001 From: Sam Germain Date: Sun, 12 Sep 2021 02:06:18 -0600 Subject: [PATCH] Updated set leverage to check trading mode --- freqtrade/exchange/binance.py | 21 +++++++++++++++++++++ freqtrade/exchange/exchange.py | 9 +++++---- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/freqtrade/exchange/binance.py b/freqtrade/exchange/binance.py index 1fcdc0ab4..178fa49da 100644 --- a/freqtrade/exchange/binance.py +++ b/freqtrade/exchange/binance.py @@ -151,3 +151,24 @@ class Binance(Exchange): if nominal_value >= min_amount: max_lev = 1/margin_req return max_lev + + @retrier + def _set_leverage(self, leverage: float, pair: Optional[str]): + """ + Set's the leverage before making a trade, in order to not + have the same leverage on every trade + """ + if not self.exchange_has("setLeverage"): + # Some exchanges only support one collateral type + return + + try: + if self.trading_mode == TradingMode.FUTURES: + self._api.set_leverage(symbol=pair, leverage=leverage) + except ccxt.DDoSProtection as e: + raise DDosProtection(e) from e + except (ccxt.NetworkError, ccxt.ExchangeError) as e: + raise TemporaryError( + f'Could not set leverage due to {e.__class__.__name__}. Message: {e}') from e + except ccxt.BaseError as e: + raise OperationalException(e) from e diff --git a/freqtrade/exchange/exchange.py b/freqtrade/exchange/exchange.py index a5778432a..bef8f5e57 100644 --- a/freqtrade/exchange/exchange.py +++ b/freqtrade/exchange/exchange.py @@ -145,7 +145,7 @@ class Exchange: self._api_async = self._init_ccxt( exchange_config, ccxt_async, ccxt_kwargs=ccxt_async_config) - trading_mode: TradingMode = ( + self.trading_mode: TradingMode = ( TradingMode(config.get('trading_mode')) if config.get('trading_mode') else TradingMode.SPOT @@ -156,7 +156,7 @@ class Exchange: else None ) - if trading_mode != TradingMode.SPOT: + if self.trading_mode != TradingMode.SPOT: self.fill_leverage_brackets() logger.info('Using Exchange "%s"', self.name) @@ -176,7 +176,7 @@ class Exchange: self.validate_order_time_in_force(config.get('order_time_in_force', {})) self.validate_required_startup_candles(config.get('startup_candle_count', 0), config.get('timeframe', '')) - self.validate_trading_mode_and_collateral(trading_mode, collateral) + self.validate_trading_mode_and_collateral(self.trading_mode, collateral) # Converts the interval provided in minutes in config to seconds self.markets_refresh_interval: int = exchange_config.get( "markets_refresh_interval", 60) * 60 @@ -777,7 +777,8 @@ class Exchange: dry_order = self.create_dry_run_order(pair, ordertype, side, amount, rate) return dry_order - self._set_leverage(pair, leverage) + if self.trading_mode != TradingMode.SPOT: + self._set_leverage(pair, leverage) params = self._params.copy() if time_in_force != 'gtc' and ordertype != 'market': param = self._ft_has.get('time_in_force_parameter', '')