Merge branch 'feat/short' into max-amount

This commit is contained in:
Sam Germain
2022-02-04 04:42:38 -06:00
10 changed files with 187 additions and 40 deletions

View File

@@ -9,3 +9,4 @@ class MarginMode(Enum):
"""
CROSS = "cross"
ISOLATED = "isolated"
NONE = ''

View File

@@ -941,11 +941,10 @@ class Exchange:
side: str,
amount: float,
rate: float,
leverage: float,
reduceOnly: bool = False,
leverage: float = 1.0,
time_in_force: str = 'gtc',
) -> Dict:
# TODO-lev: remove default for leverage
if self._config['dry_run']:
dry_order = self.create_dry_run_order(pair, ordertype, side, amount, rate, leverage)
return dry_order

View File

@@ -605,7 +605,7 @@ class FreqtradeBot(LoggingMixin):
self,
pair: str,
open_rate: float,
amount: float,
amount: float, # quote currency, includes leverage
leverage: float,
is_short: bool
) -> Tuple[float, Optional[float]]:
@@ -1285,7 +1285,8 @@ class FreqtradeBot(LoggingMixin):
# to the order dict acquired before cancelling.
# we need to fall back to the values from order if corder does not contain these keys.
trade.amount = filled_amount
# TODO-lev: Check edge cases, we don't want to make leverage > 1.0 if we don't have to
# * Check edge cases, we don't want to make leverage > 1.0 if we don't have to
# * (for leverage modes which aren't isolated futures)
trade.stake_amount = trade.amount * trade.open_rate
self.update_trade_state(trade, trade.open_order_id, corder)
@@ -1352,13 +1353,14 @@ class FreqtradeBot(LoggingMixin):
:return: amount to sell
:raise: DependencyException: if available balance is not within 2% of the available amount.
"""
# TODO-lev Maybe update?
# Update wallets to ensure amounts tied up in a stoploss is now free!
self.wallets.update()
trade_base_currency = self.exchange.get_pair_base_currency(pair)
wallet_amount = self.wallets.get_free(trade_base_currency)
logger.debug(f"{pair} - Wallet: {wallet_amount} - Trade-amount: {amount}")
if wallet_amount >= amount:
# TODO-lev: Get wallet amount + value of positions
if wallet_amount >= amount or self.trading_mode == TradingMode.FUTURES:
# A safe exit amount isn't needed for futures, you can just exit/close the position
return amount
elif wallet_amount > amount * 0.98:
logger.info(f"{pair} - Falling back to wallet-amount {wallet_amount} -> {amount}.")
@@ -1436,6 +1438,7 @@ class FreqtradeBot(LoggingMixin):
side=trade.exit_side,
amount=amount,
rate=limit,
leverage=trade.leverage,
reduceOnly=self.trading_mode == TradingMode.FUTURES,
time_in_force=time_in_force
)

View File

@@ -333,8 +333,12 @@ class Backtesting:
df_analyzed.loc[:, col] = 0 if not tag_col else None
# Update dataprovider cache
self.dataprovider._set_cached_df(pair, self.timeframe, df_analyzed, CandleType.SPOT)
# TODO-lev: Candle-type should be conditional, either "spot" or futures
self.dataprovider._set_cached_df(
pair,
self.timeframe,
df_analyzed,
self.config['candle_type_def']
)
df_analyzed = df_analyzed.drop(df_analyzed.head(1).index)
@@ -499,7 +503,7 @@ class Backtesting:
sell_candle_time: datetime = sell_row[DATE_IDX].to_pydatetime()
if self.trading_mode == TradingMode.FUTURES:
# TODO-lev: Other fees / liquidation price?
# TODO-lev: liquidation price?
trade.funding_fees = self.exchange.calculate_funding_fees(
self.futures_data[trade.pair],
amount=trade.amount,

View File

@@ -569,7 +569,6 @@ class LocalTrade():
payment = "BUY" if self.is_short else "SELL"
# * On margin shorts, you buy a little bit more than the amount (amount + interest)
logger.info(f'{order_type.upper()}_{payment} has been fulfilled for {self}.')
# TODO-lev: Double check this
self.close(safe_value_fallback(order, 'average', 'price'))
elif order_type in ('stop_loss_limit', 'stop-loss', 'stop-loss-limit', 'stop'):
self.stoploss_order_id = None

View File

@@ -431,7 +431,6 @@ def generate_candlestick_graph(pair: str, data: pd.DataFrame, trades: pd.DataFra
)
fig.add_trace(candles, 1, 1)
# TODO-lev: Needs short equivalent
if 'enter_long' in data.columns:
df_buy = data[data['enter_long'] == 1]
if len(df_buy) > 0:
@@ -537,7 +536,7 @@ def generate_profit_graph(pairs: str, data: Dict[str, pd.DataFrame],
"Profit per pair",
"Parallelism",
"Underwater",
])
])
fig['layout'].update(title="Freqtrade Profit plot")
fig['layout']['yaxis1'].update(title='Price')
fig['layout']['yaxis2'].update(title=f'Profit {stake_currency}')