Removed "is not None"
https://stackoverflow.com/users/566644/lauritz-v-thaulow freqtrade\configuration\configuration.py:461 reduced checks freqtrade\persistence\trade_model.py:fee_updated - reduced code
This commit is contained in:
parent
7b9439f2e4
commit
e7f15fb61f
@ -141,7 +141,7 @@ class Arguments:
|
||||
if ('config' in parsed_arg and parsed_arg.config is None):
|
||||
conf_required = ('command' in parsed_arg and parsed_arg.command in NO_CONF_REQURIED)
|
||||
|
||||
if 'user_data_dir' in parsed_arg and parsed_arg.user_data_dir is not None:
|
||||
if 'user_data_dir' in parsed_arg and parsed_arg.user_data_dir:
|
||||
user_dir = parsed_arg.user_data_dir
|
||||
else:
|
||||
# Default case
|
||||
|
@ -200,7 +200,7 @@ def _validate_ask_orderbook(conf: Dict[str, Any]) -> None:
|
||||
ask_strategy = conf.get('exit_pricing', {})
|
||||
ob_min = ask_strategy.get('order_book_min')
|
||||
ob_max = ask_strategy.get('order_book_max')
|
||||
if ob_min is not None and ob_max is not None and ask_strategy.get('use_order_book'):
|
||||
if ob_min and ob_max and ask_strategy.get('use_order_book'):
|
||||
if ob_min != ob_max:
|
||||
raise OperationalException(
|
||||
"Using order_book_max != order_book_min in exit_pricing is no longer supported."
|
||||
|
@ -458,8 +458,7 @@ class Configuration:
|
||||
sample: logfun=len (prints the length of the found
|
||||
configuration instead of the content)
|
||||
"""
|
||||
if (argname in self.args and self.args[argname] is not None
|
||||
and self.args[argname] is not False):
|
||||
if self.args.get(argname):
|
||||
|
||||
config.update({argname: self.args[argname]})
|
||||
if logfun:
|
||||
|
@ -224,7 +224,7 @@ def find_existing_backtest_stats(dirname: Union[Path, str], run_ids: Dict[str, s
|
||||
# This strategy is not present in analyzed backtest.
|
||||
continue
|
||||
|
||||
if min_backtest_date is not None:
|
||||
if min_backtest_date:
|
||||
backtest_date = strategy_metadata['backtest_start_time']
|
||||
backtest_date = datetime.fromtimestamp(backtest_date, tz=timezone.utc)
|
||||
if backtest_date < min_backtest_date:
|
||||
|
@ -141,7 +141,7 @@ class DataProvider:
|
||||
df, date = self.__cached_pairs[pair_key]
|
||||
else:
|
||||
df, date = self.__cached_pairs[pair_key]
|
||||
if self.__slice_index is not None:
|
||||
if self.__slice_index:
|
||||
max_index = self.__slice_index
|
||||
df = df.iloc[max(0, max_index - MAX_DATAFRAME_CANDLES):max_index]
|
||||
return df, date
|
||||
|
@ -383,8 +383,8 @@ class Exchange:
|
||||
Ensures that Configured mode aligns to
|
||||
"""
|
||||
return (
|
||||
market.get('quote', None) is not None
|
||||
and market.get('base', None) is not None
|
||||
market.get('quote', None)
|
||||
and market.get('base', None)
|
||||
and (self.precisionMode != TICK_SIZE
|
||||
# Too low precision will falsify calculations
|
||||
or market.get('precision', {}).get('price', None) > 1e-11)
|
||||
@ -403,7 +403,7 @@ class Exchange:
|
||||
if self.trading_mode == TradingMode.FUTURES:
|
||||
market = self.markets[pair]
|
||||
contract_size: float = 1.0
|
||||
if market['contractSize'] is not None:
|
||||
if market['contractSize']:
|
||||
# ccxt has contractSize in markets as string
|
||||
contract_size = float(market['contractSize'])
|
||||
return contract_size
|
||||
@ -419,11 +419,11 @@ class Exchange:
|
||||
return trades
|
||||
|
||||
def _order_contracts_to_amount(self, order: Dict) -> Dict:
|
||||
if 'symbol' in order and order['symbol'] is not None:
|
||||
if 'symbol' in order and order['symbol']:
|
||||
contract_size = self._get_contract_size(order['symbol'])
|
||||
if contract_size != 1:
|
||||
for prop in ['amount', 'cost', 'filled', 'remaining']:
|
||||
if prop in order and order[prop] is not None:
|
||||
if prop in order and order[prop]:
|
||||
order[prop] = order[prop] * contract_size
|
||||
return order
|
||||
|
||||
@ -680,7 +680,7 @@ class Exchange:
|
||||
Re-implementation of ccxt internal methods - ensuring we can test the result is correct
|
||||
based on our definitions.
|
||||
"""
|
||||
if self.markets[pair]['precision']['amount'] is not None:
|
||||
if self.markets[pair]['precision']['amount']:
|
||||
amount = float(decimal_to_precision(amount, rounding_mode=TRUNCATE,
|
||||
precision=self.markets[pair]['precision']['amount'],
|
||||
counting_mode=self.precisionMode,
|
||||
@ -760,7 +760,7 @@ class Exchange:
|
||||
|
||||
stake_limits = []
|
||||
limits = market['limits']
|
||||
if (limits['cost'][limit] is not None):
|
||||
if (limits['cost'][limit]):
|
||||
stake_limits.append(
|
||||
self._contracts_to_amount(
|
||||
pair,
|
||||
@ -768,7 +768,7 @@ class Exchange:
|
||||
)
|
||||
)
|
||||
|
||||
if (limits['amount'][limit] is not None):
|
||||
if (limits['amount'][limit]):
|
||||
stake_limits.append(
|
||||
self._contracts_to_amount(
|
||||
pair,
|
||||
@ -1593,7 +1593,7 @@ class Exchange:
|
||||
def get_fee(self, symbol: str, type: str = '', side: str = '', amount: float = 1,
|
||||
price: float = 1, taker_or_maker: str = 'maker') -> float:
|
||||
try:
|
||||
if self._config['dry_run'] and self._config.get('fee', None) is not None:
|
||||
if self._config['dry_run'] and self._config.get('fee', None):
|
||||
return self._config['fee']
|
||||
# validate that markets are loaded before trying to get fee
|
||||
if self._api.markets is None or len(self._api.markets) == 0:
|
||||
@ -1619,10 +1619,10 @@ class Exchange:
|
||||
"""
|
||||
if not isinstance(order, dict):
|
||||
return False
|
||||
return ('fee' in order and order['fee'] is not None
|
||||
return ('fee' in order and order['fee']
|
||||
and (order['fee'].keys() >= {'currency', 'cost'})
|
||||
and order['fee']['currency'] is not None
|
||||
and order['fee']['cost'] is not None
|
||||
and order['fee']['currency']
|
||||
and order['fee']['cost']
|
||||
)
|
||||
|
||||
def calculate_fee_rate(self, order: Dict) -> Optional[float]:
|
||||
@ -1630,7 +1630,7 @@ class Exchange:
|
||||
Calculate fee rate if it's not given by the exchange.
|
||||
:param order: Order or trade (one trade) dict
|
||||
"""
|
||||
if order['fee'].get('rate') is not None:
|
||||
if order['fee'].get('rate'):
|
||||
return order['fee'].get('rate')
|
||||
fee_curr = order['fee']['currency']
|
||||
# Calculate fee based on order details
|
||||
@ -1870,7 +1870,7 @@ class Exchange:
|
||||
"""
|
||||
try:
|
||||
# Fetch OHLCV asynchronously
|
||||
s = '(' + arrow.get(since_ms // 1000).isoformat() + ') ' if since_ms is not None else ''
|
||||
s = '(' + arrow.get(since_ms // 1000).isoformat() + ') ' if since_ms else ''
|
||||
logger.debug(
|
||||
"Fetching pair %s, interval %s, since %s %s...",
|
||||
pair, timeframe, since_ms, s
|
||||
@ -1941,7 +1941,7 @@ class Exchange:
|
||||
logger.debug(
|
||||
"Fetching trades for pair %s, since %s %s...",
|
||||
pair, since,
|
||||
'(' + arrow.get(since // 1000).isoformat() + ') ' if since is not None else ''
|
||||
'(' + arrow.get(since // 1000).isoformat() + ') ' if since else ''
|
||||
)
|
||||
trades = await self._api_async.fetch_trades(pair, since=since, limit=1000)
|
||||
trades = self._trades_contracts_to_amount(trades)
|
||||
@ -2263,7 +2263,7 @@ class Exchange:
|
||||
|
||||
elif self.trading_mode == TradingMode.MARGIN: # Search markets.limits for max lev
|
||||
market = self.markets[pair]
|
||||
if market['limits']['leverage']['max'] is not None:
|
||||
if market['limits']['leverage']['max']:
|
||||
return market['limits']['leverage']['max']
|
||||
else:
|
||||
return 1.0 # Default if max leverage cannot be found
|
||||
@ -2630,7 +2630,7 @@ def ccxt_exchanges(ccxt_module: CcxtModuleType = None) -> List[str]:
|
||||
"""
|
||||
Return the list of all exchanges known to ccxt
|
||||
"""
|
||||
return ccxt_module.exchanges if ccxt_module is not None else ccxt.exchanges
|
||||
return ccxt_module.exchanges if ccxt_module else ccxt.exchanges
|
||||
|
||||
|
||||
def available_exchanges(ccxt_module: CcxtModuleType = None) -> List[str]:
|
||||
|
@ -63,7 +63,7 @@ class Gateio(Exchange):
|
||||
for idx, trade in enumerate(trades):
|
||||
if trade.get('fee', {}).get('cost') is None:
|
||||
takerOrMaker = trade.get('takerOrMaker', 'taker')
|
||||
if pair_fees.get(takerOrMaker) is not None:
|
||||
if pair_fees.get(takerOrMaker):
|
||||
trades[idx]['fee'] = {
|
||||
'currency': self.get_pair_quote_currency(pair),
|
||||
'cost': trade['cost'] * pair_fees[takerOrMaker],
|
||||
|
@ -33,7 +33,7 @@ class Kucoin(Exchange):
|
||||
Verify stop_loss against stoploss-order value (limit or price)
|
||||
Returns True if adjustment is necessary.
|
||||
"""
|
||||
return order['info'].get('stop') is not None and stop_loss > float(order['stopPrice'])
|
||||
return order['info'].get('stop') and stop_loss > float(order['stopPrice'])
|
||||
|
||||
def _get_stop_params(self, ordertype: str, stop_price: float) -> Dict:
|
||||
|
||||
|
@ -112,7 +112,7 @@ class Okx(Exchange):
|
||||
|
||||
@retrier
|
||||
def _lev_prep(self, pair: str, leverage: float, side: BuySell):
|
||||
if self.trading_mode != TradingMode.SPOT and self.margin_mode is not None:
|
||||
if self.trading_mode != TradingMode.SPOT and self.margin_mode:
|
||||
try:
|
||||
# TODO-lev: Test me properly (check mgnMode passed)
|
||||
self._api.set_leverage(
|
||||
|
@ -534,12 +534,12 @@ class FreqtradeBot(LoggingMixin):
|
||||
current_profit=current_profit, min_stake=min_stake_amount,
|
||||
max_stake=min(max_stake_amount, stake_available))
|
||||
|
||||
if stake_amount is not None and stake_amount > 0.0:
|
||||
if stake_amount and stake_amount > 0.0:
|
||||
# We should increase our position
|
||||
self.execute_entry(trade.pair, stake_amount, price=current_rate,
|
||||
trade=trade, is_short=trade.is_short)
|
||||
|
||||
if stake_amount is not None and stake_amount < 0.0:
|
||||
if stake_amount and stake_amount < 0.0:
|
||||
# We should decrease our position
|
||||
# TODO: Selling part of the trade not implemented yet.
|
||||
logger.error(f"Unable to decrease trade position / sell partially"
|
||||
@ -600,7 +600,7 @@ class FreqtradeBot(LoggingMixin):
|
||||
side: BuySell = 'sell' if is_short else 'buy'
|
||||
name = 'Short' if is_short else 'Long'
|
||||
trade_side: LongShort = 'short' if is_short else 'long'
|
||||
pos_adjust = trade is not None
|
||||
pos_adjust = trade
|
||||
|
||||
enter_limit_requested, stake_amount, leverage = self.get_valid_enter_price_and_stake(
|
||||
pair, price, stake_amount, trade_side, enter_tag, trade, order_adjust)
|
||||
@ -1116,7 +1116,7 @@ class FreqtradeBot(LoggingMixin):
|
||||
|
||||
if should_exit.exit_flag:
|
||||
logger.info(f'Exit for {trade.pair} detected. Reason: {should_exit.exit_type}'
|
||||
f'Tag: {exit_tag if exit_tag is not None else "None"}')
|
||||
f'Tag: {exit_tag if exit_tag else "None"}')
|
||||
self.execute_trade_exit(trade, exit_rate, should_exit, exit_tag=exit_tag)
|
||||
return True
|
||||
return False
|
||||
@ -1769,7 +1769,7 @@ class FreqtradeBot(LoggingMixin):
|
||||
if self.exchange.order_has_fee(exectrade):
|
||||
fee_cost_, fee_currency, fee_rate_ = self.exchange.extract_cost_curr_rate(exectrade)
|
||||
fee_cost += fee_cost_
|
||||
if fee_rate_ is not None:
|
||||
if fee_rate_:
|
||||
fee_rate_array.append(fee_rate_)
|
||||
# only applies if fee is in quote currency!
|
||||
if trade_base_currency == fee_currency:
|
||||
@ -1778,7 +1778,7 @@ class FreqtradeBot(LoggingMixin):
|
||||
if fee_currency:
|
||||
# fee_rate should use mean
|
||||
fee_rate = sum(fee_rate_array) / float(len(fee_rate_array)) if fee_rate_array else None
|
||||
if fee_rate is not None and fee_rate < 0.02:
|
||||
if fee_rate and fee_rate < 0.02:
|
||||
# Only update if fee-rate is < 2%
|
||||
trade.update_fee(fee_cost, fee_currency, fee_rate, order.get('side', ''))
|
||||
|
||||
|
@ -157,7 +157,7 @@ def deep_merge_dicts(source, destination, allow_null_overrides: bool = True):
|
||||
# get node or create one
|
||||
node = destination.setdefault(key, {})
|
||||
deep_merge_dicts(value, node, allow_null_overrides)
|
||||
elif value is not None or allow_null_overrides:
|
||||
elif value or allow_null_overrides:
|
||||
destination[key] = value
|
||||
|
||||
return destination
|
||||
@ -176,10 +176,10 @@ def safe_value_fallback(obj: dict, key1: str, key2: str, default_value=None):
|
||||
Then search key2 in obj - return that if it's not none - then use default_value.
|
||||
Else falls back to None.
|
||||
"""
|
||||
if key1 in obj and obj[key1] is not None:
|
||||
if key1 in obj and obj[key1]:
|
||||
return obj[key1]
|
||||
else:
|
||||
if key2 in obj and obj[key2] is not None:
|
||||
if key2 in obj and obj[key2]:
|
||||
return obj[key2]
|
||||
return default_value
|
||||
|
||||
@ -191,10 +191,10 @@ def safe_value_fallback2(dict1: dict, dict2: dict, key1: str, key2: str, default
|
||||
Else falls back to None.
|
||||
|
||||
"""
|
||||
if key1 in dict1 and dict1[key1] is not None:
|
||||
if key1 in dict1 and dict1[key1]:
|
||||
return dict1[key1]
|
||||
else:
|
||||
if key2 in dict2 and dict2[key2] is not None:
|
||||
if key2 in dict2 and dict2[key2]:
|
||||
return dict2[key2]
|
||||
return default_value
|
||||
|
||||
|
@ -123,7 +123,7 @@ class Backtesting:
|
||||
if len(self.pairlists.whitelist) == 0:
|
||||
raise OperationalException("No pair in whitelist.")
|
||||
|
||||
if config.get('fee', None) is not None:
|
||||
if config.get('fee', None):
|
||||
self.fee = config['fee']
|
||||
else:
|
||||
self.fee = self.exchange.get_fee(symbol=self.pairlists.whitelist[0])
|
||||
@ -403,7 +403,7 @@ class Backtesting:
|
||||
if (
|
||||
not self.strategy.use_custom_stoploss and self.strategy.trailing_stop
|
||||
and self.strategy.trailing_only_offset_is_reached
|
||||
and self.strategy.trailing_stop_positive_offset is not None
|
||||
and self.strategy.trailing_stop_positive_offset
|
||||
and self.strategy.trailing_stop_positive
|
||||
):
|
||||
# Worst case: price reaches stop_positive_offset and dives down.
|
||||
@ -434,7 +434,7 @@ class Backtesting:
|
||||
leverage = trade.leverage or 1.0
|
||||
side_1 = -1 if is_short else 1
|
||||
roi_entry, roi = self.strategy.min_roi_reached_entry(trade_dur)
|
||||
if roi is not None and roi_entry is not None:
|
||||
if roi and roi_entry:
|
||||
if roi == -1 and roi_entry % self.timeframe_min == 0:
|
||||
# When force_exiting with ROI=-1, the roi time will always be equal to trade_dur.
|
||||
# If that entry is a multiple of the timeframe (so on candle open)
|
||||
@ -501,11 +501,11 @@ class Backtesting:
|
||||
max_stake=min(max_stake, stake_available))
|
||||
|
||||
# Check if we should increase our position
|
||||
if stake_amount is not None and stake_amount > 0.0:
|
||||
if stake_amount and stake_amount > 0.0:
|
||||
|
||||
pos_trade = self._enter_trade(
|
||||
trade.pair, row, 'short' if trade.is_short else 'long', stake_amount, trade)
|
||||
if pos_trade is not None:
|
||||
if pos_trade:
|
||||
self.wallets.update()
|
||||
return pos_trade
|
||||
|
||||
@ -553,7 +553,7 @@ class Backtesting:
|
||||
# row has the length for an exit tag column
|
||||
if(
|
||||
len(row) > EXIT_TAG_IDX
|
||||
and row[EXIT_TAG_IDX] is not None
|
||||
and row[EXIT_TAG_IDX]
|
||||
and len(row[EXIT_TAG_IDX]) > 0
|
||||
and exit_.exit_type in (ExitType.EXIT_SIGNAL,)
|
||||
):
|
||||
@ -671,7 +671,7 @@ class Backtesting:
|
||||
else:
|
||||
propose_rate = min(propose_rate, row[HIGH_IDX])
|
||||
|
||||
pos_adjust = trade is not None
|
||||
pos_adjust = trade
|
||||
leverage = trade.leverage if trade else 1.0
|
||||
if not pos_adjust:
|
||||
try:
|
||||
@ -724,7 +724,7 @@ class Backtesting:
|
||||
entry_tag = row[ENTER_TAG_IDX] if len(row) >= ENTER_TAG_IDX + 1 else None
|
||||
# let's call the custom entry price, using the open price as default price
|
||||
order_type = self.strategy.order_types['entry']
|
||||
pos_adjust = trade is not None and requested_rate is None
|
||||
pos_adjust = trade and requested_rate is None
|
||||
|
||||
propose_rate, stake_amount, leverage, min_stake_amount = self.get_valid_price_and_stake(
|
||||
pair, row, row[OPEN_IDX], stake_amount, direction, current_time, entry_tag, trade,
|
||||
@ -1036,7 +1036,7 @@ class Backtesting:
|
||||
(position_stacking or len(open_trades[pair]) == 0)
|
||||
and self.trade_slot_available(max_open_trades, open_trade_count_start)
|
||||
and current_time != end_date
|
||||
and trade_dir is not None
|
||||
and trade_dir
|
||||
and not PairLocks.is_pair_locked(pair, row[DATE_IDX], trade_dir)
|
||||
):
|
||||
trade = self._enter_trade(pair, row, trade_dir)
|
||||
@ -1199,7 +1199,7 @@ class Backtesting:
|
||||
# Load previous result that will be updated incrementally.
|
||||
# This can be circumvented in certain instances in combination with downloading more data
|
||||
min_backtest_date = self._get_min_cached_backtest_date()
|
||||
if min_backtest_date is not None:
|
||||
if min_backtest_date:
|
||||
self.results = find_existing_backtest_stats(
|
||||
self.config['user_data_dir'] / 'backtest_results', self.run_ids, min_backtest_date)
|
||||
|
||||
|
@ -65,13 +65,13 @@ def _hyperopt_filter_epochs_duration(epochs: List, filteroptions: dict) -> List:
|
||||
"Holding-average not available. Please omit the filter on average time, "
|
||||
"or rerun hyperopt with this version")
|
||||
|
||||
if filteroptions['filter_min_avg_time'] is not None:
|
||||
if filteroptions['filter_min_avg_time']:
|
||||
epochs = _hyperopt_filter_epochs_trade(epochs, 0)
|
||||
epochs = [
|
||||
x for x in epochs
|
||||
if get_duration_value(x) > filteroptions['filter_min_avg_time']
|
||||
]
|
||||
if filteroptions['filter_max_avg_time'] is not None:
|
||||
if filteroptions['filter_max_avg_time']:
|
||||
epochs = _hyperopt_filter_epochs_trade(epochs, 0)
|
||||
epochs = [
|
||||
x for x in epochs
|
||||
@ -83,28 +83,28 @@ def _hyperopt_filter_epochs_duration(epochs: List, filteroptions: dict) -> List:
|
||||
|
||||
def _hyperopt_filter_epochs_profit(epochs: List, filteroptions: dict) -> List:
|
||||
|
||||
if filteroptions['filter_min_avg_profit'] is not None:
|
||||
if filteroptions['filter_min_avg_profit']:
|
||||
epochs = _hyperopt_filter_epochs_trade(epochs, 0)
|
||||
epochs = [
|
||||
x for x in epochs
|
||||
if x['results_metrics'].get('profit_mean', 0) * 100
|
||||
> filteroptions['filter_min_avg_profit']
|
||||
]
|
||||
if filteroptions['filter_max_avg_profit'] is not None:
|
||||
if filteroptions['filter_max_avg_profit']:
|
||||
epochs = _hyperopt_filter_epochs_trade(epochs, 0)
|
||||
epochs = [
|
||||
x for x in epochs
|
||||
if x['results_metrics'].get('profit_mean', 0) * 100
|
||||
< filteroptions['filter_max_avg_profit']
|
||||
]
|
||||
if filteroptions['filter_min_total_profit'] is not None:
|
||||
if filteroptions['filter_min_total_profit']:
|
||||
epochs = _hyperopt_filter_epochs_trade(epochs, 0)
|
||||
epochs = [
|
||||
x for x in epochs
|
||||
if x['results_metrics'].get('profit_total_abs', 0)
|
||||
> filteroptions['filter_min_total_profit']
|
||||
]
|
||||
if filteroptions['filter_max_total_profit'] is not None:
|
||||
if filteroptions['filter_max_total_profit']:
|
||||
epochs = _hyperopt_filter_epochs_trade(epochs, 0)
|
||||
epochs = [
|
||||
x for x in epochs
|
||||
@ -116,11 +116,11 @@ def _hyperopt_filter_epochs_profit(epochs: List, filteroptions: dict) -> List:
|
||||
|
||||
def _hyperopt_filter_epochs_objective(epochs: List, filteroptions: dict) -> List:
|
||||
|
||||
if filteroptions['filter_min_objective'] is not None:
|
||||
if filteroptions['filter_min_objective']:
|
||||
epochs = _hyperopt_filter_epochs_trade(epochs, 0)
|
||||
|
||||
epochs = [x for x in epochs if x['loss'] < filteroptions['filter_min_objective']]
|
||||
if filteroptions['filter_max_objective'] is not None:
|
||||
if filteroptions['filter_max_objective']:
|
||||
epochs = _hyperopt_filter_epochs_trade(epochs, 0)
|
||||
|
||||
epochs = [x for x in epochs if x['loss'] > filteroptions['filter_max_objective']]
|
||||
|
@ -644,7 +644,7 @@ def text_table_tags(tag_type: str, tag_results: List[Dict[str, Any]], stake_curr
|
||||
floatfmt = _get_line_floatfmt(stake_currency)
|
||||
output = [
|
||||
[
|
||||
t['key'] if t['key'] is not None and len(
|
||||
t['key'] if t['key'] and len(
|
||||
t['key']) > 0 else "OTHER",
|
||||
t['trades'],
|
||||
t['profit_mean_pct'],
|
||||
@ -849,8 +849,8 @@ def show_backtest_result(strategy: str, results: Dict[str, Any], stake_currency:
|
||||
print(' BACKTESTING REPORT '.center(len(table.splitlines()[0]), '='))
|
||||
print(table)
|
||||
|
||||
if (results.get('results_per_enter_tag') is not None
|
||||
or results.get('results_per_buy_tag') is not None):
|
||||
if (results.get('results_per_enter_tag')
|
||||
or results.get('results_per_buy_tag')):
|
||||
# results_per_buy_tag is deprecated and should be removed 2 versions after short golive.
|
||||
table = text_table_tags(
|
||||
"enter_tag",
|
||||
|
@ -108,7 +108,7 @@ class Order(_DECL_BASE):
|
||||
self.remaining = order.get('remaining', self.remaining)
|
||||
self.cost = order.get('cost', self.cost)
|
||||
|
||||
if 'timestamp' in order and order['timestamp'] is not None:
|
||||
if 'timestamp' in order and order['timestamp']:
|
||||
self.order_date = datetime.fromtimestamp(order['timestamp'] / 1000, tz=timezone.utc)
|
||||
|
||||
self.ft_is_open = True
|
||||
@ -476,7 +476,7 @@ class LocalTrade():
|
||||
Method you should use to set self.stop_loss.
|
||||
Assures stop_loss is not passed the liquidation price
|
||||
"""
|
||||
if self.liquidation_price is not None:
|
||||
if self.liquidation_price:
|
||||
if self.is_short:
|
||||
sl = min(stop_loss, self.liquidation_price)
|
||||
else:
|
||||
@ -611,24 +611,22 @@ class LocalTrade():
|
||||
if self.entry_side == side and self.fee_open_currency is None:
|
||||
self.fee_open_cost = fee_cost
|
||||
self.fee_open_currency = fee_currency
|
||||
if fee_rate is not None:
|
||||
if fee_rate:
|
||||
self.fee_open = fee_rate
|
||||
# Assume close-fee will fall into the same fee category and take an educated guess
|
||||
self.fee_close = fee_rate
|
||||
elif self.exit_side == side and self.fee_close_currency is None:
|
||||
self.fee_close_cost = fee_cost
|
||||
self.fee_close_currency = fee_currency
|
||||
if fee_rate is not None:
|
||||
if fee_rate:
|
||||
self.fee_close = fee_rate
|
||||
|
||||
def fee_updated(self, side: str) -> bool:
|
||||
"""
|
||||
Verify if this side (buy / sell) has already been updated
|
||||
"""
|
||||
if self.entry_side == side:
|
||||
return self.fee_open_currency is not None
|
||||
elif self.exit_side == side:
|
||||
return self.fee_close_currency is not None
|
||||
if side in (self.entry_side, self.exit_side):
|
||||
return bool(self.fee_open_currency)
|
||||
else:
|
||||
return False
|
||||
|
||||
@ -815,9 +813,9 @@ class LocalTrade():
|
||||
|
||||
tmp_amount = o.safe_amount_after_fee
|
||||
tmp_price = o.average or o.price
|
||||
if o.filled is not None:
|
||||
if o.filled:
|
||||
tmp_amount = o.filled
|
||||
if tmp_amount > 0.0 and tmp_price is not None:
|
||||
if tmp_amount > 0.0 and tmp_price:
|
||||
total_amount += tmp_amount
|
||||
total_stake += tmp_price * tmp_amount
|
||||
|
||||
@ -828,7 +826,7 @@ class LocalTrade():
|
||||
self.amount = total_amount
|
||||
self.fee_open_cost = self.fee_open * self.stake_amount
|
||||
self.recalc_open_trade_value()
|
||||
if self.stop_loss_pct is not None and self.open_rate is not None:
|
||||
if self.stop_loss_pct and self.open_rate:
|
||||
self.adjust_stop_loss(self.open_rate, self.stop_loss_pct)
|
||||
|
||||
def select_order_by_order_id(self, order_id: str) -> Optional[Order]:
|
||||
@ -852,7 +850,7 @@ class LocalTrade():
|
||||
orders = self.orders
|
||||
if order_side:
|
||||
orders = [o for o in self.orders if o.ft_order_side == order_side]
|
||||
if is_open is not None:
|
||||
if is_open:
|
||||
orders = [o for o in orders if o.ft_is_open == is_open]
|
||||
if len(orders) > 0:
|
||||
return orders[-1]
|
||||
@ -925,7 +923,7 @@ class LocalTrade():
|
||||
"""
|
||||
|
||||
# Offline mode - without database
|
||||
if is_open is not None:
|
||||
if is_open:
|
||||
if is_open:
|
||||
sel_trades = LocalTrade.trades_open
|
||||
else:
|
||||
@ -1097,7 +1095,7 @@ class Trade(_DECL_BASE, LocalTrade):
|
||||
trade_filter.append(Trade.open_date > open_date)
|
||||
if close_date:
|
||||
trade_filter.append(Trade.close_date > close_date)
|
||||
if is_open is not None:
|
||||
if is_open:
|
||||
trade_filter.append(Trade.is_open.is_(is_open))
|
||||
return Trade.get_trades(trade_filter).all()
|
||||
else:
|
||||
@ -1120,7 +1118,7 @@ class Trade(_DECL_BASE, LocalTrade):
|
||||
"""
|
||||
if not Trade.use_db:
|
||||
raise NotImplementedError('`Trade.get_trades()` not supported in backtesting mode.')
|
||||
if trade_filter is not None:
|
||||
if trade_filter:
|
||||
if not isinstance(trade_filter, list):
|
||||
trade_filter = [trade_filter]
|
||||
return Trade.query.filter(*trade_filter)
|
||||
@ -1224,7 +1222,7 @@ class Trade(_DECL_BASE, LocalTrade):
|
||||
"""
|
||||
|
||||
filters = [Trade.is_open.is_(False)]
|
||||
if(pair is not None):
|
||||
if(pair):
|
||||
filters.append(Trade.pair == pair)
|
||||
|
||||
enter_tag_perf = Trade.query.with_entities(
|
||||
@ -1239,7 +1237,7 @@ class Trade(_DECL_BASE, LocalTrade):
|
||||
|
||||
return [
|
||||
{
|
||||
'enter_tag': enter_tag if enter_tag is not None else "Other",
|
||||
'enter_tag': enter_tag if enter_tag else "Other",
|
||||
'profit_ratio': profit,
|
||||
'profit_pct': round(profit * 100, 2),
|
||||
'profit_abs': profit_abs,
|
||||
@ -1257,7 +1255,7 @@ class Trade(_DECL_BASE, LocalTrade):
|
||||
"""
|
||||
|
||||
filters = [Trade.is_open.is_(False)]
|
||||
if(pair is not None):
|
||||
if(pair):
|
||||
filters.append(Trade.pair == pair)
|
||||
|
||||
sell_tag_perf = Trade.query.with_entities(
|
||||
@ -1272,7 +1270,7 @@ class Trade(_DECL_BASE, LocalTrade):
|
||||
|
||||
return [
|
||||
{
|
||||
'exit_reason': exit_reason if exit_reason is not None else "Other",
|
||||
'exit_reason': exit_reason if exit_reason else "Other",
|
||||
'profit_ratio': profit,
|
||||
'profit_pct': round(profit * 100, 2),
|
||||
'profit_abs': profit_abs,
|
||||
@ -1290,7 +1288,7 @@ class Trade(_DECL_BASE, LocalTrade):
|
||||
"""
|
||||
|
||||
filters = [Trade.is_open.is_(False)]
|
||||
if(pair is not None):
|
||||
if(pair):
|
||||
filters.append(Trade.pair == pair)
|
||||
|
||||
mix_tag_perf = Trade.query.with_entities(
|
||||
@ -1307,10 +1305,10 @@ class Trade(_DECL_BASE, LocalTrade):
|
||||
|
||||
return_list: List[Dict] = []
|
||||
for id, enter_tag, exit_reason, profit, profit_abs, count in mix_tag_perf:
|
||||
enter_tag = enter_tag if enter_tag is not None else "Other"
|
||||
exit_reason = exit_reason if exit_reason is not None else "Other"
|
||||
enter_tag = enter_tag if enter_tag else "Other"
|
||||
exit_reason = exit_reason if exit_reason else "Other"
|
||||
|
||||
if(exit_reason is not None and enter_tag is not None):
|
||||
if(exit_reason and enter_tag):
|
||||
mix_tag = enter_tag + " " + exit_reason
|
||||
i = 0
|
||||
if not any(item["mix_tag"] == mix_tag for item in return_list):
|
||||
|
@ -254,11 +254,11 @@ def plot_trades(fig, trades: pd.DataFrame) -> make_subplots:
|
||||
Add trades to "fig"
|
||||
"""
|
||||
# Trades can be empty
|
||||
if trades is not None and len(trades) > 0:
|
||||
if trades and len(trades) > 0:
|
||||
# Create description for sell summarizing the trade
|
||||
trades['desc'] = trades.apply(
|
||||
lambda row: f"{row['profit_ratio']:.2%}, " +
|
||||
(f"{row['enter_tag']}, " if row['enter_tag'] is not None else "") +
|
||||
(f"{row['enter_tag']}, " if row['enter_tag'] else "") +
|
||||
f"{row['exit_reason']}, " +
|
||||
f"{row['trade_duration']} min",
|
||||
axis=1)
|
||||
|
@ -108,7 +108,7 @@ class AgeFilter(IPairList):
|
||||
if pair in self._symbolsChecked:
|
||||
return True
|
||||
|
||||
if daily_candles is not None:
|
||||
if daily_candles:
|
||||
if (
|
||||
len(daily_candles) >= self._min_days_listed
|
||||
and (not self._max_days_listed or len(daily_candles) <= self._max_days_listed)
|
||||
|
@ -70,7 +70,7 @@ class PerformanceFilter(IPairList):
|
||||
sorted_df = list_df.merge(performance, on='pair', how='left')\
|
||||
.fillna(0).sort_values(by=['count', 'prior_idx'], ascending=True)\
|
||||
.sort_values(by=['profit_ratio'], ascending=False)
|
||||
if self._min_profit is not None:
|
||||
if self._min_profit:
|
||||
removed = sorted_df[sorted_df['profit_ratio'] < self._min_profit]
|
||||
for _, row in removed.iterrows():
|
||||
self.log_once(
|
||||
|
@ -90,7 +90,7 @@ class PriceFilter(IPairList):
|
||||
price = ticker['last']
|
||||
market = self._exchange.markets[pair]
|
||||
limits = market['limits']
|
||||
if (limits['amount']['min'] is not None):
|
||||
if (limits['amount']['min']):
|
||||
min_amount = limits['amount']['min']
|
||||
min_precision = market['precision']['amount']
|
||||
|
||||
|
@ -44,7 +44,7 @@ class ShuffleFilter(IPairList):
|
||||
Short whitelist method description - used for startup-messages
|
||||
"""
|
||||
return (f"{self.name} - Shuffling pairs" +
|
||||
(f", seed = {self._seed}." if self._seed is not None else "."))
|
||||
(f", seed = {self._seed}." if self._seed else "."))
|
||||
|
||||
def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]:
|
||||
"""
|
||||
|
@ -99,11 +99,11 @@ class VolatilityFilter(IPairList):
|
||||
"""
|
||||
# Check symbol in cache
|
||||
cached_res = self._pair_cache.get(pair, None)
|
||||
if cached_res is not None:
|
||||
if cached_res:
|
||||
return cached_res
|
||||
|
||||
result = False
|
||||
if daily_candles is not None and not daily_candles.empty:
|
||||
if daily_candles and not daily_candles.empty:
|
||||
returns = (np.log(daily_candles.close / daily_candles.close.shift(-1)))
|
||||
returns.fillna(0, inplace=True)
|
||||
|
||||
|
@ -134,7 +134,7 @@ class VolumePairList(IPairList):
|
||||
filtered_tickers = [
|
||||
v for k, v in tickers.items()
|
||||
if (self._exchange.get_pair_quote_currency(k) == self._stake_currency
|
||||
and (self._use_range or v[self._sort_key] is not None)
|
||||
and (self._use_range or v[self._sort_key])
|
||||
and v['symbol'] in _pairlist)]
|
||||
pairlist = [s['symbol'] for s in filtered_tickers]
|
||||
else:
|
||||
@ -192,7 +192,7 @@ class VolumePairList(IPairList):
|
||||
p['symbol'], self._lookback_timeframe, self._def_candletype
|
||||
) in candles else None
|
||||
# in case of candle data calculate typical price and quoteVolume for candle
|
||||
if pair_candles is not None and not pair_candles.empty:
|
||||
if pair_candles and not pair_candles.empty:
|
||||
if self._exchange._ft_has["ohlcv_volume_currency"] == "base":
|
||||
pair_candles['typical_price'] = (pair_candles['high'] + pair_candles['low']
|
||||
+ pair_candles['close']) / 3
|
||||
|
@ -97,11 +97,11 @@ class RangeStabilityFilter(IPairList):
|
||||
"""
|
||||
# Check symbol in cache
|
||||
cached_res = self._pair_cache.get(pair, None)
|
||||
if cached_res is not None:
|
||||
if cached_res:
|
||||
return cached_res
|
||||
|
||||
result = False
|
||||
if daily_candles is not None and not daily_candles.empty:
|
||||
if daily_candles and not daily_candles.empty:
|
||||
highest_high = daily_candles['high'].max()
|
||||
lowest_low = daily_candles['low'].min()
|
||||
pct_change = ((highest_high - lowest_low) / lowest_low) if lowest_low > 0 else 0
|
||||
|
@ -210,8 +210,8 @@ class IResolver:
|
||||
for obj in cls._get_valid_object(module_path, object_name=None,
|
||||
enum_failed=enum_failed):
|
||||
objects.append(
|
||||
{'name': obj[0].__name__ if obj is not None else '',
|
||||
'class': obj[0] if obj is not None else None,
|
||||
{'name': obj[0].__name__ if obj else '',
|
||||
'class': obj[0] if obj else None,
|
||||
'location': entry,
|
||||
})
|
||||
return objects
|
||||
|
@ -128,10 +128,10 @@ class StrategyResolver(IResolver):
|
||||
elif hasattr(strategy, attribute):
|
||||
val = getattr(strategy, attribute)
|
||||
# None's cannot exist in the config, so do not copy them
|
||||
if val is not None:
|
||||
if val:
|
||||
config[attribute] = val
|
||||
# Explicitly check for None here as other "falsy" values are possible
|
||||
elif default is not None:
|
||||
elif default:
|
||||
setattr(strategy, attribute, default)
|
||||
config[attribute] = default
|
||||
|
||||
|
@ -34,7 +34,7 @@ async def api_start_backtest(bt_settings: BacktestRequest, background_tasks: Bac
|
||||
settings = dict(bt_settings)
|
||||
# Pydantic models will contain all keys, but non-provided ones are None
|
||||
for setting in settings.keys():
|
||||
if settings[setting] is not None:
|
||||
if settings[setting]:
|
||||
btconfig[setting] = settings[setting]
|
||||
try:
|
||||
btconfig['stake_amount'] = float(btconfig['stake_amount'])
|
||||
|
@ -200,7 +200,7 @@ class RPC:
|
||||
|
||||
trade_dict = trade.to_json()
|
||||
trade_dict.update(dict(
|
||||
close_profit=trade.close_profit if trade.close_profit is not None else None,
|
||||
close_profit=trade.close_profit if trade.close_profit else None,
|
||||
current_rate=current_rate,
|
||||
current_profit=current_profit, # Deprecated
|
||||
current_profit_pct=round(current_profit * 100, 2), # Deprecated
|
||||
@ -257,9 +257,9 @@ class RPC:
|
||||
else fiat_profit_sum + fiat_profit
|
||||
detail_trade = [
|
||||
f'{trade.id} {direction_str}',
|
||||
trade.pair + ('*' if (trade.open_order_id is not None
|
||||
trade.pair + ('*' if (trade.open_order_id
|
||||
and trade.close_rate_requested is None) else '')
|
||||
+ ('**' if (trade.close_rate_requested is not None) else ''),
|
||||
+ ('**' if (trade.close_rate_requested) else ''),
|
||||
shorten_date(arrow.get(trade.open_date).humanize(only_distance=True)),
|
||||
profit_str
|
||||
]
|
||||
@ -300,7 +300,7 @@ class RPC:
|
||||
Trade.close_date < (profitday + timedelta(days=1))
|
||||
]).order_by(Trade.close_date).all()
|
||||
curdayprofit = sum(
|
||||
trade.close_profit_abs for trade in trades if trade.close_profit_abs is not None)
|
||||
trade.close_profit_abs for trade in trades if trade.close_profit_abs)
|
||||
profit_days[profitday] = {
|
||||
'amount': curdayprofit,
|
||||
'trades': len(trades)
|
||||
@ -343,7 +343,7 @@ class RPC:
|
||||
Trade.close_date < (profitweek + timedelta(weeks=1))
|
||||
]).order_by(Trade.close_date).all()
|
||||
curweekprofit = sum(
|
||||
trade.close_profit_abs for trade in trades if trade.close_profit_abs is not None)
|
||||
trade.close_profit_abs for trade in trades if trade.close_profit_abs)
|
||||
profit_weeks[profitweek] = {
|
||||
'amount': curweekprofit,
|
||||
'trades': len(trades)
|
||||
@ -385,7 +385,7 @@ class RPC:
|
||||
Trade.close_date < (profitmonth + relativedelta(months=1))
|
||||
]).order_by(Trade.close_date).all()
|
||||
curmonthprofit = sum(
|
||||
trade.close_profit_abs for trade in trades if trade.close_profit_abs is not None)
|
||||
trade.close_profit_abs for trade in trades if trade.close_profit_abs)
|
||||
profit_months[profitmonth] = {
|
||||
'amount': curmonthprofit,
|
||||
'trades': len(trades)
|
||||
@ -450,7 +450,7 @@ class RPC:
|
||||
# Duration
|
||||
dur: Dict[str, List[int]] = {'wins': [], 'draws': [], 'losses': []}
|
||||
for trade in trades:
|
||||
if trade.close_date is not None and trade.open_date is not None:
|
||||
if trade.close_date and trade.open_date:
|
||||
trade_dur = (trade.close_date - trade.open_date).total_seconds()
|
||||
dur[trade_win_loss(trade)].append(trade_dur)
|
||||
|
||||
@ -612,9 +612,9 @@ class RPC:
|
||||
currencies.append({
|
||||
'currency': coin,
|
||||
# TODO: The below can be simplified if we don't assign None to values.
|
||||
'free': balance.free if balance.free is not None else 0,
|
||||
'balance': balance.total if balance.total is not None else 0,
|
||||
'used': balance.used if balance.used is not None else 0,
|
||||
'free': balance.free if balance.free else 0,
|
||||
'balance': balance.total if balance.total else 0,
|
||||
'used': balance.used if balance.used else 0,
|
||||
'est_stake': est_stake or 0,
|
||||
'stake': stake_currency,
|
||||
'side': 'long',
|
||||
|
@ -493,12 +493,12 @@ class Telegram(RPCHandler):
|
||||
|
||||
if r['is_open']:
|
||||
if (r['stop_loss_abs'] != r['initial_stop_loss_abs']
|
||||
and r['initial_stop_loss_ratio'] is not None):
|
||||
and r['initial_stop_loss_ratio']):
|
||||
# Adding initial stoploss only if it is different from stoploss
|
||||
lines.append("*Initial Stoploss:* `{initial_stop_loss_abs:.8f}` "
|
||||
"`({initial_stop_loss_ratio:.2%})`")
|
||||
|
||||
# Adding stoploss and stoploss percentage only if it is not None
|
||||
# Adding stoploss and stoploss percentage only if it
|
||||
lines.append("*Stoploss:* `{stop_loss_abs:.8f}` " +
|
||||
("`({stop_loss_ratio:.2%})`" if r['stop_loss_ratio'] else ""))
|
||||
lines.append("*Stoploss distance:* `{stoploss_current_dist:.8f}` "
|
||||
@ -792,9 +792,9 @@ class Telegram(RPCHandler):
|
||||
duration_msg = tabulate(
|
||||
[
|
||||
['Wins', str(timedelta(seconds=durations['wins']))
|
||||
if durations['wins'] is not None else 'N/A'],
|
||||
if durations['wins'] else 'N/A'],
|
||||
['Losses', str(timedelta(seconds=durations['losses']))
|
||||
if durations['losses'] is not None else 'N/A']
|
||||
if durations['losses'] else 'N/A']
|
||||
],
|
||||
headers=['', 'Avg. Duration']
|
||||
)
|
||||
@ -1488,7 +1488,7 @@ class Telegram(RPCHandler):
|
||||
"""
|
||||
strategy_version = self._rpc._freqtrade.strategy.version()
|
||||
version_string = f'*Version:* `{__version__}`'
|
||||
if strategy_version is not None:
|
||||
if strategy_version:
|
||||
version_string += f', *Strategy version: * `{strategy_version}`'
|
||||
|
||||
self._send_msg(version_string)
|
||||
@ -1591,7 +1591,7 @@ class Telegram(RPCHandler):
|
||||
reply_markup = InlineKeyboardMarkup([
|
||||
[InlineKeyboardButton("Refresh", callback_data=callback_path)]])
|
||||
else:
|
||||
if keyboard is not None:
|
||||
if keyboard:
|
||||
reply_markup = InlineKeyboardMarkup(keyboard, resize_keyboard=True)
|
||||
else:
|
||||
reply_markup = ReplyKeyboardMarkup(self._keyboard, resize_keyboard=True)
|
||||
|
@ -85,7 +85,7 @@ class NumericParameter(BaseParameter):
|
||||
:param load: Load parameter value from {space}_params.
|
||||
:param kwargs: Extra parameters to skopt.space.*.
|
||||
"""
|
||||
if high is not None and isinstance(low, Sequence):
|
||||
if high and isinstance(low, Sequence):
|
||||
raise OperationalException(f'{self.__class__.__name__} space invalid.')
|
||||
if high is None or isinstance(low, Sequence):
|
||||
if not isinstance(low, Sequence) or len(low) != 2:
|
||||
@ -335,7 +335,7 @@ class HyperStrategyMixin:
|
||||
attr = getattr(cls, attr_name)
|
||||
if issubclass(attr.__class__, BaseParameter):
|
||||
if (attr_name.startswith(category + '_')
|
||||
and attr.category is not None and attr.category != category):
|
||||
and attr.category and attr.category != category):
|
||||
raise OperationalException(
|
||||
f'Inconclusive parameter name {attr_name}, category: {attr.category}.')
|
||||
if (category == attr.category or
|
||||
|
@ -1004,7 +1004,7 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
# Don't update stoploss if trailing_only_offset_is_reached is true.
|
||||
if not (self.trailing_only_offset_is_reached and bound_profit < sl_offset):
|
||||
# Specific handling for trailing_stop_positive
|
||||
if self.trailing_stop_positive is not None and bound_profit > sl_offset:
|
||||
if self.trailing_stop_positive and bound_profit > sl_offset:
|
||||
stop_loss_value = self.trailing_stop_positive
|
||||
logger.debug(f"{trade.pair} - Using positive stoploss: {stop_loss_value} "
|
||||
f"offset: {sl_offset:.4g} profit: {current_profit:.2%}")
|
||||
@ -1079,7 +1079,7 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
side = 'entry' if order.ft_order_side == trade.entry_side else 'exit'
|
||||
|
||||
timeout = self.config.get('unfilledtimeout', {}).get(side)
|
||||
if timeout is not None:
|
||||
if timeout:
|
||||
timeout_unit = self.config.get('unfilledtimeout', {}).get('unit', 'minutes')
|
||||
timeout_kwargs = {timeout_unit: -timeout}
|
||||
timeout_threshold = current_time + timedelta(**timeout_kwargs)
|
||||
|
@ -298,12 +298,12 @@ class Wallets:
|
||||
|
||||
max_stake_amount = min(max_stake_amount, self.get_available_stake_amount())
|
||||
|
||||
if min_stake_amount is not None and min_stake_amount > max_stake_amount:
|
||||
if min_stake_amount and min_stake_amount > max_stake_amount:
|
||||
if self._log:
|
||||
logger.warning("Minimum stake amount > available balance. "
|
||||
f"{min_stake_amount} > {max_stake_amount}")
|
||||
return 0
|
||||
if min_stake_amount is not None and stake_amount < min_stake_amount:
|
||||
if min_stake_amount and stake_amount < min_stake_amount:
|
||||
if self._log:
|
||||
logger.info(
|
||||
f"Stake amount for pair {pair} is too small "
|
||||
|
@ -118,7 +118,7 @@ class Worker:
|
||||
if (now - self._heartbeat_msg) > self._heartbeat_interval:
|
||||
version = __version__
|
||||
strategy_version = self.freqtrade.strategy.version()
|
||||
if (strategy_version is not None):
|
||||
if (strategy_version):
|
||||
version += ', strategy_version: ' + strategy_version
|
||||
logger.info(f"Bot heartbeat. PID={getpid()}, "
|
||||
f"version='{version}', state='{state.name}'")
|
||||
|
@ -258,8 +258,8 @@ def create_mock_trades(fee, is_short: Optional[bool] = False, use_db: bool = Tru
|
||||
Trade.query.session.add(trade)
|
||||
else:
|
||||
LocalTrade.add_bt_trade(trade)
|
||||
is_short1 = is_short if is_short is not None else True
|
||||
is_short2 = is_short if is_short is not None else False
|
||||
is_short1 = is_short if is_short else True
|
||||
is_short2 = is_short if is_short else False
|
||||
# Simulate dry_run entries
|
||||
trade = mock_trade_1(fee, is_short1)
|
||||
add_trade(trade)
|
||||
|
@ -621,7 +621,7 @@ def test_download_trades_history(trades_history, mocker, default_conf, testdatad
|
||||
assert ght_mock.call_count == 1
|
||||
# Check this in seconds - since we had to convert to seconds above too.
|
||||
assert int(ght_mock.call_args_list[0][1]['since'] // 1000) == since_time2 - 5
|
||||
assert ght_mock.call_args_list[0][1]['from_id'] is not None
|
||||
assert ght_mock.call_args_list[0][1]['from_id']
|
||||
|
||||
file1.unlink()
|
||||
|
||||
|
@ -173,12 +173,12 @@ class TestCCXTExchange():
|
||||
tickers = exchange.get_tickers()
|
||||
assert pair in tickers
|
||||
assert 'ask' in tickers[pair]
|
||||
assert tickers[pair]['ask'] is not None
|
||||
assert tickers[pair]['ask']
|
||||
assert 'bid' in tickers[pair]
|
||||
assert tickers[pair]['bid'] is not None
|
||||
assert tickers[pair]['bid']
|
||||
assert 'quoteVolume' in tickers[pair]
|
||||
if EXCHANGES[exchangename].get('hasQuoteVolume'):
|
||||
assert tickers[pair]['quoteVolume'] is not None
|
||||
assert tickers[pair]['quoteVolume']
|
||||
|
||||
def test_ccxt_fetch_ticker(self, exchange):
|
||||
exchange, exchangename = exchange
|
||||
@ -186,12 +186,12 @@ class TestCCXTExchange():
|
||||
|
||||
ticker = exchange.fetch_ticker(pair)
|
||||
assert 'ask' in ticker
|
||||
assert ticker['ask'] is not None
|
||||
assert ticker['ask']
|
||||
assert 'bid' in ticker
|
||||
assert ticker['bid'] is not None
|
||||
assert ticker['bid']
|
||||
assert 'quoteVolume' in ticker
|
||||
if EXCHANGES[exchangename].get('hasQuoteVolume'):
|
||||
assert ticker['quoteVolume'] is not None
|
||||
assert ticker['quoteVolume']
|
||||
|
||||
def test_ccxt_fetch_l2_orderbook(self, exchange):
|
||||
exchange, exchangename = exchange
|
||||
|
@ -2384,7 +2384,7 @@ def test_get_exit_rate(default_conf, mocker, caplog, side, bid, ask,
|
||||
caplog.set_level(logging.DEBUG)
|
||||
|
||||
default_conf['exit_pricing']['price_side'] = side
|
||||
if last_ab is not None:
|
||||
if last_ab:
|
||||
default_conf['exit_pricing']['price_last_balance'] = last_ab
|
||||
mocker.patch('freqtrade.exchange.Exchange.fetch_ticker',
|
||||
return_value={'ask': ask, 'bid': bid, 'last': last})
|
||||
|
@ -40,7 +40,7 @@ def test_stoploss_order_kucoin(default_conf, mocker, limitratio, expected, side,
|
||||
|
||||
api_mock.create_order.reset_mock()
|
||||
order_types = {'stoploss': order_type}
|
||||
if limitratio is not None:
|
||||
if limitratio:
|
||||
order_types.update({'stoploss_on_exchange_limit_ratio': limitratio})
|
||||
order = exchange.stoploss(pair='ETH/BTC', amount=1, stop_price=220,
|
||||
order_types=order_types, side=side, leverage=1.0)
|
||||
|
@ -914,7 +914,7 @@ def test_backtest_results(default_conf, fee, mocker, caplog, data: BTContainer)
|
||||
'exit': data.timeout,
|
||||
})
|
||||
# Only add this to configuration If it's necessary
|
||||
if data.trailing_stop_positive is not None:
|
||||
if data.trailing_stop_positive:
|
||||
default_conf["trailing_stop_positive"] = data.trailing_stop_positive
|
||||
default_conf["trailing_stop_positive_offset"] = data.trailing_stop_positive_offset
|
||||
default_conf["use_exit_signal"] = data.use_exit_signal
|
||||
|
@ -407,7 +407,7 @@ def test_backtesting_start(default_conf, mocker, testdatadir, caplog) -> None:
|
||||
]
|
||||
for line in exists:
|
||||
assert log_has(line, caplog)
|
||||
assert backtesting.strategy.dp._pairlists is not None
|
||||
assert backtesting.strategy.dp._pairlists
|
||||
assert backtesting.strategy.bot_loop_start.call_count == 1
|
||||
assert sbs.call_count == 1
|
||||
assert sbc.call_count == 1
|
||||
@ -540,7 +540,7 @@ def test_backtest__enter_trade(default_conf, fee, mocker) -> None:
|
||||
assert trade is None
|
||||
LocalTrade.trades_open.pop()
|
||||
trade = backtesting._enter_trade(pair, row=row, direction='long')
|
||||
assert trade is not None
|
||||
assert trade
|
||||
|
||||
backtesting.strategy.custom_stake_amount = lambda **kwargs: 123.5
|
||||
backtesting.wallets.update()
|
||||
@ -716,7 +716,7 @@ def test_backtest__get_sell_trade_entry(default_conf, fee, mocker) -> None:
|
||||
|
||||
# No data available.
|
||||
res = backtesting._get_exit_trade_entry(trade, row_sell)
|
||||
assert res is not None
|
||||
assert res
|
||||
assert res.exit_reason == ExitType.ROI.value
|
||||
assert res.close_date_utc == datetime(2020, 1, 1, 5, 0, tzinfo=timezone.utc)
|
||||
|
||||
@ -735,12 +735,12 @@ def test_backtest__get_sell_trade_entry(default_conf, fee, mocker) -> None:
|
||||
backtesting.detail_data[pair] = row_detail
|
||||
|
||||
res = backtesting._get_exit_trade_entry(trade, row_sell)
|
||||
assert res is not None
|
||||
assert res
|
||||
assert res.exit_reason == ExitType.ROI.value
|
||||
# Sell at minute 3 (not available above!)
|
||||
assert res.close_date_utc == datetime(2020, 1, 1, 5, 3, tzinfo=timezone.utc)
|
||||
sell_order = res.select_order('sell', True)
|
||||
assert sell_order is not None
|
||||
assert sell_order
|
||||
|
||||
|
||||
def test_backtest_one(default_conf, fee, mocker, testdatadir) -> None:
|
||||
@ -801,7 +801,7 @@ def test_backtest_one(default_conf, fee, mocker, testdatadir) -> None:
|
||||
for _, t in results.iterrows():
|
||||
ln = data_pair.loc[data_pair["date"] == t["open_date"]]
|
||||
# Check open trade rate alignes to open rate
|
||||
assert ln is not None
|
||||
assert ln
|
||||
assert round(ln.iloc[0]["open"], 6) == round(t["open_rate"], 6)
|
||||
# check close trade rate alignes to close rate or is between high and low
|
||||
ln = data_pair.loc[data_pair["date"] == t["close_date"]]
|
||||
|
@ -76,7 +76,7 @@ def test_backtest_position_adjustment(default_conf, fee, mocker, testdatadir) ->
|
||||
for _, t in results.iterrows():
|
||||
ln = data_pair.loc[data_pair["date"] == t["open_date"]]
|
||||
# Check open trade rate alignes to open rate
|
||||
assert ln is not None
|
||||
assert ln
|
||||
# check close trade rate alignes to close rate or is between high and low
|
||||
ln = data_pair.loc[data_pair["date"] == t["close_date"]]
|
||||
assert (round(ln.iloc[0]["open"], 6) == round(t["close_rate"], 6) or
|
||||
|
@ -1169,7 +1169,7 @@ def test_pricefilter_desc(mocker, whitelist_conf, markets, pairlistconfig,
|
||||
)
|
||||
whitelist_conf['pairlists'] = [pairlistconfig]
|
||||
|
||||
if desc_expected is not None:
|
||||
if desc_expected:
|
||||
freqtrade = get_patched_freqtradebot(mocker, whitelist_conf)
|
||||
short_desc = str(freqtrade.pairlists.short_desc())
|
||||
assert short_desc == desc_expected
|
||||
|
@ -45,7 +45,7 @@ def test_search_all_strategies_with_failed():
|
||||
assert len(strategies) == 6
|
||||
# with enum_failed=True search_all_objects() shall find 2 good strategies
|
||||
# and 1 which fails to load
|
||||
assert len([x for x in strategies if x['class'] is not None]) == 5
|
||||
assert len([x for x in strategies if x['class']]) == 5
|
||||
assert len([x for x in strategies if x['class'] is None]) == 1
|
||||
|
||||
|
||||
|
@ -131,7 +131,7 @@ def test_parse_args_backtesting_custom() -> None:
|
||||
assert call_args['config'] == ['test_conf.json']
|
||||
assert call_args['verbosity'] == 0
|
||||
assert call_args['command'] == 'backtesting'
|
||||
assert call_args['func'] is not None
|
||||
assert call_args['func']
|
||||
assert call_args['timeframe'] == '1m'
|
||||
assert type(call_args['strategy_list']) is list
|
||||
assert len(call_args['strategy_list']) == 2
|
||||
@ -150,7 +150,7 @@ def test_parse_args_hyperopt_custom() -> None:
|
||||
assert call_args['verbosity'] == 0
|
||||
assert call_args['command'] == 'hyperopt'
|
||||
assert call_args['spaces'] == ['buy']
|
||||
assert call_args['func'] is not None
|
||||
assert call_args['func']
|
||||
assert callable(call_args['func'])
|
||||
|
||||
|
||||
|
@ -160,7 +160,7 @@ def test_check_available_stake_amount(
|
||||
|
||||
for i in range(0, max_open):
|
||||
|
||||
if expected[i] is not None:
|
||||
if expected[i]:
|
||||
limit_buy_order_usdt_open['id'] = str(i)
|
||||
result = freqtrade.wallets.get_trade_stake_amount('ETH/USDT')
|
||||
assert pytest.approx(result) == expected[i]
|
||||
@ -257,18 +257,18 @@ def test_total_open_trades_stakes(mocker, default_conf_usdt, ticker_usdt, fee) -
|
||||
freqtrade.enter_positions()
|
||||
trade = Trade.query.first()
|
||||
|
||||
assert trade is not None
|
||||
assert trade
|
||||
assert trade.stake_amount == 60.0
|
||||
assert trade.is_open
|
||||
assert trade.open_date is not None
|
||||
assert trade.open_date
|
||||
|
||||
freqtrade.enter_positions()
|
||||
trade = Trade.query.order_by(Trade.id.desc()).first()
|
||||
|
||||
assert trade is not None
|
||||
assert trade
|
||||
assert trade.stake_amount == 60.0
|
||||
assert trade.is_open
|
||||
assert trade.open_date is not None
|
||||
assert trade.open_date
|
||||
|
||||
assert Trade.total_open_trades_stakes() == 120.0
|
||||
|
||||
@ -296,10 +296,10 @@ def test_create_trade(default_conf_usdt, ticker_usdt, limit_order,
|
||||
|
||||
trade = Trade.query.first()
|
||||
trade.is_short = is_short
|
||||
assert trade is not None
|
||||
assert trade
|
||||
assert pytest.approx(trade.stake_amount) == 60.0
|
||||
assert trade.is_open
|
||||
assert trade.open_date is not None
|
||||
assert trade.open_date
|
||||
assert trade.exchange == 'binance'
|
||||
|
||||
# Simulate fulfilled LIMIT_BUY order for trade
|
||||
@ -553,10 +553,10 @@ def test_process_trade_creation(default_conf_usdt, ticker_usdt, limit_order, lim
|
||||
trades = Trade.query.filter(Trade.is_open.is_(True)).all()
|
||||
assert len(trades) == 1
|
||||
trade = trades[0]
|
||||
assert trade is not None
|
||||
assert trade
|
||||
assert pytest.approx(trade.stake_amount) == default_conf_usdt['stake_amount']
|
||||
assert trade.is_open
|
||||
assert trade.open_date is not None
|
||||
assert trade.open_date
|
||||
assert trade.exchange == 'binance'
|
||||
assert trade.open_rate == ticker_usdt.return_value[ticker_side]
|
||||
assert isclose(trade.amount, 60 / ticker_usdt.return_value[ticker_side])
|
||||
@ -2150,7 +2150,7 @@ def test_handle_trade(
|
||||
assert trade.close_rate == 2.0 if is_short else 2.2
|
||||
assert trade.close_profit == close_profit
|
||||
assert trade.calc_profit() == 5.685
|
||||
assert trade.close_date is not None
|
||||
assert trade.close_date
|
||||
assert trade.exit_reason == 'sell_signal1'
|
||||
|
||||
|
||||
@ -4348,8 +4348,8 @@ def test_get_real_amount_multi(
|
||||
|
||||
assert trade.fee_open == expected_fee
|
||||
assert trade.fee_close == expected_fee
|
||||
assert trade.fee_open_cost is not None
|
||||
assert trade.fee_open_currency is not None
|
||||
assert trade.fee_open_cost
|
||||
assert trade.fee_open_currency
|
||||
assert trade.fee_close_cost is None
|
||||
assert trade.fee_close_currency is None
|
||||
|
||||
@ -4540,10 +4540,10 @@ def test_order_book_depth_of_market(
|
||||
assert trade is None
|
||||
else:
|
||||
trade.is_short = is_short
|
||||
assert trade is not None
|
||||
assert trade
|
||||
assert pytest.approx(trade.stake_amount) == 60.0
|
||||
assert trade.is_open
|
||||
assert trade.open_date is not None
|
||||
assert trade.open_date
|
||||
assert trade.exchange == 'binance'
|
||||
|
||||
assert len(Trade.query.all()) == 1
|
||||
@ -4853,15 +4853,15 @@ def test_update_closed_trades_without_assigned_fees(mocker, default_conf_usdt, f
|
||||
if trade.is_open:
|
||||
# Exclude Trade 4 - as the order is still open.
|
||||
if trade.select_order(entry_side(is_short), False):
|
||||
assert trade.fee_open_cost is not None
|
||||
assert trade.fee_open_currency is not None
|
||||
assert trade.fee_open_cost
|
||||
assert trade.fee_open_currency
|
||||
else:
|
||||
assert trade.fee_open_cost is None
|
||||
assert trade.fee_open_currency is None
|
||||
|
||||
else:
|
||||
assert trade.fee_close_cost is not None
|
||||
assert trade.fee_close_currency is not None
|
||||
assert trade.fee_close_cost
|
||||
assert trade.fee_close_currency
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("init_persistence")
|
||||
@ -4954,7 +4954,7 @@ def test_handle_insufficient_funds(mocker, default_conf_usdt, fee, is_short, cap
|
||||
assert mock_fo.call_count == 1
|
||||
assert mock_uts.call_count == 1
|
||||
# Found open buy order
|
||||
assert trade.open_order_id is not None
|
||||
assert trade.open_order_id
|
||||
assert trade.stoploss_order_id is None
|
||||
|
||||
caplog.clear()
|
||||
@ -4973,7 +4973,7 @@ def test_handle_insufficient_funds(mocker, default_conf_usdt, fee, is_short, cap
|
||||
assert mock_uts.call_count == 2
|
||||
# stoploss_order_id is "refound" and added to the trade
|
||||
assert trade.open_order_id is None
|
||||
assert trade.stoploss_order_id is not None
|
||||
assert trade.stoploss_order_id
|
||||
|
||||
caplog.clear()
|
||||
mock_fo.reset_mock()
|
||||
|
@ -374,7 +374,7 @@ def test_dca_order_adjust(default_conf_usdt, ticker_usdt, fee, mocker) -> None:
|
||||
assert len(Trade.get_trades().all()) == 1
|
||||
trade: Trade = Trade.get_trades().first()
|
||||
assert len(trade.orders) == 1
|
||||
assert trade.open_order_id is not None
|
||||
assert trade.open_order_id
|
||||
assert pytest.approx(trade.stake_amount) == 60
|
||||
assert trade.open_rate == 1.96
|
||||
assert trade.stop_loss_pct is None
|
||||
@ -385,7 +385,7 @@ def test_dca_order_adjust(default_conf_usdt, ticker_usdt, fee, mocker) -> None:
|
||||
freqtrade.process()
|
||||
trade = Trade.get_trades().first()
|
||||
assert len(trade.orders) == 1
|
||||
assert trade.open_order_id is not None
|
||||
assert trade.open_order_id
|
||||
assert pytest.approx(trade.stake_amount) == 60
|
||||
|
||||
# Cancel order and place new one
|
||||
@ -393,7 +393,7 @@ def test_dca_order_adjust(default_conf_usdt, ticker_usdt, fee, mocker) -> None:
|
||||
freqtrade.process()
|
||||
trade = Trade.get_trades().first()
|
||||
assert len(trade.orders) == 2
|
||||
assert trade.open_order_id is not None
|
||||
assert trade.open_order_id
|
||||
# Open rate is not adjusted yet
|
||||
assert trade.open_rate == 1.96
|
||||
assert trade.stop_loss_pct is None
|
||||
@ -421,7 +421,7 @@ def test_dca_order_adjust(default_conf_usdt, ticker_usdt, fee, mocker) -> None:
|
||||
freqtrade.process()
|
||||
trade = Trade.get_trades().first()
|
||||
assert len(trade.orders) == 3
|
||||
assert trade.open_order_id is not None
|
||||
assert trade.open_order_id
|
||||
assert trade.open_rate == 1.99
|
||||
assert trade.orders[-1].price == 1.96
|
||||
assert trade.orders[-1].cost == 120
|
||||
@ -432,7 +432,7 @@ def test_dca_order_adjust(default_conf_usdt, ticker_usdt, fee, mocker) -> None:
|
||||
freqtrade.process()
|
||||
trade = Trade.get_trades().first()
|
||||
assert len(trade.orders) == 4
|
||||
assert trade.open_order_id is not None
|
||||
assert trade.open_order_id
|
||||
assert trade.open_rate == 1.99
|
||||
assert trade.orders[-1].price == 1.95
|
||||
assert pytest.approx(trade.orders[-1].cost) == 120
|
||||
|
@ -38,7 +38,7 @@ def test_parse_args_backtesting(mocker) -> None:
|
||||
assert call_args['config'] == ['config.json']
|
||||
assert call_args['verbosity'] == 0
|
||||
assert call_args['command'] == 'backtesting'
|
||||
assert call_args['func'] is not None
|
||||
assert call_args['func']
|
||||
assert callable(call_args['func'])
|
||||
assert call_args['timeframe'] is None
|
||||
|
||||
@ -55,7 +55,7 @@ def test_main_start_hyperopt(mocker) -> None:
|
||||
assert call_args['config'] == ['config.json']
|
||||
assert call_args['verbosity'] == 0
|
||||
assert call_args['command'] == 'hyperopt'
|
||||
assert call_args['func'] is not None
|
||||
assert call_args['func']
|
||||
assert callable(call_args['func'])
|
||||
|
||||
|
||||
|
@ -501,7 +501,7 @@ def test_update_limit_order(fee, caplog, limit_buy_order_usdt, limit_sell_order_
|
||||
assert trade.open_order_id is None
|
||||
assert trade.close_rate == close_rate
|
||||
assert trade.close_profit == profit
|
||||
assert trade.close_date is not None
|
||||
assert trade.close_date
|
||||
assert log_has_re(f"LIMIT_{exit_side.upper()} has been fulfilled for "
|
||||
r"Trade\(id=2, pair=ADA/USDT, amount=30.00000000, "
|
||||
f"is_short={is_short}, leverage={lev}, open_rate={open_rate}0000000, "
|
||||
@ -547,7 +547,7 @@ def test_update_market_order(market_buy_order_usdt, market_sell_order_usdt, fee,
|
||||
assert trade.open_order_id is None
|
||||
assert trade.close_rate == 2.2
|
||||
assert trade.close_profit == round(0.0945137157107232, 8)
|
||||
assert trade.close_date is not None
|
||||
assert trade.close_date
|
||||
assert log_has_re(r"MARKET_SELL has been fulfilled for Trade\(id=1, "
|
||||
r"pair=ADA/USDT, amount=30.00000000, is_short=False, leverage=1.0, "
|
||||
r"open_rate=2.00000000, open_since=.*\).",
|
||||
@ -632,7 +632,7 @@ def test_trade_close(limit_buy_order_usdt, limit_sell_order_usdt, fee):
|
||||
trade.close(2.2)
|
||||
assert trade.is_open is False
|
||||
assert trade.close_profit == round(0.0945137157107232, 8)
|
||||
assert trade.close_date is not None
|
||||
assert trade.close_date
|
||||
|
||||
new_date = arrow.Arrow(2020, 2, 2, 15, 6, 1).datetime,
|
||||
assert trade.close_date != new_date
|
||||
@ -2042,7 +2042,7 @@ def test_fee_updated(fee):
|
||||
trade.update_fee(0.15, 'BTC', 0.0075, 'buy')
|
||||
assert trade.fee_updated('buy')
|
||||
assert not trade.fee_updated('sell')
|
||||
assert trade.fee_open_currency is not None
|
||||
assert trade.fee_open_currency
|
||||
assert trade.fee_close_currency is None
|
||||
|
||||
trade.update_fee(0.15, 'ABC', 0.0075, 'sell')
|
||||
@ -2204,7 +2204,7 @@ def test_update_order_from_ccxt(caplog):
|
||||
assert o.price == 1234.5
|
||||
assert o.filled == 9
|
||||
assert o.remaining == 11
|
||||
assert o.order_date is not None
|
||||
assert o.order_date
|
||||
assert o.ft_is_open
|
||||
assert o.order_filled_date is None
|
||||
|
||||
@ -2220,7 +2220,7 @@ def test_update_order_from_ccxt(caplog):
|
||||
assert o.filled == 20.0
|
||||
assert o.remaining == 0.0
|
||||
assert not o.ft_is_open
|
||||
assert o.order_filled_date is not None
|
||||
assert o.order_filled_date
|
||||
|
||||
ccxt_order.update({'id': 'somethingelse'})
|
||||
with pytest.raises(DependencyException, match=r"Order-id's don't match"):
|
||||
@ -2246,7 +2246,7 @@ def test_select_order(fee, is_short):
|
||||
order = trades[0].select_order(trades[0].entry_side, True)
|
||||
assert order is None
|
||||
order = trades[0].select_order(trades[0].entry_side, False)
|
||||
assert order is not None
|
||||
assert order
|
||||
order = trades[0].select_order(trades[0].exit_side, None)
|
||||
assert order is None
|
||||
|
||||
@ -2254,17 +2254,17 @@ def test_select_order(fee, is_short):
|
||||
order = trades[1].select_order(trades[1].entry_side, True)
|
||||
assert order is None
|
||||
order = trades[1].select_order(trades[1].entry_side, False)
|
||||
assert order is not None
|
||||
assert order
|
||||
order = trades[1].select_order(trades[1].entry_side, None)
|
||||
assert order is not None
|
||||
assert order
|
||||
order = trades[1].select_order(trades[1].exit_side, True)
|
||||
assert order is None
|
||||
order = trades[1].select_order(trades[1].exit_side, False)
|
||||
assert order is not None
|
||||
assert order
|
||||
|
||||
# Has open buy order
|
||||
order = trades[3].select_order(trades[3].entry_side, True)
|
||||
assert order is not None
|
||||
assert order
|
||||
order = trades[3].select_order(trades[3].entry_side, False)
|
||||
assert order is None
|
||||
|
||||
@ -2272,15 +2272,15 @@ def test_select_order(fee, is_short):
|
||||
order = trades[4].select_order(trades[4].entry_side, True)
|
||||
assert order is None
|
||||
order = trades[4].select_order(trades[4].entry_side, False)
|
||||
assert order is not None
|
||||
assert order
|
||||
|
||||
trades[4].orders[1].ft_order_side = trades[4].exit_side
|
||||
order = trades[4].select_order(trades[4].exit_side, True)
|
||||
assert order is not None
|
||||
assert order
|
||||
|
||||
trades[4].orders[1].ft_order_side = 'stoploss'
|
||||
order = trades[4].select_order('stoploss', None)
|
||||
assert order is not None
|
||||
assert order
|
||||
assert order.ft_order_side == 'stoploss'
|
||||
|
||||
|
||||
@ -2685,7 +2685,7 @@ def test_select_filled_orders(fee):
|
||||
|
||||
# Closed buy order, no sell order
|
||||
orders = trades[0].select_filled_orders('buy')
|
||||
assert orders is not None
|
||||
assert orders
|
||||
assert len(orders) == 1
|
||||
order = orders[0]
|
||||
assert order.amount > 0
|
||||
@ -2694,30 +2694,30 @@ def test_select_filled_orders(fee):
|
||||
assert order.ft_order_side == 'buy'
|
||||
assert order.status == 'closed'
|
||||
orders = trades[0].select_filled_orders('sell')
|
||||
assert orders is not None
|
||||
assert orders
|
||||
assert len(orders) == 0
|
||||
|
||||
# closed buy order, and closed sell order
|
||||
orders = trades[1].select_filled_orders('buy')
|
||||
assert orders is not None
|
||||
assert orders
|
||||
assert len(orders) == 1
|
||||
|
||||
orders = trades[1].select_filled_orders('sell')
|
||||
assert orders is not None
|
||||
assert orders
|
||||
assert len(orders) == 1
|
||||
|
||||
# Has open buy order
|
||||
orders = trades[3].select_filled_orders('buy')
|
||||
assert orders is not None
|
||||
assert orders
|
||||
assert len(orders) == 0
|
||||
orders = trades[3].select_filled_orders('sell')
|
||||
assert orders is not None
|
||||
assert orders
|
||||
assert len(orders) == 0
|
||||
|
||||
# Open sell order
|
||||
orders = trades[4].select_filled_orders('buy')
|
||||
assert orders is not None
|
||||
assert orders
|
||||
assert len(orders) == 1
|
||||
orders = trades[4].select_filled_orders('sell')
|
||||
assert orders is not None
|
||||
assert orders
|
||||
assert len(orders) == 0
|
||||
|
@ -147,7 +147,7 @@ def test_get_trade_stake_amount_unlimited_amount(default_conf, ticker, balance_r
|
||||
conf['dry_run_wallet'] = 100
|
||||
conf['max_open_trades'] = 2
|
||||
conf['tradable_balance_ratio'] = balance_ratio
|
||||
if capital is not None:
|
||||
if capital:
|
||||
conf['available_capital'] = capital
|
||||
|
||||
freqtrade = get_patched_freqtradebot(mocker, conf)
|
||||
|
Loading…
Reference in New Issue
Block a user