2019-02-17 03:01:17 +00:00
|
|
|
""" Kraken exchange subclass """
|
|
|
|
import logging
|
2022-01-08 10:16:56 +00:00
|
|
|
from datetime import datetime
|
2021-09-19 23:02:09 +00:00
|
|
|
from typing import Any, Dict, List, Optional, Tuple
|
2019-02-17 03:01:17 +00:00
|
|
|
|
2019-09-11 04:58:10 +00:00
|
|
|
import ccxt
|
2022-01-08 10:16:56 +00:00
|
|
|
from pandas import DataFrame
|
2021-09-09 07:19:24 +00:00
|
|
|
|
2022-05-07 08:56:13 +00:00
|
|
|
from freqtrade.constants import BuySell
|
2022-02-01 18:53:38 +00:00
|
|
|
from freqtrade.enums import MarginMode, TradingMode
|
2020-09-28 17:39:41 +00:00
|
|
|
from freqtrade.exceptions import (DDosProtection, InsufficientFundsError, InvalidOrderException,
|
|
|
|
OperationalException, TemporaryError)
|
2021-09-08 20:50:30 +00:00
|
|
|
from freqtrade.exchange import Exchange
|
2020-05-18 12:20:51 +00:00
|
|
|
from freqtrade.exchange.common import retrier
|
2022-10-11 19:33:02 +00:00
|
|
|
from freqtrade.exchange.types import Tickers
|
2021-09-09 07:19:24 +00:00
|
|
|
|
2020-09-28 17:39:41 +00:00
|
|
|
|
2019-02-17 03:01:17 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
class Kraken(Exchange):
|
|
|
|
|
2019-02-17 14:54:22 +00:00
|
|
|
_params: Dict = {"trading_agreement": "agree"}
|
2019-08-14 17:22:52 +00:00
|
|
|
_ft_has: Dict = {
|
2020-01-19 13:08:47 +00:00
|
|
|
"stoploss_on_exchange": True,
|
2020-12-20 10:44:50 +00:00
|
|
|
"ohlcv_candle_limit": 720,
|
2022-05-14 07:10:38 +00:00
|
|
|
"ohlcv_has_history": False,
|
2019-08-14 17:22:52 +00:00
|
|
|
"trades_pagination": "id",
|
|
|
|
"trades_pagination_arg": "since",
|
2021-12-05 09:01:44 +00:00
|
|
|
"mark_ohlcv_timeframe": "4h",
|
2019-08-14 17:22:52 +00:00
|
|
|
}
|
2019-09-11 04:58:10 +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)
|
2021-09-19 23:02:09 +00:00
|
|
|
]
|
|
|
|
|
2020-06-02 18:29:48 +00:00
|
|
|
def market_is_tradable(self, market: Dict[str, Any]) -> bool:
|
|
|
|
"""
|
|
|
|
Check if the market symbol is tradable by Freqtrade.
|
|
|
|
Default checks + check if pair is darkpool pair.
|
|
|
|
"""
|
|
|
|
parent_check = super().market_is_tradable(market)
|
|
|
|
|
|
|
|
return (parent_check and
|
|
|
|
market.get('darkpool', False) is False)
|
|
|
|
|
2022-10-11 19:33:02 +00:00
|
|
|
def get_tickers(self, symbols: Optional[List[str]] = None, cached: bool = False) -> Tickers:
|
2022-01-28 06:20:47 +00:00
|
|
|
# Only fetch tickers for current stake currency
|
|
|
|
# Otherwise the request for kraken becomes too large.
|
|
|
|
symbols = list(self.get_markets(quote_currencies=[self._config['stake_currency']]))
|
|
|
|
return super().get_tickers(symbols=symbols, cached=cached)
|
|
|
|
|
2019-09-11 04:58:10 +00:00
|
|
|
@retrier
|
|
|
|
def get_balances(self) -> dict:
|
|
|
|
if self._config['dry_run']:
|
|
|
|
return {}
|
|
|
|
|
|
|
|
try:
|
|
|
|
balances = self._api.fetch_balance()
|
|
|
|
# Remove additional info from ccxt results
|
|
|
|
balances.pop("info", None)
|
|
|
|
balances.pop("free", None)
|
|
|
|
balances.pop("total", None)
|
|
|
|
balances.pop("used", None)
|
|
|
|
|
|
|
|
orders = self._api.fetch_open_orders()
|
2019-09-12 05:03:52 +00:00
|
|
|
order_list = [(x["symbol"].split("/")[0 if x["side"] == "sell" else 1],
|
2020-12-29 19:06:37 +00:00
|
|
|
x["remaining"] if x["side"] == "sell" else x["remaining"] * x["price"],
|
2021-06-25 13:45:49 +00:00
|
|
|
# Don't remove the below comment, this can be important for debugging
|
2019-09-12 05:03:52 +00:00
|
|
|
# x["side"], x["amount"],
|
|
|
|
) for x in orders]
|
2019-09-11 04:58:10 +00:00
|
|
|
for bal in balances:
|
2021-05-05 04:47:26 +00:00
|
|
|
if not isinstance(balances[bal], dict):
|
|
|
|
continue
|
2019-09-11 04:58:10 +00:00
|
|
|
balances[bal]['used'] = sum(order[1] for order in order_list if order[0] == bal)
|
|
|
|
balances[bal]['free'] = balances[bal]['total'] - balances[bal]['used']
|
|
|
|
|
|
|
|
return balances
|
2020-06-28 09:17:06 +00:00
|
|
|
except ccxt.DDoSProtection as e:
|
|
|
|
raise DDosProtection(e) from e
|
2019-09-11 04:58:10 +00:00
|
|
|
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
|
|
|
raise TemporaryError(
|
|
|
|
f'Could not get balance due to {e.__class__.__name__}. Message: {e}') from e
|
|
|
|
except ccxt.BaseError as e:
|
|
|
|
raise OperationalException(e) from e
|
2020-01-19 13:08:47 +00:00
|
|
|
|
2021-09-19 23:02:09 +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-09-19 23:02:09 +00:00
|
|
|
return (order['type'] in ('stop-loss', 'stop-loss-limit') and (
|
|
|
|
(side == "sell" and stop_loss > float(order['price'])) or
|
|
|
|
(side == "buy" and stop_loss < float(order['price']))
|
|
|
|
))
|
2020-01-19 18:54:30 +00:00
|
|
|
|
2020-06-28 09:56:29 +00:00
|
|
|
@retrier(retries=0)
|
2021-09-19 23:02:09 +00:00
|
|
|
def stoploss(self, pair: str, amount: float, stop_price: float,
|
2022-05-07 09:08:54 +00:00
|
|
|
order_types: Dict, side: BuySell, leverage: float) -> Dict:
|
2020-01-19 13:08:47 +00:00
|
|
|
"""
|
|
|
|
Creates a stoploss market order.
|
|
|
|
Stoploss market orders is the only stoploss type supported by kraken.
|
2022-02-26 07:34:23 +00:00
|
|
|
TODO: investigate if this can be combined with generic implementation
|
|
|
|
(careful, prices are reversed)
|
2020-01-19 13:08:47 +00:00
|
|
|
"""
|
2020-11-25 15:27:27 +00:00
|
|
|
params = self._params.copy()
|
2022-02-02 04:23:05 +00:00
|
|
|
if self.trading_mode == TradingMode.FUTURES:
|
|
|
|
params.update({'reduceOnly': True})
|
2020-01-19 13:08:47 +00:00
|
|
|
|
2020-11-25 15:27:27 +00:00
|
|
|
if order_types.get('stoploss', 'market') == 'limit':
|
|
|
|
ordertype = "stop-loss-limit"
|
|
|
|
limit_price_pct = order_types.get('stoploss_on_exchange_limit_ratio', 0.99)
|
2021-09-19 23:02:09 +00:00
|
|
|
if side == "sell":
|
|
|
|
limit_rate = stop_price * limit_price_pct
|
|
|
|
else:
|
|
|
|
limit_rate = stop_price * (2 - limit_price_pct)
|
2020-11-25 15:27:27 +00:00
|
|
|
params['price2'] = self.price_to_precision(pair, limit_rate)
|
|
|
|
else:
|
|
|
|
ordertype = "stop-loss"
|
2020-01-19 13:08:47 +00:00
|
|
|
|
|
|
|
stop_price = self.price_to_precision(pair, stop_price)
|
|
|
|
|
|
|
|
if self._config['dry_run']:
|
2021-04-10 11:50:56 +00:00
|
|
|
dry_order = self.create_dry_run_order(
|
2022-03-03 19:51:52 +00:00
|
|
|
pair, ordertype, side, amount, stop_price, leverage, stop_loss=True)
|
2020-01-19 13:08:47 +00:00
|
|
|
return dry_order
|
|
|
|
|
|
|
|
try:
|
|
|
|
amount = self.amount_to_precision(pair, amount)
|
|
|
|
|
2021-09-19 23:02:09 +00:00
|
|
|
order = self._api.create_order(symbol=pair, type=ordertype, side=side,
|
2020-01-19 13:08:47 +00:00
|
|
|
amount=amount, price=stop_price, params=params)
|
2021-06-10 18:09:25 +00:00
|
|
|
self._log_exchange_response('create_stoploss_order', order)
|
2020-01-19 13:08:47 +00:00
|
|
|
logger.info('stoploss order added for %s. '
|
|
|
|
'stop price: %s.', pair, stop_price)
|
|
|
|
return order
|
|
|
|
except ccxt.InsufficientFunds as e:
|
2020-08-14 07:57:13 +00:00
|
|
|
raise InsufficientFundsError(
|
2021-09-19 23:02:09 +00:00
|
|
|
f'Insufficient funds to create {ordertype} {side} order on market {pair}. '
|
2020-01-19 13:08:47 +00:00
|
|
|
f'Tried to create stoploss with amount {amount} at stoploss {stop_price}. '
|
|
|
|
f'Message: {e}') from e
|
|
|
|
except ccxt.InvalidOrder as e:
|
|
|
|
raise InvalidOrderException(
|
2021-09-19 23:02:09 +00:00
|
|
|
f'Could not create {ordertype} {side} order on market {pair}. '
|
2020-01-19 13:08:47 +00:00
|
|
|
f'Tried to create stoploss with amount {amount} at stoploss {stop_price}. '
|
|
|
|
f'Message: {e}') from e
|
2020-06-28 09:17:06 +00:00
|
|
|
except ccxt.DDoSProtection as e:
|
|
|
|
raise DDosProtection(e) from e
|
2020-01-19 13:08:47 +00:00
|
|
|
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
|
|
|
raise TemporaryError(
|
2021-09-19 23:02:09 +00:00
|
|
|
f'Could not place {side} order due to {e.__class__.__name__}. Message: {e}') from e
|
2020-01-19 13:08:47 +00:00
|
|
|
except ccxt.BaseError as e:
|
|
|
|
raise OperationalException(e) from e
|
2021-09-19 23:02:09 +00:00
|
|
|
|
|
|
|
def _set_leverage(
|
|
|
|
self,
|
|
|
|
leverage: float,
|
|
|
|
pair: Optional[str] = None,
|
|
|
|
trading_mode: Optional[TradingMode] = None
|
|
|
|
):
|
|
|
|
"""
|
2021-11-09 18:22:29 +00:00
|
|
|
Kraken set's the leverage as an option in the order object, so we need to
|
|
|
|
add it to params
|
2021-09-19 23:02:09 +00:00
|
|
|
"""
|
|
|
|
return
|
|
|
|
|
2022-02-02 04:23:05 +00:00
|
|
|
def _get_params(
|
|
|
|
self,
|
2022-05-07 08:56:13 +00:00
|
|
|
side: BuySell,
|
2022-02-02 04:23:05 +00:00
|
|
|
ordertype: str,
|
|
|
|
leverage: float,
|
|
|
|
reduceOnly: bool,
|
2022-08-27 08:24:56 +00:00
|
|
|
time_in_force: str = 'GTC'
|
2022-02-02 04:23:05 +00:00
|
|
|
) -> Dict:
|
2022-03-23 05:49:07 +00:00
|
|
|
params = super()._get_params(
|
2022-05-07 08:56:13 +00:00
|
|
|
side=side,
|
2022-03-23 05:49:07 +00:00
|
|
|
ordertype=ordertype,
|
|
|
|
leverage=leverage,
|
|
|
|
reduceOnly=reduceOnly,
|
|
|
|
time_in_force=time_in_force,
|
|
|
|
)
|
2021-09-19 23:02:09 +00:00
|
|
|
if leverage > 1.0:
|
2022-02-02 04:29:04 +00:00
|
|
|
params['leverage'] = round(leverage)
|
2021-09-19 23:02:09 +00:00
|
|
|
return params
|
2021-11-06 23:12:48 +00:00
|
|
|
|
2022-01-17 18:26:03 +00:00
|
|
|
def calculate_funding_fees(
|
2021-11-06 23:12:48 +00:00
|
|
|
self,
|
2022-01-17 18:39:58 +00:00
|
|
|
df: DataFrame,
|
2022-01-08 10:16:56 +00:00
|
|
|
amount: float,
|
2022-01-17 18:59:33 +00:00
|
|
|
is_short: bool,
|
2022-01-08 10:16:56 +00:00
|
|
|
open_date: datetime,
|
|
|
|
close_date: Optional[datetime] = None,
|
2021-11-06 23:12:48 +00:00
|
|
|
time_in_ratio: Optional[float] = None
|
|
|
|
) -> float:
|
|
|
|
"""
|
2021-11-09 07:00:57 +00:00
|
|
|
# ! This method will always error when run by Freqtrade because time_in_ratio is never
|
|
|
|
# ! passed to _get_funding_fee. For kraken futures to work in dry run and backtesting
|
|
|
|
# ! functionality must be added that passes the parameter time_in_ratio to
|
|
|
|
# ! _get_funding_fee when using Kraken
|
2022-01-08 10:16:56 +00:00
|
|
|
calculates the sum of all funding fees that occurred for a pair during a futures trade
|
2022-01-17 18:39:58 +00:00
|
|
|
:param df: Dataframe containing combined funding and mark rates
|
|
|
|
as `open_fund` and `open_mark`.
|
2022-01-08 10:16:56 +00:00
|
|
|
:param amount: The quantity of the trade
|
2022-01-17 18:59:33 +00:00
|
|
|
:param is_short: trade direction
|
2022-01-08 10:16:56 +00:00
|
|
|
:param open_date: The date and time that the trade started
|
|
|
|
:param close_date: The date and time that the trade ended
|
|
|
|
:param time_in_ratio: Not used by most exchange classes
|
2021-11-06 23:12:48 +00:00
|
|
|
"""
|
|
|
|
if not time_in_ratio:
|
|
|
|
raise OperationalException(
|
|
|
|
f"time_in_ratio is required for {self.name}._get_funding_fee")
|
2022-01-08 10:16:56 +00:00
|
|
|
fees: float = 0
|
|
|
|
|
|
|
|
if not df.empty:
|
|
|
|
df = df[(df['date'] >= open_date) & (df['date'] <= close_date)]
|
|
|
|
fees = sum(df['open_fund'] * df['open_mark'] * amount * time_in_ratio)
|
|
|
|
|
2022-01-22 10:04:58 +00:00
|
|
|
return fees if is_short else -fees
|