2019-02-24 18:30:05 +00:00
|
|
|
""" Binance exchange subclass """
|
|
|
|
import logging
|
2021-09-05 03:55:55 +00:00
|
|
|
from typing import Dict, List, Optional, Tuple
|
2019-02-24 18:30:05 +00:00
|
|
|
|
2021-09-07 17:29:10 +00:00
|
|
|
import arrow
|
2019-08-25 07:50:37 +00:00
|
|
|
import ccxt
|
|
|
|
|
2021-09-05 03:55:55 +00:00
|
|
|
from freqtrade.enums import Collateral, TradingMode
|
2020-09-28 17:39:41 +00:00
|
|
|
from freqtrade.exceptions import (DDosProtection, InsufficientFundsError, InvalidOrderException,
|
|
|
|
OperationalException, TemporaryError)
|
2019-02-24 18:30:05 +00:00
|
|
|
from freqtrade.exchange import Exchange
|
2020-06-28 09:56:29 +00:00
|
|
|
from freqtrade.exchange.common import retrier
|
2019-02-24 18:30:05 +00:00
|
|
|
|
2020-09-28 17:39:41 +00:00
|
|
|
|
2019-02-24 18:30:05 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
class Binance(Exchange):
|
|
|
|
|
2019-02-24 19:01:20 +00:00
|
|
|
_ft_has: Dict = {
|
2019-02-24 18:30:05 +00:00
|
|
|
"stoploss_on_exchange": True,
|
2019-03-25 23:49:39 +00:00
|
|
|
"order_time_in_force": ['gtc', 'fok', 'ioc'],
|
2021-09-03 06:48:53 +00:00
|
|
|
"time_in_force_parameter": "timeInForce",
|
2020-12-20 10:44:50 +00:00
|
|
|
"ohlcv_candle_limit": 1000,
|
2019-08-14 17:22:52 +00:00
|
|
|
"trades_pagination": "id",
|
|
|
|
"trades_pagination_arg": "fromId",
|
2020-10-13 18:02:47 +00:00
|
|
|
"l2_limit_range": [5, 10, 20, 50, 100, 500, 1000],
|
2019-02-24 18:30:05 +00:00
|
|
|
}
|
|
|
|
|
2021-09-05 03:55:55 +00:00
|
|
|
_supported_trading_mode_collateral_pairs: List[Tuple[TradingMode, Collateral]] = [
|
|
|
|
# TradingMode.SPOT always supported and not required in this list
|
|
|
|
# (TradingMode.MARGIN, Collateral.CROSS), # TODO-lev: Uncomment once supported
|
|
|
|
# (TradingMode.FUTURES, Collateral.CROSS), # TODO-lev: Uncomment once supported
|
|
|
|
# (TradingMode.FUTURES, Collateral.ISOLATED) # TODO-lev: Uncomment once supported
|
|
|
|
]
|
|
|
|
|
2021-07-26 06:01:57 +00:00
|
|
|
def stoploss_adjust(self, stop_loss: float, order: Dict, side: str) -> bool:
|
2020-01-19 18:54:30 +00:00
|
|
|
"""
|
|
|
|
Verify stop_loss against stoploss-order value (limit or price)
|
|
|
|
Returns True if adjustment is necessary.
|
2021-07-26 06:01:57 +00:00
|
|
|
:param side: "buy" or "sell"
|
2020-01-19 18:54:30 +00:00
|
|
|
"""
|
2021-08-22 03:10:03 +00:00
|
|
|
|
|
|
|
return order['type'] == 'stop_loss_limit' and (
|
2021-09-10 19:39:42 +00:00
|
|
|
(side == "sell" and stop_loss > float(order['info']['stopPrice'])) or
|
|
|
|
(side == "buy" and stop_loss < float(order['info']['stopPrice']))
|
2021-08-22 03:10:03 +00:00
|
|
|
)
|
2020-01-19 18:54:30 +00:00
|
|
|
|
2020-06-28 09:56:29 +00:00
|
|
|
@retrier(retries=0)
|
2021-07-26 06:01:57 +00:00
|
|
|
def stoploss(self, pair: str, amount: float,
|
|
|
|
stop_price: float, order_types: Dict, side: str) -> Dict:
|
2019-08-25 07:50:37 +00:00
|
|
|
"""
|
|
|
|
creates a stoploss limit order.
|
|
|
|
this stoploss-limit is binance-specific.
|
|
|
|
It may work with a limited number of other exchanges, but this has not been tested yet.
|
2021-07-26 06:01:57 +00:00
|
|
|
:param side: "buy" or "sell"
|
2019-08-25 07:50:37 +00:00
|
|
|
"""
|
2020-01-19 12:12:28 +00:00
|
|
|
# Limit price threshold: As limit price should always be below stop-price
|
2021-09-10 19:39:42 +00:00
|
|
|
limit_price_pct = order_types.get('stoploss_on_exchange_limit_ratio', 0.99)
|
|
|
|
if side == "sell":
|
|
|
|
# TODO: Name limit_rate in other exchange subclasses
|
|
|
|
rate = stop_price * limit_price_pct
|
|
|
|
else:
|
|
|
|
rate = stop_price * (2 - limit_price_pct)
|
2020-01-19 12:12:28 +00:00
|
|
|
|
2019-08-25 07:50:37 +00:00
|
|
|
ordertype = "stop_loss_limit"
|
|
|
|
|
2020-01-12 13:55:05 +00:00
|
|
|
stop_price = self.price_to_precision(pair, stop_price)
|
2019-08-25 07:50:37 +00:00
|
|
|
|
2021-08-22 03:10:03 +00:00
|
|
|
bad_stop_price = (stop_price <= rate) if side == "sell" else (stop_price >= rate)
|
|
|
|
|
2019-08-25 07:50:37 +00:00
|
|
|
# Ensure rate is less than stop price
|
2021-08-22 03:10:03 +00:00
|
|
|
if bad_stop_price:
|
2019-08-25 07:50:37 +00:00
|
|
|
raise OperationalException(
|
2021-08-22 03:10:03 +00:00
|
|
|
'In stoploss limit order, stop price should be better than limit price')
|
2019-08-25 07:50:37 +00:00
|
|
|
|
|
|
|
if self._config['dry_run']:
|
2021-04-10 11:50:56 +00:00
|
|
|
dry_order = self.create_dry_run_order(
|
2021-08-22 03:10:03 +00:00
|
|
|
pair, ordertype, side, amount, stop_price)
|
2019-08-25 07:50:37 +00:00
|
|
|
return dry_order
|
|
|
|
|
|
|
|
try:
|
2019-08-25 08:08:06 +00:00
|
|
|
params = self._params.copy()
|
|
|
|
params.update({'stopPrice': stop_price})
|
|
|
|
|
2020-01-12 13:55:05 +00:00
|
|
|
amount = self.amount_to_precision(pair, amount)
|
2019-08-25 07:50:37 +00:00
|
|
|
|
2020-01-12 13:55:05 +00:00
|
|
|
rate = self.price_to_precision(pair, rate)
|
2019-08-25 07:50:37 +00:00
|
|
|
|
2021-08-22 03:10:03 +00:00
|
|
|
order = self._api.create_order(symbol=pair, type=ordertype, side=side,
|
2020-05-13 05:15:18 +00:00
|
|
|
amount=amount, price=rate, params=params)
|
2019-08-25 07:50:37 +00:00
|
|
|
logger.info('stoploss limit order added for %s. '
|
|
|
|
'stop price: %s. limit: %s', pair, stop_price, rate)
|
2021-06-10 18:09:25 +00:00
|
|
|
self._log_exchange_response('create_stoploss_order', order)
|
2019-08-25 07:50:37 +00:00
|
|
|
return order
|
|
|
|
except ccxt.InsufficientFunds as e:
|
2020-08-14 07:57:13 +00:00
|
|
|
raise InsufficientFundsError(
|
2021-08-22 03:10:03 +00:00
|
|
|
f'Insufficient funds to create {ordertype} {side} order on market {pair}. '
|
|
|
|
f'Tried to {side} amount {amount} at rate {rate}. '
|
2019-08-25 07:50:37 +00:00
|
|
|
f'Message: {e}') from e
|
|
|
|
except ccxt.InvalidOrder as e:
|
2019-09-01 07:08:35 +00:00
|
|
|
# Errors:
|
|
|
|
# `binance Order would trigger immediately.`
|
|
|
|
raise InvalidOrderException(
|
2021-08-22 03:10:03 +00:00
|
|
|
f'Could not create {ordertype} {side} order on market {pair}. '
|
|
|
|
f'Tried to {side} amount {amount} at rate {rate}. '
|
2019-08-25 07:50:37 +00:00
|
|
|
f'Message: {e}') from e
|
2020-06-28 09:17:06 +00:00
|
|
|
except ccxt.DDoSProtection as e:
|
|
|
|
raise DDosProtection(e) from e
|
2019-08-25 07:50:37 +00:00
|
|
|
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
|
|
|
raise TemporaryError(
|
2021-08-22 03:10:03 +00:00
|
|
|
f'Could not place {side} order due to {e.__class__.__name__}. Message: {e}') from e
|
2019-08-25 07:50:37 +00:00
|
|
|
except ccxt.BaseError as e:
|
|
|
|
raise OperationalException(e) from e
|
2021-07-24 07:32:42 +00:00
|
|
|
|
2021-09-06 04:27:14 +00:00
|
|
|
@retrier
|
2021-08-20 08:40:22 +00:00
|
|
|
def fill_leverage_brackets(self):
|
|
|
|
"""
|
|
|
|
Assigns property _leverage_brackets to a dictionary of information about the leverage
|
|
|
|
allowed on each pair
|
|
|
|
"""
|
2021-08-21 07:13:51 +00:00
|
|
|
try:
|
|
|
|
leverage_brackets = self._api.load_leverage_brackets()
|
2021-09-06 04:27:14 +00:00
|
|
|
for pair, brackets in leverage_brackets.items():
|
|
|
|
self._leverage_brackets[pair] = [
|
2021-08-21 07:13:51 +00:00
|
|
|
[
|
|
|
|
min_amount,
|
|
|
|
float(margin_req)
|
|
|
|
] for [
|
|
|
|
min_amount,
|
|
|
|
margin_req
|
|
|
|
] in brackets
|
|
|
|
]
|
|
|
|
|
|
|
|
except ccxt.DDoSProtection as e:
|
|
|
|
raise DDosProtection(e) from e
|
|
|
|
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
|
|
|
raise TemporaryError(f'Could not fetch leverage amounts due to'
|
|
|
|
f'{e.__class__.__name__}. Message: {e}') from e
|
|
|
|
except ccxt.BaseError as e:
|
|
|
|
raise OperationalException(e) from e
|
2021-08-20 08:40:22 +00:00
|
|
|
|
|
|
|
def get_max_leverage(self, pair: Optional[str], nominal_value: Optional[float]) -> float:
|
|
|
|
"""
|
|
|
|
Returns the maximum leverage that a pair can be traded at
|
|
|
|
:param pair: The base/quote currency pair being traded
|
|
|
|
:nominal_value: The total value of the trade in quote currency (collateral + debt)
|
|
|
|
"""
|
|
|
|
pair_brackets = self._leverage_brackets[pair]
|
|
|
|
max_lev = 1.0
|
|
|
|
for [min_amount, margin_req] in pair_brackets:
|
|
|
|
if nominal_value >= min_amount:
|
|
|
|
max_lev = 1/margin_req
|
|
|
|
return max_lev
|
2021-09-12 08:06:18 +00:00
|
|
|
|
2021-09-13 06:09:55 +00:00
|
|
|
def lev_prep(self, pair: str, leverage: float):
|
|
|
|
self.set_margin_mode(pair, self.collateral)
|
|
|
|
self._set_leverage(leverage, pair, self.trading_mode)
|
|
|
|
|
2021-09-12 08:06:18 +00:00
|
|
|
@retrier
|
2021-09-12 08:42:13 +00:00
|
|
|
def _set_leverage(
|
|
|
|
self,
|
|
|
|
leverage: float,
|
2021-09-12 09:09:51 +00:00
|
|
|
pair: Optional[str] = None,
|
|
|
|
trading_mode: Optional[TradingMode] = None
|
2021-09-12 08:42:13 +00:00
|
|
|
):
|
2021-09-12 08:06:18 +00:00
|
|
|
"""
|
|
|
|
Set's the leverage before making a trade, in order to not
|
|
|
|
have the same leverage on every trade
|
|
|
|
"""
|
2021-09-12 08:42:13 +00:00
|
|
|
trading_mode = trading_mode or self.trading_mode
|
2021-09-12 08:06:18 +00:00
|
|
|
|
|
|
|
try:
|
2021-09-12 08:42:13 +00:00
|
|
|
if trading_mode == TradingMode.FUTURES:
|
2021-09-12 08:06:18 +00:00
|
|
|
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
|
2021-09-07 17:29:10 +00:00
|
|
|
|
|
|
|
async def _async_get_historic_ohlcv(self, pair: str, timeframe: str,
|
|
|
|
since_ms: int, is_new_pair: bool
|
|
|
|
) -> List:
|
|
|
|
"""
|
|
|
|
Overwrite to introduce "fast new pair" functionality by detecting the pair's listing date
|
|
|
|
Does not work for other exchanges, which don't return the earliest data when called with "0"
|
|
|
|
"""
|
|
|
|
if is_new_pair:
|
|
|
|
x = await self._async_get_candle_history(pair, timeframe, 0)
|
|
|
|
if x and x[2] and x[2][0] and x[2][0][0] > since_ms:
|
|
|
|
# Set starting date to first available candle.
|
|
|
|
since_ms = x[2][0][0]
|
2021-09-07 17:51:07 +00:00
|
|
|
logger.info(f"Candle-data for {pair} available starting with "
|
2021-09-07 17:29:10 +00:00
|
|
|
f"{arrow.get(since_ms // 1000).isoformat()}.")
|
|
|
|
return await super()._async_get_historic_ohlcv(
|
|
|
|
pair=pair, timeframe=timeframe, since_ms=since_ms, is_new_pair=is_new_pair)
|