2019-02-24 18:30:05 +00:00
|
|
|
""" Binance exchange subclass """
|
|
|
|
import logging
|
2021-11-01 07:09:11 +00:00
|
|
|
from datetime import datetime
|
2021-09-19 23:02:09 +00:00
|
|
|
from pathlib import Path
|
2021-11-23 09:19:59 +00:00
|
|
|
from typing import Dict, List, Optional, Tuple
|
2019-02-24 18:30:05 +00:00
|
|
|
|
2021-09-16 04:28:10 +00:00
|
|
|
import arrow
|
2022-03-04 05:50:42 +00:00
|
|
|
import ccxt
|
2021-09-09 07:19:24 +00:00
|
|
|
|
2023-02-04 16:38:39 +00:00
|
|
|
from freqtrade.enums import CandleType, MarginMode, PriceType, TradingMode
|
2022-03-04 05:50:42 +00:00
|
|
|
from freqtrade.exceptions import DDosProtection, OperationalException, TemporaryError
|
2021-09-08 20:50:30 +00:00
|
|
|
from freqtrade.exchange import Exchange
|
2022-03-04 05:50:42 +00:00
|
|
|
from freqtrade.exchange.common import retrier
|
2023-01-05 10:30:15 +00:00
|
|
|
from freqtrade.exchange.types import OHLCVResponse, Tickers
|
2022-09-19 05:23:26 +00:00
|
|
|
from freqtrade.misc import deep_merge_dicts, json_load
|
2021-09-09 07:19:24 +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,
|
2022-02-02 19:40:40 +00:00
|
|
|
"stoploss_order_types": {"limit": "stop_loss_limit"},
|
2023-03-19 14:36:35 +00:00
|
|
|
"order_time_in_force": ["GTC", "FOK", "IOC", "PO"],
|
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
|
|
|
}
|
2022-03-17 19:05:05 +00:00
|
|
|
_ft_has_futures: Dict = {
|
2022-12-25 08:05:53 +00:00
|
|
|
"stoploss_order_types": {"limit": "stop", "market": "stop_market"},
|
2023-03-19 14:36:35 +00:00
|
|
|
"order_time_in_force": ["GTC", "FOK", "IOC"],
|
2022-03-18 15:49:37 +00:00
|
|
|
"tickers_have_price": False,
|
2023-02-07 19:51:55 +00:00
|
|
|
"floor_leverage": True,
|
2023-02-04 16:38:39 +00:00
|
|
|
"stop_price_type_field": "workingType",
|
|
|
|
"stop_price_type_value_mapping": {
|
|
|
|
PriceType.LAST: "CONTRACT_PRICE",
|
|
|
|
PriceType.MARK: "MARK_PRICE",
|
|
|
|
},
|
2022-03-17 19:05:05 +00:00
|
|
|
}
|
2019-02-24 18:30:05 +00:00
|
|
|
|
2022-02-01 18:53:38 +00:00
|
|
|
_supported_trading_mode_margin_pairs: List[Tuple[TradingMode, MarginMode]] = [
|
2021-09-19 23:02:09 +00:00
|
|
|
# TradingMode.SPOT always supported and not required in this list
|
2022-02-01 18:53:38 +00:00
|
|
|
# (TradingMode.MARGIN, MarginMode.CROSS),
|
|
|
|
# (TradingMode.FUTURES, MarginMode.CROSS),
|
|
|
|
(TradingMode.FUTURES, MarginMode.ISOLATED)
|
2021-09-19 23:02:09 +00:00
|
|
|
]
|
|
|
|
|
2022-10-11 19:33:07 +00:00
|
|
|
def get_tickers(self, symbols: Optional[List[str]] = None, cached: bool = False) -> Tickers:
|
2022-03-18 06:08:16 +00:00
|
|
|
tickers = super().get_tickers(symbols=symbols, cached=cached)
|
|
|
|
if self.trading_mode == TradingMode.FUTURES:
|
|
|
|
# Binance's future result has no bid/ask values.
|
|
|
|
# Therefore we must fetch that from fetch_bids_asks and combine the two results.
|
|
|
|
bidsasks = self.fetch_bids_asks(symbols, cached)
|
|
|
|
tickers = deep_merge_dicts(bidsasks, tickers, allow_null_overrides=False)
|
|
|
|
return tickers
|
|
|
|
|
2022-10-01 07:21:40 +00:00
|
|
|
@retrier
|
|
|
|
def additional_exchange_init(self) -> None:
|
|
|
|
"""
|
|
|
|
Additional exchange initialization logic.
|
|
|
|
.api will be available at this point.
|
|
|
|
Must be overridden in child methods if required.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
if self.trading_mode == TradingMode.FUTURES and not self._config['dry_run']:
|
|
|
|
position_side = self._api.fapiPrivateGetPositionsideDual()
|
|
|
|
self._log_exchange_response('position_side_setting', position_side)
|
|
|
|
assets_margin = self._api.fapiPrivateGetMultiAssetsMargin()
|
|
|
|
self._log_exchange_response('multi_asset_margin', assets_margin)
|
|
|
|
msg = ""
|
|
|
|
if position_side.get('dualSidePosition') is True:
|
|
|
|
msg += (
|
|
|
|
"\nHedge Mode is not supported by freqtrade. "
|
|
|
|
"Please change 'Position Mode' on your binance futures account.")
|
|
|
|
if assets_margin.get('multiAssetsMargin') is True:
|
|
|
|
msg += ("\nMulti-Asset Mode is not supported by freqtrade. "
|
|
|
|
"Please change 'Asset Mode' on your binance futures account.")
|
|
|
|
if msg:
|
|
|
|
raise OperationalException(msg)
|
|
|
|
except ccxt.DDoSProtection as e:
|
|
|
|
raise DDosProtection(e) from e
|
|
|
|
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
|
|
|
raise TemporaryError(
|
2023-01-26 18:53:14 +00:00
|
|
|
f'Error in additional_exchange_init due to {e.__class__.__name__}. Message: {e}'
|
|
|
|
) from e
|
|
|
|
|
2022-10-01 07:21:40 +00:00
|
|
|
except ccxt.BaseError as e:
|
|
|
|
raise OperationalException(e) from e
|
|
|
|
|
2021-11-21 06:21:10 +00:00
|
|
|
async def _async_get_historic_ohlcv(self, pair: str, timeframe: str,
|
2021-12-03 13:11:24 +00:00
|
|
|
since_ms: int, candle_type: CandleType,
|
|
|
|
is_new_pair: bool = False, raise_: bool = False,
|
2022-05-25 10:13:37 +00:00
|
|
|
until_ms: Optional[int] = None
|
2023-01-05 10:30:15 +00:00
|
|
|
) -> OHLCVResponse:
|
2021-09-16 04:28:10 +00:00
|
|
|
"""
|
|
|
|
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"
|
2021-12-03 13:11:24 +00:00
|
|
|
:param candle_type: Any of the enum CandleType (must match trading mode!)
|
2021-09-16 04:28:10 +00:00
|
|
|
"""
|
|
|
|
if is_new_pair:
|
2021-12-03 15:44:05 +00:00
|
|
|
x = await self._async_get_candle_history(pair, timeframe, candle_type, 0)
|
2021-11-23 16:43:37 +00:00
|
|
|
if x and x[3] and x[3][0] and x[3][0][0] > since_ms:
|
2021-09-16 04:28:10 +00:00
|
|
|
# Set starting date to first available candle.
|
2021-11-23 16:43:37 +00:00
|
|
|
since_ms = x[3][0][0]
|
2021-09-16 04:28:10 +00:00
|
|
|
logger.info(f"Candle-data for {pair} available starting with "
|
|
|
|
f"{arrow.get(since_ms // 1000).isoformat()}.")
|
2021-10-24 03:10:36 +00:00
|
|
|
|
2021-09-16 04:28:10 +00:00
|
|
|
return await super()._async_get_historic_ohlcv(
|
2021-10-24 03:10:36 +00:00
|
|
|
pair=pair,
|
|
|
|
timeframe=timeframe,
|
|
|
|
since_ms=since_ms,
|
|
|
|
is_new_pair=is_new_pair,
|
|
|
|
raise_=raise_,
|
2022-04-30 13:28:01 +00:00
|
|
|
candle_type=candle_type,
|
|
|
|
until_ms=until_ms,
|
2021-10-24 03:10:36 +00:00
|
|
|
)
|
2021-11-01 07:09:11 +00:00
|
|
|
|
2021-11-09 07:17:29 +00:00
|
|
|
def funding_fee_cutoff(self, open_date: datetime):
|
2021-11-09 18:40:42 +00:00
|
|
|
"""
|
2021-11-09 07:17:29 +00:00
|
|
|
:param open_date: The open date for a trade
|
2021-11-09 07:00:57 +00:00
|
|
|
:return: The cutoff open time for when a funding fee is charged
|
2021-11-09 18:40:42 +00:00
|
|
|
"""
|
2021-11-09 07:17:29 +00:00
|
|
|
return open_date.minute > 0 or (open_date.minute == 0 and open_date.second > 15)
|
2022-01-10 13:17:17 +00:00
|
|
|
|
2022-01-30 00:47:17 +00:00
|
|
|
def dry_run_liquidation_price(
|
2022-01-10 13:17:17 +00:00
|
|
|
self,
|
2022-01-30 00:47:17 +00:00
|
|
|
pair: str,
|
2022-01-10 13:17:17 +00:00
|
|
|
open_rate: float, # Entry price of position
|
|
|
|
is_short: bool,
|
2022-08-26 18:04:36 +00:00
|
|
|
amount: float,
|
|
|
|
stake_amount: float,
|
2022-12-31 09:41:03 +00:00
|
|
|
leverage: float,
|
2022-01-29 08:06:56 +00:00
|
|
|
wallet_balance: float, # Or margin balance
|
2022-01-30 00:47:17 +00:00
|
|
|
mm_ex_1: float = 0.0, # (Binance) Cross only
|
|
|
|
upnl_ex_1: float = 0.0, # (Binance) Cross only
|
2022-01-10 13:17:17 +00:00
|
|
|
) -> Optional[float]:
|
|
|
|
"""
|
2022-08-26 18:04:36 +00:00
|
|
|
Important: Must be fetching data from cached values as this is used by backtesting!
|
2022-01-10 13:17:17 +00:00
|
|
|
MARGIN: https://www.binance.com/en/support/faq/f6b010588e55413aa58b7d63ee0125ed
|
|
|
|
PERPETUAL: https://www.binance.com/en/support/faq/b3c689c1f50a44cabb3a84e663b81d93
|
|
|
|
|
2022-12-31 09:41:03 +00:00
|
|
|
:param pair: Pair to calculate liquidation price for
|
2022-08-26 18:04:36 +00:00
|
|
|
:param open_rate: Entry price of position
|
2022-01-10 13:17:17 +00:00
|
|
|
:param is_short: True if the trade is a short, false otherwise
|
2022-08-26 18:04:36 +00:00
|
|
|
:param amount: Absolute value of position size incl. leverage (in base currency)
|
|
|
|
:param stake_amount: Stake amount - Collateral in settle currency.
|
2022-12-31 09:41:03 +00:00
|
|
|
:param leverage: Leverage used for this position.
|
2022-08-26 18:04:36 +00:00
|
|
|
:param trading_mode: SPOT, MARGIN, FUTURES, etc.
|
|
|
|
:param margin_mode: Either ISOLATED or CROSS
|
|
|
|
:param wallet_balance: Amount of margin_mode in the wallet being used to trade
|
2022-01-10 13:17:17 +00:00
|
|
|
Cross-Margin Mode: crossWalletBalance
|
|
|
|
Isolated-Margin Mode: isolatedWalletBalance
|
|
|
|
|
|
|
|
# * Only required for Cross
|
|
|
|
:param mm_ex_1: (TMM)
|
|
|
|
Cross-Margin Mode: Maintenance Margin of all other contracts, excluding Contract 1
|
|
|
|
Isolated-Margin Mode: 0
|
|
|
|
:param upnl_ex_1: (UPNL)
|
|
|
|
Cross-Margin Mode: Unrealized PNL of all other contracts, excluding Contract 1.
|
|
|
|
Isolated-Margin Mode: 0
|
|
|
|
"""
|
|
|
|
|
2022-01-30 00:47:17 +00:00
|
|
|
side_1 = -1 if is_short else 1
|
2022-02-01 18:53:38 +00:00
|
|
|
cross_vars = upnl_ex_1 - mm_ex_1 if self.margin_mode == MarginMode.CROSS else 0.0
|
2022-01-29 08:06:56 +00:00
|
|
|
|
2022-01-30 00:47:17 +00:00
|
|
|
# mm_ratio: Binance's formula specifies maintenance margin rate which is mm_ratio * 100%
|
|
|
|
# maintenance_amt: (CUM) Maintenance Amount of position
|
2022-08-26 18:04:36 +00:00
|
|
|
mm_ratio, maintenance_amt = self.get_maintenance_ratio_and_amt(pair, stake_amount)
|
2022-01-30 00:47:17 +00:00
|
|
|
|
|
|
|
if (maintenance_amt is None):
|
2022-01-10 13:17:17 +00:00
|
|
|
raise OperationalException(
|
2022-01-30 00:47:17 +00:00
|
|
|
"Parameter maintenance_amt is required by Binance.liquidation_price"
|
|
|
|
f"for {self.trading_mode.value}"
|
2022-01-10 13:17:17 +00:00
|
|
|
)
|
|
|
|
|
2022-01-29 08:06:56 +00:00
|
|
|
if self.trading_mode == TradingMode.FUTURES:
|
2022-01-10 13:17:17 +00:00
|
|
|
return (
|
|
|
|
(
|
|
|
|
(wallet_balance + cross_vars + maintenance_amt) -
|
2022-08-26 18:04:36 +00:00
|
|
|
(side_1 * amount * open_rate)
|
2022-01-10 13:17:17 +00:00
|
|
|
) / (
|
2022-08-26 18:04:36 +00:00
|
|
|
(amount * mm_ratio) - (side_1 * amount)
|
2022-01-10 13:17:17 +00:00
|
|
|
)
|
|
|
|
)
|
2022-01-30 00:47:17 +00:00
|
|
|
else:
|
|
|
|
raise OperationalException(
|
|
|
|
"Freqtrade only supports isolated futures for leverage trading")
|
2022-02-07 07:33:42 +00:00
|
|
|
|
2022-02-15 06:04:50 +00:00
|
|
|
@retrier
|
2022-02-07 08:01:00 +00:00
|
|
|
def load_leverage_tiers(self) -> Dict[str, List[Dict]]:
|
2022-02-16 11:26:52 +00:00
|
|
|
if self.trading_mode == TradingMode.FUTURES:
|
|
|
|
if self._config['dry_run']:
|
|
|
|
leverage_tiers_path = (
|
|
|
|
Path(__file__).parent / 'binance_leverage_tiers.json'
|
|
|
|
)
|
2023-02-25 16:08:02 +00:00
|
|
|
with leverage_tiers_path.open() as json_file:
|
2022-09-19 05:23:26 +00:00
|
|
|
return json_load(json_file)
|
2022-02-16 11:26:52 +00:00
|
|
|
else:
|
|
|
|
try:
|
|
|
|
return self._api.fetch_leverage_tiers()
|
|
|
|
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
|
2022-02-07 07:33:42 +00:00
|
|
|
else:
|
2022-02-16 11:26:52 +00:00
|
|
|
return {}
|