diff --git a/en/2021.7/404.html b/en/2021.7/404.html new file mode 100644 index 000000000..20eff22e0 --- /dev/null +++ b/en/2021.7/404.html @@ -0,0 +1,857 @@ + + + + + + + + + + + + + + + + + Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+ +
+ +
+ + + + +
+
+ + + + + +
+
+
+ +
+
+ + + + +
+
+
+ + + + + +
+
+ +

404 - Not found

+ + +
+
+
+ +
+ + + + + + + + + + + + + + + +
+
+
+
+ + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/advanced-hyperopt/index.html b/en/2021.7/advanced-hyperopt/index.html new file mode 100644 index 000000000..78cebddea --- /dev/null +++ b/en/2021.7/advanced-hyperopt/index.html @@ -0,0 +1,1525 @@ + + + + + + + + + + + + + + + + + + + Advanced Hyperopt - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + Skip to content + + +
+
+ +
+ +
+ +
+ +
+ + + + +
+
+ + + + + +
+
+
+ +
+
+ + + + +
+
+
+ + + + + + + + +
+
+ + + + + + + +

Advanced Hyperopt

+

This page explains some advanced Hyperopt topics that may require higher +coding skills and Python knowledge than creation of an ordinal hyperoptimization +class.

+

Creating and using a custom loss function

+

To use a custom loss function class, make sure that the function hyperopt_loss_function is defined in your custom hyperopt loss class. +For the sample below, you then need to add the command line parameter --hyperopt-loss SuperDuperHyperOptLoss to your hyperopt call so this function is being used.

+

A sample of this can be found below, which is identical to the Default Hyperopt loss implementation. A full sample can be found in userdata/hyperopts.

+

``` python +from datetime import datetime +from typing import Dict

+

from pandas import DataFrame

+

from freqtrade.optimize.hyperopt import IHyperOptLoss

+

TARGET_TRADES = 600 +EXPECTED_MAX_PROFIT = 3.0 +MAX_ACCEPTED_TRADE_DURATION = 300

+

class SuperDuperHyperOptLoss(IHyperOptLoss): + """ + Defines the default loss function for hyperopt + """

+
@staticmethod
+def hyperopt_loss_function(results: DataFrame, trade_count: int,
+                           min_date: datetime, max_date: datetime,
+                           config: Dict, processed: Dict[str, DataFrame],
+                           backtest_stats: Dict[str, Any],
+                           *args, **kwargs) -> float:
+    """
+    Objective function, returns smaller number for better results
+    This is the legacy algorithm (used until now in freqtrade).
+    Weights are distributed as follows:
+    * 0.4 to trade duration
+    * 0.25: Avoiding trade loss
+    * 1.0 to total profit, compared to the expected value (`EXPECTED_MAX_PROFIT`) defined above
+    """
+    total_profit = results['profit_ratio'].sum()
+    trade_duration = results['trade_duration'].mean()
+
+    trade_loss = 1 - 0.25 * exp(-(trade_count - TARGET_TRADES) ** 2 / 10 ** 5.8)
+    profit_loss = max(0, 1 - total_profit / EXPECTED_MAX_PROFIT)
+    duration_loss = 0.4 * min(trade_duration / MAX_ACCEPTED_TRADE_DURATION, 1)
+    result = trade_loss + profit_loss + duration_loss
+    return result
+
+ +

```

+

Currently, the arguments are:

+
    +
  • results: DataFrame containing the resulting trades. + The following columns are available in results (corresponds to the output-file of backtesting when used with --export trades):
    +pair, profit_ratio, profit_abs, open_date, open_rate, fee_open, close_date, close_rate, fee_close, amount, trade_duration, is_open, sell_reason, stake_amount, min_rate, max_rate, stop_loss_ratio, stop_loss_abs
  • +
  • trade_count: Amount of trades (identical to len(results))
  • +
  • min_date: Start date of the timerange used
  • +
  • min_date: End date of the timerange used
  • +
  • config: Config object used (Note: Not all strategy-related parameters will be updated here if they are part of a hyperopt space).
  • +
  • processed: Dict of Dataframes with the pair as keys containing the data used for backtesting.
  • +
  • backtest_stats: Backtesting statistics using the same format as the backtesting file "strategy" substructure. Available fields can be seen in generate_strategy_stats() in optimize_reports.py.
  • +
+

This function needs to return a floating point number (float). Smaller numbers will be interpreted as better results. The parameters and balancing for this is up to you.

+
+

Note

+

This function is called once per iteration - so please make sure to have this as optimized as possible to not slow hyperopt down unnecessarily.

+
+
+

Note

+

Please keep the arguments *args and **kwargs in the interface to allow us to extend this interface later.

+
+

Overriding pre-defined spaces

+

To override a pre-defined space (roi_space, generate_roi_table, stoploss_space, trailing_space), define a nested class called Hyperopt and define the required spaces as follows:

+

python +class MyAwesomeStrategy(IStrategy): + class HyperOpt: + # Define a custom stoploss space. + def stoploss_space(self): + return [SKDecimal(-0.05, -0.01, decimals=3, name='stoploss')]

+

Space options

+

For the additional spaces, scikit-optimize (in combination with Freqtrade) provides the following space types:

+
    +
  • Categorical - Pick from a list of categories (e.g. Categorical(['a', 'b', 'c'], name="cat"))
  • +
  • Integer - Pick from a range of whole numbers (e.g. Integer(1, 10, name='rsi'))
  • +
  • SKDecimal - Pick from a range of decimal numbers with limited precision (e.g. SKDecimal(0.1, 0.5, decimals=3, name='adx')). Available only with freqtrade.
  • +
  • Real - Pick from a range of decimal numbers with full precision (e.g. Real(0.1, 0.5, name='adx')
  • +
+

You can import all of these from freqtrade.optimize.space, although Categorical, Integer and Real are only aliases for their corresponding scikit-optimize Spaces. SKDecimal is provided by freqtrade for faster optimizations.

+

python +from freqtrade.optimize.space import Categorical, Dimension, Integer, SKDecimal, Real # noqa

+
+

SKDecimal vs. Real

+

We recommend to use SKDecimal instead of the Real space in almost all cases. While the Real space provides full accuracy (up to ~16 decimal places) - this precision is rarely needed, and leads to unnecessary long hyperopt times.

+

Assuming the definition of a rather small space (SKDecimal(0.10, 0.15, decimals=2, name='xxx')) - SKDecimal will have 5 possibilities ([0.10, 0.11, 0.12, 0.13, 0.14, 0.15]).

+

A corresponding real space Real(0.10, 0.15 name='xxx') on the other hand has an almost unlimited number of possibilities ([0.10, 0.010000000001, 0.010000000002, ... 0.014999999999, 0.01500000000]).

+
+
+

Legacy Hyperopt

+

This Section explains the configuration of an explicit Hyperopt file (separate to the strategy).

+
+

Deprecated / legacy mode

+

Since the 2021.4 release you no longer have to write a separate hyperopt class, but all strategies can be hyperopted. +Please read the main hyperopt page for more details.

+
+

Prepare hyperopt file

+

Configuring an explicit hyperopt file is similar to writing your own strategy, and many tasks will be similar.

+
+

About this page

+

For this page, we will be using a fictional strategy called AwesomeStrategy - which will be optimized using the AwesomeHyperopt class.

+
+

Create a Custom Hyperopt File

+

The simplest way to get started is to use the following command, which will create a new hyperopt file from a template, which will be located under user_data/hyperopts/AwesomeHyperopt.py.

+

Let assume you want a hyperopt file AwesomeHyperopt.py:

+

bash +freqtrade new-hyperopt --hyperopt AwesomeHyperopt

+

Legacy Hyperopt checklist

+

Checklist on all tasks / possibilities in hyperopt

+

Depending on the space you want to optimize, only some of the below are required:

+
    +
  • fill buy_strategy_generator - for buy signal optimization
  • +
  • fill indicator_space - for buy signal optimization
  • +
  • fill sell_strategy_generator - for sell signal optimization
  • +
  • fill sell_indicator_space - for sell signal optimization
  • +
+
+

Note

+

populate_indicators needs to create all indicators any of thee spaces may use, otherwise hyperopt will not work.

+
+

Optional in hyperopt - can also be loaded from a strategy (recommended):

+
    +
  • populate_indicators - fallback to create indicators
  • +
  • populate_buy_trend - fallback if not optimizing for buy space. should come from strategy
  • +
  • populate_sell_trend - fallback if not optimizing for sell space. should come from strategy
  • +
+
+

Note

+

You always have to provide a strategy to Hyperopt, even if your custom Hyperopt class contains all methods. +Assuming the optional methods are not in your hyperopt file, please use --strategy AweSomeStrategy which contains these methods so hyperopt can use these methods instead.

+
+

Rarely you may also need to override:

+
    +
  • roi_space - for custom ROI optimization (if you need the ranges for the ROI parameters in the optimization hyperspace that differ from default)
  • +
  • generate_roi_table - for custom ROI optimization (if you need the ranges for the values in the ROI table that differ from default or the number of entries (steps) in the ROI table which differs from the default 4 steps)
  • +
  • stoploss_space - for custom stoploss optimization (if you need the range for the stoploss parameter in the optimization hyperspace that differs from default)
  • +
  • trailing_space - for custom trailing stop optimization (if you need the ranges for the trailing stop parameters in the optimization hyperspace that differ from default)
  • +
+

Defining a buy signal optimization

+

Let's say you are curious: should you use MACD crossings or lower Bollinger +Bands to trigger your buys. And you also wonder should you use RSI or ADX to +help with those buy decisions. If you decide to use RSI or ADX, which values +should I use for them? So let's use hyperparameter optimization to solve this +mystery.

+

We will start by defining a search space:

+

python + def indicator_space() -> List[Dimension]: + """ + Define your Hyperopt space for searching strategy parameters + """ + return [ + Integer(20, 40, name='adx-value'), + Integer(20, 40, name='rsi-value'), + Categorical([True, False], name='adx-enabled'), + Categorical([True, False], name='rsi-enabled'), + Categorical(['bb_lower', 'macd_cross_signal'], name='trigger') + ]

+

Above definition says: I have five parameters I want you to randomly combine +to find the best combination. Two of them are integer values (adx-value and rsi-value) and I want you test in the range of values 20 to 40.
+Then we have three category variables. First two are either True or False. +We use these to either enable or disable the ADX and RSI guards. +The last one we call trigger and use it to decide which buy trigger we want to use.

+

So let's write the buy strategy generator using these values:

+

```python + @staticmethod + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: + """ + Define the buy strategy parameters to be used by Hyperopt. + """ + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: + conditions = [] + # GUARDS AND TRENDS + if 'adx-enabled' in params and params['adx-enabled']: + conditions.append(dataframe['adx'] > params['adx-value']) + if 'rsi-enabled' in params and params['rsi-enabled']: + conditions.append(dataframe['rsi'] < params['rsi-value'])

+
        # TRIGGERS
+        if 'trigger' in params:
+            if params['trigger'] == 'bb_lower':
+                conditions.append(dataframe['close'] < dataframe['bb_lowerband'])
+            if params['trigger'] == 'macd_cross_signal':
+                conditions.append(qtpylib.crossed_above(
+                    dataframe['macd'], dataframe['macdsignal']
+                ))
+
+        # Check that volume is not 0
+        conditions.append(dataframe['volume'] > 0)
+
+        if conditions:
+            dataframe.loc[
+                reduce(lambda x, y: x & y, conditions),
+                'buy'] = 1
+
+        return dataframe
+
+    return populate_buy_trend
+
+ +

```

+

Hyperopt will now call populate_buy_trend() many times (epochs) with different value combinations.
+It will use the given historical data and make buys based on the buy signals generated with the above function.
+Based on the results, hyperopt will tell you which parameter combination produced the best results (based on the configured loss function).

+
+

Note

+

The above setup expects to find ADX, RSI and Bollinger Bands in the populated indicators. +When you want to test an indicator that isn't used by the bot currently, remember to +add it to the populate_indicators() method in your strategy or hyperopt file.

+
+

Sell optimization

+

Similar to the buy-signal above, sell-signals can also be optimized. +Place the corresponding settings into the following methods

+
    +
  • Inside sell_indicator_space() - the parameters hyperopt shall be optimizing.
  • +
  • Within sell_strategy_generator() - populate the nested method populate_sell_trend() to apply the parameters.
  • +
+

The configuration and rules are the same than for buy signals. +To avoid naming collisions in the search-space, please prefix all sell-spaces with sell-.

+

Execute Hyperopt

+

Once you have updated your hyperopt configuration you can run it. +Because hyperopt tries a lot of combinations to find the best parameters it will take time to get a good result. More time usually results in better results.

+

We strongly recommend to use screen or tmux to prevent any connection loss.

+

bash +freqtrade hyperopt --config config.json --hyperopt <hyperoptname> --hyperopt-loss <hyperoptlossname> --strategy <strategyname> -e 500 --spaces all

+

Use <hyperoptname> as the name of the custom hyperopt used.

+

The -e option will set how many evaluations hyperopt will do. Since hyperopt uses Bayesian search, running too many epochs at once may not produce greater results. Experience has shown that best results are usually not improving much after 500-1000 epochs.
+Doing multiple runs (executions) with a few 1000 epochs and different random state will most likely produce different results.

+

The --spaces all option determines that all possible parameters should be optimized. Possibilities are listed below.

+
+

Note

+

Hyperopt will store hyperopt results with the timestamp of the hyperopt start time. +Reading commands (hyperopt-list, hyperopt-show) can use --hyperopt-filename <filename> to read and display older hyperopt results. +You can find a list of filenames with ls -l user_data/hyperopt_results/.

+
+

Running Hyperopt using methods from a strategy

+

Hyperopt can reuse populate_indicators, populate_buy_trend, populate_sell_trend from your strategy, assuming these methods are not in your custom hyperopt file, and a strategy is provided.

+

bash +freqtrade hyperopt --hyperopt AwesomeHyperopt --hyperopt-loss SharpeHyperOptLossDaily --strategy AwesomeStrategy

+

Understand the Hyperopt Result

+

Once Hyperopt is completed you can use the result to create a new strategy. +Given the following result from hyperopt:

+

``` +Best result:

+
44/100:    135 trades. Avg profit  0.57%. Total profit  0.03871918 BTC (0.7722%). Avg duration 180.4 mins. Objective: 1.94367
+
+ +

Buy hyperspace params: +{ 'adx-value': 44, + 'rsi-value': 29, + 'adx-enabled': False, + 'rsi-enabled': True, + 'trigger': 'bb_lower'} +```

+

You should understand this result like:

+
    +
  • The buy trigger that worked best was bb_lower.
  • +
  • You should not use ADX because adx-enabled: False)
  • +
  • You should consider using the RSI indicator (rsi-enabled: True and the best value is 29.0 (rsi-value: 29.0)
  • +
+

You have to look inside your strategy file into buy_strategy_generator() +method, what those values match to.

+

So for example you had rsi-value: 29.0 so we would look at rsi-block, that translates to the following code block:

+

python +(dataframe['rsi'] < 29.0)

+

Translating your whole hyperopt result as the new buy-signal would then look like:

+

python +def populate_buy_trend(self, dataframe: DataFrame) -> DataFrame: + dataframe.loc[ + ( + (dataframe['rsi'] < 29.0) & # rsi-value + dataframe['close'] < dataframe['bb_lowerband'] # trigger + ), + 'buy'] = 1 + return dataframe

+

Validate backtesting results

+

Once the optimized parameters and conditions have been implemented into your strategy, you should backtest the strategy to make sure everything is working as expected.

+

To achieve same results (number of trades, their durations, profit, etc.) than during Hyperopt, please use same configuration and parameters (timerange, timeframe, ...) used for hyperopt --dmmp/--disable-max-market-positions and --eps/--enable-position-stacking for Backtesting.

+

Should results don't match, please double-check to make sure you transferred all conditions correctly. +Pay special care to the stoploss (and trailing stoploss) parameters, as these are often set in configuration files, which override changes to the strategy. +You should also carefully review the log of your backtest to ensure that there were no parameters inadvertently set by the configuration (like stoploss or trailing_stop).

+

Sharing methods with your strategy

+

Hyperopt classes provide access to the Strategy via the strategy class attribute. +This can be a great way to reduce code duplication if used correctly, but will also complicate usage for inexperienced users.

+

``` python +from pandas import DataFrame +from freqtrade.strategy.interface import IStrategy +import freqtrade.vendor.qtpylib.indicators as qtpylib

+

class MyAwesomeStrategy(IStrategy):

+
buy_params = {
+    'rsi-value': 30,
+    'adx-value': 35,
+}
+
+def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
+    return self.buy_strategy_generator(self.buy_params, dataframe, metadata)
+
+@staticmethod
+def buy_strategy_generator(params, dataframe: DataFrame, metadata: dict) -> DataFrame:
+    dataframe.loc[
+        (
+            qtpylib.crossed_above(dataframe['rsi'], params['rsi-value']) &
+            dataframe['adx'] > params['adx-value']) &
+            dataframe['volume'] > 0
+        )
+        , 'buy'] = 1
+    return dataframe
+
+ +

class MyAwesomeHyperOpt(IHyperOpt): + ... + @staticmethod + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: + """ + Define the buy strategy parameters to be used by Hyperopt. + """ + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: + # Call strategy's buy strategy generator + return self.StrategyClass.buy_strategy_generator(params, dataframe, metadata)

+
    return populate_buy_trend
+
+ +

```

+ + + + + + + +
+
+
+ +
+ + + + + + + + + + + + + + + +
+
+
+
+ + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/advanced-setup/index.html b/en/2021.7/advanced-setup/index.html new file mode 100644 index 000000000..332ecab11 --- /dev/null +++ b/en/2021.7/advanced-setup/index.html @@ -0,0 +1,1127 @@ + + + + + + + + + + + + + + + + + + + Advanced Post-installation Tasks - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + Skip to content + + +
+
+ +
+ +
+ +
+ +
+ + + + +
+
+ + + + + +
+
+
+ +
+
+ + + + +
+
+
+ + + + + +
+
+
+ + +
+
+
+ + +
+
+ + + + + + + +

Advanced Post-installation Tasks

+

This page explains some advanced tasks and configuration options that can be performed after the bot installation and may be uselful in some environments.

+

If you do not know what things mentioned here mean, you probably do not need it.

+

Running multiple instances of Freqtrade

+

This section will show you how to run multiple bots at the same time, on the same machine.

+

Things to consider

+
    +
  • Use different database files.
  • +
  • Use different Telegram bots (requires multiple different configuration files; applies only when Telegram is enabled).
  • +
  • Use different ports (applies only when Freqtrade REST API webserver is enabled).
  • +
+

Different database files

+

In order to keep track of your trades, profits, etc., freqtrade is using a SQLite database where it stores various types of information such as the trades you performed in the past and the current position(s) you are holding at any time. This allows you to keep track of your profits, but most importantly, keep track of ongoing activity if the bot process would be restarted or would be terminated unexpectedly.

+

Freqtrade will, by default, use separate database files for dry-run and live bots (this assumes no database-url is given in either configuration nor via command line argument). +For live trading mode, the default database will be tradesv3.sqlite and for dry-run it will be tradesv3.dryrun.sqlite.

+

The optional argument to the trade command used to specify the path of these files is --db-url, which requires a valid SQLAlchemy url. +So when you are starting a bot with only the config and strategy arguments in dry-run mode, the following 2 commands would have the same outcome.

+

``` bash +freqtrade trade -c MyConfig.json -s MyStrategy

+

is equivalent to

+

freqtrade trade -c MyConfig.json -s MyStrategy --db-url sqlite:///tradesv3.dryrun.sqlite +```

+

It means that if you are running the trade command in two different terminals, for example to test your strategy both for trades in USDT and in another instance for trades in BTC, you will have to run them with different databases.

+

If you specify the URL of a database which does not exist, freqtrade will create one with the name you specified. So to test your custom strategy with BTC and USDT stake currencies, you could use the following commands (in 2 separate terminals):

+

``` bash

+

Terminal 1:

+

freqtrade trade -c MyConfigBTC.json -s MyCustomStrategy --db-url sqlite:///user_data/tradesBTC.dryrun.sqlite

+

Terminal 2:

+

freqtrade trade -c MyConfigUSDT.json -s MyCustomStrategy --db-url sqlite:///user_data/tradesUSDT.dryrun.sqlite +```

+

Conversely, if you wish to do the same thing in production mode, you will also have to create at least one new database (in addition to the default one) and specify the path to the "live" databases, for example:

+

``` bash

+

Terminal 1:

+

freqtrade trade -c MyConfigBTC.json -s MyCustomStrategy --db-url sqlite:///user_data/tradesBTC.live.sqlite

+

Terminal 2:

+

freqtrade trade -c MyConfigUSDT.json -s MyCustomStrategy --db-url sqlite:///user_data/tradesUSDT.live.sqlite +```

+

For more information regarding usage of the sqlite databases, for example to manually enter or remove trades, please refer to the SQL Cheatsheet.

+

Configure the bot running as a systemd service

+

Copy the freqtrade.service file to your systemd user directory (usually ~/.config/systemd/user) and update WorkingDirectory and ExecStart to match your setup.

+
+

Note

+

Certain systems (like Raspbian) don't load service unit files from the user directory. In this case, copy freqtrade.service into /etc/systemd/user/ (requires superuser permissions).

+
+

After that you can start the daemon with:

+

bash +systemctl --user start freqtrade

+

For this to be persistent (run when user is logged out) you'll need to enable linger for your freqtrade user.

+

bash +sudo loginctl enable-linger "$USER"

+

If you run the bot as a service, you can use systemd service manager as a software watchdog monitoring freqtrade bot +state and restarting it in the case of failures. If the internals.sd_notify parameter is set to true in the +configuration or the --sd-notify command line option is used, the bot will send keep-alive ping messages to systemd +using the sd_notify (systemd notifications) protocol and will also tell systemd its current state (Running or Stopped) +when it changes.

+

The freqtrade.service.watchdog file contains an example of the service unit configuration file which uses systemd +as the watchdog.

+
+

Note

+

The sd_notify communication between the bot and the systemd service manager will not work if the bot runs in a Docker container.

+
+

Advanced Logging

+

On many Linux systems the bot can be configured to send its log messages to syslog or journald system services. Logging to a remote syslog server is also available on Windows. The special values for the --logfile command line option can be used for this.

+

Logging to syslog

+

To send Freqtrade log messages to a local or remote syslog service use the --logfile command line option with the value in the following format:

+
    +
  • --logfile syslog:<syslog_address> -- send log messages to syslog service using the <syslog_address> as the syslog address.
  • +
+

The syslog address can be either a Unix domain socket (socket filename) or a UDP socket specification, consisting of IP address and UDP port, separated by the : character.

+

So, the following are the examples of possible usages:

+
    +
  • --logfile syslog:/dev/log -- log to syslog (rsyslog) using the /dev/log socket, suitable for most systems.
  • +
  • --logfile syslog -- same as above, the shortcut for /dev/log.
  • +
  • --logfile syslog:/var/run/syslog -- log to syslog (rsyslog) using the /var/run/syslog socket. Use this on MacOS.
  • +
  • --logfile syslog:localhost:514 -- log to local syslog using UDP socket, if it listens on port 514.
  • +
  • --logfile syslog:<ip>:514 -- log to remote syslog at IP address and port 514. This may be used on Windows for remote logging to an external syslog server.
  • +
+

Log messages are send to syslog with the user facility. So you can see them with the following commands:

+
    +
  • tail -f /var/log/user, or
  • +
  • install a comprehensive graphical viewer (for instance, 'Log File Viewer' for Ubuntu).
  • +
+

On many systems syslog (rsyslog) fetches data from journald (and vice versa), so both --logfile syslog or --logfile journald can be used and the messages be viewed with both journalctl and a syslog viewer utility. You can combine this in any way which suites you better.

+

For rsyslog the messages from the bot can be redirected into a separate dedicated log file. To achieve this, add +if $programname startswith "freqtrade" then -/var/log/freqtrade.log +to one of the rsyslog configuration files, for example at the end of the /etc/rsyslog.d/50-default.conf.

+

For syslog (rsyslog), the reduction mode can be switched on. This will reduce the number of repeating messages. For instance, multiple bot Heartbeat messages will be reduced to a single message when nothing else happens with the bot. To achieve this, set in /etc/rsyslog.conf: +```

+

Filter duplicated messages

+

$RepeatedMsgReduction on +```

+

Logging to journald

+

This needs the systemd python package installed as the dependency, which is not available on Windows. Hence, the whole journald logging functionality is not available for a bot running on Windows.

+

To send Freqtrade log messages to journald system service use the --logfile command line option with the value in the following format:

+
    +
  • --logfile journald -- send log messages to journald.
  • +
+

Log messages are send to journald with the user facility. So you can see them with the following commands:

+
    +
  • journalctl -f -- shows Freqtrade log messages sent to journald along with other log messages fetched by journald.
  • +
  • journalctl -f -u freqtrade.service -- this command can be used when the bot is run as a systemd service.
  • +
+

There are many other options in the journalctl utility to filter the messages, see manual pages for this utility.

+

On many systems syslog (rsyslog) fetches data from journald (and vice versa), so both --logfile syslog or --logfile journald can be used and the messages be viewed with both journalctl and a syslog viewer utility. You can combine this in any way which suites you better.

+ + + + + + + +
+
+
+ +
+ + + + + + + + + + + + + + + +
+
+
+
+ + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/assets/ccxt-logo.svg b/en/2021.7/assets/ccxt-logo.svg new file mode 100644 index 000000000..e52682546 --- /dev/null +++ b/en/2021.7/assets/ccxt-logo.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/en/2021.7/assets/freqtrade-screenshot.png b/en/2021.7/assets/freqtrade-screenshot.png new file mode 100644 index 000000000..4ad681579 Binary files /dev/null and b/en/2021.7/assets/freqtrade-screenshot.png differ diff --git a/en/2021.7/assets/freqtrade_poweredby.svg b/en/2021.7/assets/freqtrade_poweredby.svg new file mode 100644 index 000000000..957ec6401 --- /dev/null +++ b/en/2021.7/assets/freqtrade_poweredby.svg @@ -0,0 +1,44 @@ + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + Freqtrade + + + + + poweredby + + diff --git a/en/2021.7/assets/images/favicon.png b/en/2021.7/assets/images/favicon.png new file mode 100644 index 000000000..1cf13b9f9 Binary files /dev/null and b/en/2021.7/assets/images/favicon.png differ diff --git a/en/2021.7/assets/javascripts/bundle.716f8af4.min.js b/en/2021.7/assets/javascripts/bundle.716f8af4.min.js new file mode 100644 index 000000000..9f6c51023 --- /dev/null +++ b/en/2021.7/assets/javascripts/bundle.716f8af4.min.js @@ -0,0 +1,29 @@ +(()=>{var ea=Object.create;var St=Object.defineProperty;var ta=Object.getOwnPropertyDescriptor;var ra=Object.getOwnPropertyNames,wt=Object.getOwnPropertySymbols,oa=Object.getPrototypeOf,ir=Object.prototype.hasOwnProperty,qr=Object.prototype.propertyIsEnumerable;var Qr=(e,t,r)=>t in e?St(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,P=(e,t)=>{for(var r in t||(t={}))ir.call(t,r)&&Qr(e,r,t[r]);if(wt)for(var r of wt(t))qr.call(t,r)&&Qr(e,r,t[r]);return e};var na=e=>St(e,"__esModule",{value:!0});var Kr=(e,t)=>{var r={};for(var o in e)ir.call(e,o)&&t.indexOf(o)<0&&(r[o]=e[o]);if(e!=null&&wt)for(var o of wt(e))t.indexOf(o)<0&&qr.call(e,o)&&(r[o]=e[o]);return r};var Et=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ia=(e,t,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ra(t))!ir.call(e,o)&&o!=="default"&&St(e,o,{get:()=>t[o],enumerable:!(r=ta(t,o))||r.enumerable});return e},pt=e=>ia(na(St(e!=null?ea(oa(e)):{},"default",e&&e.__esModule&&"default"in e?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e);var Jr=Et((ar,Br)=>{(function(e,t){typeof ar=="object"&&typeof Br!="undefined"?t():typeof define=="function"&&define.amd?define(t):t()})(ar,function(){"use strict";function e(r){var o=!0,n=!1,i=null,a={text:!0,search:!0,url:!0,tel:!0,email:!0,password:!0,number:!0,date:!0,month:!0,week:!0,time:!0,datetime:!0,"datetime-local":!0};function s(w){return!!(w&&w!==document&&w.nodeName!=="HTML"&&w.nodeName!=="BODY"&&"classList"in w&&"contains"in w.classList)}function c(w){var We=w.type,Te=w.tagName;return!!(Te==="INPUT"&&a[We]&&!w.readOnly||Te==="TEXTAREA"&&!w.readOnly||w.isContentEditable)}function l(w){w.classList.contains("focus-visible")||(w.classList.add("focus-visible"),w.setAttribute("data-focus-visible-added",""))}function p(w){!w.hasAttribute("data-focus-visible-added")||(w.classList.remove("focus-visible"),w.removeAttribute("data-focus-visible-added"))}function m(w){w.metaKey||w.altKey||w.ctrlKey||(s(r.activeElement)&&l(r.activeElement),o=!0)}function f(w){o=!1}function d(w){!s(w.target)||(o||c(w.target))&&l(w.target)}function v(w){!s(w.target)||(w.target.classList.contains("focus-visible")||w.target.hasAttribute("data-focus-visible-added"))&&(n=!0,window.clearTimeout(i),i=window.setTimeout(function(){n=!1},100),p(w.target))}function h(w){document.visibilityState==="hidden"&&(n&&(o=!0),W())}function W(){document.addEventListener("mousemove",j),document.addEventListener("mousedown",j),document.addEventListener("mouseup",j),document.addEventListener("pointermove",j),document.addEventListener("pointerdown",j),document.addEventListener("pointerup",j),document.addEventListener("touchmove",j),document.addEventListener("touchstart",j),document.addEventListener("touchend",j)}function B(){document.removeEventListener("mousemove",j),document.removeEventListener("mousedown",j),document.removeEventListener("mouseup",j),document.removeEventListener("pointermove",j),document.removeEventListener("pointerdown",j),document.removeEventListener("pointerup",j),document.removeEventListener("touchmove",j),document.removeEventListener("touchstart",j),document.removeEventListener("touchend",j)}function j(w){w.target.nodeName&&w.target.nodeName.toLowerCase()==="html"||(o=!1,B())}document.addEventListener("keydown",m,!0),document.addEventListener("mousedown",f,!0),document.addEventListener("pointerdown",f,!0),document.addEventListener("touchstart",f,!0),document.addEventListener("visibilitychange",h,!0),W(),r.addEventListener("focus",d,!0),r.addEventListener("blur",v,!0),r.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&r.host?r.host.setAttribute("data-js-focus-visible",""):r.nodeType===Node.DOCUMENT_NODE&&(document.documentElement.classList.add("js-focus-visible"),document.documentElement.setAttribute("data-js-focus-visible",""))}if(typeof window!="undefined"&&typeof document!="undefined"){window.applyFocusVisiblePolyfill=e;var t;try{t=new CustomEvent("focus-visible-polyfill-ready")}catch(r){t=document.createEvent("CustomEvent"),t.initCustomEvent("focus-visible-polyfill-ready",!1,!1,{})}window.dispatchEvent(t)}typeof document!="undefined"&&e(document)})});var vo=Et((cs,_t)=>{/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */var Yr,Gr,Xr,Zr,eo,to,ro,oo,no,Tt,sr,io,ao,so,Ke,co,lo,po,uo,fo,mo,ho,bo,Ot;(function(e){var t=typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:{};typeof define=="function"&&define.amd?define("tslib",["exports"],function(o){e(r(t,r(o)))}):typeof _t=="object"&&typeof _t.exports=="object"?e(r(t,r(_t.exports))):e(r(t));function r(o,n){return o!==t&&(typeof Object.create=="function"?Object.defineProperty(o,"__esModule",{value:!0}):o.__esModule=!0),function(i,a){return o[i]=n?n(i,a):a}}})(function(e){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,n){o.__proto__=n}||function(o,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(o[i]=n[i])};Yr=function(o,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");t(o,n);function i(){this.constructor=o}o.prototype=n===null?Object.create(n):(i.prototype=n.prototype,new i)},Gr=Object.assign||function(o){for(var n,i=1,a=arguments.length;i=0;p--)(l=o[p])&&(c=(s<3?l(c):s>3?l(n,i,c):l(n,i))||c);return s>3&&c&&Object.defineProperty(n,i,c),c},eo=function(o,n){return function(i,a){n(i,a,o)}},to=function(o,n){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,n)},ro=function(o,n,i,a){function s(c){return c instanceof i?c:new i(function(l){l(c)})}return new(i||(i=Promise))(function(c,l){function p(d){try{f(a.next(d))}catch(v){l(v)}}function m(d){try{f(a.throw(d))}catch(v){l(v)}}function f(d){d.done?c(d.value):s(d.value).then(p,m)}f((a=a.apply(o,n||[])).next())})},oo=function(o,n){var i={label:0,sent:function(){if(c[0]&1)throw c[1];return c[1]},trys:[],ops:[]},a,s,c,l;return l={next:p(0),throw:p(1),return:p(2)},typeof Symbol=="function"&&(l[Symbol.iterator]=function(){return this}),l;function p(f){return function(d){return m([f,d])}}function m(f){if(a)throw new TypeError("Generator is already executing.");for(;i;)try{if(a=1,s&&(c=f[0]&2?s.return:f[0]?s.throw||((c=s.return)&&c.call(s),0):s.next)&&!(c=c.call(s,f[1])).done)return c;switch(s=0,c&&(f=[f[0]&2,c.value]),f[0]){case 0:case 1:c=f;break;case 4:return i.label++,{value:f[1],done:!1};case 5:i.label++,s=f[1],f=[0];continue;case 7:f=i.ops.pop(),i.trys.pop();continue;default:if(c=i.trys,!(c=c.length>0&&c[c.length-1])&&(f[0]===6||f[0]===2)){i=0;continue}if(f[0]===3&&(!c||f[1]>c[0]&&f[1]=o.length&&(o=void 0),{value:o&&o[a++],done:!o}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")},sr=function(o,n){var i=typeof Symbol=="function"&&o[Symbol.iterator];if(!i)return o;var a=i.call(o),s,c=[],l;try{for(;(n===void 0||n-- >0)&&!(s=a.next()).done;)c.push(s.value)}catch(p){l={error:p}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(l)throw l.error}}return c},io=function(){for(var o=[],n=0;n1||p(h,W)})})}function p(h,W){try{m(a[h](W))}catch(B){v(c[0][3],B)}}function m(h){h.value instanceof Ke?Promise.resolve(h.value.v).then(f,d):v(c[0][2],h)}function f(h){p("next",h)}function d(h){p("throw",h)}function v(h,W){h(W),c.shift(),c.length&&p(c[0][0],c[0][1])}},lo=function(o){var n,i;return n={},a("next"),a("throw",function(s){throw s}),a("return"),n[Symbol.iterator]=function(){return this},n;function a(s,c){n[s]=o[s]?function(l){return(i=!i)?{value:Ke(o[s](l)),done:s==="return"}:c?c(l):l}:c}},po=function(o){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=o[Symbol.asyncIterator],i;return n?n.call(o):(o=typeof Tt=="function"?Tt(o):o[Symbol.iterator](),i={},a("next"),a("throw"),a("return"),i[Symbol.asyncIterator]=function(){return this},i);function a(c){i[c]=o[c]&&function(l){return new Promise(function(p,m){l=o[c](l),s(p,m,l.done,l.value)})}}function s(c,l,p,m){Promise.resolve(m).then(function(f){c({value:f,done:p})},l)}},uo=function(o,n){return Object.defineProperty?Object.defineProperty(o,"raw",{value:n}):o.raw=n,o};var r=Object.create?function(o,n){Object.defineProperty(o,"default",{enumerable:!0,value:n})}:function(o,n){o.default=n};fo=function(o){if(o&&o.__esModule)return o;var n={};if(o!=null)for(var i in o)i!=="default"&&Object.prototype.hasOwnProperty.call(o,i)&&Ot(n,o,i);return r(n,o),n},mo=function(o){return o&&o.__esModule?o:{default:o}},ho=function(o,n){if(!n.has(o))throw new TypeError("attempted to get private field on non-instance");return n.get(o)},bo=function(o,n,i){if(!n.has(o))throw new TypeError("attempted to set private field on non-instance");return n.set(o,i),i},e("__extends",Yr),e("__assign",Gr),e("__rest",Xr),e("__decorate",Zr),e("__param",eo),e("__metadata",to),e("__awaiter",ro),e("__generator",oo),e("__exportStar",no),e("__createBinding",Ot),e("__values",Tt),e("__read",sr),e("__spread",io),e("__spreadArrays",ao),e("__spreadArray",so),e("__await",Ke),e("__asyncGenerator",co),e("__asyncDelegator",lo),e("__asyncValues",po),e("__makeTemplateObject",uo),e("__importStar",fo),e("__importDefault",mo),e("__classPrivateFieldGet",ho),e("__classPrivateFieldSet",bo)})});var Fr=Et((gt,jr)=>{/*! + * clipboard.js v2.0.8 + * https://clipboardjs.com/ + * + * Licensed MIT © Zeno Rocha + */(function(t,r){typeof gt=="object"&&typeof jr=="object"?jr.exports=r():typeof define=="function"&&define.amd?define([],r):typeof gt=="object"?gt.ClipboardJS=r():t.ClipboardJS=r()})(gt,function(){return function(){var e={134:function(o,n,i){"use strict";i.d(n,{default:function(){return Xi}});var a=i(279),s=i.n(a),c=i(370),l=i.n(c),p=i(817),m=i.n(p);function f(_){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?f=function(b){return typeof b}:f=function(b){return b&&typeof Symbol=="function"&&b.constructor===Symbol&&b!==Symbol.prototype?"symbol":typeof b},f(_)}function d(_,x){if(!(_ instanceof x))throw new TypeError("Cannot call a class as a function")}function v(_,x){for(var b=0;b0&&arguments[0]!==void 0?arguments[0]:{};this.action=b.action,this.container=b.container,this.emitter=b.emitter,this.target=b.target,this.text=b.text,this.trigger=b.trigger,this.selectedText=""}},{key:"initSelection",value:function(){this.text?this.selectFake():this.target&&this.selectTarget()}},{key:"createFakeElement",value:function(){var b=document.documentElement.getAttribute("dir")==="rtl";this.fakeElem=document.createElement("textarea"),this.fakeElem.style.fontSize="12pt",this.fakeElem.style.border="0",this.fakeElem.style.padding="0",this.fakeElem.style.margin="0",this.fakeElem.style.position="absolute",this.fakeElem.style[b?"right":"left"]="-9999px";var k=window.pageYOffset||document.documentElement.scrollTop;return this.fakeElem.style.top="".concat(k,"px"),this.fakeElem.setAttribute("readonly",""),this.fakeElem.value=this.text,this.fakeElem}},{key:"selectFake",value:function(){var b=this,k=this.createFakeElement();this.fakeHandlerCallback=function(){return b.removeFake()},this.fakeHandler=this.container.addEventListener("click",this.fakeHandlerCallback)||!0,this.container.appendChild(k),this.selectedText=m()(k),this.copyText(),this.removeFake()}},{key:"removeFake",value:function(){this.fakeHandler&&(this.container.removeEventListener("click",this.fakeHandlerCallback),this.fakeHandler=null,this.fakeHandlerCallback=null),this.fakeElem&&(this.container.removeChild(this.fakeElem),this.fakeElem=null)}},{key:"selectTarget",value:function(){this.selectedText=m()(this.target),this.copyText()}},{key:"copyText",value:function(){var b;try{b=document.execCommand(this.action)}catch(k){b=!1}this.handleResult(b)}},{key:"handleResult",value:function(b){this.emitter.emit(b?"success":"error",{action:this.action,text:this.selectedText,trigger:this.trigger,clearSelection:this.clearSelection.bind(this)})}},{key:"clearSelection",value:function(){this.trigger&&this.trigger.focus(),document.activeElement.blur(),window.getSelection().removeAllRanges()}},{key:"destroy",value:function(){this.removeFake()}},{key:"action",set:function(){var b=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"copy";if(this._action=b,this._action!=="copy"&&this._action!=="cut")throw new Error('Invalid "action" value, use either "copy" or "cut"')},get:function(){return this._action}},{key:"target",set:function(b){if(b!==void 0)if(b&&f(b)==="object"&&b.nodeType===1){if(this.action==="copy"&&b.hasAttribute("disabled"))throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute');if(this.action==="cut"&&(b.hasAttribute("readonly")||b.hasAttribute("disabled")))throw new Error(`Invalid "target" attribute. You can't cut text from elements with "readonly" or "disabled" attributes`);this._target=b}else throw new Error('Invalid "target" value, use a valid Element')},get:function(){return this._target}}]),_}(),B=W;function j(_){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?j=function(b){return typeof b}:j=function(b){return b&&typeof Symbol=="function"&&b.constructor===Symbol&&b!==Symbol.prototype?"symbol":typeof b},j(_)}function w(_,x){if(!(_ instanceof x))throw new TypeError("Cannot call a class as a function")}function We(_,x){for(var b=0;b0&&arguments[0]!==void 0?arguments[0]:{};this.action=typeof R.action=="function"?R.action:this.defaultAction,this.target=typeof R.target=="function"?R.target:this.defaultTarget,this.text=typeof R.text=="function"?R.text:this.defaultText,this.container=j(R.container)==="object"?R.container:document.body}},{key:"listenClick",value:function(R){var Z=this;this.listener=l()(R,"click",function(lt){return Z.onClick(lt)})}},{key:"onClick",value:function(R){var Z=R.delegateTarget||R.currentTarget;this.clipboardAction&&(this.clipboardAction=null),this.clipboardAction=new B({action:this.action(Z),target:this.target(Z),text:this.text(Z),container:this.container,trigger:Z,emitter:this})}},{key:"defaultAction",value:function(R){return nr("action",R)}},{key:"defaultTarget",value:function(R){var Z=nr("target",R);if(Z)return document.querySelector(Z)}},{key:"defaultText",value:function(R){return nr("text",R)}},{key:"destroy",value:function(){this.listener.destroy(),this.clipboardAction&&(this.clipboardAction.destroy(),this.clipboardAction=null)}}],[{key:"isSupported",value:function(){var R=arguments.length>0&&arguments[0]!==void 0?arguments[0]:["copy","cut"],Z=typeof R=="string"?[R]:R,lt=!!document.queryCommandSupported;return Z.forEach(function(Zi){lt=lt&&!!document.queryCommandSupported(Zi)}),lt}}]),b}(s()),Xi=Gi},828:function(o){var n=9;if(typeof Element!="undefined"&&!Element.prototype.matches){var i=Element.prototype;i.matches=i.matchesSelector||i.mozMatchesSelector||i.msMatchesSelector||i.oMatchesSelector||i.webkitMatchesSelector}function a(s,c){for(;s&&s.nodeType!==n;){if(typeof s.matches=="function"&&s.matches(c))return s;s=s.parentNode}}o.exports=a},438:function(o,n,i){var a=i(828);function s(p,m,f,d,v){var h=l.apply(this,arguments);return p.addEventListener(f,h,v),{destroy:function(){p.removeEventListener(f,h,v)}}}function c(p,m,f,d,v){return typeof p.addEventListener=="function"?s.apply(null,arguments):typeof f=="function"?s.bind(null,document).apply(null,arguments):(typeof p=="string"&&(p=document.querySelectorAll(p)),Array.prototype.map.call(p,function(h){return s(h,m,f,d,v)}))}function l(p,m,f,d){return function(v){v.delegateTarget=a(v.target,m),v.delegateTarget&&d.call(p,v)}}o.exports=c},879:function(o,n){n.node=function(i){return i!==void 0&&i instanceof HTMLElement&&i.nodeType===1},n.nodeList=function(i){var a=Object.prototype.toString.call(i);return i!==void 0&&(a==="[object NodeList]"||a==="[object HTMLCollection]")&&"length"in i&&(i.length===0||n.node(i[0]))},n.string=function(i){return typeof i=="string"||i instanceof String},n.fn=function(i){var a=Object.prototype.toString.call(i);return a==="[object Function]"}},370:function(o,n,i){var a=i(879),s=i(438);function c(f,d,v){if(!f&&!d&&!v)throw new Error("Missing required arguments");if(!a.string(d))throw new TypeError("Second argument must be a String");if(!a.fn(v))throw new TypeError("Third argument must be a Function");if(a.node(f))return l(f,d,v);if(a.nodeList(f))return p(f,d,v);if(a.string(f))return m(f,d,v);throw new TypeError("First argument must be a String, HTMLElement, HTMLCollection, or NodeList")}function l(f,d,v){return f.addEventListener(d,v),{destroy:function(){f.removeEventListener(d,v)}}}function p(f,d,v){return Array.prototype.forEach.call(f,function(h){h.addEventListener(d,v)}),{destroy:function(){Array.prototype.forEach.call(f,function(h){h.removeEventListener(d,v)})}}}function m(f,d,v){return s(document.body,f,d,v)}o.exports=c},817:function(o){function n(i){var a;if(i.nodeName==="SELECT")i.focus(),a=i.value;else if(i.nodeName==="INPUT"||i.nodeName==="TEXTAREA"){var s=i.hasAttribute("readonly");s||i.setAttribute("readonly",""),i.select(),i.setSelectionRange(0,i.value.length),s||i.removeAttribute("readonly"),a=i.value}else{i.hasAttribute("contenteditable")&&i.focus();var c=window.getSelection(),l=document.createRange();l.selectNodeContents(i),c.removeAllRanges(),c.addRange(l),a=c.toString()}return a}o.exports=n},279:function(o){function n(){}n.prototype={on:function(i,a,s){var c=this.e||(this.e={});return(c[i]||(c[i]=[])).push({fn:a,ctx:s}),this},once:function(i,a,s){var c=this;function l(){c.off(i,l),a.apply(s,arguments)}return l._=a,this.on(i,l,s)},emit:function(i){var a=[].slice.call(arguments,1),s=((this.e||(this.e={}))[i]||[]).slice(),c=0,l=s.length;for(c;c{/*! + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu + * MIT Licensed + */"use strict";var Qa=/["'&<>]/;gi.exports=Ka;function Ka(e){var t=""+e,r=Qa.exec(t);if(!r)return t;var o,n="",i=0,a=0;for(i=r.index;i0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(r){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,r)},t.prototype._subscribe=function(r){return this._throwIfClosed(),this._checkFinalizedStatuses(r),this._innerSubscribe(r)},t.prototype._innerSubscribe=function(r){var o=this,n=o.hasError,i=o.isStopped,a=o.observers;return n||i?cr:(a.push(r),new ae(function(){return Oe(a,r)}))},t.prototype._checkFinalizedStatuses=function(r){var o=this,n=o.hasError,i=o.thrownError,a=o.isStopped;n?r.error(i):a&&r.complete()},t.prototype.asObservable=function(){var r=new A;return r.source=this,r},t.create=function(r,o){return new Co(r,o)},t}(A);var Co=function(e){G(t,e);function t(r,o){var n=e.call(this)||this;return n.destination=r,n.source=o,n}return t.prototype.next=function(r){var o,n;(n=(o=this.destination)===null||o===void 0?void 0:o.next)===null||n===void 0||n.call(o,r)},t.prototype.error=function(r){var o,n;(n=(o=this.destination)===null||o===void 0?void 0:o.error)===null||n===void 0||n.call(o,r)},t.prototype.complete=function(){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.complete)===null||o===void 0||o.call(r)},t.prototype._subscribe=function(r){var o,n;return(n=(o=this.source)===null||o===void 0?void 0:o.subscribe(r))!==null&&n!==void 0?n:cr},t}(T);var mt={now:function(){return(mt.delegate||Date).now()},delegate:void 0};var dt=function(e){G(t,e);function t(r,o,n){r===void 0&&(r=1/0),o===void 0&&(o=1/0),n===void 0&&(n=mt);var i=e.call(this)||this;return i._bufferSize=r,i._windowTime=o,i._timestampProvider=n,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=o===1/0,i._bufferSize=Math.max(1,r),i._windowTime=Math.max(1,o),i}return t.prototype.next=function(r){var o=this,n=o.isStopped,i=o._buffer,a=o._infiniteTimeWindow,s=o._timestampProvider,c=o._windowTime;n||(i.push(r),!a&&i.push(s.now()+c)),this._trimBuffer(),e.prototype.next.call(this,r)},t.prototype._subscribe=function(r){this._throwIfClosed(),this._trimBuffer();for(var o=this._innerSubscribe(r),n=this,i=n._infiniteTimeWindow,a=n._buffer,s=a.slice(),c=0;c0?e.prototype.requestAsyncId.call(this,r,o,n):(r.actions.push(this),r._scheduled||(r._scheduled=Ye.requestAnimationFrame(function(){return r.flush(void 0)})))},t.prototype.recycleAsyncId=function(r,o,n){if(n===void 0&&(n=0),n!=null&&n>0||n==null&&this.delay>0)return e.prototype.recycleAsyncId.call(this,r,o,n);r.actions.length===0&&(Ye.cancelAnimationFrame(o),r._scheduled=void 0)},t}(jt);var Fo=function(e){G(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.flush=function(r){this._active=!0,this._scheduled=void 0;var o=this.actions,n,i=-1;r=r||o.shift();var a=o.length;do if(n=r.execute(r.state,r.delay))break;while(++i=2,!0))}function ie(e){e===void 0&&(e={});var t=e.connector,r=t===void 0?function(){return new T}:t,o=e.resetOnError,n=o===void 0?!0:o,i=e.resetOnComplete,a=i===void 0?!0:i,s=e.resetOnRefCountZero,c=s===void 0?!0:s;return function(l){var p=null,m=null,f=null,d=0,v=!1,h=!1,W=function(){m==null||m.unsubscribe(),m=null},B=function(){W(),p=f=null,v=h=!1},j=function(){var w=p;B(),w==null||w.unsubscribe()};return g(function(w,We){d++,!h&&!v&&W();var Te=f=f!=null?f:r();We.add(function(){d--,d===0&&!h&&!v&&(m=Tr(j,c))}),Te.subscribe(We),p||(p=new ft({next:function(Qe){return Te.next(Qe)},error:function(Qe){h=!0,W(),m=Tr(B,n,Qe),Te.error(Qe)},complete:function(){v=!0,W(),m=Tr(B,a),Te.complete()}}),ye(w).subscribe(p))})(l)}}function Tr(e,t){for(var r=[],o=2;ot==="focus"),N(e===De()))}var rn=new T,Ha=_e(()=>F(new ResizeObserver(e=>{for(let t of e)rn.next(t)}))).pipe(O(e=>J.pipe(N(e)).pipe(I(()=>e.disconnect()))),re(1));function Fe(e){return{width:e.offsetWidth,height:e.offsetHeight}}function Bt(e){return{width:e.scrollWidth,height:e.scrollHeight}}function Ie(e){return Ha.pipe(L(t=>t.observe(e)),O(t=>rn.pipe(M(({target:r})=>r===e),I(()=>t.unobserve(e)),u(()=>Fe(e)))),N(Fe(e)))}function on(e){return{x:e.scrollLeft,y:e.scrollTop}}function ja(e){return $(E(e,"scroll"),E(window,"resize")).pipe(u(()=>on(e)),N(on(e)))}function nn(e,t=16){return ja(e).pipe(u(({y:r})=>{let o=Fe(e),n=Bt(e);return r>=n.height-o.height-t}),D())}function an(e){if(e instanceof HTMLInputElement)e.select();else throw new Error("Not implemented")}var Jt={drawer:he("[data-md-toggle=drawer]"),search:he("[data-md-toggle=search]")};function sn(e){return Jt[e].checked}function Re(e,t){Jt[e].checked!==t&&Jt[e].click()}function Yt(e){let t=Jt[e];return E(t,"change").pipe(u(()=>t.checked),N(t.checked))}function Fa(e){switch(e.tagName){case"INPUT":case"SELECT":case"TEXTAREA":return!0;default:return e.isContentEditable}}function cn(){return E(window,"keydown").pipe(M(e=>!(e.metaKey||e.ctrlKey)),u(e=>({mode:sn("search")?"search":"global",type:e.key,claim(){e.preventDefault(),e.stopPropagation()}})),M(({mode:e})=>{if(e==="global"){let t=De();if(typeof t!="undefined")return!Fa(t)}return!0}),ie())}function Pe(){return new URL(location.href)}function ln(e){location.href=e.href}function pn(){return new T}function un(){return location.hash.substring(1)}function fn(e){let t=nt("a");t.href=e,t.addEventListener("click",r=>r.stopPropagation()),t.click()}function Ia(){return E(window,"hashchange").pipe(u(un),N(un()),M(e=>e.length>0),ie())}function mn(){return Ia().pipe(O(e=>F(se(`[id="${e}"]`))))}function xt(e){let t=matchMedia(e);return Qt(r=>t.addListener(()=>r(t.matches))).pipe(N(t.matches))}function dn(){return E(window,"beforeprint").pipe(oe(void 0))}function Cr(e,t){return e.pipe(O(r=>r?t():J))}function Gt(e,t={credentials:"same-origin"}){return ye(fetch(`${e}`,t)).pipe(M(r=>r.status===200))}function we(e,t){return Gt(e,t).pipe(O(r=>r.json()),re(1))}function hn(e,t){let r=new DOMParser;return Gt(e,t).pipe(O(o=>o.text()),u(o=>r.parseFromString(o,"text/xml")),re(1))}function bn(){return{x:Math.max(0,pageXOffset),y:Math.max(0,pageYOffset)}}function Hr({x:e,y:t}){window.scrollTo(e||0,t||0)}function vn(){return $(E(window,"scroll",{passive:!0}),E(window,"resize",{passive:!0})).pipe(u(bn),N(bn()))}function xn(){return{width:innerWidth,height:innerHeight}}function gn(){return E(window,"resize",{passive:!0}).pipe(u(xn),N(xn()))}function yn(){return Q([vn(),gn()]).pipe(u(([e,t])=>({offset:e,size:t})),re(1))}function Xt(e,{viewport$:t,header$:r}){let o=t.pipe(U("size")),n=Q([o,r]).pipe(u(()=>({x:e.offsetLeft,y:e.offsetTop})));return Q([r,t,n]).pipe(u(([{height:i},{offset:a,size:s},{x:c,y:l}])=>({offset:{x:a.x-c,y:a.y-l+i},size:s})))}function Sn(e,{tx$:t}){let r=E(e,"message").pipe(u(({data:o})=>o));return t.pipe(Lr(()=>r,{leading:!0,trailing:!0}),L(o=>e.postMessage(o)),_r(r),ie())}var Ra=he("#__config"),it=JSON.parse(Ra.textContent);it.base=new URL(it.base,Pe()).toString().replace(/\/$/,"");function ce(){return it}function Ae(e){return it.features.includes(e)}function Y(e,t){return typeof t!="undefined"?it.translations[e].replace("#",t.toString()):it.translations[e]}function Ee(e,t=document){return he(`[data-md-component=${e}]`,t)}function ne(e,t=document){return K(`[data-md-component=${e}]`,t)}var ii=pt(Fr());function wn(e,t=0){e.setAttribute("tabindex",t.toString())}function En(e){e.removeAttribute("tabindex")}function Tn(e,t){e.setAttribute("data-md-state","lock"),e.style.top=`-${t}px`}function On(e){let t=-1*parseInt(e.style.top,10);e.removeAttribute("data-md-state"),e.style.top="",t&&window.scrollTo(0,t)}function _n(e,t){e.setAttribute("data-md-state",t)}function Mn(e){e.removeAttribute("data-md-state")}function An(e,t){e.classList.toggle("md-nav__link--active",t)}function Ln(e){e.classList.remove("md-nav__link--active")}function kn(e,t){e.firstElementChild.innerHTML=t}function Cn(e,t){e.setAttribute("data-md-state",t)}function Hn(e){e.removeAttribute("data-md-state")}function jn(e,t){e.setAttribute("data-md-state",t)}function Fn(e){e.removeAttribute("data-md-state")}function In(e,t){e.setAttribute("data-md-state",t)}function Rn(e){e.removeAttribute("data-md-state")}function Pn(e,t){e.placeholder=t}function $n(e){e.placeholder=Y("search.placeholder")}function Wn(e,t){if(typeof t=="string"||typeof t=="number")e.innerHTML+=t.toString();else if(t instanceof Node)e.appendChild(t);else if(Array.isArray(t))for(let r of t)Wn(e,r)}function V(e,t,...r){let o=document.createElement(e);if(t)for(let n of Object.keys(t))typeof t[n]!="boolean"?o.setAttribute(n,t[n]):t[n]&&o.setAttribute(n,"");for(let n of r)Wn(o,n);return o}function Vn(e,t){let r=t;if(e.length>r){for(;e[r]!==" "&&--r>0;);return`${e.substring(0,r)}...`}return e}function Zt(e){if(e>999){let t=+((e-950)%1e3>99);return`${((e+1e-6)/1e3).toFixed(t)}k`}else return e.toString()}function Un(e,t){switch(t){case 0:e.textContent=Y("search.result.none");break;case 1:e.textContent=Y("search.result.one");break;default:e.textContent=Y("search.result.other",Zt(t))}}function Ir(e){e.textContent=Y("search.result.placeholder")}function Nn(e,t){e.appendChild(t)}function Dn(e){e.innerHTML=""}function zn(e,t){e.style.top=`${t}px`}function qn(e){e.style.top=""}function Qn(e,t){let r=e.firstElementChild;r.style.height=`${t-2*r.offsetTop}px`}function Kn(e){let t=e.firstElementChild;t.style.height=""}function Bn(e,t){e.lastElementChild.appendChild(t)}function Jn(e,t){e.lastElementChild.setAttribute("data-md-state",t)}function Yn(e,t){e.setAttribute("data-md-state",t)}function Rr(e){e.removeAttribute("data-md-state")}function Gn(e,t){e.setAttribute("data-md-state",t)}function Pr(e){e.removeAttribute("data-md-state")}function Xn(e,t){e.style.top=`${t}px`}function Zn(e){e.style.top=""}function ei(e){return V("button",{class:"md-clipboard md-icon",title:Y("clipboard.copy"),"data-clipboard-target":`#${e} > code`})}var qe;(function(r){r[r.TEASER=1]="TEASER",r[r.PARENT=2]="PARENT"})(qe||(qe={}));function $r(e,t){let r=t&2,o=t&1,n=Object.keys(e.terms).filter(a=>!e.terms[a]).map(a=>[V("del",null,a)," "]).flat().slice(0,-1),i=new URL(e.location);return Ae("search.highlight")&&i.searchParams.set("h",Object.entries(e.terms).filter(([,a])=>a).reduce((a,[s])=>`${a} ${s}`.trim(),"")),V("a",{href:`${i}`,class:"md-search-result__link",tabIndex:-1},V("article",{class:["md-search-result__article",...r?["md-search-result__article--document"]:[]].join(" "),"data-md-score":e.score.toFixed(2)},r>0&&V("div",{class:"md-search-result__icon md-icon"}),V("h1",{class:"md-search-result__title"},e.title),o>0&&e.text.length>0&&V("p",{class:"md-search-result__teaser"},Vn(e.text,320)),o>0&&n.length>0&&V("p",{class:"md-search-result__terms"},Y("search.result.term.missing"),": ",n)))}function ti(e){let t=e[0].score,r=[...e],o=r.findIndex(l=>!l.location.includes("#")),[n]=r.splice(o,1),i=r.findIndex(l=>l.score$r(l,1)),...s.length?[V("details",{class:"md-search-result__more"},V("summary",{tabIndex:-1},s.length>0&&s.length===1?Y("search.result.more.one"):Y("search.result.more.other",s.length)),s.map(l=>$r(l,1)))]:[]];return V("li",{class:"md-search-result__item"},c)}function ri(e){return V("ul",{class:"md-source__facts"},Object.entries(e).map(([t,r])=>V("li",{class:`md-source__fact md-source__fact--${t}`},typeof r=="number"?Zt(r):r)))}function oi(e){return V("div",{class:"md-typeset__scrollwrap"},V("div",{class:"md-typeset__table"},e))}function Pa(e){let t=ce(),r=new URL(`${e.version}/`,t.base);return V("li",{class:"md-version__item"},V("a",{href:r.toString(),class:"md-version__link"},e.title))}function ni(e){let t=ce(),[,r]=t.base.match(/([^/]+)\/?$/),o=e.find(({version:n,aliases:i})=>n===r||i.includes(r))||e[0];return V("div",{class:"md-version"},V("button",{class:"md-version__current","aria-label":Y("select.version.title")},o.title),V("ul",{class:"md-version__list"},e.map(Pa)))}var $a=0;function Wa(e,{viewport$:t}){let r=F(e).pipe(O(o=>{let n=o.closest("[data-tabs]");return n instanceof HTMLElement?$(...K("input",n).map(i=>E(i,"change"))):J}));return $(t.pipe(U("size")),r).pipe(u(()=>{let o=Fe(e);return{scroll:Bt(e).width>o.width}}),U("scroll"))}function ai(e,t){let r=new T;if(r.pipe(ue(xt("(hover)"))).subscribe(([{scroll:o},n])=>{o&&n?wn(e):En(e)}),ii.default.isSupported()){let o=e.closest("pre");o.id=`__code_${$a++}`,o.insertBefore(ei(o.id),e)}return Wa(e,t).pipe(L(r),I(()=>r.complete()),u(o=>P({ref:e},o)))}function Va(e,{target$:t,print$:r}){return t.pipe(u(o=>o.closest("details:not([open])")),M(o=>e===o),Ne(r),oe(e))}function si(e,t){let r=new T;return r.subscribe(()=>{e.setAttribute("open",""),e.scrollIntoView()}),Va(e,t).pipe(L(r),I(()=>r.complete()),oe({ref:e}))}var ci=nt("table");function li(e){return ze(e,ci),ze(ci,oi(e)),F({ref:e})}function pi(e,{target$:t,viewport$:r,print$:o}){return $(...K("pre > code",e).map(n=>ai(n,{viewport$:r})),...K("table:not([class])",e).map(n=>li(n)),...K("details",e).map(n=>si(n,{target$:t,print$:o})))}function Ua(e,{alert$:t}){return t.pipe(O(r=>$(F(!0),F(!1).pipe(Me(2e3))).pipe(u(o=>({message:r,open:o})))))}function ui(e,t){let r=new T;return r.pipe(q(X)).subscribe(({message:o,open:n})=>{kn(e,o),n?Cn(e,"open"):Hn(e)}),Ua(e,t).pipe(L(r),I(()=>r.complete()),u(o=>P({ref:e},o)))}function Na({viewport$:e}){if(!Ae("header.autohide"))return F(!1);let t=e.pipe(u(({offset:{y:n}})=>n),xe(2,1),u(([n,i])=>[nMath.abs(i-n.y)>100),u(([,[n]])=>n),D()),o=Yt("search");return Q([e,o]).pipe(u(([{offset:n},i])=>n.y>400&&!i),D(),O(n=>n?r:F(!1)),N(!1))}function fi(e,t){return _e(()=>{let r=getComputedStyle(e);return F(r.position==="sticky"||r.position==="-webkit-sticky")}).pipe(rt(Ie(e),Na(t)),u(([r,{height:o},n])=>({height:r?o:0,sticky:r,hidden:n})),D((r,o)=>r.sticky===o.sticky&&r.height===o.height&&r.hidden===o.hidden),re(1))}function mi(e,{header$:t,main$:r}){let o=new T;return o.pipe(U("active"),rt(t),q(X)).subscribe(([{active:n},{hidden:i}])=>{n?jn(e,i?"hidden":"shadow"):Fn(e)}),r.subscribe(n=>o.next(n)),t.pipe(u(n=>P({ref:e},n)))}function Da(e,{viewport$:t,header$:r}){return Xt(e,{header$:r,viewport$:t}).pipe(u(({offset:{y:o}})=>{let{height:n}=Fe(e);return{active:o>=n}}),U("active"))}function di(e,t){let r=new T;r.pipe(q(X)).subscribe(({active:n})=>{n?In(e,"active"):Rn(e)});let o=se("article h1");return typeof o=="undefined"?J:Da(o,t).pipe(L(r),I(()=>r.complete()),u(n=>P({ref:e},n)))}function hi(e,{viewport$:t,header$:r}){let o=r.pipe(u(({height:i})=>i),D()),n=o.pipe(O(()=>Ie(e).pipe(u(({height:i})=>({top:e.offsetTop,bottom:e.offsetTop+i})),U("bottom"))));return Q([o,n,t]).pipe(u(([i,{top:a,bottom:s},{offset:{y:c},size:{height:l}}])=>(l=Math.max(0,l-Math.max(0,a-c,i)-Math.max(0,l+c-s)),{offset:a-i,height:l,active:a-i<=c})),D((i,a)=>i.offset===a.offset&&i.height===a.height&&i.active===a.active))}function za(e){let t=localStorage.getItem(__prefix("__palette")),r=JSON.parse(t)||{index:e.findIndex(n=>matchMedia(n.getAttribute("data-md-color-media")).matches)},o=F(...e).pipe(te(n=>E(n,"change").pipe(oe(n))),N(e[Math.max(0,r.index)]),u(n=>({index:e.indexOf(n),color:{scheme:n.getAttribute("data-md-color-scheme"),primary:n.getAttribute("data-md-color-primary"),accent:n.getAttribute("data-md-color-accent")}})),re(1));return o.subscribe(n=>{localStorage.setItem(__prefix("__palette"),JSON.stringify(n))}),o}function bi(e){let t=new T;t.subscribe(o=>{for(let[n,i]of Object.entries(o.color))typeof i=="string"&&document.body.setAttribute(`data-md-color-${n}`,i);for(let n=0;nt.complete()),u(o=>P({ref:e},o)))}var Wr=pt(Fr());function vi({alert$:e}){Wr.default.isSupported()&&new A(t=>{new Wr.default("[data-clipboard-target], [data-clipboard-text]").on("success",r=>t.next(r))}).subscribe(()=>e.next(Y("clipboard.copied")))}function qa(e){if(e.length<2)return e;let[t,r]=e.sort((i,a)=>i.length-a.length).map(i=>i.replace(/[^/]+$/,"")),o=0;if(t===r)o=t.length;else for(;t.charCodeAt(o)===r.charCodeAt(o);)o++;let n=ce();return e.map(i=>i.replace(t.slice(0,o),`${n.base}/`))}function xi({document$:e,location$:t,viewport$:r}){let o=ce();if(location.protocol==="file:")return;"scrollRestoration"in history&&(history.scrollRestoration="manual",E(window,"beforeunload").subscribe(()=>{history.scrollRestoration="auto"}));let n=se("link[rel=icon]");typeof n!="undefined"&&(n.href=n.href);let i=hn(`${o.base}/sitemap.xml`).pipe(u(l=>qa(K("loc",l).map(p=>p.textContent))),O(l=>E(document.body,"click").pipe(M(p=>!p.metaKey&&!p.ctrlKey),O(p=>{if(p.target instanceof Element){let m=p.target.closest("a");if(m&&!m.target&&l.includes(m.href))return p.preventDefault(),F({url:new URL(m.href)})}return J}))),ie()),a=E(window,"popstate").pipe(M(l=>l.state!==null),u(l=>({url:new URL(location.href),offset:l.state})),ie());$(i,a).pipe(D((l,p)=>l.url.href===p.url.href),u(({url:l})=>l)).subscribe(t);let s=t.pipe(U("pathname"),O(l=>Gt(l.href).pipe(tt(()=>(ln(l),J)))),ie());i.pipe(ot(s)).subscribe(({url:l})=>{history.pushState({},"",`${l}`)});let c=new DOMParser;s.pipe(O(l=>l.text()),u(l=>c.parseFromString(l,"text/html"))).subscribe(e),$(i,a).pipe(ot(e)).subscribe(({url:l,offset:p})=>{l.hash&&!p?fn(l.hash):Hr(p||{y:0})}),e.pipe(Kt(1)).subscribe(l=>{for(let p of["title","link[rel=canonical]","meta[name=author]","meta[name=description]","[data-md-component=announce]","[data-md-component=container]","[data-md-component=header-topic]","[data-md-component=logo], .md-logo","[data-md-component=skip]"]){let m=se(p),f=se(p,l);typeof m!="undefined"&&typeof f!="undefined"&&ze(m,f)}}),e.pipe(Kt(1),u(()=>Ee("container")),O(l=>F(...K("script",l))),gr(l=>{let p=nt("script");if(l.src){for(let m of l.getAttributeNames())p.setAttribute(m,l.getAttribute(m));return ze(l,p),new A(m=>{p.onload=()=>m.complete()})}else return p.textContent=l.textContent,ze(l,p),ve})).subscribe(),r.pipe(Or(i),yr(250),U("offset")).subscribe(({offset:l})=>{history.replaceState(l,"")}),$(i,a).pipe(xe(2,1),M(([l,p])=>l.url.pathname===p.url.pathname),u(([,l])=>l)).subscribe(({offset:l})=>{Hr(l||{y:0})})}var Ba=pt(yi());function Vr(e){let t=new RegExp(e.separator,"img"),r=(o,n,i)=>`${n}${i}`;return o=>{o=o.replace(/[\s*+\-:~^]+/g," ").trim();let n=new RegExp(`(^|${e.separator})(${o.replace(/[|\\{}()[\]^$+*?.-]/g,"\\$&").replace(t,"|")})`,"img");return i=>i.replace(n,r).replace(/<\/mark>(\s+)]*>/img,"$1")}}function Si(e){return e.split(/"([^"]+)"/g).map((t,r)=>r&1?t.replace(/^\b|^(?![^\x00-\x7F]|$)|\s+/g," +"):t).join("").replace(/"|(?:^|\s+)[*+\-:^~]+(?=\s+|$)/g,"").trim()}var Le;(function(n){n[n.SETUP=0]="SETUP",n[n.READY=1]="READY",n[n.QUERY=2]="QUERY",n[n.RESULT=3]="RESULT"})(Le||(Le={}));function at(e){return e.type===1}function wi(e){return e.type===2}function st(e){return e.type===3}function Ja({config:e,docs:t,index:r}){e.lang.length===1&&e.lang[0]==="en"&&(e.lang=[Y("search.config.lang")]),e.separator==="[\\s\\-]+"&&(e.separator=Y("search.config.separator"));let n={pipeline:Y("search.config.pipeline").split(/\s*,\s*/).filter(Boolean),suggestions:Ae("search.suggest")};return{config:e,docs:t,index:r,options:n}}function Ei(e,t){let r=ce(),o=new Worker(e),n=new T,i=Sn(o,{tx$:n}).pipe(u(a=>{if(st(a))for(let s of a.data.items)for(let c of s)c.location=`${r.base}/${c.location}`;return a}),ie());return ye(t).pipe(u(a=>({type:Le.SETUP,data:Ja(a)}))).subscribe(n.next.bind(n)),{tx$:n,rx$:i}}function Ti(){let e=ce();we(new URL("versions.json",e.base)).subscribe(t=>{he(".md-header__topic").appendChild(ni(t))})}function Ya(e,{rx$:t}){let r=(__search==null?void 0:__search.transform)||Si,o=tn(e),n=$(E(e,"keyup"),E(e,"focus").pipe(Me(1))).pipe(u(()=>r(e.value)),D()),i=Pe();return i.searchParams.has("q")&&(Re("search",!0),t.pipe(M(at),de(1)).subscribe(()=>{e.value=i.searchParams.get("q"),ge(e)})),Q([n,o]).pipe(u(([a,s])=>({value:a,focus:s})))}function Oi(e,{tx$:t,rx$:r}){let o=new T;return o.pipe(U("value"),u(({value:n})=>({type:Le.QUERY,data:n}))).subscribe(t.next.bind(t)),o.pipe(U("focus")).subscribe(({focus:n})=>{n?(Re("search",n),Pn(e,"")):$n(e)}),E(e.form,"reset").pipe(Mr(o.pipe(wr(1)))).subscribe(()=>ge(e)),Ya(e,{tx$:t,rx$:r}).pipe(L(o),I(()=>o.complete()),u(n=>P({ref:e},n)))}function _i(e,{rx$:t},{query$:r}){let o=new T,n=nn(e.parentElement).pipe(M(Boolean)),i=he(":scope > :first-child",e),a=he(":scope > :last-child",e);return t.pipe(M(at),de(1)).subscribe(()=>{Ir(i)}),o.pipe(q(X),ue(r)).subscribe(([{items:c},{value:l}])=>{l?Un(i,c.length):Ir(i)}),o.pipe(q(X),L(()=>Dn(a)),O(({items:c})=>$(F(...c.slice(0,10)),F(...c.slice(10)).pipe(xe(4),kr(n),O(([l])=>F(...l)))))).subscribe(c=>{Nn(a,ti(c))}),t.pipe(M(st),u(({data:c})=>c)).pipe(L(o),I(()=>o.complete()),u(c=>P({ref:e},c)))}function Ga(e,{query$:t}){return t.pipe(u(({value:r})=>{let o=Pe();return o.hash="",o.searchParams.delete("h"),o.searchParams.set("q",r),{url:o}}))}function Mi(e,t){let r=new T;return r.subscribe(({url:o})=>{e.setAttribute("data-clipboard-text",e.href),e.href=`${o}`}),E(e,"click").subscribe(o=>o.preventDefault()),Ga(e,t).pipe(L(r),I(()=>r.complete()),u(o=>P({ref:e},o)))}function Ai(e,{rx$:t},{keyboard$:r}){let o=new T,n=Ee("search-query"),i=E(n,"keydown").pipe(q(Ce),u(()=>n.value),D());return o.pipe(rt(i),u(([{suggestions:s},c])=>{let l=c.split(/([\s-]+)/);if((s==null?void 0:s.length)&&l[l.length-1]){let p=s[s.length-1];p.startsWith(l[l.length-1])&&(l[l.length-1]=p)}else l.length=0;return l})).subscribe(s=>e.innerHTML=s.join("").replace(/\s/g," ")),r.pipe(M(({mode:s})=>s==="search")).subscribe(s=>{switch(s.type){case"ArrowRight":e.innerText.length&&n.selectionStart===n.value.length&&(n.value=e.innerText);break}}),t.pipe(M(st),u(({data:s})=>s)).pipe(L(o),I(()=>o.complete()),u(()=>({ref:e})))}function Li(e,{index$:t,keyboard$:r}){let o=ce();try{let n=Ei(o.search,t),i=Ee("search-query",e),a=Ee("search-result",e),{tx$:s,rx$:c}=n;s.pipe(M(wi),ot(c.pipe(M(at),de(1)))).subscribe(s.next.bind(s)),r.pipe(M(({mode:m})=>m==="search")).subscribe(m=>{let f=De();switch(m.type){case"Enter":if(f===i){let d=new Map;for(let v of K(":first-child [href]",a)){let h=v.firstElementChild;d.set(v,parseFloat(h.getAttribute("data-md-score")))}if(d.size){let[[v]]=[...d].sort(([,h],[,W])=>W-h);v.click()}m.claim()}break;case"Escape":case"Tab":Re("search",!1),ge(i,!1);break;case"ArrowUp":case"ArrowDown":if(typeof f=="undefined")ge(i);else{let d=[i,...K(":not(details) > [href], summary, details[open] [href]",a)],v=Math.max(0,(Math.max(0,d.indexOf(f))+d.length+(m.type==="ArrowUp"?-1:1))%d.length);ge(d[v])}m.claim();break;default:i!==De()&&ge(i)}}),r.pipe(M(({mode:m})=>m==="global")).subscribe(m=>{switch(m.type){case"f":case"s":case"/":ge(i),an(i),m.claim();break}});let l=Oi(i,n),p=_i(a,n,{query$:l});return $(l,p).pipe(Ne(...ne("search-share",e).map(m=>Mi(m,{query$:l})),...ne("search-suggest",e).map(m=>Ai(m,n,{keyboard$:r}))))}catch(n){return e.hidden=!0,J}}function ki(e,{index$:t,location$:r}){return Q([t,r.pipe(N(Pe()),M(o=>o.searchParams.has("h")))]).pipe(u(([o,n])=>Vr(o.config)(n.searchParams.get("h"))),u(o=>{var a;let n=new Map,i=document.createNodeIterator(e,NodeFilter.SHOW_TEXT);for(let s=i.nextNode();s;s=i.nextNode())if((a=s.parentElement)==null?void 0:a.offsetHeight){let c=s.textContent,l=o(c);l.length>c.length&&n.set(s,l)}for(let[s,c]of n){let{childNodes:l}=V("span",null,c);s.replaceWith(...Array.from(l))}return{ref:e,nodes:n}}))}function Xa(e,{viewport$:t,main$:r}){let o=e.parentElement.offsetTop-e.parentElement.parentElement.offsetTop;return Q([r,t]).pipe(u(([{offset:n,height:i},{offset:{y:a}}])=>(i=i+Math.min(o,Math.max(0,a-n))-o,{height:i,locked:a>=n+o})),D((n,i)=>n.height===i.height&&n.locked===i.locked))}function Ur(e,o){var n=o,{header$:t}=n,r=Kr(n,["header$"]);let i=new T;return i.pipe(q(X),ue(t)).subscribe({next([{height:a},{height:s}]){Qn(e,a),zn(e,s)},complete(){qn(e),Kn(e)}}),Xa(e,r).pipe(L(i),I(()=>i.complete()),u(a=>P({ref:e},a)))}function Ci(e,t){if(typeof t!="undefined"){let r=`https://api.github.com/repos/${e}/${t}`;return vt(we(`${r}/releases/latest`).pipe(u(o=>({version:o.tag_name})),Ue({})),we(r).pipe(u(o=>({stars:o.stargazers_count,forks:o.forks_count})),Ue({}))).pipe(u(([o,n])=>P(P({},o),n)))}else{let r=`https://api.github.com/repos/${e}`;return we(r).pipe(u(o=>({repositories:o.public_repos})),Ue({}))}}function Hi(e,t){let r=`https://${e}/api/v4/projects/${encodeURIComponent(t)}`;return we(r).pipe(u(({star_count:o,forks_count:n})=>({stars:o,forks:n})),Ue({}))}function ji(e){let[t]=e.match(/(git(?:hub|lab))/i)||[];switch(t.toLowerCase()){case"github":let[,r,o]=e.match(/^.+github\.com\/([^/]+)\/?([^/]+)?/i);return Ci(r,o);case"gitlab":let[,n,i]=e.match(/^.+?([^/]*gitlab[^/]+)\/(.+?)\/?$/i);return Hi(n,i);default:return J}}var Za;function es(e){return Za||(Za=_e(()=>{let t=sessionStorage.getItem(__prefix("__source"));if(t)return F(JSON.parse(t));{let r=ji(e.href);return r.subscribe(o=>{try{sessionStorage.setItem(__prefix("__source"),JSON.stringify(o))}catch(n){}}),r}}).pipe(tt(()=>J),M(t=>Object.keys(t).length>0),u(t=>({facts:t})),re(1)))}function Fi(e){let t=new T;return t.subscribe(({facts:r})=>{Bn(e,ri(r)),Jn(e,"done")}),es(e).pipe(L(t),I(()=>t.complete()),u(r=>P({ref:e},r)))}function ts(e,{viewport$:t,header$:r}){return Ie(document.body).pipe(O(()=>Xt(e,{header$:r,viewport$:t})),u(({offset:{y:o}})=>({hidden:o>=10})),U("hidden"))}function Ii(e,t){let r=new T;return r.pipe(q(X)).subscribe({next({hidden:o}){o?Yn(e,"hidden"):Rr(e)},complete(){Rr(e)}}),ts(e,t).pipe(L(r),I(()=>r.complete()),u(o=>P({ref:e},o)))}function rs(e,{viewport$:t,header$:r}){let o=new Map;for(let a of e){let s=decodeURIComponent(a.hash.substring(1)),c=se(`[id="${s}"]`);typeof c!="undefined"&&o.set(a,c)}let n=r.pipe(u(a=>24+a.height));return Ie(document.body).pipe(U("height"),u(()=>{let a=[];return[...o].reduce((s,[c,l])=>{for(;a.length&&o.get(a[a.length-1]).tagName>=l.tagName;)a.pop();let p=l.offsetTop;for(;!p&&l.parentElement;)l=l.parentElement,p=l.offsetTop;return s.set([...a=[...a,c]].reverse(),p)},new Map)}),u(a=>new Map([...a].sort(([,s],[,c])=>s-c))),O(a=>Q([n,t]).pipe(Er(([s,c],[l,{offset:{y:p}}])=>{for(;c.length;){let[,m]=c[0];if(m-l=p)c=[s.pop(),...c];else break}return[s,c]},[[],[...a]]),D((s,c)=>s[0]===c[0]&&s[1]===c[1])))).pipe(u(([a,s])=>({prev:a.map(([c])=>c),next:s.map(([c])=>c)})),N({prev:[],next:[]}),xe(2,1),u(([a,s])=>a.prev.length{for(let[a]of i)Ln(a),Mn(a);for(let[a,[s]]of n.entries())An(s,a===n.length-1),_n(s,"blur")});let o=K("[href^=\\#]",e);return rs(o,t).pipe(L(r),I(()=>r.complete()),u(n=>P({ref:e},n)))}function os(e,{viewport$:t,main$:r}){let o=t.pipe(u(({offset:{y:i}})=>i),xe(2,1),u(([i,a])=>i>a&&a),D()),n=r.pipe(U("active"));return Q([n,o]).pipe(u(([{active:i},a])=>({hidden:!(i&&a)})),D((i,a)=>i.hidden===a.hidden))}function Pi(e,{viewport$:t,header$:r,main$:o}){let n=new T;return n.pipe(q(X),ue(r.pipe(U("height")))).subscribe({next([{hidden:i},{height:a}]){Xn(e,a+16),i?(Gn(e,"hidden"),ge(e,!1)):Pr(e)},complete(){Zn(e),Pr(e)}}),os(e,{viewport$:t,header$:r,main$:o}).pipe(L(n),I(()=>n.complete()),u(i=>P({ref:e},i)))}function $i({document$:e,tablet$:t}){e.pipe(O(()=>F(...K("[data-md-state=indeterminate]"))),L(r=>{r.indeterminate=!0,r.checked=!1}),te(r=>E(r,"change").pipe(Ar(()=>r.hasAttribute("data-md-state")),oe(r))),ue(t)).subscribe(([r,o])=>{r.removeAttribute("data-md-state"),o&&(r.checked=!1)})}function ns(){return/(iPad|iPhone|iPod)/.test(navigator.userAgent)}function Wi({document$:e}){e.pipe(O(()=>F(...K("[data-md-scrollfix]"))),L(t=>t.removeAttribute("data-md-scrollfix")),M(ns),te(t=>E(t,"touchstart").pipe(oe(t)))).subscribe(t=>{let r=t.scrollTop;r===0?t.scrollTop=1:r+t.offsetHeight===t.scrollHeight&&(t.scrollTop=r-1)})}function Vi({viewport$:e,tablet$:t}){Q([Yt("search"),t]).pipe(u(([r,o])=>r&&!o),O(r=>F(r).pipe(Me(r?400:100),q(X))),ue(e)).subscribe(([r,{offset:{y:o}}])=>{r?Tn(document.body,o):On(document.body)})}document.documentElement.classList.remove("no-js");document.documentElement.classList.add("js");var ct=en(),er=pn(),Nr=mn(),Dr=cn(),fe=yn(),tr=xt("(min-width: 960px)"),Ui=xt("(min-width: 1220px)"),Ni=dn(),Di=ce(),zi=document.forms.namedItem("search")?(__search==null?void 0:__search.index)||we(`${Di.base}/search/search_index.json`):J,zr=new T;vi({alert$:zr});Ae("navigation.instant")&&xi({document$:ct,location$:er,viewport$:fe});var Qi;((Qi=Di.version)==null?void 0:Qi.provider)==="mike"&&Ti();$(er,Nr).pipe(Me(125)).subscribe(()=>{Re("drawer",!1),Re("search",!1)});Dr.pipe(M(({mode:e})=>e==="global")).subscribe(e=>{switch(e.type){case"p":case",":let t=se("[href][rel=prev]");typeof t!="undefined"&&t.click();break;case"n":case".":let r=se("[href][rel=next]");typeof r!="undefined"&&r.click();break}});$i({document$:ct,tablet$:tr});Wi({document$:ct});Vi({viewport$:fe,tablet$:tr});var $e=fi(Ee("header"),{viewport$:fe}),rr=ct.pipe(u(()=>Ee("main")),O(e=>hi(e,{viewport$:fe,header$:$e})),re(1)),is=$(...ne("dialog").map(e=>ui(e,{alert$:zr})),...ne("header").map(e=>mi(e,{viewport$:fe,header$:$e,main$:rr})),...ne("palette").map(e=>bi(e)),...ne("search").map(e=>Li(e,{index$:zi,keyboard$:Dr})),...ne("source").map(e=>Fi(e))),as=_e(()=>$(...ne("content").map(e=>pi(e,{target$:Nr,viewport$:fe,print$:Ni})),...ne("content").map(e=>Ae("search.highlight")?ki(e,{index$:zi,location$:er}):J),...ne("header-title").map(e=>di(e,{viewport$:fe,header$:$e})),...ne("sidebar").map(e=>e.getAttribute("data-md-type")==="navigation"?Cr(Ui,()=>Ur(e,{viewport$:fe,header$:$e,main$:rr})):Cr(tr,()=>Ur(e,{viewport$:fe,header$:$e,main$:rr}))),...ne("tabs").map(e=>Ii(e,{viewport$:fe,header$:$e})),...ne("toc").map(e=>Ri(e,{viewport$:fe,header$:$e})),...ne("top").map(e=>Pi(e,{viewport$:fe,header$:$e,main$:rr})))),qi=ct.pipe(O(()=>as),Ne(is),re(1));qi.subscribe();window.document$=ct;window.location$=er;window.target$=Nr;window.keyboard$=Dr;window.viewport$=fe;window.tablet$=tr;window.screen$=Ui;window.print$=Ni;window.alert$=zr;window.component$=qi;})(); +//# sourceMappingURL=bundle.716f8af4.min.js.map + diff --git a/en/2021.7/assets/javascripts/bundle.716f8af4.min.js.map b/en/2021.7/assets/javascripts/bundle.716f8af4.min.js.map new file mode 100644 index 000000000..e4b10b822 --- /dev/null +++ b/en/2021.7/assets/javascripts/bundle.716f8af4.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["node_modules/focus-visible/dist/focus-visible.js", "node_modules/rxjs/node_modules/tslib/tslib.js", "node_modules/clipboard/dist/clipboard.js", "node_modules/escape-html/index.js", "src/assets/javascripts/bundle.ts", "node_modules/rxjs/node_modules/tslib/modules/index.js", "node_modules/rxjs/src/internal/util/isFunction.ts", "node_modules/rxjs/src/internal/util/createErrorClass.ts", "node_modules/rxjs/src/internal/util/UnsubscriptionError.ts", "node_modules/rxjs/src/internal/util/arrRemove.ts", "node_modules/rxjs/src/internal/Subscription.ts", "node_modules/rxjs/src/internal/config.ts", "node_modules/rxjs/src/internal/scheduler/timeoutProvider.ts", "node_modules/rxjs/src/internal/util/reportUnhandledError.ts", "node_modules/rxjs/src/internal/util/noop.ts", "node_modules/rxjs/src/internal/NotificationFactories.ts", "node_modules/rxjs/src/internal/util/errorContext.ts", "node_modules/rxjs/src/internal/Subscriber.ts", "node_modules/rxjs/src/internal/symbol/observable.ts", "node_modules/rxjs/src/internal/util/identity.ts", "node_modules/rxjs/src/internal/util/pipe.ts", "node_modules/rxjs/src/internal/Observable.ts", "node_modules/rxjs/src/internal/util/lift.ts", "node_modules/rxjs/src/internal/operators/OperatorSubscriber.ts", "node_modules/rxjs/src/internal/scheduler/animationFrameProvider.ts", "node_modules/rxjs/src/internal/util/ObjectUnsubscribedError.ts", "node_modules/rxjs/src/internal/Subject.ts", "node_modules/rxjs/src/internal/scheduler/dateTimestampProvider.ts", "node_modules/rxjs/src/internal/ReplaySubject.ts", "node_modules/rxjs/src/internal/scheduler/Action.ts", "node_modules/rxjs/src/internal/scheduler/intervalProvider.ts", "node_modules/rxjs/src/internal/scheduler/AsyncAction.ts", "node_modules/rxjs/src/internal/Scheduler.ts", "node_modules/rxjs/src/internal/scheduler/AsyncScheduler.ts", "node_modules/rxjs/src/internal/scheduler/async.ts", "node_modules/rxjs/src/internal/scheduler/AnimationFrameAction.ts", "node_modules/rxjs/src/internal/scheduler/AnimationFrameScheduler.ts", "node_modules/rxjs/src/internal/scheduler/animationFrame.ts", "node_modules/rxjs/src/internal/observable/empty.ts", "node_modules/rxjs/src/internal/scheduled/scheduleArray.ts", "node_modules/rxjs/src/internal/util/isArrayLike.ts", "node_modules/rxjs/src/internal/util/isPromise.ts", "node_modules/rxjs/src/internal/scheduled/scheduleObservable.ts", "node_modules/rxjs/src/internal/scheduled/schedulePromise.ts", "node_modules/rxjs/src/internal/symbol/iterator.ts", "node_modules/rxjs/src/internal/util/caughtSchedule.ts", "node_modules/rxjs/src/internal/scheduled/scheduleIterable.ts", "node_modules/rxjs/src/internal/scheduled/scheduleAsyncIterable.ts", "node_modules/rxjs/src/internal/util/isInteropObservable.ts", "node_modules/rxjs/src/internal/util/isIterable.ts", "node_modules/rxjs/src/internal/util/isAsyncIterable.ts", "node_modules/rxjs/src/internal/util/throwUnobservableError.ts", "node_modules/rxjs/src/internal/util/isReadableStreamLike.ts", "node_modules/rxjs/src/internal/scheduled/scheduleReadableStreamLike.ts", "node_modules/rxjs/src/internal/scheduled/scheduled.ts", "node_modules/rxjs/src/internal/observable/from.ts", "node_modules/rxjs/src/internal/observable/fromArray.ts", "node_modules/rxjs/src/internal/util/isScheduler.ts", "node_modules/rxjs/src/internal/util/args.ts", "node_modules/rxjs/src/internal/observable/of.ts", "node_modules/rxjs/src/internal/util/isDate.ts", "node_modules/rxjs/src/internal/operators/map.ts", "node_modules/rxjs/src/internal/util/mapOneOrManyArgs.ts", "node_modules/rxjs/src/internal/operators/observeOn.ts", "node_modules/rxjs/src/internal/util/argsArgArrayOrObject.ts", "node_modules/rxjs/src/internal/util/createObject.ts", "node_modules/rxjs/src/internal/observable/combineLatest.ts", "node_modules/rxjs/src/internal/operators/mergeInternals.ts", "node_modules/rxjs/src/internal/operators/mergeMap.ts", "node_modules/rxjs/src/internal/operators/mergeAll.ts", "node_modules/rxjs/src/internal/operators/concatAll.ts", "node_modules/rxjs/src/internal/observable/concat.ts", "node_modules/rxjs/src/internal/observable/defer.ts", "node_modules/rxjs/src/internal/observable/fromEvent.ts", "node_modules/rxjs/src/internal/observable/fromEventPattern.ts", "node_modules/rxjs/src/internal/observable/timer.ts", "node_modules/rxjs/src/internal/observable/merge.ts", "node_modules/rxjs/src/internal/observable/never.ts", "node_modules/rxjs/src/internal/util/argsOrArgArray.ts", "node_modules/rxjs/src/internal/operators/filter.ts", "node_modules/rxjs/src/internal/observable/zip.ts", "node_modules/rxjs/src/internal/operators/bufferCount.ts", "node_modules/rxjs/src/internal/operators/catchError.ts", "node_modules/rxjs/src/internal/operators/scanInternals.ts", "node_modules/rxjs/src/internal/operators/combineLatest.ts", "node_modules/rxjs/src/internal/operators/combineLatestWith.ts", "node_modules/rxjs/src/internal/operators/concatMap.ts", "node_modules/rxjs/src/internal/operators/debounceTime.ts", "node_modules/rxjs/src/internal/operators/defaultIfEmpty.ts", "node_modules/rxjs/src/internal/operators/take.ts", "node_modules/rxjs/src/internal/operators/ignoreElements.ts", "node_modules/rxjs/src/internal/operators/mapTo.ts", "node_modules/rxjs/src/internal/operators/delayWhen.ts", "node_modules/rxjs/src/internal/operators/delay.ts", "node_modules/rxjs/src/internal/operators/distinctUntilChanged.ts", "node_modules/rxjs/src/internal/operators/distinctUntilKeyChanged.ts", "node_modules/rxjs/src/internal/operators/finalize.ts", "node_modules/rxjs/src/internal/operators/takeLast.ts", "node_modules/rxjs/src/internal/operators/merge.ts", "node_modules/rxjs/src/internal/operators/mergeWith.ts", "node_modules/rxjs/src/internal/operators/sample.ts", "node_modules/rxjs/src/internal/operators/scan.ts", "node_modules/rxjs/src/internal/operators/share.ts", "node_modules/rxjs/src/internal/operators/shareReplay.ts", "node_modules/rxjs/src/internal/operators/skip.ts", "node_modules/rxjs/src/internal/operators/skipUntil.ts", "node_modules/rxjs/src/internal/operators/startWith.ts", "node_modules/rxjs/src/internal/operators/switchMap.ts", "node_modules/rxjs/src/internal/operators/switchMapTo.ts", "node_modules/rxjs/src/internal/operators/takeUntil.ts", "node_modules/rxjs/src/internal/operators/takeWhile.ts", "node_modules/rxjs/src/internal/operators/tap.ts", "node_modules/rxjs/src/internal/operators/throttle.ts", "node_modules/rxjs/src/internal/operators/withLatestFrom.ts", "node_modules/rxjs/src/internal/operators/zip.ts", "node_modules/rxjs/src/internal/operators/zipWith.ts", "src/assets/javascripts/browser/document/index.ts", "src/assets/javascripts/browser/element/_/index.ts", "src/assets/javascripts/browser/element/focus/index.ts", "src/assets/javascripts/browser/element/size/index.ts", "src/assets/javascripts/browser/element/offset/index.ts", "src/assets/javascripts/browser/element/selection/index.ts", "src/assets/javascripts/browser/toggle/index.ts", "src/assets/javascripts/browser/keyboard/index.ts", "src/assets/javascripts/browser/location/_/index.ts", "src/assets/javascripts/browser/location/hash/index.ts", "src/assets/javascripts/browser/media/index.ts", "src/assets/javascripts/browser/request/index.ts", "src/assets/javascripts/browser/viewport/offset/index.ts", "src/assets/javascripts/browser/viewport/size/index.ts", "src/assets/javascripts/browser/viewport/_/index.ts", "src/assets/javascripts/browser/worker/index.ts", "src/assets/javascripts/_/index.ts", "src/assets/javascripts/components/_/index.ts", "src/assets/javascripts/components/content/code/index.ts", "src/assets/javascripts/actions/_/index.ts", "src/assets/javascripts/actions/anchor/index.ts", "src/assets/javascripts/actions/dialog/index.ts", "src/assets/javascripts/actions/header/_/index.ts", "src/assets/javascripts/actions/header/title/index.ts", "src/assets/javascripts/actions/search/query/index.ts", "src/assets/javascripts/utilities/h/index.ts", "src/assets/javascripts/utilities/string/index.ts", "src/assets/javascripts/actions/search/result/index.ts", "src/assets/javascripts/actions/sidebar/index.ts", "src/assets/javascripts/actions/source/index.ts", "src/assets/javascripts/actions/tabs/index.ts", "src/assets/javascripts/actions/top/index.ts", "src/assets/javascripts/templates/clipboard/index.tsx", "src/assets/javascripts/templates/search/index.tsx", "src/assets/javascripts/templates/source/index.tsx", "src/assets/javascripts/templates/table/index.tsx", "src/assets/javascripts/templates/version/index.tsx", "src/assets/javascripts/components/content/details/index.ts", "src/assets/javascripts/components/content/table/index.ts", "src/assets/javascripts/components/content/_/index.ts", "src/assets/javascripts/components/dialog/index.ts", "src/assets/javascripts/components/header/_/index.ts", "src/assets/javascripts/components/header/title/index.ts", "src/assets/javascripts/components/main/index.ts", "src/assets/javascripts/components/palette/index.ts", "src/assets/javascripts/integrations/clipboard/index.ts", "src/assets/javascripts/integrations/instant/index.ts", "src/assets/javascripts/integrations/search/document/index.ts", "src/assets/javascripts/integrations/search/highlighter/index.ts", "src/assets/javascripts/integrations/search/query/transform/index.ts", "src/assets/javascripts/integrations/search/worker/message/index.ts", "src/assets/javascripts/integrations/search/worker/_/index.ts", "src/assets/javascripts/integrations/version/index.ts", "src/assets/javascripts/components/search/query/index.ts", "src/assets/javascripts/components/search/result/index.ts", "src/assets/javascripts/components/search/share/index.ts", "src/assets/javascripts/components/search/suggest/index.ts", "src/assets/javascripts/components/search/_/index.ts", "src/assets/javascripts/components/search/highlight/index.ts", "src/assets/javascripts/components/sidebar/index.ts", "src/assets/javascripts/components/source/facts/github/index.ts", "src/assets/javascripts/components/source/facts/gitlab/index.ts", "src/assets/javascripts/components/source/facts/_/index.ts", "src/assets/javascripts/components/source/_/index.ts", "src/assets/javascripts/components/tabs/index.ts", "src/assets/javascripts/components/toc/index.ts", "src/assets/javascripts/components/top/index.ts", "src/assets/javascripts/patches/indeterminate/index.ts", "src/assets/javascripts/patches/scrollfix/index.ts", "src/assets/javascripts/patches/scrolllock/index.ts"], + "sourcesContent": ["(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (factory());\n}(this, (function () { 'use strict';\n\n /**\n * Applies the :focus-visible polyfill at the given scope.\n * A scope in this case is either the top-level Document or a Shadow Root.\n *\n * @param {(Document|ShadowRoot)} scope\n * @see https://github.com/WICG/focus-visible\n */\n function applyFocusVisiblePolyfill(scope) {\n var hadKeyboardEvent = true;\n var hadFocusVisibleRecently = false;\n var hadFocusVisibleRecentlyTimeout = null;\n\n var inputTypesAllowlist = {\n text: true,\n search: true,\n url: true,\n tel: true,\n email: true,\n password: true,\n number: true,\n date: true,\n month: true,\n week: true,\n time: true,\n datetime: true,\n 'datetime-local': true\n };\n\n /**\n * Helper function for legacy browsers and iframes which sometimes focus\n * elements like document, body, and non-interactive SVG.\n * @param {Element} el\n */\n function isValidFocusTarget(el) {\n if (\n el &&\n el !== document &&\n el.nodeName !== 'HTML' &&\n el.nodeName !== 'BODY' &&\n 'classList' in el &&\n 'contains' in el.classList\n ) {\n return true;\n }\n return false;\n }\n\n /**\n * Computes whether the given element should automatically trigger the\n * `focus-visible` class being added, i.e. whether it should always match\n * `:focus-visible` when focused.\n * @param {Element} el\n * @return {boolean}\n */\n function focusTriggersKeyboardModality(el) {\n var type = el.type;\n var tagName = el.tagName;\n\n if (tagName === 'INPUT' && inputTypesAllowlist[type] && !el.readOnly) {\n return true;\n }\n\n if (tagName === 'TEXTAREA' && !el.readOnly) {\n return true;\n }\n\n if (el.isContentEditable) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Add the `focus-visible` class to the given element if it was not added by\n * the author.\n * @param {Element} el\n */\n function addFocusVisibleClass(el) {\n if (el.classList.contains('focus-visible')) {\n return;\n }\n el.classList.add('focus-visible');\n el.setAttribute('data-focus-visible-added', '');\n }\n\n /**\n * Remove the `focus-visible` class from the given element if it was not\n * originally added by the author.\n * @param {Element} el\n */\n function removeFocusVisibleClass(el) {\n if (!el.hasAttribute('data-focus-visible-added')) {\n return;\n }\n el.classList.remove('focus-visible');\n el.removeAttribute('data-focus-visible-added');\n }\n\n /**\n * If the most recent user interaction was via the keyboard;\n * and the key press did not include a meta, alt/option, or control key;\n * then the modality is keyboard. Otherwise, the modality is not keyboard.\n * Apply `focus-visible` to any current active element and keep track\n * of our keyboard modality state with `hadKeyboardEvent`.\n * @param {KeyboardEvent} e\n */\n function onKeyDown(e) {\n if (e.metaKey || e.altKey || e.ctrlKey) {\n return;\n }\n\n if (isValidFocusTarget(scope.activeElement)) {\n addFocusVisibleClass(scope.activeElement);\n }\n\n hadKeyboardEvent = true;\n }\n\n /**\n * If at any point a user clicks with a pointing device, ensure that we change\n * the modality away from keyboard.\n * This avoids the situation where a user presses a key on an already focused\n * element, and then clicks on a different element, focusing it with a\n * pointing device, while we still think we're in keyboard modality.\n * @param {Event} e\n */\n function onPointerDown(e) {\n hadKeyboardEvent = false;\n }\n\n /**\n * On `focus`, add the `focus-visible` class to the target if:\n * - the target received focus as a result of keyboard navigation, or\n * - the event target is an element that will likely require interaction\n * via the keyboard (e.g. a text box)\n * @param {Event} e\n */\n function onFocus(e) {\n // Prevent IE from focusing the document or HTML element.\n if (!isValidFocusTarget(e.target)) {\n return;\n }\n\n if (hadKeyboardEvent || focusTriggersKeyboardModality(e.target)) {\n addFocusVisibleClass(e.target);\n }\n }\n\n /**\n * On `blur`, remove the `focus-visible` class from the target.\n * @param {Event} e\n */\n function onBlur(e) {\n if (!isValidFocusTarget(e.target)) {\n return;\n }\n\n if (\n e.target.classList.contains('focus-visible') ||\n e.target.hasAttribute('data-focus-visible-added')\n ) {\n // To detect a tab/window switch, we look for a blur event followed\n // rapidly by a visibility change.\n // If we don't see a visibility change within 100ms, it's probably a\n // regular focus change.\n hadFocusVisibleRecently = true;\n window.clearTimeout(hadFocusVisibleRecentlyTimeout);\n hadFocusVisibleRecentlyTimeout = window.setTimeout(function() {\n hadFocusVisibleRecently = false;\n }, 100);\n removeFocusVisibleClass(e.target);\n }\n }\n\n /**\n * If the user changes tabs, keep track of whether or not the previously\n * focused element had .focus-visible.\n * @param {Event} e\n */\n function onVisibilityChange(e) {\n if (document.visibilityState === 'hidden') {\n // If the tab becomes active again, the browser will handle calling focus\n // on the element (Safari actually calls it twice).\n // If this tab change caused a blur on an element with focus-visible,\n // re-apply the class when the user switches back to the tab.\n if (hadFocusVisibleRecently) {\n hadKeyboardEvent = true;\n }\n addInitialPointerMoveListeners();\n }\n }\n\n /**\n * Add a group of listeners to detect usage of any pointing devices.\n * These listeners will be added when the polyfill first loads, and anytime\n * the window is blurred, so that they are active when the window regains\n * focus.\n */\n function addInitialPointerMoveListeners() {\n document.addEventListener('mousemove', onInitialPointerMove);\n document.addEventListener('mousedown', onInitialPointerMove);\n document.addEventListener('mouseup', onInitialPointerMove);\n document.addEventListener('pointermove', onInitialPointerMove);\n document.addEventListener('pointerdown', onInitialPointerMove);\n document.addEventListener('pointerup', onInitialPointerMove);\n document.addEventListener('touchmove', onInitialPointerMove);\n document.addEventListener('touchstart', onInitialPointerMove);\n document.addEventListener('touchend', onInitialPointerMove);\n }\n\n function removeInitialPointerMoveListeners() {\n document.removeEventListener('mousemove', onInitialPointerMove);\n document.removeEventListener('mousedown', onInitialPointerMove);\n document.removeEventListener('mouseup', onInitialPointerMove);\n document.removeEventListener('pointermove', onInitialPointerMove);\n document.removeEventListener('pointerdown', onInitialPointerMove);\n document.removeEventListener('pointerup', onInitialPointerMove);\n document.removeEventListener('touchmove', onInitialPointerMove);\n document.removeEventListener('touchstart', onInitialPointerMove);\n document.removeEventListener('touchend', onInitialPointerMove);\n }\n\n /**\n * When the polfyill first loads, assume the user is in keyboard modality.\n * If any event is received from a pointing device (e.g. mouse, pointer,\n * touch), turn off keyboard modality.\n * This accounts for situations where focus enters the page from the URL bar.\n * @param {Event} e\n */\n function onInitialPointerMove(e) {\n // Work around a Safari quirk that fires a mousemove on whenever the\n // window blurs, even if you're tabbing out of the page. \u00AF\\_(\u30C4)_/\u00AF\n if (e.target.nodeName && e.target.nodeName.toLowerCase() === 'html') {\n return;\n }\n\n hadKeyboardEvent = false;\n removeInitialPointerMoveListeners();\n }\n\n // For some kinds of state, we are interested in changes at the global scope\n // only. For example, global pointer input, global key presses and global\n // visibility change should affect the state at every scope:\n document.addEventListener('keydown', onKeyDown, true);\n document.addEventListener('mousedown', onPointerDown, true);\n document.addEventListener('pointerdown', onPointerDown, true);\n document.addEventListener('touchstart', onPointerDown, true);\n document.addEventListener('visibilitychange', onVisibilityChange, true);\n\n addInitialPointerMoveListeners();\n\n // For focus and blur, we specifically care about state changes in the local\n // scope. This is because focus / blur events that originate from within a\n // shadow root are not re-dispatched from the host element if it was already\n // the active element in its own scope:\n scope.addEventListener('focus', onFocus, true);\n scope.addEventListener('blur', onBlur, true);\n\n // We detect that a node is a ShadowRoot by ensuring that it is a\n // DocumentFragment and also has a host property. This check covers native\n // implementation and polyfill implementation transparently. If we only cared\n // about the native implementation, we could just check if the scope was\n // an instance of a ShadowRoot.\n if (scope.nodeType === Node.DOCUMENT_FRAGMENT_NODE && scope.host) {\n // Since a ShadowRoot is a special kind of DocumentFragment, it does not\n // have a root element to add a class to. So, we add this attribute to the\n // host element instead:\n scope.host.setAttribute('data-js-focus-visible', '');\n } else if (scope.nodeType === Node.DOCUMENT_NODE) {\n document.documentElement.classList.add('js-focus-visible');\n document.documentElement.setAttribute('data-js-focus-visible', '');\n }\n }\n\n // It is important to wrap all references to global window and document in\n // these checks to support server-side rendering use cases\n // @see https://github.com/WICG/focus-visible/issues/199\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n // Make the polyfill helper globally available. This can be used as a signal\n // to interested libraries that wish to coordinate with the polyfill for e.g.,\n // applying the polyfill to a shadow root:\n window.applyFocusVisiblePolyfill = applyFocusVisiblePolyfill;\n\n // Notify interested libraries of the polyfill's presence, in case the\n // polyfill was loaded lazily:\n var event;\n\n try {\n event = new CustomEvent('focus-visible-polyfill-ready');\n } catch (error) {\n // IE11 does not support using CustomEvent as a constructor directly:\n event = document.createEvent('CustomEvent');\n event.initCustomEvent('focus-visible-polyfill-ready', false, false, {});\n }\n\n window.dispatchEvent(event);\n }\n\n if (typeof document !== 'undefined') {\n // Apply the polyfill to the global document, so that no JavaScript\n // coordination is required to use the polyfill in the top-level document:\n applyFocusVisiblePolyfill(document);\n }\n\n})));\n", "/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global global, define, System, Reflect, Promise */\r\nvar __extends;\r\nvar __assign;\r\nvar __rest;\r\nvar __decorate;\r\nvar __param;\r\nvar __metadata;\r\nvar __awaiter;\r\nvar __generator;\r\nvar __exportStar;\r\nvar __values;\r\nvar __read;\r\nvar __spread;\r\nvar __spreadArrays;\r\nvar __spreadArray;\r\nvar __await;\r\nvar __asyncGenerator;\r\nvar __asyncDelegator;\r\nvar __asyncValues;\r\nvar __makeTemplateObject;\r\nvar __importStar;\r\nvar __importDefault;\r\nvar __classPrivateFieldGet;\r\nvar __classPrivateFieldSet;\r\nvar __createBinding;\r\n(function (factory) {\r\n var root = typeof global === \"object\" ? global : typeof self === \"object\" ? self : typeof this === \"object\" ? this : {};\r\n if (typeof define === \"function\" && define.amd) {\r\n define(\"tslib\", [\"exports\"], function (exports) { factory(createExporter(root, createExporter(exports))); });\r\n }\r\n else if (typeof module === \"object\" && typeof module.exports === \"object\") {\r\n factory(createExporter(root, createExporter(module.exports)));\r\n }\r\n else {\r\n factory(createExporter(root));\r\n }\r\n function createExporter(exports, previous) {\r\n if (exports !== root) {\r\n if (typeof Object.create === \"function\") {\r\n Object.defineProperty(exports, \"__esModule\", { value: true });\r\n }\r\n else {\r\n exports.__esModule = true;\r\n }\r\n }\r\n return function (id, v) { return exports[id] = previous ? previous(id, v) : v; };\r\n }\r\n})\r\n(function (exporter) {\r\n var extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n\r\n __extends = function (d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n };\r\n\r\n __assign = Object.assign || function (t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n\r\n __rest = function (s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n };\r\n\r\n __decorate = function (decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n };\r\n\r\n __param = function (paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n };\r\n\r\n __metadata = function (metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n };\r\n\r\n __awaiter = function (thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n };\r\n\r\n __generator = function (thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n };\r\n\r\n __exportStar = function(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n };\r\n\r\n __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n }) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n });\r\n\r\n __values = function (o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n };\r\n\r\n __read = function (o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n };\r\n\r\n /** @deprecated */\r\n __spread = function () {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n };\r\n\r\n /** @deprecated */\r\n __spreadArrays = function () {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n };\r\n\r\n __spreadArray = function (to, from) {\r\n for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)\r\n to[j] = from[i];\r\n return to;\r\n };\r\n\r\n __await = function (v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n };\r\n\r\n __asyncGenerator = function (thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n };\r\n\r\n __asyncDelegator = function (o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n };\r\n\r\n __asyncValues = function (o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n };\r\n\r\n __makeTemplateObject = function (cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n };\r\n\r\n var __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n }) : function(o, v) {\r\n o[\"default\"] = v;\r\n };\r\n\r\n __importStar = function (mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n };\r\n\r\n __importDefault = function (mod) {\r\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\r\n };\r\n\r\n __classPrivateFieldGet = function (receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n };\r\n\r\n __classPrivateFieldSet = function (receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n };\r\n\r\n exporter(\"__extends\", __extends);\r\n exporter(\"__assign\", __assign);\r\n exporter(\"__rest\", __rest);\r\n exporter(\"__decorate\", __decorate);\r\n exporter(\"__param\", __param);\r\n exporter(\"__metadata\", __metadata);\r\n exporter(\"__awaiter\", __awaiter);\r\n exporter(\"__generator\", __generator);\r\n exporter(\"__exportStar\", __exportStar);\r\n exporter(\"__createBinding\", __createBinding);\r\n exporter(\"__values\", __values);\r\n exporter(\"__read\", __read);\r\n exporter(\"__spread\", __spread);\r\n exporter(\"__spreadArrays\", __spreadArrays);\r\n exporter(\"__spreadArray\", __spreadArray);\r\n exporter(\"__await\", __await);\r\n exporter(\"__asyncGenerator\", __asyncGenerator);\r\n exporter(\"__asyncDelegator\", __asyncDelegator);\r\n exporter(\"__asyncValues\", __asyncValues);\r\n exporter(\"__makeTemplateObject\", __makeTemplateObject);\r\n exporter(\"__importStar\", __importStar);\r\n exporter(\"__importDefault\", __importDefault);\r\n exporter(\"__classPrivateFieldGet\", __classPrivateFieldGet);\r\n exporter(\"__classPrivateFieldSet\", __classPrivateFieldSet);\r\n});\r\n", "/*!\n * clipboard.js v2.0.8\n * https://clipboardjs.com/\n *\n * Licensed MIT \u00A9 Zeno Rocha\n */\n(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"ClipboardJS\"] = factory();\n\telse\n\t\troot[\"ClipboardJS\"] = factory();\n})(this, function() {\nreturn /******/ (function() { // webpackBootstrap\n/******/ \tvar __webpack_modules__ = ({\n\n/***/ 134:\n/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n\n// EXPORTS\n__webpack_require__.d(__webpack_exports__, {\n \"default\": function() { return /* binding */ clipboard; }\n});\n\n// EXTERNAL MODULE: ./node_modules/tiny-emitter/index.js\nvar tiny_emitter = __webpack_require__(279);\nvar tiny_emitter_default = /*#__PURE__*/__webpack_require__.n(tiny_emitter);\n// EXTERNAL MODULE: ./node_modules/good-listener/src/listen.js\nvar listen = __webpack_require__(370);\nvar listen_default = /*#__PURE__*/__webpack_require__.n(listen);\n// EXTERNAL MODULE: ./node_modules/select/src/select.js\nvar src_select = __webpack_require__(817);\nvar select_default = /*#__PURE__*/__webpack_require__.n(src_select);\n;// CONCATENATED MODULE: ./src/clipboard-action.js\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\n\n/**\n * Inner class which performs selection from either `text` or `target`\n * properties and then executes copy or cut operations.\n */\n\nvar ClipboardAction = /*#__PURE__*/function () {\n /**\n * @param {Object} options\n */\n function ClipboardAction(options) {\n _classCallCheck(this, ClipboardAction);\n\n this.resolveOptions(options);\n this.initSelection();\n }\n /**\n * Defines base properties passed from constructor.\n * @param {Object} options\n */\n\n\n _createClass(ClipboardAction, [{\n key: \"resolveOptions\",\n value: function resolveOptions() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n this.action = options.action;\n this.container = options.container;\n this.emitter = options.emitter;\n this.target = options.target;\n this.text = options.text;\n this.trigger = options.trigger;\n this.selectedText = '';\n }\n /**\n * Decides which selection strategy is going to be applied based\n * on the existence of `text` and `target` properties.\n */\n\n }, {\n key: \"initSelection\",\n value: function initSelection() {\n if (this.text) {\n this.selectFake();\n } else if (this.target) {\n this.selectTarget();\n }\n }\n /**\n * Creates a fake textarea element, sets its value from `text` property,\n */\n\n }, {\n key: \"createFakeElement\",\n value: function createFakeElement() {\n var isRTL = document.documentElement.getAttribute('dir') === 'rtl';\n this.fakeElem = document.createElement('textarea'); // Prevent zooming on iOS\n\n this.fakeElem.style.fontSize = '12pt'; // Reset box model\n\n this.fakeElem.style.border = '0';\n this.fakeElem.style.padding = '0';\n this.fakeElem.style.margin = '0'; // Move element out of screen horizontally\n\n this.fakeElem.style.position = 'absolute';\n this.fakeElem.style[isRTL ? 'right' : 'left'] = '-9999px'; // Move element to the same position vertically\n\n var yPosition = window.pageYOffset || document.documentElement.scrollTop;\n this.fakeElem.style.top = \"\".concat(yPosition, \"px\");\n this.fakeElem.setAttribute('readonly', '');\n this.fakeElem.value = this.text;\n return this.fakeElem;\n }\n /**\n * Get's the value of fakeElem,\n * and makes a selection on it.\n */\n\n }, {\n key: \"selectFake\",\n value: function selectFake() {\n var _this = this;\n\n var fakeElem = this.createFakeElement();\n\n this.fakeHandlerCallback = function () {\n return _this.removeFake();\n };\n\n this.fakeHandler = this.container.addEventListener('click', this.fakeHandlerCallback) || true;\n this.container.appendChild(fakeElem);\n this.selectedText = select_default()(fakeElem);\n this.copyText();\n this.removeFake();\n }\n /**\n * Only removes the fake element after another click event, that way\n * a user can hit `Ctrl+C` to copy because selection still exists.\n */\n\n }, {\n key: \"removeFake\",\n value: function removeFake() {\n if (this.fakeHandler) {\n this.container.removeEventListener('click', this.fakeHandlerCallback);\n this.fakeHandler = null;\n this.fakeHandlerCallback = null;\n }\n\n if (this.fakeElem) {\n this.container.removeChild(this.fakeElem);\n this.fakeElem = null;\n }\n }\n /**\n * Selects the content from element passed on `target` property.\n */\n\n }, {\n key: \"selectTarget\",\n value: function selectTarget() {\n this.selectedText = select_default()(this.target);\n this.copyText();\n }\n /**\n * Executes the copy operation based on the current selection.\n */\n\n }, {\n key: \"copyText\",\n value: function copyText() {\n var succeeded;\n\n try {\n succeeded = document.execCommand(this.action);\n } catch (err) {\n succeeded = false;\n }\n\n this.handleResult(succeeded);\n }\n /**\n * Fires an event based on the copy operation result.\n * @param {Boolean} succeeded\n */\n\n }, {\n key: \"handleResult\",\n value: function handleResult(succeeded) {\n this.emitter.emit(succeeded ? 'success' : 'error', {\n action: this.action,\n text: this.selectedText,\n trigger: this.trigger,\n clearSelection: this.clearSelection.bind(this)\n });\n }\n /**\n * Moves focus away from `target` and back to the trigger, removes current selection.\n */\n\n }, {\n key: \"clearSelection\",\n value: function clearSelection() {\n if (this.trigger) {\n this.trigger.focus();\n }\n\n document.activeElement.blur();\n window.getSelection().removeAllRanges();\n }\n /**\n * Sets the `action` to be performed which can be either 'copy' or 'cut'.\n * @param {String} action\n */\n\n }, {\n key: \"destroy\",\n\n /**\n * Destroy lifecycle.\n */\n value: function destroy() {\n this.removeFake();\n }\n }, {\n key: \"action\",\n set: function set() {\n var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'copy';\n this._action = action;\n\n if (this._action !== 'copy' && this._action !== 'cut') {\n throw new Error('Invalid \"action\" value, use either \"copy\" or \"cut\"');\n }\n }\n /**\n * Gets the `action` property.\n * @return {String}\n */\n ,\n get: function get() {\n return this._action;\n }\n /**\n * Sets the `target` property using an element\n * that will be have its content copied.\n * @param {Element} target\n */\n\n }, {\n key: \"target\",\n set: function set(target) {\n if (target !== undefined) {\n if (target && _typeof(target) === 'object' && target.nodeType === 1) {\n if (this.action === 'copy' && target.hasAttribute('disabled')) {\n throw new Error('Invalid \"target\" attribute. Please use \"readonly\" instead of \"disabled\" attribute');\n }\n\n if (this.action === 'cut' && (target.hasAttribute('readonly') || target.hasAttribute('disabled'))) {\n throw new Error('Invalid \"target\" attribute. You can\\'t cut text from elements with \"readonly\" or \"disabled\" attributes');\n }\n\n this._target = target;\n } else {\n throw new Error('Invalid \"target\" value, use a valid Element');\n }\n }\n }\n /**\n * Gets the `target` property.\n * @return {String|HTMLElement}\n */\n ,\n get: function get() {\n return this._target;\n }\n }]);\n\n return ClipboardAction;\n}();\n\n/* harmony default export */ var clipboard_action = (ClipboardAction);\n;// CONCATENATED MODULE: ./src/clipboard.js\nfunction clipboard_typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { clipboard_typeof = function _typeof(obj) { return typeof obj; }; } else { clipboard_typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return clipboard_typeof(obj); }\n\nfunction clipboard_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction clipboard_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction clipboard_createClass(Constructor, protoProps, staticProps) { if (protoProps) clipboard_defineProperties(Constructor.prototype, protoProps); if (staticProps) clipboard_defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (clipboard_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n\n\n\n/**\n * Helper function to retrieve attribute value.\n * @param {String} suffix\n * @param {Element} element\n */\n\nfunction getAttributeValue(suffix, element) {\n var attribute = \"data-clipboard-\".concat(suffix);\n\n if (!element.hasAttribute(attribute)) {\n return;\n }\n\n return element.getAttribute(attribute);\n}\n/**\n * Base class which takes one or more elements, adds event listeners to them,\n * and instantiates a new `ClipboardAction` on each click.\n */\n\n\nvar Clipboard = /*#__PURE__*/function (_Emitter) {\n _inherits(Clipboard, _Emitter);\n\n var _super = _createSuper(Clipboard);\n\n /**\n * @param {String|HTMLElement|HTMLCollection|NodeList} trigger\n * @param {Object} options\n */\n function Clipboard(trigger, options) {\n var _this;\n\n clipboard_classCallCheck(this, Clipboard);\n\n _this = _super.call(this);\n\n _this.resolveOptions(options);\n\n _this.listenClick(trigger);\n\n return _this;\n }\n /**\n * Defines if attributes would be resolved using internal setter functions\n * or custom functions that were passed in the constructor.\n * @param {Object} options\n */\n\n\n clipboard_createClass(Clipboard, [{\n key: \"resolveOptions\",\n value: function resolveOptions() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n this.action = typeof options.action === 'function' ? options.action : this.defaultAction;\n this.target = typeof options.target === 'function' ? options.target : this.defaultTarget;\n this.text = typeof options.text === 'function' ? options.text : this.defaultText;\n this.container = clipboard_typeof(options.container) === 'object' ? options.container : document.body;\n }\n /**\n * Adds a click event listener to the passed trigger.\n * @param {String|HTMLElement|HTMLCollection|NodeList} trigger\n */\n\n }, {\n key: \"listenClick\",\n value: function listenClick(trigger) {\n var _this2 = this;\n\n this.listener = listen_default()(trigger, 'click', function (e) {\n return _this2.onClick(e);\n });\n }\n /**\n * Defines a new `ClipboardAction` on each click event.\n * @param {Event} e\n */\n\n }, {\n key: \"onClick\",\n value: function onClick(e) {\n var trigger = e.delegateTarget || e.currentTarget;\n\n if (this.clipboardAction) {\n this.clipboardAction = null;\n }\n\n this.clipboardAction = new clipboard_action({\n action: this.action(trigger),\n target: this.target(trigger),\n text: this.text(trigger),\n container: this.container,\n trigger: trigger,\n emitter: this\n });\n }\n /**\n * Default `action` lookup function.\n * @param {Element} trigger\n */\n\n }, {\n key: \"defaultAction\",\n value: function defaultAction(trigger) {\n return getAttributeValue('action', trigger);\n }\n /**\n * Default `target` lookup function.\n * @param {Element} trigger\n */\n\n }, {\n key: \"defaultTarget\",\n value: function defaultTarget(trigger) {\n var selector = getAttributeValue('target', trigger);\n\n if (selector) {\n return document.querySelector(selector);\n }\n }\n /**\n * Returns the support of the given action, or all actions if no action is\n * given.\n * @param {String} [action]\n */\n\n }, {\n key: \"defaultText\",\n\n /**\n * Default `text` lookup function.\n * @param {Element} trigger\n */\n value: function defaultText(trigger) {\n return getAttributeValue('text', trigger);\n }\n /**\n * Destroy lifecycle.\n */\n\n }, {\n key: \"destroy\",\n value: function destroy() {\n this.listener.destroy();\n\n if (this.clipboardAction) {\n this.clipboardAction.destroy();\n this.clipboardAction = null;\n }\n }\n }], [{\n key: \"isSupported\",\n value: function isSupported() {\n var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['copy', 'cut'];\n var actions = typeof action === 'string' ? [action] : action;\n var support = !!document.queryCommandSupported;\n actions.forEach(function (action) {\n support = support && !!document.queryCommandSupported(action);\n });\n return support;\n }\n }]);\n\n return Clipboard;\n}((tiny_emitter_default()));\n\n/* harmony default export */ var clipboard = (Clipboard);\n\n/***/ }),\n\n/***/ 828:\n/***/ (function(module) {\n\nvar DOCUMENT_NODE_TYPE = 9;\n\n/**\n * A polyfill for Element.matches()\n */\nif (typeof Element !== 'undefined' && !Element.prototype.matches) {\n var proto = Element.prototype;\n\n proto.matches = proto.matchesSelector ||\n proto.mozMatchesSelector ||\n proto.msMatchesSelector ||\n proto.oMatchesSelector ||\n proto.webkitMatchesSelector;\n}\n\n/**\n * Finds the closest parent that matches a selector.\n *\n * @param {Element} element\n * @param {String} selector\n * @return {Function}\n */\nfunction closest (element, selector) {\n while (element && element.nodeType !== DOCUMENT_NODE_TYPE) {\n if (typeof element.matches === 'function' &&\n element.matches(selector)) {\n return element;\n }\n element = element.parentNode;\n }\n}\n\nmodule.exports = closest;\n\n\n/***/ }),\n\n/***/ 438:\n/***/ (function(module, __unused_webpack_exports, __webpack_require__) {\n\nvar closest = __webpack_require__(828);\n\n/**\n * Delegates event to a selector.\n *\n * @param {Element} element\n * @param {String} selector\n * @param {String} type\n * @param {Function} callback\n * @param {Boolean} useCapture\n * @return {Object}\n */\nfunction _delegate(element, selector, type, callback, useCapture) {\n var listenerFn = listener.apply(this, arguments);\n\n element.addEventListener(type, listenerFn, useCapture);\n\n return {\n destroy: function() {\n element.removeEventListener(type, listenerFn, useCapture);\n }\n }\n}\n\n/**\n * Delegates event to a selector.\n *\n * @param {Element|String|Array} [elements]\n * @param {String} selector\n * @param {String} type\n * @param {Function} callback\n * @param {Boolean} useCapture\n * @return {Object}\n */\nfunction delegate(elements, selector, type, callback, useCapture) {\n // Handle the regular Element usage\n if (typeof elements.addEventListener === 'function') {\n return _delegate.apply(null, arguments);\n }\n\n // Handle Element-less usage, it defaults to global delegation\n if (typeof type === 'function') {\n // Use `document` as the first parameter, then apply arguments\n // This is a short way to .unshift `arguments` without running into deoptimizations\n return _delegate.bind(null, document).apply(null, arguments);\n }\n\n // Handle Selector-based usage\n if (typeof elements === 'string') {\n elements = document.querySelectorAll(elements);\n }\n\n // Handle Array-like based usage\n return Array.prototype.map.call(elements, function (element) {\n return _delegate(element, selector, type, callback, useCapture);\n });\n}\n\n/**\n * Finds closest match and invokes callback.\n *\n * @param {Element} element\n * @param {String} selector\n * @param {String} type\n * @param {Function} callback\n * @return {Function}\n */\nfunction listener(element, selector, type, callback) {\n return function(e) {\n e.delegateTarget = closest(e.target, selector);\n\n if (e.delegateTarget) {\n callback.call(element, e);\n }\n }\n}\n\nmodule.exports = delegate;\n\n\n/***/ }),\n\n/***/ 879:\n/***/ (function(__unused_webpack_module, exports) {\n\n/**\n * Check if argument is a HTML element.\n *\n * @param {Object} value\n * @return {Boolean}\n */\nexports.node = function(value) {\n return value !== undefined\n && value instanceof HTMLElement\n && value.nodeType === 1;\n};\n\n/**\n * Check if argument is a list of HTML elements.\n *\n * @param {Object} value\n * @return {Boolean}\n */\nexports.nodeList = function(value) {\n var type = Object.prototype.toString.call(value);\n\n return value !== undefined\n && (type === '[object NodeList]' || type === '[object HTMLCollection]')\n && ('length' in value)\n && (value.length === 0 || exports.node(value[0]));\n};\n\n/**\n * Check if argument is a string.\n *\n * @param {Object} value\n * @return {Boolean}\n */\nexports.string = function(value) {\n return typeof value === 'string'\n || value instanceof String;\n};\n\n/**\n * Check if argument is a function.\n *\n * @param {Object} value\n * @return {Boolean}\n */\nexports.fn = function(value) {\n var type = Object.prototype.toString.call(value);\n\n return type === '[object Function]';\n};\n\n\n/***/ }),\n\n/***/ 370:\n/***/ (function(module, __unused_webpack_exports, __webpack_require__) {\n\nvar is = __webpack_require__(879);\nvar delegate = __webpack_require__(438);\n\n/**\n * Validates all params and calls the right\n * listener function based on its target type.\n *\n * @param {String|HTMLElement|HTMLCollection|NodeList} target\n * @param {String} type\n * @param {Function} callback\n * @return {Object}\n */\nfunction listen(target, type, callback) {\n if (!target && !type && !callback) {\n throw new Error('Missing required arguments');\n }\n\n if (!is.string(type)) {\n throw new TypeError('Second argument must be a String');\n }\n\n if (!is.fn(callback)) {\n throw new TypeError('Third argument must be a Function');\n }\n\n if (is.node(target)) {\n return listenNode(target, type, callback);\n }\n else if (is.nodeList(target)) {\n return listenNodeList(target, type, callback);\n }\n else if (is.string(target)) {\n return listenSelector(target, type, callback);\n }\n else {\n throw new TypeError('First argument must be a String, HTMLElement, HTMLCollection, or NodeList');\n }\n}\n\n/**\n * Adds an event listener to a HTML element\n * and returns a remove listener function.\n *\n * @param {HTMLElement} node\n * @param {String} type\n * @param {Function} callback\n * @return {Object}\n */\nfunction listenNode(node, type, callback) {\n node.addEventListener(type, callback);\n\n return {\n destroy: function() {\n node.removeEventListener(type, callback);\n }\n }\n}\n\n/**\n * Add an event listener to a list of HTML elements\n * and returns a remove listener function.\n *\n * @param {NodeList|HTMLCollection} nodeList\n * @param {String} type\n * @param {Function} callback\n * @return {Object}\n */\nfunction listenNodeList(nodeList, type, callback) {\n Array.prototype.forEach.call(nodeList, function(node) {\n node.addEventListener(type, callback);\n });\n\n return {\n destroy: function() {\n Array.prototype.forEach.call(nodeList, function(node) {\n node.removeEventListener(type, callback);\n });\n }\n }\n}\n\n/**\n * Add an event listener to a selector\n * and returns a remove listener function.\n *\n * @param {String} selector\n * @param {String} type\n * @param {Function} callback\n * @return {Object}\n */\nfunction listenSelector(selector, type, callback) {\n return delegate(document.body, selector, type, callback);\n}\n\nmodule.exports = listen;\n\n\n/***/ }),\n\n/***/ 817:\n/***/ (function(module) {\n\nfunction select(element) {\n var selectedText;\n\n if (element.nodeName === 'SELECT') {\n element.focus();\n\n selectedText = element.value;\n }\n else if (element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') {\n var isReadOnly = element.hasAttribute('readonly');\n\n if (!isReadOnly) {\n element.setAttribute('readonly', '');\n }\n\n element.select();\n element.setSelectionRange(0, element.value.length);\n\n if (!isReadOnly) {\n element.removeAttribute('readonly');\n }\n\n selectedText = element.value;\n }\n else {\n if (element.hasAttribute('contenteditable')) {\n element.focus();\n }\n\n var selection = window.getSelection();\n var range = document.createRange();\n\n range.selectNodeContents(element);\n selection.removeAllRanges();\n selection.addRange(range);\n\n selectedText = selection.toString();\n }\n\n return selectedText;\n}\n\nmodule.exports = select;\n\n\n/***/ }),\n\n/***/ 279:\n/***/ (function(module) {\n\nfunction E () {\n // Keep this empty so it's easier to inherit from\n // (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3)\n}\n\nE.prototype = {\n on: function (name, callback, ctx) {\n var e = this.e || (this.e = {});\n\n (e[name] || (e[name] = [])).push({\n fn: callback,\n ctx: ctx\n });\n\n return this;\n },\n\n once: function (name, callback, ctx) {\n var self = this;\n function listener () {\n self.off(name, listener);\n callback.apply(ctx, arguments);\n };\n\n listener._ = callback\n return this.on(name, listener, ctx);\n },\n\n emit: function (name) {\n var data = [].slice.call(arguments, 1);\n var evtArr = ((this.e || (this.e = {}))[name] || []).slice();\n var i = 0;\n var len = evtArr.length;\n\n for (i; i < len; i++) {\n evtArr[i].fn.apply(evtArr[i].ctx, data);\n }\n\n return this;\n },\n\n off: function (name, callback) {\n var e = this.e || (this.e = {});\n var evts = e[name];\n var liveEvents = [];\n\n if (evts && callback) {\n for (var i = 0, len = evts.length; i < len; i++) {\n if (evts[i].fn !== callback && evts[i].fn._ !== callback)\n liveEvents.push(evts[i]);\n }\n }\n\n // Remove event from queue to prevent memory leak\n // Suggested by https://github.com/lazd\n // Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910\n\n (liveEvents.length)\n ? e[name] = liveEvents\n : delete e[name];\n\n return this;\n }\n};\n\nmodule.exports = E;\nmodule.exports.TinyEmitter = E;\n\n\n/***/ })\n\n/******/ \t});\n/************************************************************************/\n/******/ \t// The module cache\n/******/ \tvar __webpack_module_cache__ = {};\n/******/ \t\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(__webpack_module_cache__[moduleId]) {\n/******/ \t\t\treturn __webpack_module_cache__[moduleId].exports;\n/******/ \t\t}\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = __webpack_module_cache__[moduleId] = {\n/******/ \t\t\t// no module.id needed\n/******/ \t\t\t// no module.loaded needed\n/******/ \t\t\texports: {}\n/******/ \t\t};\n/******/ \t\n/******/ \t\t// Execute the module function\n/******/ \t\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n/******/ \t\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/ \t\n/************************************************************************/\n/******/ \t/* webpack/runtime/compat get default export */\n/******/ \t!function() {\n/******/ \t\t// getDefaultExport function for compatibility with non-harmony modules\n/******/ \t\t__webpack_require__.n = function(module) {\n/******/ \t\t\tvar getter = module && module.__esModule ?\n/******/ \t\t\t\tfunction() { return module['default']; } :\n/******/ \t\t\t\tfunction() { return module; };\n/******/ \t\t\t__webpack_require__.d(getter, { a: getter });\n/******/ \t\t\treturn getter;\n/******/ \t\t};\n/******/ \t}();\n/******/ \t\n/******/ \t/* webpack/runtime/define property getters */\n/******/ \t!function() {\n/******/ \t\t// define getter functions for harmony exports\n/******/ \t\t__webpack_require__.d = function(exports, definition) {\n/******/ \t\t\tfor(var key in definition) {\n/******/ \t\t\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n/******/ \t\t\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n/******/ \t\t\t\t}\n/******/ \t\t\t}\n/******/ \t\t};\n/******/ \t}();\n/******/ \t\n/******/ \t/* webpack/runtime/hasOwnProperty shorthand */\n/******/ \t!function() {\n/******/ \t\t__webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }\n/******/ \t}();\n/******/ \t\n/************************************************************************/\n/******/ \t// module exports must be returned from runtime so entry inlining is disabled\n/******/ \t// startup\n/******/ \t// Load entry module and return exports\n/******/ \treturn __webpack_require__(134);\n/******/ })()\n.default;\n});", "/*!\n * escape-html\n * Copyright(c) 2012-2013 TJ Holowaychuk\n * Copyright(c) 2015 Andreas Lubbe\n * Copyright(c) 2015 Tiancheng \"Timothy\" Gu\n * MIT Licensed\n */\n\n'use strict';\n\n/**\n * Module variables.\n * @private\n */\n\nvar matchHtmlRegExp = /[\"'&<>]/;\n\n/**\n * Module exports.\n * @public\n */\n\nmodule.exports = escapeHtml;\n\n/**\n * Escape special characters in the given string of html.\n *\n * @param {string} string The string to escape for inserting into HTML\n * @return {string}\n * @public\n */\n\nfunction escapeHtml(string) {\n var str = '' + string;\n var match = matchHtmlRegExp.exec(str);\n\n if (!match) {\n return str;\n }\n\n var escape;\n var html = '';\n var index = 0;\n var lastIndex = 0;\n\n for (index = match.index; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34: // \"\n escape = '"';\n break;\n case 38: // &\n escape = '&';\n break;\n case 39: // '\n escape = ''';\n break;\n case 60: // <\n escape = '<';\n break;\n case 62: // >\n escape = '>';\n break;\n default:\n continue;\n }\n\n if (lastIndex !== index) {\n html += str.substring(lastIndex, index);\n }\n\n lastIndex = index + 1;\n html += escape;\n }\n\n return lastIndex !== index\n ? html + str.substring(lastIndex, index)\n : html;\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport \"focus-visible\"\nimport { NEVER, Subject, defer, merge } from \"rxjs\"\nimport {\n delay,\n filter,\n map,\n mergeWith,\n shareReplay,\n switchMap\n} from \"rxjs/operators\"\n\nimport { configuration, feature } from \"./_\"\nimport {\n at,\n getElement,\n requestJSON,\n setToggle,\n watchDocument,\n watchKeyboard,\n watchLocation,\n watchLocationTarget,\n watchMedia,\n watchPrint,\n watchViewport\n} from \"./browser\"\nimport {\n getComponentElement,\n getComponentElements,\n mountBackToTop,\n mountContent,\n mountDialog,\n mountHeader,\n mountHeaderTitle,\n mountPalette,\n mountSearch,\n mountSearchHiglight,\n mountSidebar,\n mountSource,\n mountTableOfContents,\n mountTabs,\n watchHeader,\n watchMain\n} from \"./components\"\nimport {\n SearchIndex,\n setupClipboardJS,\n setupInstantLoading,\n setupVersionSelector\n} from \"./integrations\"\nimport {\n patchIndeterminate,\n patchScrollfix,\n patchScrolllock\n} from \"./patches\"\n\n/* ----------------------------------------------------------------------------\n * Application\n * ------------------------------------------------------------------------- */\n\n/* Yay, JavaScript is available */\ndocument.documentElement.classList.remove(\"no-js\")\ndocument.documentElement.classList.add(\"js\")\n\n/* Set up navigation observables and subjects */\nconst document$ = watchDocument()\nconst location$ = watchLocation()\nconst target$ = watchLocationTarget()\nconst keyboard$ = watchKeyboard()\n\n/* Set up media observables */\nconst viewport$ = watchViewport()\nconst tablet$ = watchMedia(\"(min-width: 960px)\")\nconst screen$ = watchMedia(\"(min-width: 1220px)\")\nconst print$ = watchPrint()\n\n/* Retrieve search index, if search is enabled */\nconst config = configuration()\nconst index$ = document.forms.namedItem(\"search\")\n ? __search?.index || requestJSON(\n `${config.base}/search/search_index.json`\n )\n : NEVER\n\n/* Set up Clipboard.js integration */\nconst alert$ = new Subject()\nsetupClipboardJS({ alert$ })\n\n/* Set up instant loading, if enabled */\nif (feature(\"navigation.instant\"))\n setupInstantLoading({ document$, location$, viewport$ })\n\n/* Set up version selector */\nif (config.version?.provider === \"mike\")\n setupVersionSelector()\n\n/* Always close drawer and search on navigation */\nmerge(location$, target$)\n .pipe(\n delay(125)\n )\n .subscribe(() => {\n setToggle(\"drawer\", false)\n setToggle(\"search\", false)\n })\n\n/* Set up global keyboard handlers */\nkeyboard$\n .pipe(\n filter(({ mode }) => mode === \"global\")\n )\n .subscribe(key => {\n switch (key.type) {\n\n /* Go to previous page */\n case \"p\":\n case \",\":\n const prev = getElement(\"[href][rel=prev]\")\n if (typeof prev !== \"undefined\")\n prev.click()\n break\n\n /* Go to next page */\n case \"n\":\n case \".\":\n const next = getElement(\"[href][rel=next]\")\n if (typeof next !== \"undefined\")\n next.click()\n break\n }\n })\n\n/* Set up patches */\npatchIndeterminate({ document$, tablet$ })\npatchScrollfix({ document$ })\npatchScrolllock({ viewport$, tablet$ })\n\n/* Set up header and main area observable */\nconst header$ = watchHeader(getComponentElement(\"header\"), { viewport$ })\nconst main$ = document$\n .pipe(\n map(() => getComponentElement(\"main\")),\n switchMap(el => watchMain(el, { viewport$, header$ })),\n shareReplay(1)\n )\n\n/* Set up control component observables */\nconst control$ = merge(\n\n /* Dialog */\n ...getComponentElements(\"dialog\")\n .map(el => mountDialog(el, { alert$ })),\n\n /* Header */\n ...getComponentElements(\"header\")\n .map(el => mountHeader(el, { viewport$, header$, main$ })),\n\n /* Color palette */\n ...getComponentElements(\"palette\")\n .map(el => mountPalette(el)),\n\n /* Search */\n ...getComponentElements(\"search\")\n .map(el => mountSearch(el, { index$, keyboard$ })),\n\n /* Repository information */\n ...getComponentElements(\"source\")\n .map(el => mountSource(el))\n)\n\n/* Set up content component observables */\nconst content$ = defer(() => merge(\n\n /* Content */\n ...getComponentElements(\"content\")\n .map(el => mountContent(el, { target$, viewport$, print$ })),\n\n /* Search highlighting */\n ...getComponentElements(\"content\")\n .map(el => feature(\"search.highlight\")\n ? mountSearchHiglight(el, { index$, location$ })\n : NEVER\n ),\n\n /* Header title */\n ...getComponentElements(\"header-title\")\n .map(el => mountHeaderTitle(el, { viewport$, header$ })),\n\n /* Sidebar */\n ...getComponentElements(\"sidebar\")\n .map(el => el.getAttribute(\"data-md-type\") === \"navigation\"\n ? at(screen$, () => mountSidebar(el, { viewport$, header$, main$ }))\n : at(tablet$, () => mountSidebar(el, { viewport$, header$, main$ }))\n ),\n\n /* Navigation tabs */\n ...getComponentElements(\"tabs\")\n .map(el => mountTabs(el, { viewport$, header$ })),\n\n /* Table of contents */\n ...getComponentElements(\"toc\")\n .map(el => mountTableOfContents(el, { viewport$, header$ })),\n\n /* Back-to-top button */\n ...getComponentElements(\"top\")\n .map(el => mountBackToTop(el, { viewport$, header$, main$ }))\n))\n\n/* Set up component observables */\nconst component$ = document$\n .pipe(\n switchMap(() => content$),\n mergeWith(control$),\n shareReplay(1)\n )\n\n/* Subscribe to all components */\ncomponent$.subscribe()\n\n/* ----------------------------------------------------------------------------\n * Exports\n * ------------------------------------------------------------------------- */\n\nwindow.document$ = document$ /* Document observable */\nwindow.location$ = location$ /* Location subject */\nwindow.target$ = target$ /* Location target observable */\nwindow.keyboard$ = keyboard$ /* Keyboard observable */\nwindow.viewport$ = viewport$ /* Viewport observable */\nwindow.tablet$ = tablet$ /* Tablet observable */\nwindow.screen$ = screen$ /* Screen observable */\nwindow.print$ = print$ /* Print mode observable */\nwindow.alert$ = alert$ /* Alert subject */\nwindow.component$ = component$ /* Component observable */\n", "import tslib from '../tslib.js';\r\nconst {\r\n __extends,\r\n __assign,\r\n __rest,\r\n __decorate,\r\n __param,\r\n __metadata,\r\n __awaiter,\r\n __generator,\r\n __exportStar,\r\n __createBinding,\r\n __values,\r\n __read,\r\n __spread,\r\n __spreadArrays,\r\n __spreadArray,\r\n __await,\r\n __asyncGenerator,\r\n __asyncDelegator,\r\n __asyncValues,\r\n __makeTemplateObject,\r\n __importStar,\r\n __importDefault,\r\n __classPrivateFieldGet,\r\n __classPrivateFieldSet,\r\n} = tslib;\r\nexport {\r\n __extends,\r\n __assign,\r\n __rest,\r\n __decorate,\r\n __param,\r\n __metadata,\r\n __awaiter,\r\n __generator,\r\n __exportStar,\r\n __createBinding,\r\n __values,\r\n __read,\r\n __spread,\r\n __spreadArrays,\r\n __spreadArray,\r\n __await,\r\n __asyncGenerator,\r\n __asyncDelegator,\r\n __asyncValues,\r\n __makeTemplateObject,\r\n __importStar,\r\n __importDefault,\r\n __classPrivateFieldGet,\r\n __classPrivateFieldSet,\r\n};\r\n", null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { ReplaySubject, Subject, fromEvent } from \"rxjs\"\nimport { mapTo } from \"rxjs/operators\"\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch document\n *\n * Documents are implemented as subjects, so all downstream observables are\n * automatically updated when a new document is emitted.\n *\n * @returns Document subject\n */\nexport function watchDocument(): Subject {\n const document$ = new ReplaySubject()\n fromEvent(document, \"DOMContentLoaded\")\n .pipe(\n mapTo(document)\n )\n .subscribe(document$)\n\n /* Return document */\n return document$\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Retrieve an element matching the query selector\n *\n * @template T - Element type\n *\n * @param selector - Query selector\n * @param node - Node of reference\n *\n * @returns Element or nothing\n */\nexport function getElement(\n selector: T, node?: ParentNode\n): HTMLElementTagNameMap[T]\n\nexport function getElement(\n selector: string, node?: ParentNode\n): T | undefined\n\nexport function getElement(\n selector: string, node: ParentNode = document\n): T | undefined {\n return node.querySelector(selector) || undefined\n}\n\n/**\n * Retrieve an element matching a query selector or throw a reference error\n *\n * @template T - Element type\n *\n * @param selector - Query selector\n * @param node - Node of reference\n *\n * @returns Element\n */\nexport function getElementOrThrow(\n selector: T, node?: ParentNode\n): HTMLElementTagNameMap[T]\n\nexport function getElementOrThrow(\n selector: string, node?: ParentNode\n): T\n\nexport function getElementOrThrow(\n selector: string, node: ParentNode = document\n): T {\n const el = getElement(selector, node)\n if (typeof el === \"undefined\")\n throw new ReferenceError(\n `Missing element: expected \"${selector}\" to be present`\n )\n return el\n}\n\n/**\n * Retrieve the currently active element\n *\n * @returns Element or nothing\n */\nexport function getActiveElement(): HTMLElement | undefined {\n return document.activeElement instanceof HTMLElement\n ? document.activeElement\n : undefined\n}\n\n/**\n * Retrieve all elements matching the query selector\n *\n * @template T - Element type\n *\n * @param selector - Query selector\n * @param node - Node of reference\n *\n * @returns Elements\n */\nexport function getElements(\n selector: T, node?: ParentNode\n): HTMLElementTagNameMap[T][]\n\nexport function getElements(\n selector: string, node?: ParentNode\n): T[]\n\nexport function getElements(\n selector: string, node: ParentNode = document\n): T[] {\n return Array.from(node.querySelectorAll(selector))\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Create an element\n *\n * @template T - Tag name type\n *\n * @param tagName - Tag name\n *\n * @returns Element\n */\nexport function createElement(\n tagName: T\n): HTMLElementTagNameMap[T] {\n return document.createElement(tagName)\n}\n\n/**\n * Replace an element with the given list of nodes\n *\n * @param el - Element\n * @param nodes - Replacement nodes\n */\nexport function replaceElement(\n el: HTMLElement, ...nodes: Node[]\n): void {\n el.replaceWith(...nodes)\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { Observable, fromEvent, merge } from \"rxjs\"\nimport { map, startWith } from \"rxjs/operators\"\n\nimport { getActiveElement } from \"../_\"\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Set element focus\n *\n * @param el - Element\n * @param value - Whether the element should be focused\n */\nexport function setElementFocus(\n el: HTMLElement, value = true\n): void {\n if (value)\n el.focus()\n else\n el.blur()\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Watch element focus\n *\n * @param el - Element\n *\n * @returns Element focus observable\n */\nexport function watchElementFocus(\n el: HTMLElement\n): Observable {\n return merge(\n fromEvent(el, \"focus\"),\n fromEvent(el, \"blur\")\n )\n .pipe(\n map(({ type }) => type === \"focus\"),\n startWith(el === getActiveElement())\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport {\n NEVER,\n Observable,\n Subject,\n defer,\n of\n} from \"rxjs\"\nimport {\n filter,\n finalize,\n map,\n shareReplay,\n startWith,\n switchMap,\n tap\n} from \"rxjs/operators\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Element offset\n */\nexport interface ElementSize {\n width: number /* Element width */\n height: number /* Element height */\n}\n\n/* ----------------------------------------------------------------------------\n * Data\n * ------------------------------------------------------------------------- */\n\n/**\n * Resize observer entry subject\n */\nconst entry$ = new Subject()\n\n/**\n * Resize observer observable\n *\n * This observable will create a `ResizeObserver` on the first subscription\n * and will automatically terminate it when there are no more subscribers.\n * It's quite important to centralize observation in a single `ResizeObserver`,\n * as the performance difference can be quite dramatic, as the link shows.\n *\n * @see https://bit.ly/3iIYfEm - Google Groups on performance\n */\nconst observer$ = defer(() => of(\n new ResizeObserver(entries => {\n for (const entry of entries)\n entry$.next(entry)\n })\n))\n .pipe(\n switchMap(resize => NEVER.pipe(startWith(resize))\n .pipe(\n finalize(() => resize.disconnect())\n )\n ),\n shareReplay(1)\n )\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Retrieve element size\n *\n * @param el - Element\n *\n * @returns Element size\n */\nexport function getElementSize(el: HTMLElement): ElementSize {\n return {\n width: el.offsetWidth,\n height: el.offsetHeight\n }\n}\n\n/**\n * Retrieve element content size, i.e. including overflowing content\n *\n * @param el - Element\n *\n * @returns Element size\n */\nexport function getElementContentSize(el: HTMLElement): ElementSize {\n return {\n width: el.scrollWidth,\n height: el.scrollHeight\n }\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Watch element size\n *\n * This function returns an observable that subscribes to a single internal\n * instance of `ResizeObserver` upon subscription, and emit resize events until\n * termination. Note that this function should not be called with the same\n * element twice, as the first unsubscription will terminate observation.\n *\n * Sadly, we can't use the `DOMRect` objects returned by the observer, because\n * we need the emitted values to be consistent with `getElementSize`, which will\n * return the used values (rounded) and not actual values (unrounded). Thus, we\n * use the `offset*` properties. See the linked GitHub issue.\n *\n * @see https://bit.ly/3m0k3he - GitHub issue\n *\n * @param el - Element\n *\n * @returns Element size observable\n */\nexport function watchElementSize(\n el: HTMLElement\n): Observable {\n return observer$\n .pipe(\n tap(observer => observer.observe(el)),\n switchMap(observer => entry$\n .pipe(\n filter(({ target }) => target === el),\n finalize(() => observer.unobserve(el)),\n map(() => getElementSize(el))\n )\n ),\n startWith(getElementSize(el))\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { Observable, fromEvent, merge } from \"rxjs\"\nimport {\n distinctUntilChanged,\n map,\n startWith\n} from \"rxjs/operators\"\n\nimport {\n getElementContentSize,\n getElementSize\n} from \"../size\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Element offset\n */\nexport interface ElementOffset {\n x: number /* Horizontal offset */\n y: number /* Vertical offset */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Retrieve element offset\n *\n * @param el - Element\n *\n * @returns Element offset\n */\nexport function getElementOffset(el: HTMLElement): ElementOffset {\n return {\n x: el.scrollLeft,\n y: el.scrollTop\n }\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Watch element offset\n *\n * @param el - Element\n *\n * @returns Element offset observable\n */\nexport function watchElementOffset(\n el: HTMLElement\n): Observable {\n return merge(\n fromEvent(el, \"scroll\"),\n fromEvent(window, \"resize\")\n )\n .pipe(\n map(() => getElementOffset(el)),\n startWith(getElementOffset(el))\n )\n}\n\n/**\n * Watch element threshold\n *\n * This function returns an observable which emits whether the bottom scroll\n * offset of an elements is within a certain threshold.\n *\n * @param el - Element\n * @param threshold - Threshold\n *\n * @returns Element threshold observable\n */\nexport function watchElementThreshold(\n el: HTMLElement, threshold = 16\n): Observable {\n return watchElementOffset(el)\n .pipe(\n map(({ y }) => {\n const visible = getElementSize(el)\n const content = getElementContentSize(el)\n return y >= (\n content.height - visible.height - threshold\n )\n }),\n distinctUntilChanged()\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Set element text selection\n *\n * @param el - Element\n */\nexport function setElementSelection(\n el: HTMLElement\n): void {\n if (el instanceof HTMLInputElement)\n el.select()\n else\n throw new Error(\"Not implemented\")\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { Observable, fromEvent } from \"rxjs\"\nimport { map, startWith } from \"rxjs/operators\"\n\nimport { getElementOrThrow } from \"../element\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Toggle\n */\nexport type Toggle =\n | \"drawer\" /* Toggle for drawer */\n | \"search\" /* Toggle for search */\n\n/* ----------------------------------------------------------------------------\n * Data\n * ------------------------------------------------------------------------- */\n\n/**\n * Toggle map\n */\nconst toggles: Record = {\n drawer: getElementOrThrow(\"[data-md-toggle=drawer]\"),\n search: getElementOrThrow(\"[data-md-toggle=search]\")\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Retrieve the value of a toggle\n *\n * @param name - Toggle\n *\n * @returns Toggle value\n */\nexport function getToggle(name: Toggle): boolean {\n return toggles[name].checked\n}\n\n/**\n * Set toggle\n *\n * Simulating a click event seems to be the most cross-browser compatible way\n * of changing the value while also emitting a `change` event. Before, Material\n * used `CustomEvent` to programmatically change the value of a toggle, but this\n * is a much simpler and cleaner solution which doesn't require a polyfill.\n *\n * @param name - Toggle\n * @param value - Toggle value\n */\nexport function setToggle(name: Toggle, value: boolean): void {\n if (toggles[name].checked !== value)\n toggles[name].click()\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Watch toggle\n *\n * @param name - Toggle\n *\n * @returns Toggle value observable\n */\nexport function watchToggle(name: Toggle): Observable {\n const el = toggles[name]\n return fromEvent(el, \"change\")\n .pipe(\n map(() => el.checked),\n startWith(el.checked)\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { Observable, fromEvent } from \"rxjs\"\nimport { filter, map, share } from \"rxjs/operators\"\n\nimport { getActiveElement } from \"../element\"\nimport { getToggle } from \"../toggle\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Keyboard mode\n */\nexport type KeyboardMode =\n | \"global\" /* Global */\n | \"search\" /* Search is open */\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Keyboard\n */\nexport interface Keyboard {\n mode: KeyboardMode /* Keyboard mode */\n type: string /* Key type */\n claim(): void /* Key claim */\n}\n\n/* ----------------------------------------------------------------------------\n * Helper functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Check whether an element may receive keyboard input\n *\n * @param el - Element\n *\n * @returns Test result\n */\nfunction isSusceptibleToKeyboard(el: HTMLElement): boolean {\n switch (el.tagName) {\n\n /* Form elements */\n case \"INPUT\":\n case \"SELECT\":\n case \"TEXTAREA\":\n return true\n\n /* Everything else */\n default:\n return el.isContentEditable\n }\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch keyboard\n *\n * @returns Keyboard observable\n */\nexport function watchKeyboard(): Observable {\n return fromEvent(window, \"keydown\")\n .pipe(\n filter(ev => !(ev.metaKey || ev.ctrlKey)),\n map(ev => ({\n mode: getToggle(\"search\") ? \"search\" : \"global\",\n type: ev.key,\n claim() {\n ev.preventDefault()\n ev.stopPropagation()\n }\n } as Keyboard)),\n filter(({ mode }) => {\n if (mode === \"global\") {\n const active = getActiveElement()\n if (typeof active !== \"undefined\")\n return !isSusceptibleToKeyboard(active)\n }\n return true\n }),\n share()\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { Subject } from \"rxjs\"\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Retrieve location\n *\n * This function returns a `URL` object (and not `Location`) to normalize the\n * typings across the application. Furthermore, locations need to be tracked\n * without setting them and `Location` is a singleton which represents the\n * current location.\n *\n * @returns URL\n */\nexport function getLocation(): URL {\n return new URL(location.href)\n}\n\n/**\n * Set location\n *\n * @param url - URL to change to\n */\nexport function setLocation(url: URL): void {\n location.href = url.href\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Watch location\n *\n * @returns Location subject\n */\nexport function watchLocation(): Subject {\n return new Subject()\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { Observable, fromEvent, of } from \"rxjs\"\nimport { filter, map, share, startWith, switchMap } from \"rxjs/operators\"\n\nimport { createElement, getElement } from \"~/browser\"\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Retrieve location hash\n *\n * @returns Location hash\n */\nexport function getLocationHash(): string {\n return location.hash.substring(1)\n}\n\n/**\n * Set location hash\n *\n * Setting a new fragment identifier via `location.hash` will have no effect\n * if the value doesn't change. When a new fragment identifier is set, we want\n * the browser to target the respective element at all times, which is why we\n * use this dirty little trick.\n *\n * @param hash - Location hash\n */\nexport function setLocationHash(hash: string): void {\n const el = createElement(\"a\")\n el.href = hash\n el.addEventListener(\"click\", ev => ev.stopPropagation())\n el.click()\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Watch location hash\n *\n * @returns Location hash observable\n */\nexport function watchLocationHash(): Observable {\n return fromEvent(window, \"hashchange\")\n .pipe(\n map(getLocationHash),\n startWith(getLocationHash()),\n filter(hash => hash.length > 0),\n share()\n )\n}\n\n/**\n * Watch location target\n *\n * @returns Location target observable\n */\nexport function watchLocationTarget(): Observable {\n return watchLocationHash()\n .pipe(\n switchMap(id => of(getElement(`[id=\"${id}\"]`)!))\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport {\n NEVER,\n Observable,\n fromEvent,\n fromEventPattern\n} from \"rxjs\"\nimport {\n mapTo,\n startWith,\n switchMap\n} from \"rxjs/operators\"\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch media query\n *\n * Note that although `MediaQueryList.addListener` is deprecated we have to\n * use it, because it's the only way to ensure proper downward compatibility.\n *\n * @see https://bit.ly/3dUBH2m - GitHub issue\n *\n * @param query - Media query\n *\n * @returns Media observable\n */\nexport function watchMedia(query: string): Observable {\n const media = matchMedia(query)\n return fromEventPattern(next => (\n media.addListener(() => next(media.matches))\n ))\n .pipe(\n startWith(media.matches)\n )\n}\n\n/**\n * Watch print mode, cross-browser\n *\n * @returns Print mode observable\n */\nexport function watchPrint(): Observable {\n return fromEvent(window, \"beforeprint\")\n .pipe(\n mapTo(undefined)\n )\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Toggle an observable with a media observable\n *\n * @template T - Data type\n *\n * @param query$ - Media observable\n * @param factory - Observable factory\n *\n * @returns Toggled observable\n */\nexport function at(\n query$: Observable, factory: () => Observable\n): Observable {\n return query$\n .pipe(\n switchMap(active => active ? factory() : NEVER)\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { Observable, from } from \"rxjs\"\nimport {\n filter,\n map,\n shareReplay,\n switchMap\n} from \"rxjs/operators\"\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Fetch the given URL\n *\n * @param url - Request URL\n * @param options - Options\n *\n * @returns Response observable\n */\nexport function request(\n url: URL | string, options: RequestInit = { credentials: \"same-origin\" }\n): Observable {\n return from(fetch(`${url}`, options))\n .pipe(\n filter(res => res.status === 200),\n )\n}\n\n/**\n * Fetch JSON from the given URL\n *\n * @template T - Data type\n *\n * @param url - Request URL\n * @param options - Options\n *\n * @returns Data observable\n */\nexport function requestJSON(\n url: URL | string, options?: RequestInit\n): Observable {\n return request(url, options)\n .pipe(\n switchMap(res => res.json()),\n shareReplay(1)\n )\n}\n\n/**\n * Fetch XML from the given URL\n *\n * @param url - Request URL\n * @param options - Options\n *\n * @returns Data observable\n */\nexport function requestXML(\n url: URL | string, options?: RequestInit\n): Observable {\n const dom = new DOMParser()\n return request(url, options)\n .pipe(\n switchMap(res => res.text()),\n map(res => dom.parseFromString(res, \"text/xml\")),\n shareReplay(1)\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { Observable, fromEvent, merge } from \"rxjs\"\nimport { map, startWith } from \"rxjs/operators\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Viewport offset\n */\nexport interface ViewportOffset {\n x: number /* Horizontal offset */\n y: number /* Vertical offset */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Retrieve viewport offset\n *\n * On iOS Safari, viewport offset can be negative due to overflow scrolling.\n * As this may induce strange behaviors downstream, we'll just limit it to 0.\n *\n * @returns Viewport offset\n */\nexport function getViewportOffset(): ViewportOffset {\n return {\n x: Math.max(0, pageXOffset),\n y: Math.max(0, pageYOffset)\n }\n}\n\n/**\n * Set viewport offset\n *\n * @param offset - Viewport offset\n */\nexport function setViewportOffset(\n { x, y }: Partial\n): void {\n window.scrollTo(x || 0, y || 0)\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Watch viewport offset\n *\n * @returns Viewport offset observable\n */\nexport function watchViewportOffset(): Observable {\n return merge(\n fromEvent(window, \"scroll\", { passive: true }),\n fromEvent(window, \"resize\", { passive: true })\n )\n .pipe(\n map(getViewportOffset),\n startWith(getViewportOffset())\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { Observable, fromEvent } from \"rxjs\"\nimport { map, startWith } from \"rxjs/operators\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Viewport size\n */\nexport interface ViewportSize {\n width: number /* Viewport width */\n height: number /* Viewport height */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Retrieve viewport size\n *\n * @returns Viewport size\n */\nexport function getViewportSize(): ViewportSize {\n return {\n width: innerWidth,\n height: innerHeight\n }\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Watch viewport size\n *\n * @returns Viewport size observable\n */\nexport function watchViewportSize(): Observable {\n return fromEvent(window, \"resize\", { passive: true })\n .pipe(\n map(getViewportSize),\n startWith(getViewportSize())\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { Observable, combineLatest } from \"rxjs\"\nimport {\n distinctUntilKeyChanged,\n map,\n shareReplay\n} from \"rxjs/operators\"\n\nimport { Header } from \"~/components\"\n\nimport {\n ViewportOffset,\n watchViewportOffset\n} from \"../offset\"\nimport {\n ViewportSize,\n watchViewportSize\n} from \"../size\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Viewport\n */\nexport interface Viewport {\n offset: ViewportOffset /* Viewport offset */\n size: ViewportSize /* Viewport size */\n}\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch at options\n */\ninterface WatchAtOptions {\n viewport$: Observable /* Viewport observable */\n header$: Observable
/* Header observable */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch viewport\n *\n * @returns Viewport observable\n */\nexport function watchViewport(): Observable {\n return combineLatest([\n watchViewportOffset(),\n watchViewportSize()\n ])\n .pipe(\n map(([offset, size]) => ({ offset, size })),\n shareReplay(1)\n )\n}\n\n/**\n * Watch viewport relative to element\n *\n * @param el - Element\n * @param options - Options\n *\n * @returns Viewport observable\n */\nexport function watchViewportAt(\n el: HTMLElement, { viewport$, header$ }: WatchAtOptions\n): Observable {\n const size$ = viewport$\n .pipe(\n distinctUntilKeyChanged(\"size\")\n )\n\n /* Compute element offset */\n const offset$ = combineLatest([size$, header$])\n .pipe(\n map((): ViewportOffset => ({\n x: el.offsetLeft,\n y: el.offsetTop\n }))\n )\n\n /* Compute relative viewport, return hot observable */\n return combineLatest([header$, viewport$, offset$])\n .pipe(\n map(([{ height }, { offset, size }, { x, y }]) => ({\n offset: {\n x: offset.x - x,\n y: offset.y - y + height\n },\n size\n }))\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { Observable, Subject, fromEvent } from \"rxjs\"\nimport {\n map,\n share,\n switchMapTo,\n tap,\n throttle\n} from \"rxjs/operators\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Worker message\n */\nexport interface WorkerMessage {\n type: unknown /* Message type */\n data?: unknown /* Message data */\n}\n\n/**\n * Worker handler\n *\n * @template T - Message type\n */\nexport interface WorkerHandler<\n T extends WorkerMessage\n> {\n tx$: Subject /* Message transmission subject */\n rx$: Observable /* Message receive observable */\n}\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch options\n *\n * @template T - Worker message type\n */\ninterface WatchOptions {\n tx$: Observable /* Message transmission observable */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch a web worker\n *\n * This function returns an observable that sends all values emitted by the\n * message observable to the web worker. Web worker communication is expected\n * to be bidirectional (request-response) and synchronous. Messages that are\n * emitted during a pending request are throttled, the last one is emitted.\n *\n * @param worker - Web worker\n * @param options - Options\n *\n * @returns Worker message observable\n */\nexport function watchWorker(\n worker: Worker, { tx$ }: WatchOptions\n): Observable {\n\n /* Intercept messages from worker-like objects */\n const rx$ = fromEvent(worker, \"message\")\n .pipe(\n map(({ data }) => data as T)\n )\n\n /* Send and receive messages, return hot observable */\n return tx$\n .pipe(\n throttle(() => rx$, { leading: true, trailing: true }),\n tap(message => worker.postMessage(message)),\n switchMapTo(rx$),\n share()\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { getElementOrThrow, getLocation } from \"~/browser\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Feature flag\n */\nexport type Flag =\n | \"header.autohide\" /* Hide header */\n | \"navigation.expand\" /* Automatic expansion */\n | \"navigation.instant\" /* Instant loading */\n | \"navigation.sections\" /* Sections navigation */\n | \"navigation.tabs\" /* Tabs navigation */\n | \"navigation.top\" /* Back-to-top button */\n | \"search.highlight\" /* Search highlighting */\n | \"search.share\" /* Search sharing */\n | \"search.suggest\" /* Search suggestions */\n | \"toc.integrate\" /* Integrated table of contents */\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Translation\n */\nexport type Translation =\n | \"clipboard.copy\" /* Copy to clipboard */\n | \"clipboard.copied\" /* Copied to clipboard */\n | \"search.config.lang\" /* Search language */\n | \"search.config.pipeline\" /* Search pipeline */\n | \"search.config.separator\" /* Search separator */\n | \"search.placeholder\" /* Search */\n | \"search.result.placeholder\" /* Type to start searching */\n | \"search.result.none\" /* No matching documents */\n | \"search.result.one\" /* 1 matching document */\n | \"search.result.other\" /* # matching documents */\n | \"search.result.more.one\" /* 1 more on this page */\n | \"search.result.more.other\" /* # more on this page */\n | \"search.result.term.missing\" /* Missing */\n | \"select.version.title\" /* Version selector */\n\n/**\n * Translations\n */\nexport type Translations = Record\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Versioning\n */\nexport interface Versioning {\n provider: \"mike\" /* Version provider */\n}\n\n/**\n * Configuration\n */\nexport interface Config {\n base: string /* Base URL */\n features: Flag[] /* Feature flags */\n translations: Translations /* Translations */\n search: string /* Search worker URL */\n version?: Versioning /* Versioning */\n}\n\n/* ----------------------------------------------------------------------------\n * Data\n * ------------------------------------------------------------------------- */\n\n/**\n * Retrieve global configuration and make base URL absolute\n */\nconst script = getElementOrThrow(\"#__config\")\nconst config: Config = JSON.parse(script.textContent!)\nconfig.base = new URL(config.base, getLocation())\n .toString()\n .replace(/\\/$/, \"\")\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Retrieve global configuration\n *\n * @returns Global configuration\n */\nexport function configuration(): Config {\n return config\n}\n\n/**\n * Check whether a feature flag is enabled\n *\n * @param flag - Feature flag\n *\n * @returns Test result\n */\nexport function feature(flag: Flag): boolean {\n return config.features.includes(flag)\n}\n\n/**\n * Retrieve the translation for the given key\n *\n * @param key - Key to be translated\n * @param value - Positional value, if any\n *\n * @returns Translation\n */\nexport function translation(\n key: Translation, value?: string | number\n): string {\n return typeof value !== \"undefined\"\n ? config.translations[key].replace(\"#\", value.toString())\n : config.translations[key]\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { getElementOrThrow, getElements } from \"~/browser\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Component\n */\nexport type ComponentType =\n | \"announce\" /* Announcement bar */\n | \"container\" /* Container */\n | \"content\" /* Content */\n | \"dialog\" /* Dialog */\n | \"header\" /* Header */\n | \"header-title\" /* Header title */\n | \"header-topic\" /* Header topic */\n | \"main\" /* Main area */\n | \"palette\" /* Color palette */\n | \"search\" /* Search */\n | \"search-query\" /* Search input */\n | \"search-result\" /* Search results */\n | \"search-share\" /* Search sharing */\n | \"search-suggest\" /* Search suggestions */\n | \"sidebar\" /* Sidebar */\n | \"skip\" /* Skip link */\n | \"source\" /* Repository information */\n | \"tabs\" /* Navigation tabs */\n | \"toc\" /* Table of contents */\n | \"top\" /* Back-to-top button */\n\n/**\n * A component\n *\n * @template T - Component type\n * @template U - Reference type\n */\nexport type Component<\n T extends {} = {},\n U extends HTMLElement = HTMLElement\n> =\n T & {\n ref: U /* Component reference */\n }\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Component type map\n */\ninterface ComponentTypeMap {\n \"announce\": HTMLElement /* Announcement bar */\n \"container\": HTMLElement /* Container */\n \"content\": HTMLElement /* Content */\n \"dialog\": HTMLElement /* Dialog */\n \"header\": HTMLElement /* Header */\n \"header-title\": HTMLElement /* Header title */\n \"header-topic\": HTMLElement /* Header topic */\n \"main\": HTMLElement /* Main area */\n \"palette\": HTMLElement /* Color palette */\n \"search\": HTMLElement /* Search */\n \"search-query\": HTMLInputElement /* Search input */\n \"search-result\": HTMLElement /* Search results */\n \"search-share\": HTMLAnchorElement /* Search sharing */\n \"search-suggest\": HTMLElement /* Search suggestions */\n \"sidebar\": HTMLElement /* Sidebar */\n \"skip\": HTMLAnchorElement /* Skip link */\n \"source\": HTMLAnchorElement /* Repository information */\n \"tabs\": HTMLElement /* Navigation tabs */\n \"toc\": HTMLElement /* Table of contents */\n \"top\": HTMLAnchorElement /* Back-to-top button */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Retrieve the element for a given component or throw a reference error\n *\n * @template T - Component type\n *\n * @param type - Component type\n * @param node - Node of reference\n *\n * @returns Element\n */\nexport function getComponentElement(\n type: T, node: ParentNode = document\n): ComponentTypeMap[T] {\n return getElementOrThrow(`[data-md-component=${type}]`, node)\n}\n\n/**\n * Retrieve all elements for a given component\n *\n * @template T - Component type\n *\n * @param type - Component type\n * @param node - Node of reference\n *\n * @returns Elements\n */\nexport function getComponentElements(\n type: T, node: ParentNode = document\n): ComponentTypeMap[T][] {\n return getElements(`[data-md-component=${type}]`, node)\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport ClipboardJS from \"clipboard\"\nimport {\n NEVER,\n Observable,\n Subject,\n fromEvent,\n merge,\n of\n} from \"rxjs\"\nimport {\n distinctUntilKeyChanged,\n finalize,\n map,\n switchMap,\n tap,\n withLatestFrom\n} from \"rxjs/operators\"\n\nimport { resetFocusable, setFocusable } from \"~/actions\"\nimport {\n Viewport,\n getElementContentSize,\n getElementSize,\n getElements,\n watchMedia\n} from \"~/browser\"\nimport { renderClipboardButton } from \"~/templates\"\n\nimport { Component } from \"../../_\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Code block\n */\nexport interface CodeBlock {\n scroll: boolean /* Code block overflows */\n}\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch options\n */\ninterface WatchOptions {\n viewport$: Observable /* Viewport observable */\n}\n\n/**\n * Mount options\n */\ninterface MountOptions {\n viewport$: Observable /* Viewport observable */\n}\n\n/* ----------------------------------------------------------------------------\n * Data\n * ------------------------------------------------------------------------- */\n\n/**\n * Global index for Clipboard.js integration\n */\nlet index = 0\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch code block\n *\n * This function monitors size changes of the viewport, as well as switches of\n * content tabs with embedded code blocks, as both may trigger overflow.\n *\n * @param el - Code block element\n * @param options - Options\n *\n * @returns Code block observable\n */\nexport function watchCodeBlock(\n el: HTMLElement, { viewport$ }: WatchOptions\n): Observable {\n const container$ = of(el)\n .pipe(\n switchMap(child => {\n const container = child.closest(\"[data-tabs]\")\n if (container instanceof HTMLElement) {\n return merge(\n ...getElements(\"input\", container)\n .map(input => fromEvent(input, \"change\"))\n )\n }\n return NEVER\n })\n )\n\n /* Check overflow on resize and tab change */\n return merge(\n viewport$.pipe(distinctUntilKeyChanged(\"size\")),\n container$\n )\n .pipe(\n map(() => {\n const visible = getElementSize(el)\n const content = getElementContentSize(el)\n return {\n scroll: content.width > visible.width\n }\n }),\n distinctUntilKeyChanged(\"scroll\")\n )\n}\n\n/**\n * Mount code block\n *\n * This function ensures that an overflowing code block is focusable through\n * keyboard, so it can be scrolled without a mouse to improve on accessibility.\n *\n * @param el - Code block element\n * @param options - Options\n *\n * @returns Code block component observable\n */\nexport function mountCodeBlock(\n el: HTMLElement, options: MountOptions\n): Observable> {\n const internal$ = new Subject()\n internal$\n .pipe(\n withLatestFrom(watchMedia(\"(hover)\"))\n )\n .subscribe(([{ scroll }, hover]) => {\n if (scroll && hover)\n setFocusable(el)\n else\n resetFocusable(el)\n })\n\n /* Render button for Clipboard.js integration */\n if (ClipboardJS.isSupported()) {\n const parent = el.closest(\"pre\")!\n parent.id = `__code_${index++}`\n parent.insertBefore(\n renderClipboardButton(parent.id),\n el\n )\n }\n\n /* Create and return component */\n return watchCodeBlock(el, options)\n .pipe(\n tap(internal$),\n finalize(() => internal$.complete()),\n map(state => ({ ref: el, ...state }))\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Set focusable property\n *\n * @param el - Element\n * @param value - Tabindex value\n */\nexport function setFocusable(\n el: HTMLElement, value = 0\n): void {\n el.setAttribute(\"tabindex\", value.toString())\n}\n\n/**\n * Reset focusable property\n *\n * @param el - Element\n */\nexport function resetFocusable(\n el: HTMLElement\n): void {\n el.removeAttribute(\"tabindex\")\n}\n\n/**\n * Set scroll lock\n *\n * @param el - Scrollable element\n * @param value - Vertical offset\n */\nexport function setScrollLock(\n el: HTMLElement, value: number\n): void {\n el.setAttribute(\"data-md-state\", \"lock\")\n el.style.top = `-${value}px`\n}\n\n/**\n * Reset scroll lock\n *\n * @param el - Scrollable element\n */\nexport function resetScrollLock(\n el: HTMLElement\n): void {\n const value = -1 * parseInt(el.style.top, 10)\n el.removeAttribute(\"data-md-state\")\n el.style.top = \"\"\n if (value)\n window.scrollTo(0, value)\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Set anchor state\n *\n * @param el - Anchor element\n * @param state - Anchor state\n */\nexport function setAnchorState(\n el: HTMLElement, state: \"blur\"\n): void {\n el.setAttribute(\"data-md-state\", state)\n}\n\n/**\n * Reset anchor state\n *\n * @param el - Anchor element\n */\nexport function resetAnchorState(\n el: HTMLElement\n): void {\n el.removeAttribute(\"data-md-state\")\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Set anchor active\n *\n * @param el - Anchor element\n * @param value - Whether the anchor is active\n */\nexport function setAnchorActive(\n el: HTMLElement, value: boolean\n): void {\n el.classList.toggle(\"md-nav__link--active\", value)\n}\n\n/**\n * Reset anchor active\n *\n * @param el - Anchor element\n */\nexport function resetAnchorActive(\n el: HTMLElement\n): void {\n el.classList.remove(\"md-nav__link--active\")\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Set dialog message\n *\n * @param el - Dialog element\n * @param value - Dialog message\n */\nexport function setDialogMessage(\n el: HTMLElement, value: string\n): void {\n el.firstElementChild!.innerHTML = value\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Set dialog state\n *\n * @param el - Dialog element\n * @param state - Dialog state\n */\nexport function setDialogState(\n el: HTMLElement, state: \"open\"\n): void {\n el.setAttribute(\"data-md-state\", state)\n}\n\n/**\n * Reset dialog state\n *\n * @param el - Dialog element\n */\nexport function resetDialogState(\n el: HTMLElement\n): void {\n el.removeAttribute(\"data-md-state\")\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Set header state\n *\n * @param el - Header element\n * @param state - Header state\n */\nexport function setHeaderState(\n el: HTMLElement, state: \"shadow\" | \"hidden\"\n): void {\n el.setAttribute(\"data-md-state\", state)\n}\n\n/**\n * Reset header state\n *\n * @param el - Header element\n */\nexport function resetHeaderState(\n el: HTMLElement\n): void {\n el.removeAttribute(\"data-md-state\")\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Set header title state\n *\n * @param el - Header title element\n * @param state - Header title state\n */\nexport function setHeaderTitleState(\n el: HTMLElement, state: \"active\"\n): void {\n el.setAttribute(\"data-md-state\", state)\n}\n\n/**\n * Reset header title state\n *\n * @param el - Header title element\n */\nexport function resetHeaderTitleState(\n el: HTMLElement\n): void {\n el.removeAttribute(\"data-md-state\")\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { translation } from \"~/_\"\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Set search query placeholder\n *\n * @param el - Search query element\n * @param value - Placeholder\n */\nexport function setSearchQueryPlaceholder(\n el: HTMLInputElement, value: string\n): void {\n el.placeholder = value\n}\n\n/**\n * Reset search query placeholder\n *\n * @param el - Search query element\n */\nexport function resetSearchQueryPlaceholder(\n el: HTMLInputElement\n): void {\n el.placeholder = translation(\"search.placeholder\")\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { JSX as JSXInternal } from \"preact\"\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * HTML attributes\n */\ntype Attributes =\n & JSXInternal.HTMLAttributes\n & JSXInternal.SVGAttributes\n & Record\n\n/**\n * Child element\n */\ntype Child =\n | HTMLElement\n | Text\n | string\n | number\n\n/* ----------------------------------------------------------------------------\n * Helper functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Append a child node to an element\n *\n * @param el - Element\n * @param child - Child node(s)\n */\nfunction appendChild(el: HTMLElement, child: Child | Child[]): void {\n\n /* Handle primitive types (including raw HTML) */\n if (typeof child === \"string\" || typeof child === \"number\") {\n el.innerHTML += child.toString()\n\n /* Handle nodes */\n } else if (child instanceof Node) {\n el.appendChild(child)\n\n /* Handle nested children */\n } else if (Array.isArray(child)) {\n for (const node of child)\n appendChild(el, node)\n }\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * JSX factory\n *\n * @param tag - HTML tag\n * @param attributes - HTML attributes\n * @param children - Child elements\n *\n * @returns Element\n */\nexport function h(\n tag: string, attributes: Attributes | null, ...children: Child[]\n): HTMLElement {\n const el = document.createElement(tag)\n\n /* Set attributes, if any */\n if (attributes)\n for (const attr of Object.keys(attributes))\n if (typeof attributes[attr] !== \"boolean\")\n el.setAttribute(attr, attributes[attr])\n else if (attributes[attr])\n el.setAttribute(attr, \"\")\n\n /* Append child nodes */\n for (const child of children)\n appendChild(el, child)\n\n /* Return element */\n return el\n}\n\n/* ----------------------------------------------------------------------------\n * Namespace\n * ------------------------------------------------------------------------- */\n\nexport declare namespace h {\n namespace JSX {\n type Element = HTMLElement\n type IntrinsicElements = JSXInternal.IntrinsicElements\n }\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Truncate a string after the given number of characters\n *\n * This is not a very reasonable approach, since the summaries kind of suck.\n * It would be better to create something more intelligent, highlighting the\n * search occurrences and making a better summary out of it, but this note was\n * written three years ago, so who knows if we'll ever fix it.\n *\n * @param value - Value to be truncated\n * @param n - Number of characters\n *\n * @returns Truncated value\n */\nexport function truncate(value: string, n: number): string {\n let i = n\n if (value.length > i) {\n while (value[i] !== \" \" && --i > 0) { /* keep eating */ }\n return `${value.substring(0, i)}...`\n }\n return value\n}\n\n/**\n * Round a number for display with repository facts\n *\n * This is a reverse-engineered version of GitHub's weird rounding algorithm\n * for stars, forks and all other numbers. While all numbers below `1,000` are\n * returned as-is, bigger numbers are converted to fixed numbers:\n *\n * - `1,049` => `1k`\n * - `1,050` => `1.1k`\n * - `1,949` => `1.9k`\n * - `1,950` => `2k`\n *\n * @param value - Original value\n *\n * @returns Rounded value\n */\nexport function round(value: number): string {\n if (value > 999) {\n const digits = +((value - 950) % 1000 > 99)\n return `${((value + 0.000001) / 1000).toFixed(digits)}k`\n } else {\n return value.toString()\n }\n}\n\n/**\n * Simple hash function\n *\n * @see https://bit.ly/2wsVjJ4 - Original source\n *\n * @param value - Value to be hashed\n *\n * @returns Hash as 32bit integer\n */\nexport function hash(value: string): number {\n let h = 0\n for (let i = 0, len = value.length; i < len; i++) {\n h = ((h << 5) - h) + value.charCodeAt(i)\n h |= 0 // Convert to 32bit integer\n }\n return h\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { translation } from \"~/_\"\nimport { round } from \"~/utilities\"\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Set number of search results\n *\n * @param el - Search result metadata element\n * @param value - Number of results\n */\nexport function setSearchResultMeta(\n el: HTMLElement, value: number\n): void {\n switch (value) {\n\n /* No results */\n case 0:\n el.textContent = translation(\"search.result.none\")\n break\n\n /* One result */\n case 1:\n el.textContent = translation(\"search.result.one\")\n break\n\n /* Multiple result */\n default:\n el.textContent = translation(\"search.result.other\", round(value))\n }\n}\n\n/**\n * Reset number of search results\n *\n * @param el - Search result metadata element\n */\nexport function resetSearchResultMeta(\n el: HTMLElement\n): void {\n el.textContent = translation(\"search.result.placeholder\")\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Add an element to the search result list\n *\n * @param el - Search result list element\n * @param child - Search result element\n */\nexport function addToSearchResultList(\n el: HTMLElement, child: Element\n): void {\n el.appendChild(child)\n}\n\n/**\n * Reset search result list\n *\n * @param el - Search result list element\n */\nexport function resetSearchResultList(\n el: HTMLElement\n): void {\n el.innerHTML = \"\"\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Set sidebar offset\n *\n * @param el - Sidebar element\n * @param value - Sidebar offset\n */\nexport function setSidebarOffset(\n el: HTMLElement, value: number\n): void {\n el.style.top = `${value}px`\n}\n\n/**\n * Reset sidebar offset\n *\n * @param el - Sidebar element\n */\nexport function resetSidebarOffset(\n el: HTMLElement\n): void {\n el.style.top = \"\"\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Set sidebar height\n *\n * This function doesn't set the height of the actual sidebar, but of its first\n * child \u2013 the `.md-sidebar__scrollwrap` element in order to mitigiate jittery\n * sidebars when the footer is scrolled into view. At some point we switched\n * from `absolute` / `fixed` positioning to `sticky` positioning, significantly\n * reducing jitter in some browsers (respectively Firefox and Safari) when\n * scrolling from the top. However, top-aligned sticky positioning means that\n * the sidebar snaps to the bottom when the end of the container is reached.\n * This is what leads to the mentioned jitter, as the sidebar's height may be\n * updated too slowly.\n *\n * This behaviour can be mitigiated by setting the height of the sidebar to `0`\n * while preserving the padding, and the height on its first element.\n *\n * @param el - Sidebar element\n * @param value - Sidebar height\n */\nexport function setSidebarHeight(\n el: HTMLElement, value: number\n): void {\n const scrollwrap = el.firstElementChild as HTMLElement\n scrollwrap.style.height = `${value - 2 * scrollwrap.offsetTop}px`\n}\n\n/**\n * Reset sidebar height\n *\n * @param el - Sidebar element\n */\nexport function resetSidebarHeight(\n el: HTMLElement\n): void {\n const scrollwrap = el.firstElementChild as HTMLElement\n scrollwrap.style.height = \"\"\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Set repository facts\n *\n * @param el - Repository element\n * @param child - Repository facts element\n */\nexport function setSourceFacts(\n el: HTMLElement, child: Element\n): void {\n el.lastElementChild!.appendChild(child)\n}\n\n/**\n * Set repository state\n *\n * @param el - Repository element\n * @param state - Repository state\n */\nexport function setSourceState(\n el: HTMLElement, state: \"done\"\n): void {\n el.lastElementChild!.setAttribute(\"data-md-state\", state)\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Set tabs state\n *\n * @param el - Tabs element\n * @param state - Tabs state\n */\nexport function setTabsState(\n el: HTMLElement, state: \"hidden\"\n): void {\n el.setAttribute(\"data-md-state\", state)\n}\n\n/**\n * Reset tabs state\n *\n * @param el - Tabs element\n */\nexport function resetTabsState(\n el: HTMLElement\n): void {\n el.removeAttribute(\"data-md-state\")\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Set back-to-top state\n *\n * @param el - Back-to-top element\n * @param state - Back-to-top state\n */\nexport function setBackToTopState(\n el: HTMLElement, state: \"hidden\"\n): void {\n el.setAttribute(\"data-md-state\", state)\n}\n\n/**\n * Reset back-to-top state\n *\n * @param el - Back-to-top element\n */\nexport function resetBackToTopState(\n el: HTMLElement\n): void {\n el.removeAttribute(\"data-md-state\")\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Set back-to-top offset\n *\n * @param el - Back-to-top element\n * @param value - Back-to-top offset\n */\nexport function setBackToTopOffset(\n el: HTMLElement, value: number\n): void {\n el.style.top = `${value}px`\n}\n\n/**\n * Reset back-to-top offset\n *\n * @param el - Back-to-top element\n */\nexport function resetBackToTopOffset(\n el: HTMLElement\n): void {\n el.style.top = \"\"\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { translation } from \"~/_\"\nimport { h } from \"~/utilities\"\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Render a 'copy-to-clipboard' button\n *\n * @param id - Unique identifier\n *\n * @returns Element\n */\nexport function renderClipboardButton(id: string): HTMLElement {\n return (\n code`}\n >\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { feature, translation } from \"~/_\"\nimport {\n SearchDocument,\n SearchMetadata,\n SearchResultItem\n} from \"~/integrations/search\"\nimport { h, truncate } from \"~/utilities\"\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Render flag\n */\nconst enum Flag {\n TEASER = 1, /* Render teaser */\n PARENT = 2 /* Render as parent */\n}\n\n/* ----------------------------------------------------------------------------\n * Helper function\n * ------------------------------------------------------------------------- */\n\n/**\n * Render a search document\n *\n * @param document - Search document\n * @param flag - Render flags\n *\n * @returns Element\n */\nfunction renderSearchDocument(\n document: SearchDocument & SearchMetadata, flag: Flag\n): HTMLElement {\n const parent = flag & Flag.PARENT\n const teaser = flag & Flag.TEASER\n\n /* Render missing query terms */\n const missing = Object.keys(document.terms)\n .filter(key => !document.terms[key])\n .map(key => [{key}, \" \"])\n .flat()\n .slice(0, -1)\n\n /* Assemble query string for highlighting */\n const url = new URL(document.location)\n if (feature(\"search.highlight\"))\n url.searchParams.set(\"h\", Object.entries(document.terms)\n .filter(([, match]) => match)\n .reduce((highlight, [value]) => `${highlight} ${value}`.trim(), \"\")\n )\n\n /* Render article or section, depending on flags */\n return (\n \n \n {parent > 0 &&
}\n

{document.title}

\n {teaser > 0 && document.text.length > 0 &&\n

\n {truncate(document.text, 320)}\n

\n }\n {teaser > 0 && missing.length > 0 &&\n

\n {translation(\"search.result.term.missing\")}: {...missing}\n

\n }\n \n
\n )\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Render a search result\n *\n * @param result - Search result\n *\n * @returns Element\n */\nexport function renderSearchResultItem(\n result: SearchResultItem\n): HTMLElement {\n const threshold = result[0].score\n const docs = [...result]\n\n /* Find and extract parent article */\n const parent = docs.findIndex(doc => !doc.location.includes(\"#\"))\n const [article] = docs.splice(parent, 1)\n\n /* Determine last index above threshold */\n let index = docs.findIndex(doc => doc.score < threshold)\n if (index === -1)\n index = docs.length\n\n /* Partition sections */\n const best = docs.slice(0, index)\n const more = docs.slice(index)\n\n /* Render children */\n const children = [\n renderSearchDocument(article, Flag.PARENT | +(!parent && index === 0)),\n ...best.map(section => renderSearchDocument(section, Flag.TEASER)),\n ...more.length ? [\n
\n \n {more.length > 0 && more.length === 1\n ? translation(\"search.result.more.one\")\n : translation(\"search.result.more.other\", more.length)\n }\n \n {...more.map(section => renderSearchDocument(section, Flag.TEASER))}\n
\n ] : []\n ]\n\n /* Render search result */\n return (\n
  • \n {children}\n
  • \n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { SourceFacts } from \"~/components\"\nimport { h, round } from \"~/utilities\"\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Render repository facts\n *\n * @param facts - Repository facts\n *\n * @returns Element\n */\nexport function renderSourceFacts(facts: SourceFacts): HTMLElement {\n return (\n
      \n {Object.entries(facts).map(([key, value]) => (\n
    • \n {typeof value === \"number\" ? round(value) : value}\n
    • \n ))}\n
    \n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { h } from \"~/utilities\"\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Render a table inside a wrapper to improve scrolling on mobile\n *\n * @param table - Table element\n *\n * @returns Element\n */\nexport function renderTable(table: HTMLElement): HTMLElement {\n return (\n
    \n
    \n {table}\n
    \n
    \n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { configuration, translation } from \"~/_\"\nimport { h } from \"~/utilities\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Version\n */\nexport interface Version {\n version: string /* Version identifier */\n title: string /* Version title */\n aliases: string[] /* Version aliases */\n}\n\n/* ----------------------------------------------------------------------------\n * Helper functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Render a version\n *\n * @param version - Version\n *\n * @returns Element\n */\nfunction renderVersion(version: Version): HTMLElement {\n const config = configuration()\n\n /* Ensure trailing slash, see https://bit.ly/3rL5u3f */\n const url = new URL(`${version.version}/`, config.base)\n return (\n
  • \n \n {version.title}\n \n
  • \n )\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Render a version selector\n *\n * @param versions - Versions\n *\n * @returns Element\n */\nexport function renderVersionSelector(versions: Version[]): HTMLElement {\n const config = configuration()\n\n /* Determine active version */\n const [, current] = config.base.match(/([^/]+)\\/?$/)!\n const active =\n versions.find(({ version, aliases }) => (\n version === current || aliases.includes(current)\n )) || versions[0]\n\n /* Render version selector */\n return (\n
    \n \n {active.title}\n \n
      \n {versions.map(renderVersion)}\n
    \n
    \n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { Observable, Subject } from \"rxjs\"\nimport {\n filter,\n finalize,\n map,\n mapTo,\n mergeWith,\n tap\n} from \"rxjs/operators\"\n\nimport { Component } from \"../../_\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Details\n */\nexport interface Details {}\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch options\n */\ninterface WatchOptions {\n target$: Observable /* Location target observable */\n print$: Observable /* Print mode observable */\n}\n\n/**\n * Mount options\n */\ninterface MountOptions {\n target$: Observable /* Location target observable */\n print$: Observable /* Print mode observable */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch details\n *\n * @param el - Details element\n * @param options - Options\n *\n * @returns Details observable\n */\nexport function watchDetails(\n el: HTMLDetailsElement, { target$, print$ }: WatchOptions\n): Observable
    {\n return target$\n .pipe(\n map(target => target.closest(\"details:not([open])\")!),\n filter(details => el === details),\n mergeWith(print$),\n mapTo(el)\n )\n}\n\n/**\n * Mount details\n *\n * This function ensures that `details` tags are opened on anchor jumps and\n * prior to printing, so the whole content of the page is visible.\n *\n * @param el - Details element\n * @param options - Options\n *\n * @returns Details component observable\n */\nexport function mountDetails(\n el: HTMLDetailsElement, options: MountOptions\n): Observable> {\n const internal$ = new Subject
    ()\n internal$.subscribe(() => {\n el.setAttribute(\"open\", \"\")\n el.scrollIntoView()\n })\n\n /* Create and return component */\n return watchDetails(el, options)\n .pipe(\n tap(internal$),\n finalize(() => internal$.complete()),\n mapTo({ ref: el })\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { Observable, of } from \"rxjs\"\n\nimport { createElement, replaceElement } from \"~/browser\"\nimport { renderTable } from \"~/templates\"\n\nimport { Component } from \"../../_\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Data table\n */\nexport interface DataTable {}\n\n/* ----------------------------------------------------------------------------\n * Data\n * ------------------------------------------------------------------------- */\n\n/**\n * Sentinel for replacement\n */\nconst sentinel = createElement(\"table\")\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Mount data table\n *\n * This function wraps a data table in another scrollable container, so it can\n * be smoothly scrolled on smaller screen sizes and won't break the layout.\n *\n * @param el - Data table element\n *\n * @returns Data table component observable\n */\nexport function mountDataTable(\n el: HTMLElement\n): Observable> {\n replaceElement(el, sentinel)\n replaceElement(sentinel, renderTable(el))\n\n /* Create and return component */\n return of({ ref: el })\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { Observable, merge } from \"rxjs\"\n\nimport { Viewport, getElements } from \"~/browser\"\n\nimport { Component } from \"../../_\"\nimport { CodeBlock, mountCodeBlock } from \"../code\"\nimport { Details, mountDetails } from \"../details\"\nimport { DataTable, mountDataTable } from \"../table\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Content\n */\nexport type Content =\n | CodeBlock\n | DataTable\n | Details\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Mount options\n */\ninterface MountOptions {\n target$: Observable /* Location target observable */\n viewport$: Observable /* Viewport observable */\n print$: Observable /* Print mode observable */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Mount content\n *\n * This function mounts all components that are found in the content of the\n * actual article, including code blocks, data tables and details.\n *\n * @param el - Content element\n * @param options - Options\n *\n * @returns Content component observable\n */\nexport function mountContent(\n el: HTMLElement, { target$, viewport$, print$ }: MountOptions\n): Observable> {\n return merge(\n\n /* Code blocks */\n ...getElements(\"pre > code\", el)\n .map(child => mountCodeBlock(child, { viewport$ })),\n\n /* Data tables */\n ...getElements(\"table:not([class])\", el)\n .map(child => mountDataTable(child)),\n\n /* Details */\n ...getElements(\"details\", el)\n .map(child => mountDetails(child, { target$, print$ }))\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport {\n Observable,\n Subject,\n animationFrameScheduler,\n merge,\n of\n} from \"rxjs\"\nimport {\n delay,\n finalize,\n map,\n observeOn,\n switchMap,\n tap\n} from \"rxjs/operators\"\n\nimport {\n resetDialogState,\n setDialogMessage,\n setDialogState\n} from \"~/actions\"\n\nimport { Component } from \"../_\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Dialog\n */\nexport interface Dialog {\n message: string /* Dialog message */\n open: boolean /* Dialog is visible */\n}\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch options\n */\ninterface WatchOptions {\n alert$: Subject /* Alert subject */\n}\n\n/**\n * Mount options\n */\ninterface MountOptions {\n alert$: Subject /* Alert subject */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch dialog\n *\n * @param _el - Dialog element\n * @param options - Options\n *\n * @returns Dialog observable\n */\nexport function watchDialog(\n _el: HTMLElement, { alert$ }: WatchOptions\n): Observable {\n return alert$\n .pipe(\n switchMap(message => merge(\n of(true),\n of(false).pipe(delay(2000))\n )\n .pipe(\n map(open => ({ message, open }))\n )\n )\n )\n}\n\n/**\n * Mount dialog\n *\n * This function reveals the dialog in the right cornerwhen a new alert is\n * emitted through the subject that is passed as part of the options.\n *\n * @param el - Dialog element\n * @param options - Options\n *\n * @returns Dialog component observable\n */\nexport function mountDialog(\n el: HTMLElement, options: MountOptions\n): Observable> {\n const internal$ = new Subject()\n internal$\n .pipe(\n observeOn(animationFrameScheduler)\n )\n .subscribe(({ message, open }) => {\n setDialogMessage(el, message)\n if (open)\n setDialogState(el, \"open\")\n else\n resetDialogState(el)\n })\n\n /* Create and return component */\n return watchDialog(el, options)\n .pipe(\n tap(internal$),\n finalize(() => internal$.complete()),\n map(state => ({ ref: el, ...state }))\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport {\n Observable,\n Subject,\n animationFrameScheduler,\n combineLatest,\n defer,\n of\n} from \"rxjs\"\nimport {\n bufferCount,\n combineLatestWith,\n distinctUntilChanged,\n distinctUntilKeyChanged,\n filter,\n map,\n observeOn,\n shareReplay,\n startWith,\n switchMap\n} from \"rxjs/operators\"\n\nimport { feature } from \"~/_\"\nimport { resetHeaderState, setHeaderState } from \"~/actions\"\nimport {\n Viewport,\n watchElementSize,\n watchToggle\n} from \"~/browser\"\n\nimport { Component } from \"../../_\"\nimport { Main } from \"../../main\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Header\n */\nexport interface Header {\n height: number /* Header visible height */\n sticky: boolean /* Header stickyness */\n hidden: boolean /* User scrolled past threshold */\n}\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch options\n */\ninterface WatchOptions {\n viewport$: Observable /* Viewport observable */\n}\n\n/**\n * Mount options\n */\ninterface MountOptions {\n viewport$: Observable /* Viewport observable */\n header$: Observable
    /* Header observable */\n main$: Observable
    /* Main area observable */\n}\n\n/* ----------------------------------------------------------------------------\n * Helper functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Compute whether the header is hidden\n *\n * If the user scrolls past a certain threshold, the header can be hidden when\n * scrolling down, and shown when scrolling up.\n *\n * @param options - Options\n *\n * @returns Toggle observable\n */\nfunction isHidden({ viewport$ }: WatchOptions): Observable {\n if (!feature(\"header.autohide\"))\n return of(false)\n\n /* Compute direction and turning point */\n const direction$ = viewport$\n .pipe(\n map(({ offset: { y } }) => y),\n bufferCount(2, 1),\n map(([a, b]) => [a < b, b] as const),\n distinctUntilKeyChanged(0)\n )\n\n /* Compute whether header should be hidden */\n const hidden$ = combineLatest([viewport$, direction$])\n .pipe(\n filter(([{ offset }, [, y]]) => Math.abs(y - offset.y) > 100),\n map(([, [direction]]) => direction),\n distinctUntilChanged()\n )\n\n /* Compute threshold for hiding */\n const search$ = watchToggle(\"search\")\n return combineLatest([viewport$, search$])\n .pipe(\n map(([{ offset }, search]) => offset.y > 400 && !search),\n distinctUntilChanged(),\n switchMap(active => active ? hidden$ : of(false)),\n startWith(false)\n )\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch header\n *\n * @param el - Header element\n * @param options - Options\n *\n * @returns Header observable\n */\nexport function watchHeader(\n el: HTMLElement, options: WatchOptions\n): Observable
    {\n return defer(() => {\n const styles = getComputedStyle(el)\n return of(\n styles.position === \"sticky\" ||\n styles.position === \"-webkit-sticky\"\n )\n })\n .pipe(\n combineLatestWith(watchElementSize(el), isHidden(options)),\n map(([sticky, { height }, hidden]) => ({\n height: sticky ? height : 0,\n sticky,\n hidden\n })),\n distinctUntilChanged((a, b) => (\n a.sticky === b.sticky &&\n a.height === b.height &&\n a.hidden === b.hidden\n )),\n shareReplay(1)\n )\n}\n\n/**\n * Mount header\n *\n * This function manages the different states of the header, i.e. whether it's\n * hidden or rendered with a shadow. This depends heavily on the main area.\n *\n * @param el - Header element\n * @param options - Options\n *\n * @returns Header component observable\n */\nexport function mountHeader(\n el: HTMLElement, { header$, main$ }: MountOptions\n): Observable> {\n const internal$ = new Subject
    ()\n internal$\n .pipe(\n distinctUntilKeyChanged(\"active\"),\n combineLatestWith(header$),\n observeOn(animationFrameScheduler)\n )\n .subscribe(([{ active }, { hidden }]) => {\n if (active)\n setHeaderState(el, hidden ? \"hidden\" : \"shadow\")\n else\n resetHeaderState(el)\n })\n\n /* Connect to long-living subject and return component */\n main$.subscribe(main => internal$.next(main))\n return header$\n .pipe(\n map(state => ({ ref: el, ...state }))\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport {\n NEVER,\n Observable,\n Subject,\n animationFrameScheduler\n} from \"rxjs\"\nimport {\n distinctUntilKeyChanged,\n finalize,\n map,\n observeOn,\n tap\n} from \"rxjs/operators\"\n\nimport {\n resetHeaderTitleState,\n setHeaderTitleState\n} from \"~/actions\"\nimport {\n Viewport,\n getElement,\n getElementSize,\n watchViewportAt\n} from \"~/browser\"\n\nimport { Component } from \"../../_\"\nimport { Header } from \"../_\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Header\n */\nexport interface HeaderTitle {\n active: boolean /* User scrolled past first headline */\n}\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch options\n */\ninterface WatchOptions {\n viewport$: Observable /* Viewport observable */\n header$: Observable
    /* Header observable */\n}\n\n/**\n * Mount options\n */\ninterface MountOptions {\n viewport$: Observable /* Viewport observable */\n header$: Observable
    /* Header observable */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch header title\n *\n * @param el - Heading element\n * @param options - Options\n *\n * @returns Header title observable\n */\nexport function watchHeaderTitle(\n el: HTMLHeadingElement, { viewport$, header$ }: WatchOptions\n): Observable {\n return watchViewportAt(el, { header$, viewport$ })\n .pipe(\n map(({ offset: { y } }) => {\n const { height } = getElementSize(el)\n return {\n active: y >= height\n }\n }),\n distinctUntilKeyChanged(\"active\")\n )\n}\n\n/**\n * Mount header title\n *\n * This function swaps the header title from the site title to the title of the\n * current page when the user scrolls past the first headline.\n *\n * @param el - Header title element\n * @param options - Options\n *\n * @returns Header title component observable\n */\nexport function mountHeaderTitle(\n el: HTMLElement, options: MountOptions\n): Observable> {\n const internal$ = new Subject()\n internal$\n .pipe(\n observeOn(animationFrameScheduler)\n )\n .subscribe(({ active }) => {\n if (active)\n setHeaderTitleState(el, \"active\")\n else\n resetHeaderTitleState(el)\n })\n\n /* Obtain headline, if any */\n const headline = getElement(\"article h1\")\n if (typeof headline === \"undefined\")\n return NEVER\n\n /* Create and return component */\n return watchHeaderTitle(headline, options)\n .pipe(\n tap(internal$),\n finalize(() => internal$.complete()),\n map(state => ({ ref: el, ...state }))\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport {\n Observable,\n combineLatest\n} from \"rxjs\"\nimport {\n distinctUntilChanged,\n distinctUntilKeyChanged,\n map,\n switchMap\n} from \"rxjs/operators\"\n\nimport { Viewport, watchElementSize } from \"~/browser\"\n\nimport { Header } from \"../header\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Main area\n */\nexport interface Main {\n offset: number /* Main area top offset */\n height: number /* Main area visible height */\n active: boolean /* User scrolled past header */\n}\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch options\n */\ninterface WatchOptions {\n viewport$: Observable /* Viewport observable */\n header$: Observable
    /* Header observable */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch main area\n *\n * This function returns an observable that computes the visual parameters of\n * the main area which depends on the viewport vertical offset and height, as\n * well as the height of the header element, if the header is fixed.\n *\n * @param el - Main area element\n * @param options - Options\n *\n * @returns Main area observable\n */\nexport function watchMain(\n el: HTMLElement, { viewport$, header$ }: WatchOptions\n): Observable
    {\n\n /* Compute necessary adjustment for header */\n const adjust$ = header$\n .pipe(\n map(({ height }) => height),\n distinctUntilChanged()\n )\n\n /* Compute the main area's top and bottom borders */\n const border$ = adjust$\n .pipe(\n switchMap(() => watchElementSize(el)\n .pipe(\n map(({ height }) => ({\n top: el.offsetTop,\n bottom: el.offsetTop + height\n })),\n distinctUntilKeyChanged(\"bottom\")\n )\n )\n )\n\n /* Compute the main area's offset, visible height and if we scrolled past */\n return combineLatest([adjust$, border$, viewport$])\n .pipe(\n map(([header, { top, bottom }, { offset: { y }, size: { height } }]) => {\n height = Math.max(0, height\n - Math.max(0, top - y, header)\n - Math.max(0, height + y - bottom)\n )\n return {\n offset: top - header,\n height,\n active: top - header <= y\n }\n }),\n distinctUntilChanged((a, b) => (\n a.offset === b.offset &&\n a.height === b.height &&\n a.active === b.active\n ))\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport {\n Observable,\n Subject,\n fromEvent,\n of\n} from \"rxjs\"\nimport {\n finalize,\n map,\n mapTo,\n mergeMap,\n shareReplay,\n startWith,\n tap\n} from \"rxjs/operators\"\n\nimport { getElements } from \"~/browser\"\n\nimport { Component } from \"../_\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Palette colors\n */\nexport interface PaletteColor {\n scheme?: string /* Color scheme */\n primary?: string /* Primary color */\n accent?: string /* Accent color */\n}\n\n/**\n * Palette\n */\nexport interface Palette {\n index: number /* Palette index */\n color: PaletteColor /* Palette colors */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch color palette\n *\n * @param inputs - Color palette element\n *\n * @returns Color palette observable\n */\nexport function watchPalette(\n inputs: HTMLInputElement[]\n): Observable {\n const data = localStorage.getItem(__prefix(\"__palette\"))!\n const current = JSON.parse(data) || {\n index: inputs.findIndex(input => (\n matchMedia(input.getAttribute(\"data-md-color-media\")!).matches\n ))\n }\n\n /* Emit changes in color palette */\n const palette$ = of(...inputs)\n .pipe(\n mergeMap(input => fromEvent(input, \"change\")\n .pipe(\n mapTo(input)\n )\n ),\n startWith(inputs[Math.max(0, current.index)]),\n map(input => ({\n index: inputs.indexOf(input),\n color: {\n scheme: input.getAttribute(\"data-md-color-scheme\"),\n primary: input.getAttribute(\"data-md-color-primary\"),\n accent: input.getAttribute(\"data-md-color-accent\")\n }\n } as Palette)),\n shareReplay(1)\n )\n\n /* Persist preference in local storage */\n palette$.subscribe(palette => {\n localStorage.setItem(__prefix(\"__palette\"), JSON.stringify(palette))\n })\n\n /* Return palette */\n return palette$\n}\n\n/**\n * Mount color palette\n *\n * @param el - Color palette element\n *\n * @returns Color palette component observable\n */\nexport function mountPalette(\n el: HTMLElement\n): Observable> {\n const internal$ = new Subject()\n\n /* Set color palette */\n internal$.subscribe(palette => {\n for (const [key, value] of Object.entries(palette.color))\n if (typeof value === \"string\")\n document.body.setAttribute(`data-md-color-${key}`, value)\n\n /* Toggle visibility */\n for (let index = 0; index < inputs.length; index++) {\n const label = inputs[index].nextElementSibling\n if (label instanceof HTMLElement)\n label.hidden = palette.index !== index\n }\n })\n\n /* Create and return component */\n const inputs = getElements(\"input\", el)\n return watchPalette(inputs)\n .pipe(\n tap(internal$),\n finalize(() => internal$.complete()),\n map(state => ({ ref: el, ...state }))\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport ClipboardJS from \"clipboard\"\nimport { Observable, Subject } from \"rxjs\"\n\nimport { translation } from \"~/_\"\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Setup options\n */\ninterface SetupOptions {\n alert$: Subject /* Alert subject */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Set up Clipboard.js integration\n *\n * @param options - Options\n */\nexport function setupClipboardJS(\n { alert$ }: SetupOptions\n): void {\n if (ClipboardJS.isSupported()) {\n new Observable(subscriber => {\n new ClipboardJS(\"[data-clipboard-target], [data-clipboard-text]\")\n .on(\"success\", ev => subscriber.next(ev))\n })\n .subscribe(() => alert$.next(translation(\"clipboard.copied\")))\n }\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport {\n EMPTY,\n NEVER,\n Observable,\n Subject,\n fromEvent,\n merge,\n of\n} from \"rxjs\"\nimport {\n bufferCount,\n catchError,\n concatMap,\n debounceTime,\n distinctUntilChanged,\n distinctUntilKeyChanged,\n filter,\n map,\n sample,\n share,\n skip,\n skipUntil,\n switchMap\n} from \"rxjs/operators\"\n\nimport { configuration } from \"~/_\"\nimport {\n Viewport,\n ViewportOffset,\n createElement,\n getElement,\n getElements,\n replaceElement,\n request,\n requestXML,\n setLocation,\n setLocationHash,\n setViewportOffset\n} from \"~/browser\"\nimport { getComponentElement } from \"~/components\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * History state\n */\nexport interface HistoryState {\n url: URL /* State URL */\n offset?: ViewportOffset /* State viewport offset */\n}\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Setup options\n */\ninterface SetupOptions {\n document$: Subject /* Document subject */\n location$: Subject /* Location subject */\n viewport$: Observable /* Viewport observable */\n}\n\n/* ----------------------------------------------------------------------------\n * Helper functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Preprocess a list of URLs\n *\n * This function replaces the `site_url` in the sitemap with the actual base\n * URL, to allow instant loading to work in occasions like Netlify previews.\n *\n * @param urls - URLs\n *\n * @returns Processed URLs\n */\nfunction preprocess(urls: string[]): string[] {\n if (urls.length < 2)\n return urls\n\n /* Take the first two URLs and remove everything after the last slash */\n const [root, next] = urls\n .sort((a, b) => a.length - b.length)\n .map(url => url.replace(/[^/]+$/, \"\"))\n\n /* Compute common prefix */\n let index = 0\n if (root === next)\n index = root.length\n else\n while (root.charCodeAt(index) === next.charCodeAt(index))\n index++\n\n /* Replace common prefix (i.e. base) with effective base */\n const config = configuration()\n return urls.map(url => (\n url.replace(root.slice(0, index), `${config.base}/`)\n ))\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Set up instant loading\n *\n * When fetching, theoretically, we could use `responseType: \"document\"`, but\n * since all MkDocs links are relative, we need to make sure that the current\n * location matches the document we just loaded. Otherwise any relative links\n * in the document could use the old location.\n *\n * This is the reason why we need to synchronize history events and the process\n * of fetching the document for navigation changes (except `popstate` events):\n *\n * 1. Fetch document via `XMLHTTPRequest`\n * 2. Set new location via `history.pushState`\n * 3. Parse and emit fetched document\n *\n * For `popstate` events, we must not use `history.pushState`, or the forward\n * history will be irreversibly overwritten. In case the request fails, the\n * location change is dispatched regularly.\n *\n * @param options - Options\n */\nexport function setupInstantLoading(\n { document$, location$, viewport$ }: SetupOptions\n): void {\n const config = configuration()\n if (location.protocol === \"file:\")\n return\n\n /* Disable automatic scroll restoration */\n if (\"scrollRestoration\" in history) {\n history.scrollRestoration = \"manual\"\n\n /* Hack: ensure that reloads restore viewport offset */\n fromEvent(window, \"beforeunload\")\n .subscribe(() => {\n history.scrollRestoration = \"auto\"\n })\n }\n\n /* Hack: ensure absolute favicon link to omit 404s when switching */\n const favicon = getElement(\"link[rel=icon]\")\n if (typeof favicon !== \"undefined\")\n favicon.href = favicon.href\n\n /* Intercept internal navigation */\n const push$ = requestXML(`${config.base}/sitemap.xml`)\n .pipe(\n map(sitemap => preprocess(getElements(\"loc\", sitemap)\n .map(node => node.textContent!)\n )),\n switchMap(urls => fromEvent(document.body, \"click\")\n .pipe(\n filter(ev => !ev.metaKey && !ev.ctrlKey),\n switchMap(ev => {\n\n /* Handle HTML and SVG elements */\n if (ev.target instanceof Element) {\n const el = ev.target.closest(\"a\")\n if (el && !el.target && urls.includes(el.href)) {\n ev.preventDefault()\n return of({\n url: new URL(el.href)\n })\n }\n }\n return NEVER\n })\n )\n ),\n share()\n )\n\n /* Intercept history back and forward */\n const pop$ = fromEvent(window, \"popstate\")\n .pipe(\n filter(ev => ev.state !== null),\n map(ev => ({\n url: new URL(location.href),\n offset: ev.state\n })),\n share()\n )\n\n /* Emit location change */\n merge(push$, pop$)\n .pipe(\n distinctUntilChanged((a, b) => a.url.href === b.url.href),\n map(({ url }) => url)\n )\n .subscribe(location$)\n\n /* Fetch document via `XMLHTTPRequest` */\n const response$ = location$\n .pipe(\n distinctUntilKeyChanged(\"pathname\"),\n switchMap(url => request(url.href)\n .pipe(\n catchError(() => {\n setLocation(url)\n return NEVER\n })\n )\n ),\n share()\n )\n\n /* Set new location via `history.pushState` */\n push$\n .pipe(\n sample(response$)\n )\n .subscribe(({ url }) => {\n history.pushState({}, \"\", `${url}`)\n })\n\n /* Parse and emit fetched document */\n const dom = new DOMParser()\n response$\n .pipe(\n switchMap(res => res.text()),\n map(res => dom.parseFromString(res, \"text/html\"))\n )\n .subscribe(document$)\n\n /* Emit history state change */\n merge(push$, pop$)\n .pipe(\n sample(document$)\n )\n .subscribe(({ url, offset }) => {\n if (url.hash && !offset)\n setLocationHash(url.hash)\n else\n setViewportOffset(offset || { y: 0 })\n })\n\n /* Replace meta tags and components */\n document$\n .pipe(\n skip(1)\n )\n .subscribe(replacement => {\n for (const selector of [\n\n /* Meta tags */\n \"title\",\n \"link[rel=canonical]\",\n \"meta[name=author]\",\n \"meta[name=description]\",\n\n /* Components */\n \"[data-md-component=announce]\",\n \"[data-md-component=container]\",\n \"[data-md-component=header-topic]\",\n \"[data-md-component=logo], .md-logo\", // compat\n \"[data-md-component=skip]\"\n ]) {\n const source = getElement(selector)\n const target = getElement(selector, replacement)\n if (\n typeof source !== \"undefined\" &&\n typeof target !== \"undefined\"\n ) {\n replaceElement(source, target)\n }\n }\n })\n\n /* Re-evaluate scripts */\n document$\n .pipe(\n skip(1),\n map(() => getComponentElement(\"container\")),\n switchMap(el => of(...getElements(\"script\", el))),\n concatMap(el => {\n const script = createElement(\"script\")\n if (el.src) {\n for (const name of el.getAttributeNames())\n script.setAttribute(name, el.getAttribute(name)!)\n replaceElement(el, script)\n\n /* Complete when script is loaded */\n return new Observable(observer => {\n script.onload = () => observer.complete()\n })\n\n /* Complete immediately */\n } else {\n script.textContent = el.textContent\n replaceElement(el, script)\n return EMPTY\n }\n })\n )\n .subscribe()\n\n /* Debounce update of viewport offset */\n viewport$\n .pipe(\n skipUntil(push$),\n debounceTime(250),\n distinctUntilKeyChanged(\"offset\")\n )\n .subscribe(({ offset }) => {\n history.replaceState(offset, \"\")\n })\n\n /* Set viewport offset from history */\n merge(push$, pop$)\n .pipe(\n bufferCount(2, 1),\n filter(([a, b]) => a.url.pathname === b.url.pathname),\n map(([, state]) => state)\n )\n .subscribe(({ offset }) => {\n setViewportOffset(offset || { y: 0 })\n })\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport escapeHTML from \"escape-html\"\n\nimport { SearchIndexDocument } from \"../_\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Search document\n */\nexport interface SearchDocument extends SearchIndexDocument {\n parent?: SearchIndexDocument /* Parent article */\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Search document mapping\n */\nexport type SearchDocumentMap = Map\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Create a search document mapping\n *\n * @param docs - Search index documents\n *\n * @returns Search document map\n */\nexport function setupSearchDocumentMap(\n docs: SearchIndexDocument[]\n): SearchDocumentMap {\n const documents = new Map()\n const parents = new Set()\n for (const doc of docs) {\n const [path, hash] = doc.location.split(\"#\")\n\n /* Extract location and title */\n const location = doc.location\n const title = doc.title\n\n /* Escape and cleanup text */\n const text = escapeHTML(doc.text)\n .replace(/\\s+(?=[,.:;!?])/g, \"\")\n .replace(/\\s+/g, \" \")\n\n /* Handle section */\n if (hash) {\n const parent = documents.get(path)!\n\n /* Ignore first section, override article */\n if (!parents.has(parent)) {\n parent.title = doc.title\n parent.text = text\n\n /* Remember that we processed the article */\n parents.add(parent)\n\n /* Add subsequent section */\n } else {\n documents.set(location, {\n location,\n title,\n text,\n parent\n })\n }\n\n /* Add article */\n } else {\n documents.set(location, {\n location,\n title,\n text\n })\n }\n }\n return documents\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { SearchIndexConfig } from \"../_\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Search highlight function\n *\n * @param value - Value\n *\n * @returns Highlighted value\n */\nexport type SearchHighlightFn = (value: string) => string\n\n/**\n * Search highlight factory function\n *\n * @param query - Query value\n *\n * @returns Search highlight function\n */\nexport type SearchHighlightFactoryFn = (query: string) => SearchHighlightFn\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Create a search highlighter\n *\n * @param config - Search index configuration\n *\n * @returns Search highlight factory function\n */\nexport function setupSearchHighlighter(\n config: SearchIndexConfig\n): SearchHighlightFactoryFn {\n const separator = new RegExp(config.separator, \"img\")\n const highlight = (_: unknown, data: string, term: string) => {\n return `${data}${term}`\n }\n\n /* Return factory function */\n return (query: string) => {\n query = query\n .replace(/[\\s*+\\-:~^]+/g, \" \")\n .trim()\n\n /* Create search term match expression */\n const match = new RegExp(`(^|${config.separator})(${\n query\n .replace(/[|\\\\{}()[\\]^$+*?.-]/g, \"\\\\$&\")\n .replace(separator, \"|\")\n })`, \"img\")\n\n /* Highlight string value */\n return value => value\n .replace(match, highlight)\n .replace(/<\\/mark>(\\s+)]*>/img, \"$1\")\n }\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Search transformation function\n *\n * @param value - Query value\n *\n * @returns Transformed query value\n */\nexport type SearchTransformFn = (value: string) => string\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Default transformation function\n *\n * 1. Search for terms in quotation marks and prepend a `+` modifier to denote\n * that the resulting document must contain all terms, converting the query\n * to an `AND` query (as opposed to the default `OR` behavior). While users\n * may expect terms enclosed in quotation marks to map to span queries, i.e.\n * for which order is important, Lunr.js doesn't support them, so the best\n * we can do is to convert the terms to an `AND` query.\n *\n * 2. Replace control characters which are not located at the beginning of the\n * query or preceded by white space, or are not followed by a non-whitespace\n * character or are at the end of the query string. Furthermore, filter\n * unmatched quotation marks.\n *\n * 3. Trim excess whitespace from left and right.\n *\n * @param query - Query value\n *\n * @returns Transformed query value\n */\nexport function defaultTransform(query: string): string {\n return query\n .split(/\"([^\"]+)\"/g) /* => 1 */\n .map((terms, index) => index & 1\n ? terms.replace(/^\\b|^(?![^\\x00-\\x7F]|$)|\\s+/g, \" +\")\n : terms\n )\n .join(\"\")\n .replace(/\"|(?:^|\\s+)[*+\\-:^~]+(?=\\s+|$)/g, \"\") /* => 2 */\n .trim() /* => 3 */\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A RTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { SearchIndex, SearchResult } from \"../../_\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Search message type\n */\nexport const enum SearchMessageType {\n SETUP, /* Search index setup */\n READY, /* Search index ready */\n QUERY, /* Search query */\n RESULT /* Search results */\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * A message containing the data necessary to setup the search index\n */\nexport interface SearchSetupMessage {\n type: SearchMessageType.SETUP /* Message type */\n data: SearchIndex /* Message data */\n}\n\n/**\n * A message indicating the search index is ready\n */\nexport interface SearchReadyMessage {\n type: SearchMessageType.READY /* Message type */\n}\n\n/**\n * A message containing a search query\n */\nexport interface SearchQueryMessage {\n type: SearchMessageType.QUERY /* Message type */\n data: string /* Message data */\n}\n\n/**\n * A message containing results for a search query\n */\nexport interface SearchResultMessage {\n type: SearchMessageType.RESULT /* Message type */\n data: SearchResult /* Message data */\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * A message exchanged with the search worker\n */\nexport type SearchMessage =\n | SearchSetupMessage\n | SearchReadyMessage\n | SearchQueryMessage\n | SearchResultMessage\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Type guard for search setup messages\n *\n * @param message - Search worker message\n *\n * @returns Test result\n */\nexport function isSearchSetupMessage(\n message: SearchMessage\n): message is SearchSetupMessage {\n return message.type === SearchMessageType.SETUP\n}\n\n/**\n * Type guard for search ready messages\n *\n * @param message - Search worker message\n *\n * @returns Test result\n */\nexport function isSearchReadyMessage(\n message: SearchMessage\n): message is SearchReadyMessage {\n return message.type === SearchMessageType.READY\n}\n\n/**\n * Type guard for search query messages\n *\n * @param message - Search worker message\n *\n * @returns Test result\n */\nexport function isSearchQueryMessage(\n message: SearchMessage\n): message is SearchQueryMessage {\n return message.type === SearchMessageType.QUERY\n}\n\n/**\n * Type guard for search result messages\n *\n * @param message - Search worker message\n *\n * @returns Test result\n */\nexport function isSearchResultMessage(\n message: SearchMessage\n): message is SearchResultMessage {\n return message.type === SearchMessageType.RESULT\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A RTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { ObservableInput, Subject, from } from \"rxjs\"\nimport { map, share } from \"rxjs/operators\"\n\nimport { configuration, feature, translation } from \"~/_\"\nimport { WorkerHandler, watchWorker } from \"~/browser\"\n\nimport { SearchIndex } from \"../../_\"\nimport {\n SearchOptions,\n SearchPipeline\n} from \"../../options\"\nimport {\n SearchMessage,\n SearchMessageType,\n SearchSetupMessage,\n isSearchResultMessage\n} from \"../message\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Search worker\n */\nexport type SearchWorker = WorkerHandler\n\n/* ----------------------------------------------------------------------------\n * Helper functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Set up search index\n *\n * @param data - Search index\n *\n * @returns Search index\n */\nfunction setupSearchIndex(\n { config, docs, index }: SearchIndex\n): SearchIndex {\n\n /* Override default language with value from translation */\n if (config.lang.length === 1 && config.lang[0] === \"en\")\n config.lang = [\n translation(\"search.config.lang\")\n ]\n\n /* Override default separator with value from translation */\n if (config.separator === \"[\\\\s\\\\-]+\")\n config.separator = translation(\"search.config.separator\")\n\n /* Set pipeline from translation */\n const pipeline = translation(\"search.config.pipeline\")\n .split(/\\s*,\\s*/)\n .filter(Boolean) as SearchPipeline\n\n /* Determine search options */\n const options: SearchOptions = {\n pipeline,\n suggestions: feature(\"search.suggest\")\n }\n\n /* Return search index after defaulting */\n return { config, docs, index, options }\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Set up search worker\n *\n * This function creates a web worker to set up and query the search index,\n * which is done using Lunr.js. The index must be passed as an observable to\n * enable hacks like _localsearch_ via search index embedding as JSON.\n *\n * @param url - Worker URL\n * @param index - Search index observable input\n *\n * @returns Search worker\n */\nexport function setupSearchWorker(\n url: string, index: ObservableInput\n): SearchWorker {\n const config = configuration()\n const worker = new Worker(url)\n\n /* Create communication channels and resolve relative links */\n const tx$ = new Subject()\n const rx$ = watchWorker(worker, { tx$ })\n .pipe(\n map(message => {\n if (isSearchResultMessage(message)) {\n for (const result of message.data.items)\n for (const document of result)\n document.location = `${config.base}/${document.location}`\n }\n return message\n }),\n share()\n )\n\n /* Set up search index */\n from(index)\n .pipe(\n map(data => ({\n type: SearchMessageType.SETUP,\n data: setupSearchIndex(data)\n }))\n )\n .subscribe(tx$.next.bind(tx$))\n\n /* Return search worker */\n return { tx$, rx$ }\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { configuration } from \"~/_\"\nimport { getElementOrThrow, requestJSON } from \"~/browser\"\nimport { Version, renderVersionSelector } from \"~/templates\"\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Set up version selector\n */\nexport function setupVersionSelector(): void {\n const config = configuration()\n requestJSON(new URL(\"versions.json\", config.base))\n .subscribe(versions => {\n const topic = getElementOrThrow(\".md-header__topic\")\n topic.appendChild(renderVersionSelector(versions))\n })\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport {\n Observable,\n Subject,\n combineLatest,\n fromEvent,\n merge\n} from \"rxjs\"\nimport {\n delay,\n distinctUntilChanged,\n distinctUntilKeyChanged,\n filter,\n finalize,\n map,\n take,\n takeLast,\n takeUntil,\n tap\n} from \"rxjs/operators\"\n\nimport {\n resetSearchQueryPlaceholder,\n setSearchQueryPlaceholder\n} from \"~/actions\"\nimport {\n getLocation,\n setElementFocus,\n setToggle,\n watchElementFocus\n} from \"~/browser\"\nimport {\n SearchMessageType,\n SearchQueryMessage,\n SearchWorker,\n defaultTransform,\n isSearchReadyMessage\n} from \"~/integrations\"\n\nimport { Component } from \"../../_\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Search query\n */\nexport interface SearchQuery {\n value: string /* Query value */\n focus: boolean /* Query focus */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch search query\n *\n * Note that the focus event which triggers re-reading the current query value\n * is delayed by `1ms` so the input's empty state is allowed to propagate.\n *\n * @param el - Search query element\n * @param worker - Search worker\n *\n * @returns Search query observable\n */\nexport function watchSearchQuery(\n el: HTMLInputElement, { rx$ }: SearchWorker\n): Observable {\n const fn = __search?.transform || defaultTransform\n\n /* Intercept focus and input events */\n const focus$ = watchElementFocus(el)\n const value$ = merge(\n fromEvent(el, \"keyup\"),\n fromEvent(el, \"focus\").pipe(delay(1))\n )\n .pipe(\n map(() => fn(el.value)),\n distinctUntilChanged()\n )\n\n /* Intercept deep links */\n const location = getLocation()\n if (location.searchParams.has(\"q\")) {\n setToggle(\"search\", true)\n rx$\n .pipe(\n filter(isSearchReadyMessage),\n take(1)\n )\n .subscribe(() => {\n el.value = location.searchParams.get(\"q\")!\n setElementFocus(el)\n })\n }\n\n /* Combine into single observable */\n return combineLatest([value$, focus$])\n .pipe(\n map(([value, focus]) => ({ value, focus }))\n )\n}\n\n/**\n * Mount search query\n *\n * @param el - Search query element\n * @param worker - Search worker\n *\n * @returns Search query component observable\n */\nexport function mountSearchQuery(\n el: HTMLInputElement, { tx$, rx$ }: SearchWorker\n): Observable> {\n const internal$ = new Subject()\n\n /* Handle value changes */\n internal$\n .pipe(\n distinctUntilKeyChanged(\"value\"),\n map(({ value }): SearchQueryMessage => ({\n type: SearchMessageType.QUERY,\n data: value\n }))\n )\n .subscribe(tx$.next.bind(tx$))\n\n /* Handle focus changes */\n internal$\n .pipe(\n distinctUntilKeyChanged(\"focus\")\n )\n .subscribe(({ focus }) => {\n if (focus) {\n setToggle(\"search\", focus)\n setSearchQueryPlaceholder(el, \"\")\n } else {\n resetSearchQueryPlaceholder(el)\n }\n })\n\n /* Handle reset */\n fromEvent(el.form!, \"reset\")\n .pipe(\n takeUntil(internal$.pipe(takeLast(1)))\n )\n .subscribe(() => setElementFocus(el))\n\n /* Create and return component */\n return watchSearchQuery(el, { tx$, rx$ })\n .pipe(\n tap(internal$),\n finalize(() => internal$.complete()),\n map(state => ({ ref: el, ...state }))\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport {\n Observable,\n Subject,\n animationFrameScheduler,\n merge,\n of\n} from \"rxjs\"\nimport {\n bufferCount,\n filter,\n finalize,\n map,\n observeOn,\n switchMap,\n take,\n tap,\n withLatestFrom,\n zipWith\n} from \"rxjs/operators\"\n\nimport {\n addToSearchResultList,\n resetSearchResultList,\n resetSearchResultMeta,\n setSearchResultMeta\n} from \"~/actions\"\nimport {\n getElementOrThrow,\n watchElementThreshold\n} from \"~/browser\"\nimport {\n SearchResult,\n SearchWorker,\n isSearchReadyMessage,\n isSearchResultMessage\n} from \"~/integrations\"\nimport { renderSearchResultItem } from \"~/templates\"\n\nimport { Component } from \"../../_\"\nimport { SearchQuery } from \"../query\"\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Mount options\n */\ninterface MountOptions {\n query$: Observable /* Search query observable */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Mount search result list\n *\n * This function performs a lazy rendering of the search results, depending on\n * the vertical offset of the search result container.\n *\n * @param el - Search result list element\n * @param worker - Search worker\n * @param options - Options\n *\n * @returns Search result list component observable\n */\nexport function mountSearchResult(\n el: HTMLElement, { rx$ }: SearchWorker, { query$ }: MountOptions\n): Observable> {\n const internal$ = new Subject()\n const boundary$ = watchElementThreshold(el.parentElement!)\n .pipe(\n filter(Boolean)\n )\n\n /* Retrieve nested components */\n const meta = getElementOrThrow(\":scope > :first-child\", el)\n const list = getElementOrThrow(\":scope > :last-child\", el)\n\n /* Update search result metadata when ready */\n rx$\n .pipe(\n filter(isSearchReadyMessage),\n take(1)\n )\n .subscribe(() => {\n resetSearchResultMeta(meta)\n })\n\n /* Update search result metadata */\n internal$\n .pipe(\n observeOn(animationFrameScheduler),\n withLatestFrom(query$)\n )\n .subscribe(([{ items }, { value }]) => {\n if (value)\n setSearchResultMeta(meta, items.length)\n else\n resetSearchResultMeta(meta)\n })\n\n /* Update search result list */\n internal$\n .pipe(\n observeOn(animationFrameScheduler),\n tap(() => resetSearchResultList(list)),\n switchMap(({ items }) => merge(\n of(...items.slice(0, 10)),\n of(...items.slice(10))\n .pipe(\n bufferCount(4),\n zipWith(boundary$),\n switchMap(([chunk]) => of(...chunk))\n )\n ))\n )\n .subscribe(result => {\n addToSearchResultList(list, renderSearchResultItem(result))\n })\n\n /* Filter search result message */\n const result$ = rx$\n .pipe(\n filter(isSearchResultMessage),\n map(({ data }) => data)\n )\n\n /* Create and return component */\n return result$\n .pipe(\n tap(internal$),\n finalize(() => internal$.complete()),\n map(state => ({ ref: el, ...state }))\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport {\n Observable,\n Subject,\n fromEvent\n} from \"rxjs\"\nimport {\n finalize,\n map,\n tap\n} from \"rxjs/operators\"\n\nimport { getLocation } from \"~/browser\"\n\nimport { Component } from \"../../_\"\nimport { SearchQuery } from \"../query\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Search sharing\n */\nexport interface SearchShare {\n url: URL /* Deep link for sharing */\n}\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch options\n */\ninterface WatchOptions {\n query$: Observable /* Search query observable */\n}\n\n/**\n * Mount options\n */\ninterface MountOptions {\n query$: Observable /* Search query observable */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Mount search sharing\n *\n * @param _el - Search sharing element\n * @param options - Options\n *\n * @returns Search sharing observable\n */\nexport function watchSearchShare(\n _el: HTMLElement, { query$ }: WatchOptions\n): Observable {\n return query$\n .pipe(\n map(({ value }) => {\n const url = getLocation()\n url.hash = \"\"\n url.searchParams.delete(\"h\")\n url.searchParams.set(\"q\", value)\n return { url }\n })\n )\n}\n\n/**\n * Mount search sharing\n *\n * @param el - Search sharing element\n * @param options - Options\n *\n * @returns Search sharing component observable\n */\nexport function mountSearchShare(\n el: HTMLAnchorElement, options: MountOptions\n): Observable> {\n const internal$ = new Subject()\n internal$.subscribe(({ url }) => {\n el.setAttribute(\"data-clipboard-text\", el.href)\n el.href = `${url}`\n })\n\n /* Prevent following of link */\n fromEvent(el, \"click\")\n .subscribe(ev => ev.preventDefault())\n\n /* Create and return component */\n return watchSearchShare(el, options)\n .pipe(\n tap(internal$),\n finalize(() => internal$.complete()),\n map(state => ({ ref: el, ...state }))\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport {\n Observable,\n Subject,\n asyncScheduler,\n fromEvent\n} from \"rxjs\"\nimport {\n combineLatestWith,\n distinctUntilChanged,\n filter,\n finalize,\n map,\n observeOn,\n tap\n} from \"rxjs/operators\"\n\nimport { Keyboard } from \"~/browser\"\nimport {\n SearchResult,\n SearchWorker,\n isSearchResultMessage\n} from \"~/integrations\"\n\nimport { Component, getComponentElement } from \"../../_\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Search suggestions\n */\nexport interface SearchSuggest {}\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Mount options\n */\ninterface MountOptions {\n keyboard$: Observable /* Keyboard observable */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Mount search suggestions\n *\n * This function will perform a lazy rendering of the search results, depending\n * on the vertical offset of the search result container.\n *\n * @param el - Search result list element\n * @param worker - Search worker\n * @param options - Options\n *\n * @returns Search result list component observable\n */\nexport function mountSearchSuggest(\n el: HTMLElement, { rx$ }: SearchWorker, { keyboard$ }: MountOptions\n): Observable> {\n const internal$ = new Subject()\n\n /* Retrieve query component and track all changes */\n const query = getComponentElement(\"search-query\")\n const query$ = fromEvent(query, \"keydown\")\n .pipe(\n observeOn(asyncScheduler),\n map(() => query.value),\n distinctUntilChanged(),\n )\n\n /* Update search suggestions */\n internal$\n .pipe(\n combineLatestWith(query$),\n map(([{ suggestions }, value]) => {\n const words = value.split(/([\\s-]+)/)\n if (suggestions?.length && words[words.length - 1]) {\n const last = suggestions[suggestions.length - 1]\n if (last.startsWith(words[words.length - 1]))\n words[words.length - 1] = last\n } else {\n words.length = 0\n }\n return words\n })\n )\n .subscribe(words => el.innerHTML = words\n .join(\"\")\n .replace(/\\s/g, \" \")\n )\n\n /* Set up search keyboard handlers */\n keyboard$\n .pipe(\n filter(({ mode }) => mode === \"search\")\n )\n .subscribe(key => {\n switch (key.type) {\n\n /* Right arrow: accept current suggestion */\n case \"ArrowRight\":\n if (\n el.innerText.length &&\n query.selectionStart === query.value.length\n )\n query.value = el.innerText\n break\n }\n })\n\n /* Filter search result message */\n const result$ = rx$\n .pipe(\n filter(isSearchResultMessage),\n map(({ data }) => data)\n )\n\n /* Create and return component */\n return result$\n .pipe(\n tap(internal$),\n finalize(() => internal$.complete()),\n map(() => ({ ref: el }))\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { NEVER, Observable, ObservableInput, merge } from \"rxjs\"\nimport { filter, mergeWith, sample, take } from \"rxjs/operators\"\n\nimport { configuration } from \"~/_\"\nimport {\n Keyboard,\n getActiveElement,\n getElements,\n setElementFocus,\n setElementSelection,\n setToggle\n} from \"~/browser\"\nimport {\n SearchIndex,\n SearchResult,\n isSearchQueryMessage,\n isSearchReadyMessage,\n setupSearchWorker\n} from \"~/integrations\"\n\nimport {\n Component,\n getComponentElement,\n getComponentElements\n} from \"../../_\"\nimport { SearchQuery, mountSearchQuery } from \"../query\"\nimport { mountSearchResult } from \"../result\"\nimport { SearchShare, mountSearchShare } from \"../share\"\nimport { SearchSuggest, mountSearchSuggest } from \"../suggest\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Search\n */\nexport type Search =\n | SearchQuery\n | SearchResult\n | SearchShare\n | SearchSuggest\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Mount options\n */\ninterface MountOptions {\n index$: ObservableInput /* Search index observable */\n keyboard$: Observable /* Keyboard observable */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Mount search\n *\n * This function sets up the search functionality, including the underlying\n * web worker and all keyboard bindings.\n *\n * @param el - Search element\n * @param options - Options\n *\n * @returns Search component observable\n */\nexport function mountSearch(\n el: HTMLElement, { index$, keyboard$ }: MountOptions\n): Observable> {\n const config = configuration()\n try {\n const worker = setupSearchWorker(config.search, index$)\n\n /* Retrieve query and result components */\n const query = getComponentElement(\"search-query\", el)\n const result = getComponentElement(\"search-result\", el)\n\n /* Re-emit query when search is ready */\n const { tx$, rx$ } = worker\n tx$\n .pipe(\n filter(isSearchQueryMessage),\n sample(rx$\n .pipe(\n filter(isSearchReadyMessage),\n take(1)\n )\n )\n )\n .subscribe(tx$.next.bind(tx$))\n\n /* Set up search keyboard handlers */\n keyboard$\n .pipe(\n filter(({ mode }) => mode === \"search\")\n )\n .subscribe(key => {\n const active = getActiveElement()\n switch (key.type) {\n\n /* Enter: go to first (best) result */\n case \"Enter\":\n if (active === query) {\n const anchors = new Map()\n for (const anchor of getElements(\n \":first-child [href]\", result\n )) {\n const article = anchor.firstElementChild!\n anchors.set(anchor, parseFloat(\n article.getAttribute(\"data-md-score\")!\n ))\n }\n\n /* Go to result with highest score, if any */\n if (anchors.size) {\n const [[best]] = [...anchors].sort(([, a], [, b]) => b - a)\n best.click()\n }\n\n /* Otherwise omit form submission */\n key.claim()\n }\n break\n\n /* Escape or Tab: close search */\n case \"Escape\":\n case \"Tab\":\n setToggle(\"search\", false)\n setElementFocus(query, false)\n break\n\n /* Vertical arrows: select previous or next search result */\n case \"ArrowUp\":\n case \"ArrowDown\":\n if (typeof active === \"undefined\") {\n setElementFocus(query)\n } else {\n const els = [query, ...getElements(\n \":not(details) > [href], summary, details[open] [href]\",\n result\n )]\n const i = Math.max(0, (\n Math.max(0, els.indexOf(active)) + els.length + (\n key.type === \"ArrowUp\" ? -1 : +1\n )\n ) % els.length)\n setElementFocus(els[i])\n }\n\n /* Prevent scrolling of page */\n key.claim()\n break\n\n /* All other keys: hand to search query */\n default:\n if (query !== getActiveElement())\n setElementFocus(query)\n }\n })\n\n /* Set up global keyboard handlers */\n keyboard$\n .pipe(\n filter(({ mode }) => mode === \"global\"),\n )\n .subscribe(key => {\n switch (key.type) {\n\n /* Open search and select query */\n case \"f\":\n case \"s\":\n case \"/\":\n setElementFocus(query)\n setElementSelection(query)\n key.claim()\n break\n }\n })\n\n /* Create and return component */\n const query$ = mountSearchQuery(query, worker)\n const result$ = mountSearchResult(result, worker, { query$ })\n return merge(query$, result$)\n .pipe(\n mergeWith(\n\n /* Search sharing */\n ...getComponentElements(\"search-share\", el)\n .map(child => mountSearchShare(child, { query$ })),\n\n /* Search suggestions */\n ...getComponentElements(\"search-suggest\", el)\n .map(child => mountSearchSuggest(child, worker, { keyboard$ }))\n )\n )\n\n /* Gracefully handle broken search */\n } catch (err) {\n el.hidden = true\n return NEVER\n }\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport {\n Observable,\n ObservableInput,\n combineLatest\n} from \"rxjs\"\nimport { filter, map, startWith } from \"rxjs/operators\"\n\nimport { getLocation } from \"~/browser\"\nimport {\n SearchIndex,\n setupSearchHighlighter\n} from \"~/integrations\"\nimport { h } from \"~/utilities\"\n\nimport { Component } from \"../../_\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Search highlighting\n */\nexport interface SearchHighlight {\n nodes: Map /* Map of replacements */\n}\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Mount options\n */\ninterface MountOptions {\n index$: ObservableInput /* Search index observable */\n location$: Observable /* Location observable */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Mount search highlighting\n *\n * @param el - Content element\n * @param options - Options\n *\n * @returns Search highlighting component observable\n */\nexport function mountSearchHiglight(\n el: HTMLElement, { index$, location$ }: MountOptions\n): Observable> {\n return combineLatest([\n index$,\n location$\n .pipe(\n startWith(getLocation()),\n filter(url => url.searchParams.has(\"h\"))\n )\n ])\n .pipe(\n map(([index, url]) => setupSearchHighlighter(index.config)(\n url.searchParams.get(\"h\")!\n )),\n map(fn => {\n const nodes = new Map()\n\n /* Traverse text nodes and collect matches */\n const it = document.createNodeIterator(el, NodeFilter.SHOW_TEXT)\n for (let node = it.nextNode(); node; node = it.nextNode()) {\n if (node.parentElement?.offsetHeight) {\n const original = node.textContent!\n const replaced = fn(original)\n if (replaced.length > original.length)\n nodes.set(node as ChildNode, replaced)\n }\n }\n\n /* Replace original nodes with matches */\n for (const [node, text] of nodes) {\n const { childNodes } = h(\"span\", null, text)\n node.replaceWith(...Array.from(childNodes))\n }\n\n /* Return component */\n return { ref: el, nodes }\n })\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport {\n Observable,\n Subject,\n animationFrameScheduler,\n combineLatest\n} from \"rxjs\"\nimport {\n distinctUntilChanged,\n finalize,\n map,\n observeOn,\n tap,\n withLatestFrom\n} from \"rxjs/operators\"\n\nimport {\n resetSidebarHeight,\n resetSidebarOffset,\n setSidebarHeight,\n setSidebarOffset\n} from \"~/actions\"\nimport { Viewport } from \"~/browser\"\n\nimport { Component } from \"../_\"\nimport { Header } from \"../header\"\nimport { Main } from \"../main\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Sidebar\n */\nexport interface Sidebar {\n height: number /* Sidebar height */\n locked: boolean /* User scrolled past header */\n}\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch options\n */\ninterface WatchOptions {\n viewport$: Observable /* Viewport observable */\n main$: Observable
    /* Main area observable */\n}\n\n/**\n * Mount options\n */\ninterface MountOptions {\n viewport$: Observable /* Viewport observable */\n header$: Observable
    /* Header observable */\n main$: Observable
    /* Main area observable */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch sidebar\n *\n * This function returns an observable that computes the visual parameters of\n * the sidebar which depends on the vertical viewport offset, as well as the\n * height of the main area. When the page is scrolled beyond the header, the\n * sidebar is locked and fills the remaining space.\n *\n * @param el - Sidebar element\n * @param options - Options\n *\n * @returns Sidebar observable\n */\nexport function watchSidebar(\n el: HTMLElement, { viewport$, main$ }: WatchOptions\n): Observable {\n const adjust =\n el.parentElement!.offsetTop -\n el.parentElement!.parentElement!.offsetTop\n\n /* Compute the sidebar's available height and if it should be locked */\n return combineLatest([main$, viewport$])\n .pipe(\n map(([{ offset, height }, { offset: { y } }]) => {\n height = height\n + Math.min(adjust, Math.max(0, y - offset))\n - adjust\n return {\n height,\n locked: y >= offset + adjust\n }\n }),\n distinctUntilChanged((a, b) => (\n a.height === b.height &&\n a.locked === b.locked\n ))\n )\n}\n\n/**\n * Mount sidebar\n *\n * @param el - Sidebar element\n * @param options - Options\n *\n * @returns Sidebar component observable\n */\nexport function mountSidebar(\n el: HTMLElement, { header$, ...options }: MountOptions\n): Observable> {\n const internal$ = new Subject()\n internal$\n .pipe(\n observeOn(animationFrameScheduler),\n withLatestFrom(header$)\n )\n .subscribe({\n\n /* Update height and offset */\n next([{ height }, { height: offset }]) {\n setSidebarHeight(el, height)\n setSidebarOffset(el, offset)\n },\n\n /* Reset on complete */\n complete() {\n resetSidebarOffset(el)\n resetSidebarHeight(el)\n }\n })\n\n /* Create and return component */\n return watchSidebar(el, options)\n .pipe(\n tap(internal$),\n finalize(() => internal$.complete()),\n map(state => ({ ref: el, ...state }))\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { Repo, User } from \"github-types\"\nimport { Observable, zip } from \"rxjs\"\nimport { defaultIfEmpty, map } from \"rxjs/operators\"\n\nimport { requestJSON } from \"~/browser\"\n\nimport { SourceFacts } from \"../_\"\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * GitHub release (partial)\n */\ninterface Release {\n tag_name: string /* Tag name */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Fetch GitHub repository facts\n *\n * @param user - GitHub user\n * @param repo - GitHub repository\n *\n * @returns Repository facts observable\n */\nexport function fetchSourceFactsFromGitHub(\n user: string, repo?: string\n): Observable {\n if (typeof repo !== \"undefined\") {\n const url = `https://api.github.com/repos/${user}/${repo}`\n return zip(\n\n /* Fetch version */\n requestJSON(`${url}/releases/latest`)\n .pipe(\n map(release => ({\n version: release.tag_name\n })),\n defaultIfEmpty({})\n ),\n\n /* Fetch stars and forks */\n requestJSON(url)\n .pipe(\n map(info => ({\n stars: info.stargazers_count,\n forks: info.forks_count\n })),\n defaultIfEmpty({})\n )\n )\n .pipe(\n map(([release, info]) => ({ ...release, ...info }))\n )\n\n /* User or organization */\n } else {\n const url = `https://api.github.com/repos/${user}`\n return requestJSON(url)\n .pipe(\n map(info => ({\n repositories: info.public_repos\n })),\n defaultIfEmpty({})\n )\n }\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { ProjectSchema } from \"gitlab\"\nimport { Observable } from \"rxjs\"\nimport { defaultIfEmpty, map } from \"rxjs/operators\"\n\nimport { requestJSON } from \"~/browser\"\n\nimport { SourceFacts } from \"../_\"\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Fetch GitLab repository facts\n *\n * @param base - GitLab base\n * @param project - GitLab project\n *\n * @returns Repository facts observable\n */\nexport function fetchSourceFactsFromGitLab(\n base: string, project: string\n): Observable {\n const url = `https://${base}/api/v4/projects/${encodeURIComponent(project)}`\n return requestJSON(url)\n .pipe(\n map(({ star_count, forks_count }) => ({\n stars: star_count,\n forks: forks_count\n })),\n defaultIfEmpty({})\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { NEVER, Observable } from \"rxjs\"\n\nimport { fetchSourceFactsFromGitHub } from \"../github\"\nimport { fetchSourceFactsFromGitLab } from \"../gitlab\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Repository facts for repositories\n */\nexport interface RepositoryFacts {\n stars?: number /* Number of stars */\n forks?: number /* Number of forks */\n version?: string /* Latest version */\n}\n\n/**\n * Repository facts for organizations\n */\nexport interface OrganizationFacts {\n repositories?: number /* Number of repositories */\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Repository facts\n */\nexport type SourceFacts =\n | RepositoryFacts\n | OrganizationFacts\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Fetch repository facts\n *\n * @param url - Repository URL\n *\n * @returns Repository facts observable\n */\nexport function fetchSourceFacts(\n url: string\n): Observable {\n const [type] = url.match(/(git(?:hub|lab))/i) || []\n switch (type.toLowerCase()) {\n\n /* GitHub repository */\n case \"github\":\n const [, user, repo] = url.match(/^.+github\\.com\\/([^/]+)\\/?([^/]+)?/i)!\n return fetchSourceFactsFromGitHub(user, repo)\n\n /* GitLab repository */\n case \"gitlab\":\n const [, base, slug] = url.match(/^.+?([^/]*gitlab[^/]+)\\/(.+?)\\/?$/i)!\n return fetchSourceFactsFromGitLab(base, slug)\n\n /* Everything else */\n default:\n return NEVER\n }\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { NEVER, Observable, Subject, defer, of } from \"rxjs\"\nimport {\n catchError,\n filter,\n finalize,\n map,\n shareReplay,\n tap\n} from \"rxjs/operators\"\n\nimport { setSourceFacts, setSourceState } from \"~/actions\"\nimport { renderSourceFacts } from \"~/templates\"\n\nimport { Component } from \"../../_\"\nimport { SourceFacts, fetchSourceFacts } from \"../facts\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Repository information\n */\nexport interface Source {\n facts: SourceFacts /* Repository facts */\n}\n\n/* ----------------------------------------------------------------------------\n * Data\n * ------------------------------------------------------------------------- */\n\n/**\n * Repository information observable\n */\nlet fetch$: Observable\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch repository information\n *\n * This function tries to read the repository facts from session storage, and\n * if unsuccessful, fetches them from the underlying provider.\n *\n * @param el - Repository information element\n *\n * @returns Repository information observable\n */\nexport function watchSource(\n el: HTMLAnchorElement\n): Observable {\n return fetch$ ||= defer(() => {\n const data = sessionStorage.getItem(__prefix(\"__source\"))\n if (data) {\n return of(JSON.parse(data))\n } else {\n const value$ = fetchSourceFacts(el.href)\n value$.subscribe(value => {\n try {\n sessionStorage.setItem(__prefix(\"__source\"), JSON.stringify(value))\n } catch (err) {\n /* Uncritical, just swallow */\n }\n })\n\n /* Return value */\n return value$\n }\n })\n .pipe(\n catchError(() => NEVER),\n filter(facts => Object.keys(facts).length > 0),\n map(facts => ({ facts })),\n shareReplay(1)\n )\n}\n\n/**\n * Mount repository information\n *\n * @param el - Repository information element\n *\n * @returns Repository information component observable\n */\nexport function mountSource(\n el: HTMLAnchorElement\n): Observable> {\n const internal$ = new Subject()\n internal$.subscribe(({ facts }) => {\n setSourceFacts(el, renderSourceFacts(facts))\n setSourceState(el, \"done\")\n })\n\n /* Create and return component */\n return watchSource(el)\n .pipe(\n tap(internal$),\n finalize(() => internal$.complete()),\n map(state => ({ ref: el, ...state }))\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { Observable, Subject, animationFrameScheduler } from \"rxjs\"\nimport {\n distinctUntilKeyChanged,\n finalize,\n map,\n observeOn,\n switchMap,\n tap\n} from \"rxjs/operators\"\n\nimport { resetTabsState, setTabsState } from \"~/actions\"\nimport {\n Viewport,\n watchElementSize,\n watchViewportAt\n} from \"~/browser\"\n\nimport { Component } from \"../_\"\nimport { Header } from \"../header\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Navigation tabs\n */\nexport interface Tabs {\n hidden: boolean /* User scrolled past tabs */\n}\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch options\n */\ninterface WatchOptions {\n viewport$: Observable /* Viewport observable */\n header$: Observable
    /* Header observable */\n}\n\n/**\n * Mount options\n */\ninterface MountOptions {\n viewport$: Observable /* Viewport observable */\n header$: Observable
    /* Header observable */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch navigation tabs\n *\n * @param el - Navigation tabs element\n * @param options - Options\n *\n * @returns Navigation tabs observable\n */\nexport function watchTabs(\n el: HTMLElement, { viewport$, header$ }: WatchOptions\n): Observable {\n return watchElementSize(document.body)\n .pipe(\n switchMap(() => watchViewportAt(el, { header$, viewport$ })),\n map(({ offset: { y } }) => {\n return {\n hidden: y >= 10\n }\n }),\n distinctUntilKeyChanged(\"hidden\")\n )\n}\n\n/**\n * Mount navigation tabs\n *\n * This function hides the navigation tabs when scrolling past the threshold\n * and makes them reappear in a nice CSS animation when scrolling back up.\n *\n * @param el - Navigation tabs element\n * @param options - Options\n *\n * @returns Navigation tabs component observable\n */\nexport function mountTabs(\n el: HTMLElement, options: MountOptions\n): Observable> {\n const internal$ = new Subject()\n internal$\n .pipe(\n observeOn(animationFrameScheduler)\n )\n .subscribe({\n\n /* Update state */\n next({ hidden }) {\n if (hidden)\n setTabsState(el, \"hidden\")\n else\n resetTabsState(el)\n },\n\n /* Reset on complete */\n complete() {\n resetTabsState(el)\n }\n })\n\n /* Create and return component */\n return watchTabs(el, options)\n .pipe(\n tap(internal$),\n finalize(() => internal$.complete()),\n map(state => ({ ref: el, ...state }))\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport {\n Observable,\n Subject,\n animationFrameScheduler,\n combineLatest\n} from \"rxjs\"\nimport {\n bufferCount,\n distinctUntilChanged,\n distinctUntilKeyChanged,\n finalize,\n map,\n observeOn,\n scan,\n startWith,\n switchMap,\n tap\n} from \"rxjs/operators\"\n\nimport {\n resetAnchorActive,\n resetAnchorState,\n setAnchorActive,\n setAnchorState\n} from \"~/actions\"\nimport {\n Viewport,\n getElement,\n getElements,\n watchElementSize\n} from \"~/browser\"\n\nimport { Component } from \"../_\"\nimport { Header } from \"../header\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Table of contents\n */\nexport interface TableOfContents {\n prev: HTMLAnchorElement[][] /* Anchors (previous) */\n next: HTMLAnchorElement[][] /* Anchors (next) */\n}\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch options\n */\ninterface WatchOptions {\n viewport$: Observable /* Viewport observable */\n header$: Observable
    /* Header observable */\n}\n\n/**\n * Mount options\n */\ninterface MountOptions {\n viewport$: Observable /* Viewport observable */\n header$: Observable
    /* Header observable */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch table of contents\n *\n * This is effectively a scroll spy implementation which will account for the\n * fixed header and automatically re-calculate anchor offsets when the viewport\n * is resized. The returned observable will only emit if the table of contents\n * needs to be repainted.\n *\n * This implementation tracks an anchor element's entire path starting from its\n * level up to the top-most anchor element, e.g. `[h3, h2, h1]`. Although the\n * Material theme currently doesn't make use of this information, it enables\n * the styling of the entire hierarchy through customization.\n *\n * Note that the current anchor is the last item of the `prev` anchor list.\n *\n * @param anchors - Anchor elements\n * @param options - Options\n *\n * @returns Table of contents observable\n */\nexport function watchTableOfContents(\n anchors: HTMLAnchorElement[], { viewport$, header$ }: WatchOptions\n): Observable {\n const table = new Map()\n for (const anchor of anchors) {\n const id = decodeURIComponent(anchor.hash.substring(1))\n const target = getElement(`[id=\"${id}\"]`)\n if (typeof target !== \"undefined\")\n table.set(anchor, target)\n }\n\n /* Compute necessary adjustment for header */\n const adjust$ = header$\n .pipe(\n map(header => 24 + header.height)\n )\n\n /* Compute partition of previous and next anchors */\n const partition$ = watchElementSize(document.body)\n .pipe(\n distinctUntilKeyChanged(\"height\"),\n\n /* Build index to map anchor paths to vertical offsets */\n map(() => {\n let path: HTMLAnchorElement[] = []\n return [...table].reduce((index, [anchor, target]) => {\n while (path.length) {\n const last = table.get(path[path.length - 1])!\n if (last.tagName >= target.tagName) {\n path.pop()\n } else {\n break\n }\n }\n\n /* If the current anchor is hidden, continue with its parent */\n let offset = target.offsetTop\n while (!offset && target.parentElement) {\n target = target.parentElement\n offset = target.offsetTop\n }\n\n /* Map reversed anchor path to vertical offset */\n return index.set(\n [...path = [...path, anchor]].reverse(),\n offset\n )\n }, new Map())\n }),\n\n /* Sort index by vertical offset (see https://bit.ly/30z6QSO) */\n map(index => new Map([...index].sort(([, a], [, b]) => a - b))),\n\n /* Re-compute partition when viewport offset changes */\n switchMap(index => combineLatest([adjust$, viewport$])\n .pipe(\n scan(([prev, next], [adjust, { offset: { y } }]) => {\n\n /* Look forward */\n while (next.length) {\n const [, offset] = next[0]\n if (offset - adjust < y) {\n prev = [...prev, next.shift()!]\n } else {\n break\n }\n }\n\n /* Look backward */\n while (prev.length) {\n const [, offset] = prev[prev.length - 1]\n if (offset - adjust >= y) {\n next = [prev.pop()!, ...next]\n } else {\n break\n }\n }\n\n /* Return partition */\n return [prev, next]\n }, [[], [...index]]),\n distinctUntilChanged((a, b) => (\n a[0] === b[0] &&\n a[1] === b[1]\n ))\n )\n )\n )\n\n /* Compute and return anchor list migrations */\n return partition$\n .pipe(\n map(([prev, next]) => ({\n prev: prev.map(([path]) => path),\n next: next.map(([path]) => path)\n })),\n\n /* Extract anchor list migrations */\n startWith({ prev: [], next: [] }),\n bufferCount(2, 1),\n map(([a, b]) => {\n\n /* Moving down */\n if (a.prev.length < b.prev.length) {\n return {\n prev: b.prev.slice(Math.max(0, a.prev.length - 1), b.prev.length),\n next: []\n }\n\n /* Moving up */\n } else {\n return {\n prev: b.prev.slice(-1),\n next: b.next.slice(0, b.next.length - a.next.length)\n }\n }\n })\n )\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Mount table of contents\n *\n * @param el - Anchor list element\n * @param options - Options\n *\n * @returns Table of contents component observable\n */\nexport function mountTableOfContents(\n el: HTMLElement, options: MountOptions\n): Observable> {\n const internal$ = new Subject()\n internal$\n .pipe(\n observeOn(animationFrameScheduler),\n )\n .subscribe(({ prev, next }) => {\n\n /* Look forward */\n for (const [anchor] of next) {\n resetAnchorActive(anchor)\n resetAnchorState(anchor)\n }\n\n /* Look backward */\n for (const [index, [anchor]] of prev.entries()) {\n setAnchorActive(anchor, index === prev.length - 1)\n setAnchorState(anchor, \"blur\")\n }\n })\n\n /* Create and return component */\n const anchors = getElements(\"[href^=\\\\#]\", el)\n return watchTableOfContents(anchors, options)\n .pipe(\n tap(internal$),\n finalize(() => internal$.complete()),\n map(state => ({ ref: el, ...state }))\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport {\n Observable,\n Subject,\n animationFrameScheduler,\n combineLatest\n} from \"rxjs\"\nimport {\n bufferCount,\n distinctUntilChanged,\n distinctUntilKeyChanged,\n finalize,\n map,\n observeOn,\n tap,\n withLatestFrom\n} from \"rxjs/operators\"\n\nimport {\n resetBackToTopOffset,\n resetBackToTopState,\n setBackToTopOffset,\n setBackToTopState\n} from \"~/actions\"\nimport { Viewport, setElementFocus } from \"~/browser\"\n\nimport { Component } from \"../_\"\nimport { Header } from \"../header\"\nimport { Main } from \"../main\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Back-to-top button\n */\nexport interface BackToTop {\n hidden: boolean /* User scrolled up */\n}\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch options\n */\ninterface WatchOptions {\n viewport$: Observable /* Viewport observable */\n header$: Observable
    /* Header observable */\n main$: Observable
    /* Main area observable */\n}\n\n/**\n * Mount options\n */\ninterface MountOptions {\n viewport$: Observable /* Viewport observable */\n header$: Observable
    /* Header observable */\n main$: Observable
    /* Main area observable */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Watch back-to-top\n *\n * @param _el - Back-to-top element\n * @param options - Options\n *\n * @returns Back-to-top observable\n */\nexport function watchBackToTop(\n _el: HTMLElement, { viewport$, main$ }: WatchOptions\n): Observable {\n\n /* Compute direction */\n const direction$ = viewport$\n .pipe(\n map(({ offset: { y } }) => y),\n bufferCount(2, 1),\n map(([a, b]) => a > b && b),\n distinctUntilChanged()\n )\n\n /* Compute whether button should be hidden */\n const hidden$ = main$\n .pipe(\n distinctUntilKeyChanged(\"active\")\n )\n\n /* Compute threshold for hiding */\n return combineLatest([hidden$, direction$])\n .pipe(\n map(([{ active }, direction]) => ({\n hidden: !(active && direction)\n })),\n distinctUntilChanged((a, b) => (\n a.hidden === b.hidden\n ))\n )\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Mount back-to-top\n *\n * @param el - Back-to-top element\n * @param options - Options\n *\n * @returns Back-to-top component observable\n */\nexport function mountBackToTop(\n el: HTMLElement, { viewport$, header$, main$ }: MountOptions\n): Observable> {\n const internal$ = new Subject()\n internal$\n .pipe(\n observeOn(animationFrameScheduler),\n withLatestFrom(header$\n .pipe(\n distinctUntilKeyChanged(\"height\")\n )\n )\n )\n .subscribe({\n\n /* Update state */\n next([{ hidden }, { height }]) {\n setBackToTopOffset(el, height + 16)\n if (hidden) {\n setBackToTopState(el, \"hidden\")\n setElementFocus(el, false)\n } else {\n resetBackToTopState(el)\n }\n },\n\n /* Reset on complete */\n complete() {\n resetBackToTopOffset(el)\n resetBackToTopState(el)\n }\n })\n\n /* Create and return component */\n return watchBackToTop(el, { viewport$, header$, main$ })\n .pipe(\n tap(internal$),\n finalize(() => internal$.complete()),\n map(state => ({ ref: el, ...state }))\n )\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { Observable, fromEvent, of } from \"rxjs\"\nimport {\n mapTo,\n mergeMap,\n switchMap,\n takeWhile,\n tap,\n withLatestFrom\n} from \"rxjs/operators\"\n\nimport { getElements } from \"~/browser\"\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Patch options\n */\ninterface PatchOptions {\n document$: Observable /* Document observable */\n tablet$: Observable /* Tablet breakpoint observable */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Patch indeterminate checkboxes\n *\n * This function replaces the indeterminate \"pseudo state\" with the actual\n * indeterminate state, which is used to keep navigation always expanded.\n *\n * @param options - Options\n */\nexport function patchIndeterminate(\n { document$, tablet$ }: PatchOptions\n): void {\n document$\n .pipe(\n switchMap(() => of(...getElements(\n \"[data-md-state=indeterminate]\"\n ))),\n tap(el => {\n el.indeterminate = true\n el.checked = false\n }),\n mergeMap(el => fromEvent(el, \"change\")\n .pipe(\n takeWhile(() => el.hasAttribute(\"data-md-state\")),\n mapTo(el)\n )\n ),\n withLatestFrom(tablet$)\n )\n .subscribe(([el, tablet]) => {\n el.removeAttribute(\"data-md-state\")\n if (tablet)\n el.checked = false\n })\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { Observable, fromEvent, of } from \"rxjs\"\nimport {\n filter,\n mapTo,\n mergeMap,\n switchMap,\n tap\n} from \"rxjs/operators\"\n\nimport { getElements } from \"~/browser\"\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Patch options\n */\ninterface PatchOptions {\n document$: Observable /* Document observable */\n}\n\n/* ----------------------------------------------------------------------------\n * Helper functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Check whether the given device is an Apple device\n *\n * @returns Test result\n */\nfunction isAppleDevice(): boolean {\n return /(iPad|iPhone|iPod)/.test(navigator.userAgent)\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Patch all elements with `data-md-scrollfix` attributes\n *\n * This is a year-old patch which ensures that overflow scrolling works at the\n * top and bottom of containers on iOS by ensuring a `1px` scroll offset upon\n * the start of a touch event.\n *\n * @see https://bit.ly/2SCtAOO - Original source\n *\n * @param options - Options\n */\nexport function patchScrollfix(\n { document$ }: PatchOptions\n): void {\n document$\n .pipe(\n switchMap(() => of(...getElements(\"[data-md-scrollfix]\"))),\n tap(el => el.removeAttribute(\"data-md-scrollfix\")),\n filter(isAppleDevice),\n mergeMap(el => fromEvent(el, \"touchstart\")\n .pipe(\n mapTo(el)\n )\n )\n )\n .subscribe(el => {\n const top = el.scrollTop\n\n /* We're at the top of the container */\n if (top === 0) {\n el.scrollTop = 1\n\n /* We're at the bottom of the container */\n } else if (top + el.offsetHeight === el.scrollHeight) {\n el.scrollTop = top - 1\n }\n })\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport {\n Observable,\n animationFrameScheduler,\n combineLatest,\n of\n} from \"rxjs\"\nimport {\n delay,\n map,\n observeOn,\n switchMap,\n withLatestFrom\n} from \"rxjs/operators\"\n\nimport { resetScrollLock, setScrollLock } from \"~/actions\"\nimport { Viewport, watchToggle } from \"~/browser\"\n\n/* ----------------------------------------------------------------------------\n * Helper types\n * ------------------------------------------------------------------------- */\n\n/**\n * Patch options\n */\ninterface PatchOptions {\n viewport$: Observable /* Viewport observable */\n tablet$: Observable /* Tablet breakpoint observable */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Patch the document body to lock when search is open\n *\n * For mobile and tablet viewports, the search is rendered full screen, which\n * leads to scroll leaking when at the top or bottom of the search result. This\n * function locks the body when the search is in full screen mode, and restores\n * the scroll position when leaving.\n *\n * @param options - Options\n */\nexport function patchScrolllock(\n { viewport$, tablet$ }: PatchOptions\n): void {\n combineLatest([watchToggle(\"search\"), tablet$])\n .pipe(\n map(([active, tablet]) => active && !tablet),\n switchMap(active => of(active)\n .pipe(\n delay(active ? 400 : 100),\n observeOn(animationFrameScheduler)\n )\n ),\n withLatestFrom(viewport$)\n )\n .subscribe(([active, { offset: { y }}]) => {\n if (active)\n setScrollLock(document.body, y)\n else\n resetScrollLock(document.body)\n })\n}\n"], + "mappings": "4iCAAA,oBAAC,UAAU,EAAQ,EAAS,CAC1B,MAAO,KAAY,UAAY,MAAO,KAAW,YAAc,IAC/D,MAAO,SAAW,YAAc,OAAO,IAAM,OAAO,GACnD,MACD,GAAO,UAAY,CAAE,aASrB,WAAmC,EAAO,CACxC,GAAI,GAAmB,GACnB,EAA0B,GAC1B,EAAiC,KAEjC,EAAsB,CACxB,KAAM,GACN,OAAQ,GACR,IAAK,GACL,IAAK,GACL,MAAO,GACP,SAAU,GACV,OAAQ,GACR,KAAM,GACN,MAAO,GACP,KAAM,GACN,KAAM,GACN,SAAU,GACV,iBAAkB,IAQpB,WAA4B,EAAI,CAC9B,MACE,MACA,IAAO,UACP,EAAG,WAAa,QAChB,EAAG,WAAa,QAChB,aAAe,IACf,YAAc,GAAG,WAcrB,WAAuC,EAAI,CACzC,GAAI,IAAO,EAAG,KACV,GAAU,EAAG,QAUjB,MARI,QAAY,SAAW,E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,WAAS,YAGnD,GAAG,GAAqB,WACrB,IAAI,GAAM,GAAa,IAG1B,GAAG,GAAqB,UACrB,IAAI,GAAM,GAAY,EAAI,CAAE,UAAQ,gBAGvC,GAAG,GAAqB,UACrB,IAAI,GAAM,GAAY,KAIrB,GAAW,GAAM,IAAM,EAG3B,GAAG,GAAqB,WACrB,IAAI,GAAM,GAAa,EAAI,CAAE,WAAS,aAAW,aAGpD,GAAG,GAAqB,WACrB,IAAI,GAAM,GAAQ,oBACf,GAAoB,EAAI,CAAE,UAAQ,eAClC,GAIN,GAAG,GAAqB,gBACrB,IAAI,GAAM,GAAiB,EAAI,CAAE,aAAW,cAG/C,GAAG,GAAqB,WACrB,IAAI,GAAM,EAAG,aAAa,kBAAoB,aAC3C,GAAG,GAAS,IAAM,GAAa,EAAI,CAAE,aAAW,WAAS,YACzD,GAAG,GAAS,IAAM,GAAa,EAAI,CAAE,aAAW,WAAS,aAI/D,GAAG,GAAqB,QACrB,IAAI,GAAM,GAAU,EAAI,CAAE,aAAW,cAGxC,GAAG,GAAqB,OACrB,IAAI,GAAM,GAAqB,EAAI,CAAE,aAAW,cAGnD,GAAG,GAAqB,OACrB,IAAI,GAAM,GAAe,EAAI,CAAE,aAAW,WAAS,cAIlD,GAAa,GAChB,KACC,EAAU,IAAM,IAChB,GAAU,IACV,GAAY,IAIhB,GAAW,YAMX,OAAO,UAAa,GACpB,OAAO,UAAa,GACpB,OAAO,QAAa,GACpB,OAAO,UAAa,GACpB,OAAO,UAAa,GACpB,OAAO,QAAa,GACpB,OAAO,QAAa,GACpB,OAAO,OAAa,GACpB,OAAO,OAAa,GACpB,OAAO,WAAa", + "names": [] +} diff --git a/en/2021.7/assets/javascripts/lunr/min/lunr.ar.min.js b/en/2021.7/assets/javascripts/lunr/min/lunr.ar.min.js new file mode 100644 index 000000000..248ddc5d1 --- /dev/null +++ b/en/2021.7/assets/javascripts/lunr/min/lunr.ar.min.js @@ -0,0 +1 @@ +!function(e,r){"function"==typeof define&&define.amd?define(r):"object"==typeof exports?module.exports=r():r()(e.lunr)}(this,function(){return function(e){if(void 0===e)throw new Error("Lunr is not present. Please include / require Lunr before this script.");if(void 0===e.stemmerSupport)throw new Error("Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.");e.ar=function(){this.pipeline.reset(),this.pipeline.add(e.ar.trimmer,e.ar.stopWordFilter,e.ar.stemmer),this.searchPipeline&&(this.searchPipeline.reset(),this.searchPipeline.add(e.ar.stemmer))},e.ar.wordCharacters="ء-ٛٱـ",e.ar.trimmer=e.trimmerSupport.generateTrimmer(e.ar.wordCharacters),e.Pipeline.registerFunction(e.ar.trimmer,"trimmer-ar"),e.ar.stemmer=function(){var e=this;return e.result=!1,e.preRemoved=!1,e.sufRemoved=!1,e.pre={pre1:"ف ك ب و س ل ن ا ي ت",pre2:"ال لل",pre3:"بال وال فال تال كال ولل",pre4:"فبال كبال وبال وكال"},e.suf={suf1:"ه ك ت ن ا ي",suf2:"نك نه ها وك يا اه ون ين تن تم نا وا ان كم كن ني نن ما هم هن تك ته ات يه",suf3:"تين كهم نيه نهم ونه وها يهم ونا ونك وني وهم تكم تنا تها تني تهم كما كها ناه نكم هنا تان يها",suf4:"كموه ناها ونني ونهم تكما تموه تكاه كماه ناكم ناهم نيها وننا"},e.patterns=JSON.parse('{"pt43":[{"pt":[{"c":"ا","l":1}]},{"pt":[{"c":"ا,ت,ن,ي","l":0}],"mPt":[{"c":"ف","l":0,"m":1},{"c":"ع","l":1,"m":2},{"c":"ل","l":2,"m":3}]},{"pt":[{"c":"و","l":2}],"mPt":[{"c":"ف","l":0,"m":0},{"c":"ع","l":1,"m":1},{"c":"ل","l":2,"m":3}]},{"pt":[{"c":"ا","l":2}]},{"pt":[{"c":"ي","l":2}],"mPt":[{"c":"ف","l":0,"m":0},{"c":"ع","l":1,"m":1},{"c":"ا","l":2},{"c":"ل","l":3,"m":3}]},{"pt":[{"c":"م","l":0}]}],"pt53":[{"pt":[{"c":"ت","l":0},{"c":"ا","l":2}]},{"pt":[{"c":"ا,ن,ت,ي","l":0},{"c":"ت","l":2}],"mPt":[{"c":"ا","l":0},{"c":"ف","l":1,"m":1},{"c":"ت","l":2},{"c":"ع","l":3,"m":3},{"c":"ا","l":4},{"c":"ل","l":5,"m":4}]},{"pt":[{"c":"ا","l":0},{"c":"ا","l":2}],"mPt":[{"c":"ا","l":0},{"c":"ف","l":1,"m":1},{"c":"ع","l":2,"m":3},{"c":"ل","l":3,"m":4},{"c":"ا","l":4},{"c":"ل","l":5,"m":4}]},{"pt":[{"c":"ا","l":0},{"c":"ا","l":3}],"mPt":[{"c":"ف","l":0,"m":1},{"c":"ع","l":1,"m":2},{"c":"ل","l":2,"m":4}]},{"pt":[{"c":"ا","l":3},{"c":"ن","l":4}]},{"pt":[{"c":"ت","l":0},{"c":"ي","l":3}]},{"pt":[{"c":"م","l":0},{"c":"و","l":3}]},{"pt":[{"c":"ا","l":1},{"c":"و","l":3}]},{"pt":[{"c":"و","l":1},{"c":"ا","l":2}]},{"pt":[{"c":"م","l":0},{"c":"ا","l":3}]},{"pt":[{"c":"م","l":0},{"c":"ي","l":3}]},{"pt":[{"c":"ا","l":2},{"c":"ن","l":3}]},{"pt":[{"c":"م","l":0},{"c":"ن","l":1}],"mPt":[{"c":"ا","l":0},{"c":"ن","l":1},{"c":"ف","l":2,"m":2},{"c":"ع","l":3,"m":3},{"c":"ا","l":4},{"c":"ل","l":5,"m":4}]},{"pt":[{"c":"م","l":0},{"c":"ت","l":2}],"mPt":[{"c":"ا","l":0},{"c":"ف","l":1,"m":1},{"c":"ت","l":2},{"c":"ع","l":3,"m":3},{"c":"ا","l":4},{"c":"ل","l":5,"m":4}]},{"pt":[{"c":"م","l":0},{"c":"ا","l":2}]},{"pt":[{"c":"م","l":1},{"c":"ا","l":3}]},{"pt":[{"c":"ي,ت,ا,ن","l":0},{"c":"ت","l":1}],"mPt":[{"c":"ف","l":0,"m":2},{"c":"ع","l":1,"m":3},{"c":"ا","l":2},{"c":"ل","l":3,"m":4}]},{"pt":[{"c":"ت,ي,ا,ن","l":0},{"c":"ت","l":2}],"mPt":[{"c":"ا","l":0},{"c":"ف","l":1,"m":1},{"c":"ت","l":2},{"c":"ع","l":3,"m":3},{"c":"ا","l":4},{"c":"ل","l":5,"m":4}]},{"pt":[{"c":"ا","l":2},{"c":"ي","l":3}]},{"pt":[{"c":"ا,ي,ت,ن","l":0},{"c":"ن","l":1}],"mPt":[{"c":"ا","l":0},{"c":"ن","l":1},{"c":"ف","l":2,"m":2},{"c":"ع","l":3,"m":3},{"c":"ا","l":4},{"c":"ل","l":5,"m":4}]},{"pt":[{"c":"ا","l":3},{"c":"ء","l":4}]}],"pt63":[{"pt":[{"c":"ا","l":0},{"c":"ت","l":2},{"c":"ا","l":4}]},{"pt":[{"c":"ا,ت,ن,ي","l":0},{"c":"س","l":1},{"c":"ت","l":2}],"mPt":[{"c":"ا","l":0},{"c":"س","l":1},{"c":"ت","l":2},{"c":"ف","l":3,"m":3},{"c":"ع","l":4,"m":4},{"c":"ا","l":5},{"c":"ل","l":6,"m":5}]},{"pt":[{"c":"ا,ن,ت,ي","l":0},{"c":"و","l":3}]},{"pt":[{"c":"م","l":0},{"c":"س","l":1},{"c":"ت","l":2}],"mPt":[{"c":"ا","l":0},{"c":"س","l":1},{"c":"ت","l":2},{"c":"ف","l":3,"m":3},{"c":"ع","l":4,"m":4},{"c":"ا","l":5},{"c":"ل","l":6,"m":5}]},{"pt":[{"c":"ي","l":1},{"c":"ي","l":3},{"c":"ا","l":4},{"c":"ء","l":5}]},{"pt":[{"c":"ا","l":0},{"c":"ن","l":1},{"c":"ا","l":4}]}],"pt54":[{"pt":[{"c":"ت","l":0}]},{"pt":[{"c":"ا,ي,ت,ن","l":0}],"mPt":[{"c":"ا","l":0},{"c":"ف","l":1,"m":1},{"c":"ع","l":2,"m":2},{"c":"ل","l":3,"m":3},{"c":"ر","l":4,"m":4},{"c":"ا","l":5},{"c":"ر","l":6,"m":4}]},{"pt":[{"c":"م","l":0}],"mPt":[{"c":"ا","l":0},{"c":"ف","l":1,"m":1},{"c":"ع","l":2,"m":2},{"c":"ل","l":3,"m":3},{"c":"ر","l":4,"m":4},{"c":"ا","l":5},{"c":"ر","l":6,"m":4}]},{"pt":[{"c":"ا","l":2}]},{"pt":[{"c":"ا","l":0},{"c":"ن","l":2}]}],"pt64":[{"pt":[{"c":"ا","l":0},{"c":"ا","l":4}]},{"pt":[{"c":"م","l":0},{"c":"ت","l":1}]}],"pt73":[{"pt":[{"c":"ا","l":0},{"c":"س","l":1},{"c":"ت","l":2},{"c":"ا","l":5}]}],"pt75":[{"pt":[{"c":"ا","l":0},{"c":"ا","l":5}]}]}'),e.execArray=["cleanWord","removeDiacritics","cleanAlef","removeStopWords","normalizeHamzaAndAlef","removeStartWaw","removePre432","removeEndTaa","wordCheck"],e.stem=function(){var r=0;for(e.result=!1,e.preRemoved=!1,e.sufRemoved=!1;r=0)return!0},e.normalizeHamzaAndAlef=function(){return e.word=e.word.replace("ؤ","ء"),e.word=e.word.replace("ئ","ء"),e.word=e.word.replace(/([\u0627])\1+/gi,"ا"),!1},e.removeEndTaa=function(){return!(e.word.length>2)||(e.word=e.word.replace(/[\u0627]$/,""),e.word=e.word.replace("ة",""),!1)},e.removeStartWaw=function(){return e.word.length>3&&"و"==e.word[0]&&"و"==e.word[1]&&(e.word=e.word.slice(1)),!1},e.removePre432=function(){var r=e.word;if(e.word.length>=7){var t=new RegExp("^("+e.pre.pre4.split(" ").join("|")+")");e.word=e.word.replace(t,"")}if(e.word==r&&e.word.length>=6){var c=new RegExp("^("+e.pre.pre3.split(" ").join("|")+")");e.word=e.word.replace(c,"")}if(e.word==r&&e.word.length>=5){var l=new RegExp("^("+e.pre.pre2.split(" ").join("|")+")");e.word=e.word.replace(l,"")}return r!=e.word&&(e.preRemoved=!0),!1},e.patternCheck=function(r){for(var t=0;t3){var t=new RegExp("^("+e.pre.pre1.split(" ").join("|")+")");e.word=e.word.replace(t,"")}return r!=e.word&&(e.preRemoved=!0),!1},e.removeSuf1=function(){var r=e.word;if(0==e.sufRemoved&&e.word.length>3){var t=new RegExp("("+e.suf.suf1.split(" ").join("|")+")$");e.word=e.word.replace(t,"")}return r!=e.word&&(e.sufRemoved=!0),!1},e.removeSuf432=function(){var r=e.word;if(e.word.length>=6){var t=new RegExp("("+e.suf.suf4.split(" ").join("|")+")$");e.word=e.word.replace(t,"")}if(e.word==r&&e.word.length>=5){var c=new RegExp("("+e.suf.suf3.split(" ").join("|")+")$");e.word=e.word.replace(c,"")}if(e.word==r&&e.word.length>=4){var l=new RegExp("("+e.suf.suf2.split(" ").join("|")+")$");e.word=e.word.replace(l,"")}return r!=e.word&&(e.sufRemoved=!0),!1},e.wordCheck=function(){for(var r=(e.word,[e.removeSuf432,e.removeSuf1,e.removePre1]),t=0,c=!1;e.word.length>=7&&!e.result&&t=f.limit)return;f.cursor++}for(;!f.out_grouping(w,97,248);){if(f.cursor>=f.limit)return;f.cursor++}d=f.cursor,d=d&&(r=f.limit_backward,f.limit_backward=d,f.ket=f.cursor,e=f.find_among_b(c,32),f.limit_backward=r,e))switch(f.bra=f.cursor,e){case 1:f.slice_del();break;case 2:f.in_grouping_b(p,97,229)&&f.slice_del()}}function t(){var e,r=f.limit-f.cursor;f.cursor>=d&&(e=f.limit_backward,f.limit_backward=d,f.ket=f.cursor,f.find_among_b(l,4)?(f.bra=f.cursor,f.limit_backward=e,f.cursor=f.limit-r,f.cursor>f.limit_backward&&(f.cursor--,f.bra=f.cursor,f.slice_del())):f.limit_backward=e)}function s(){var e,r,i,n=f.limit-f.cursor;if(f.ket=f.cursor,f.eq_s_b(2,"st")&&(f.bra=f.cursor,f.eq_s_b(2,"ig")&&f.slice_del()),f.cursor=f.limit-n,f.cursor>=d&&(r=f.limit_backward,f.limit_backward=d,f.ket=f.cursor,e=f.find_among_b(m,5),f.limit_backward=r,e))switch(f.bra=f.cursor,e){case 1:f.slice_del(),i=f.limit-f.cursor,t(),f.cursor=f.limit-i;break;case 2:f.slice_from("løs")}}function o(){var e;f.cursor>=d&&(e=f.limit_backward,f.limit_backward=d,f.ket=f.cursor,f.out_grouping_b(w,97,248)?(f.bra=f.cursor,u=f.slice_to(u),f.limit_backward=e,f.eq_v_b(u)&&f.slice_del()):f.limit_backward=e)}var a,d,u,c=[new r("hed",-1,1),new r("ethed",0,1),new r("ered",-1,1),new r("e",-1,1),new r("erede",3,1),new r("ende",3,1),new r("erende",5,1),new r("ene",3,1),new r("erne",3,1),new r("ere",3,1),new r("en",-1,1),new r("heden",10,1),new r("eren",10,1),new r("er",-1,1),new r("heder",13,1),new r("erer",13,1),new r("s",-1,2),new r("heds",16,1),new r("es",16,1),new r("endes",18,1),new r("erendes",19,1),new r("enes",18,1),new r("ernes",18,1),new r("eres",18,1),new r("ens",16,1),new r("hedens",24,1),new r("erens",24,1),new r("ers",16,1),new r("ets",16,1),new r("erets",28,1),new r("et",-1,1),new r("eret",30,1)],l=[new r("gd",-1,-1),new r("dt",-1,-1),new r("gt",-1,-1),new r("kt",-1,-1)],m=[new r("ig",-1,1),new r("lig",0,1),new r("elig",1,1),new r("els",-1,1),new r("løst",-1,2)],w=[17,65,16,1,0,0,0,0,0,0,0,0,0,0,0,0,48,0,128],p=[239,254,42,3,0,0,0,0,0,0,0,0,0,0,0,0,16],f=new i;this.setCurrent=function(e){f.setCurrent(e)},this.getCurrent=function(){return f.getCurrent()},this.stem=function(){var r=f.cursor;return e(),f.limit_backward=r,f.cursor=f.limit,n(),f.cursor=f.limit,t(),f.cursor=f.limit,s(),f.cursor=f.limit,o(),!0}};return function(e){return"function"==typeof e.update?e.update(function(e){return n.setCurrent(e),n.stem(),n.getCurrent()}):(n.setCurrent(e),n.stem(),n.getCurrent())}}(),e.Pipeline.registerFunction(e.da.stemmer,"stemmer-da"),e.da.stopWordFilter=e.generateStopWordFilter("ad af alle alt anden at blev blive bliver da de dem den denne der deres det dette dig din disse dog du efter eller en end er et for fra ham han hans har havde have hende hendes her hos hun hvad hvis hvor i ikke ind jeg jer jo kunne man mange med meget men mig min mine mit mod ned noget nogle nu når og også om op os over på selv sig sin sine sit skal skulle som sådan thi til ud under var vi vil ville vor være været".split(" ")),e.Pipeline.registerFunction(e.da.stopWordFilter,"stopWordFilter-da")}}); \ No newline at end of file diff --git a/en/2021.7/assets/javascripts/lunr/min/lunr.de.min.js b/en/2021.7/assets/javascripts/lunr/min/lunr.de.min.js new file mode 100644 index 000000000..f3b5c108c --- /dev/null +++ b/en/2021.7/assets/javascripts/lunr/min/lunr.de.min.js @@ -0,0 +1,18 @@ +/*! + * Lunr languages, `German` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +!function(e,r){"function"==typeof define&&define.amd?define(r):"object"==typeof exports?module.exports=r():r()(e.lunr)}(this,function(){return function(e){if(void 0===e)throw new Error("Lunr is not present. Please include / require Lunr before this script.");if(void 0===e.stemmerSupport)throw new Error("Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.");e.de=function(){this.pipeline.reset(),this.pipeline.add(e.de.trimmer,e.de.stopWordFilter,e.de.stemmer),this.searchPipeline&&(this.searchPipeline.reset(),this.searchPipeline.add(e.de.stemmer))},e.de.wordCharacters="A-Za-zªºÀ-ÖØ-öø-ʸˠ-ˤᴀ-ᴥᴬ-ᵜᵢ-ᵥᵫ-ᵷᵹ-ᶾḀ-ỿⁱⁿₐ-ₜKÅℲⅎⅠ-ↈⱠ-ⱿꜢ-ꞇꞋ-ꞭꞰ-ꞷꟷ-ꟿꬰ-ꭚꭜ-ꭤff-stA-Za-z",e.de.trimmer=e.trimmerSupport.generateTrimmer(e.de.wordCharacters),e.Pipeline.registerFunction(e.de.trimmer,"trimmer-de"),e.de.stemmer=function(){var r=e.stemmerSupport.Among,n=e.stemmerSupport.SnowballProgram,i=new function(){function e(e,r,n){return!(!v.eq_s(1,e)||(v.ket=v.cursor,!v.in_grouping(p,97,252)))&&(v.slice_from(r),v.cursor=n,!0)}function i(){for(var r,n,i,s,t=v.cursor;;)if(r=v.cursor,v.bra=r,v.eq_s(1,"ß"))v.ket=v.cursor,v.slice_from("ss");else{if(r>=v.limit)break;v.cursor=r+1}for(v.cursor=t;;)for(n=v.cursor;;){if(i=v.cursor,v.in_grouping(p,97,252)){if(s=v.cursor,v.bra=s,e("u","U",i))break;if(v.cursor=s,e("y","Y",i))break}if(i>=v.limit)return void(v.cursor=n);v.cursor=i+1}}function s(){for(;!v.in_grouping(p,97,252);){if(v.cursor>=v.limit)return!0;v.cursor++}for(;!v.out_grouping(p,97,252);){if(v.cursor>=v.limit)return!0;v.cursor++}return!1}function t(){m=v.limit,l=m;var e=v.cursor+3;0<=e&&e<=v.limit&&(d=e,s()||(m=v.cursor,m=v.limit)return;v.cursor++}}}function c(){return m<=v.cursor}function u(){return l<=v.cursor}function a(){var e,r,n,i,s=v.limit-v.cursor;if(v.ket=v.cursor,(e=v.find_among_b(w,7))&&(v.bra=v.cursor,c()))switch(e){case 1:v.slice_del();break;case 2:v.slice_del(),v.ket=v.cursor,v.eq_s_b(1,"s")&&(v.bra=v.cursor,v.eq_s_b(3,"nis")&&v.slice_del());break;case 3:v.in_grouping_b(g,98,116)&&v.slice_del()}if(v.cursor=v.limit-s,v.ket=v.cursor,(e=v.find_among_b(f,4))&&(v.bra=v.cursor,c()))switch(e){case 1:v.slice_del();break;case 2:if(v.in_grouping_b(k,98,116)){var t=v.cursor-3;v.limit_backward<=t&&t<=v.limit&&(v.cursor=t,v.slice_del())}}if(v.cursor=v.limit-s,v.ket=v.cursor,(e=v.find_among_b(_,8))&&(v.bra=v.cursor,u()))switch(e){case 1:v.slice_del(),v.ket=v.cursor,v.eq_s_b(2,"ig")&&(v.bra=v.cursor,r=v.limit-v.cursor,v.eq_s_b(1,"e")||(v.cursor=v.limit-r,u()&&v.slice_del()));break;case 2:n=v.limit-v.cursor,v.eq_s_b(1,"e")||(v.cursor=v.limit-n,v.slice_del());break;case 3:if(v.slice_del(),v.ket=v.cursor,i=v.limit-v.cursor,!v.eq_s_b(2,"er")&&(v.cursor=v.limit-i,!v.eq_s_b(2,"en")))break;v.bra=v.cursor,c()&&v.slice_del();break;case 4:v.slice_del(),v.ket=v.cursor,e=v.find_among_b(b,2),e&&(v.bra=v.cursor,u()&&1==e&&v.slice_del())}}var d,l,m,h=[new r("",-1,6),new r("U",0,2),new r("Y",0,1),new r("ä",0,3),new r("ö",0,4),new r("ü",0,5)],w=[new r("e",-1,2),new r("em",-1,1),new r("en",-1,2),new r("ern",-1,1),new r("er",-1,1),new r("s",-1,3),new r("es",5,2)],f=[new r("en",-1,1),new r("er",-1,1),new r("st",-1,2),new r("est",2,1)],b=[new r("ig",-1,1),new r("lich",-1,1)],_=[new r("end",-1,1),new r("ig",-1,2),new r("ung",-1,1),new r("lich",-1,3),new r("isch",-1,2),new r("ik",-1,2),new r("heit",-1,3),new r("keit",-1,4)],p=[17,65,16,1,0,0,0,0,0,0,0,0,0,0,0,0,8,0,32,8],g=[117,30,5],k=[117,30,4],v=new n;this.setCurrent=function(e){v.setCurrent(e)},this.getCurrent=function(){return v.getCurrent()},this.stem=function(){var e=v.cursor;return i(),v.cursor=e,t(),v.limit_backward=e,v.cursor=v.limit,a(),v.cursor=v.limit_backward,o(),!0}};return function(e){return"function"==typeof e.update?e.update(function(e){return i.setCurrent(e),i.stem(),i.getCurrent()}):(i.setCurrent(e),i.stem(),i.getCurrent())}}(),e.Pipeline.registerFunction(e.de.stemmer,"stemmer-de"),e.de.stopWordFilter=e.generateStopWordFilter("aber alle allem allen aller alles als also am an ander andere anderem anderen anderer anderes anderm andern anderr anders auch auf aus bei bin bis bist da damit dann das dasselbe dazu daß dein deine deinem deinen deiner deines dem demselben den denn denselben der derer derselbe derselben des desselben dessen dich die dies diese dieselbe dieselben diesem diesen dieser dieses dir doch dort du durch ein eine einem einen einer eines einig einige einigem einigen einiger einiges einmal er es etwas euch euer eure eurem euren eurer eures für gegen gewesen hab habe haben hat hatte hatten hier hin hinter ich ihm ihn ihnen ihr ihre ihrem ihren ihrer ihres im in indem ins ist jede jedem jeden jeder jedes jene jenem jenen jener jenes jetzt kann kein keine keinem keinen keiner keines können könnte machen man manche manchem manchen mancher manches mein meine meinem meinen meiner meines mich mir mit muss musste nach nicht nichts noch nun nur ob oder ohne sehr sein seine seinem seinen seiner seines selbst sich sie sind so solche solchem solchen solcher solches soll sollte sondern sonst um und uns unse unsem unsen unser unses unter viel vom von vor war waren warst was weg weil weiter welche welchem welchen welcher welches wenn werde werden wie wieder will wir wird wirst wo wollen wollte während würde würden zu zum zur zwar zwischen über".split(" ")),e.Pipeline.registerFunction(e.de.stopWordFilter,"stopWordFilter-de")}}); \ No newline at end of file diff --git a/en/2021.7/assets/javascripts/lunr/min/lunr.du.min.js b/en/2021.7/assets/javascripts/lunr/min/lunr.du.min.js new file mode 100644 index 000000000..49a0f3f0a --- /dev/null +++ b/en/2021.7/assets/javascripts/lunr/min/lunr.du.min.js @@ -0,0 +1,18 @@ +/*! + * Lunr languages, `Dutch` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +!function(e,r){"function"==typeof define&&define.amd?define(r):"object"==typeof exports?module.exports=r():r()(e.lunr)}(this,function(){return function(e){if(void 0===e)throw new Error("Lunr is not present. Please include / require Lunr before this script.");if(void 0===e.stemmerSupport)throw new Error("Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.");console.warn('[Lunr Languages] Please use the "nl" instead of the "du". The "nl" code is the standard code for Dutch language, and "du" will be removed in the next major versions.'),e.du=function(){this.pipeline.reset(),this.pipeline.add(e.du.trimmer,e.du.stopWordFilter,e.du.stemmer),this.searchPipeline&&(this.searchPipeline.reset(),this.searchPipeline.add(e.du.stemmer))},e.du.wordCharacters="A-Za-zªºÀ-ÖØ-öø-ʸˠ-ˤᴀ-ᴥᴬ-ᵜᵢ-ᵥᵫ-ᵷᵹ-ᶾḀ-ỿⁱⁿₐ-ₜKÅℲⅎⅠ-ↈⱠ-ⱿꜢ-ꞇꞋ-ꞭꞰ-ꞷꟷ-ꟿꬰ-ꭚꭜ-ꭤff-stA-Za-z",e.du.trimmer=e.trimmerSupport.generateTrimmer(e.du.wordCharacters),e.Pipeline.registerFunction(e.du.trimmer,"trimmer-du"),e.du.stemmer=function(){var r=e.stemmerSupport.Among,i=e.stemmerSupport.SnowballProgram,n=new function(){function e(){for(var e,r,i,o=C.cursor;;){if(C.bra=C.cursor,e=C.find_among(b,11))switch(C.ket=C.cursor,e){case 1:C.slice_from("a");continue;case 2:C.slice_from("e");continue;case 3:C.slice_from("i");continue;case 4:C.slice_from("o");continue;case 5:C.slice_from("u");continue;case 6:if(C.cursor>=C.limit)break;C.cursor++;continue}break}for(C.cursor=o,C.bra=o,C.eq_s(1,"y")?(C.ket=C.cursor,C.slice_from("Y")):C.cursor=o;;)if(r=C.cursor,C.in_grouping(q,97,232)){if(i=C.cursor,C.bra=i,C.eq_s(1,"i"))C.ket=C.cursor,C.in_grouping(q,97,232)&&(C.slice_from("I"),C.cursor=r);else if(C.cursor=i,C.eq_s(1,"y"))C.ket=C.cursor,C.slice_from("Y"),C.cursor=r;else if(n(r))break}else if(n(r))break}function n(e){return C.cursor=e,e>=C.limit||(C.cursor++,!1)}function o(){_=C.limit,f=_,t()||(_=C.cursor,_<3&&(_=3),t()||(f=C.cursor))}function t(){for(;!C.in_grouping(q,97,232);){if(C.cursor>=C.limit)return!0;C.cursor++}for(;!C.out_grouping(q,97,232);){if(C.cursor>=C.limit)return!0;C.cursor++}return!1}function s(){for(var e;;)if(C.bra=C.cursor,e=C.find_among(p,3))switch(C.ket=C.cursor,e){case 1:C.slice_from("y");break;case 2:C.slice_from("i");break;case 3:if(C.cursor>=C.limit)return;C.cursor++}}function u(){return _<=C.cursor}function c(){return f<=C.cursor}function a(){var e=C.limit-C.cursor;C.find_among_b(g,3)&&(C.cursor=C.limit-e,C.ket=C.cursor,C.cursor>C.limit_backward&&(C.cursor--,C.bra=C.cursor,C.slice_del()))}function l(){var e;w=!1,C.ket=C.cursor,C.eq_s_b(1,"e")&&(C.bra=C.cursor,u()&&(e=C.limit-C.cursor,C.out_grouping_b(q,97,232)&&(C.cursor=C.limit-e,C.slice_del(),w=!0,a())))}function m(){var e;u()&&(e=C.limit-C.cursor,C.out_grouping_b(q,97,232)&&(C.cursor=C.limit-e,C.eq_s_b(3,"gem")||(C.cursor=C.limit-e,C.slice_del(),a())))}function d(){var e,r,i,n,o,t,s=C.limit-C.cursor;if(C.ket=C.cursor,e=C.find_among_b(h,5))switch(C.bra=C.cursor,e){case 1:u()&&C.slice_from("heid");break;case 2:m();break;case 3:u()&&C.out_grouping_b(z,97,232)&&C.slice_del()}if(C.cursor=C.limit-s,l(),C.cursor=C.limit-s,C.ket=C.cursor,C.eq_s_b(4,"heid")&&(C.bra=C.cursor,c()&&(r=C.limit-C.cursor,C.eq_s_b(1,"c")||(C.cursor=C.limit-r,C.slice_del(),C.ket=C.cursor,C.eq_s_b(2,"en")&&(C.bra=C.cursor,m())))),C.cursor=C.limit-s,C.ket=C.cursor,e=C.find_among_b(k,6))switch(C.bra=C.cursor,e){case 1:if(c()){if(C.slice_del(),i=C.limit-C.cursor,C.ket=C.cursor,C.eq_s_b(2,"ig")&&(C.bra=C.cursor,c()&&(n=C.limit-C.cursor,!C.eq_s_b(1,"e")))){C.cursor=C.limit-n,C.slice_del();break}C.cursor=C.limit-i,a()}break;case 2:c()&&(o=C.limit-C.cursor,C.eq_s_b(1,"e")||(C.cursor=C.limit-o,C.slice_del()));break;case 3:c()&&(C.slice_del(),l());break;case 4:c()&&C.slice_del();break;case 5:c()&&w&&C.slice_del()}C.cursor=C.limit-s,C.out_grouping_b(j,73,232)&&(t=C.limit-C.cursor,C.find_among_b(v,4)&&C.out_grouping_b(q,97,232)&&(C.cursor=C.limit-t,C.ket=C.cursor,C.cursor>C.limit_backward&&(C.cursor--,C.bra=C.cursor,C.slice_del())))}var f,_,w,b=[new r("",-1,6),new r("á",0,1),new r("ä",0,1),new r("é",0,2),new r("ë",0,2),new r("í",0,3),new r("ï",0,3),new r("ó",0,4),new r("ö",0,4),new r("ú",0,5),new r("ü",0,5)],p=[new r("",-1,3),new r("I",0,2),new r("Y",0,1)],g=[new r("dd",-1,-1),new r("kk",-1,-1),new r("tt",-1,-1)],h=[new r("ene",-1,2),new r("se",-1,3),new r("en",-1,2),new r("heden",2,1),new r("s",-1,3)],k=[new r("end",-1,1),new r("ig",-1,2),new r("ing",-1,1),new r("lijk",-1,3),new r("baar",-1,4),new r("bar",-1,5)],v=[new r("aa",-1,-1),new r("ee",-1,-1),new r("oo",-1,-1),new r("uu",-1,-1)],q=[17,65,16,1,0,0,0,0,0,0,0,0,0,0,0,0,128],j=[1,0,0,17,65,16,1,0,0,0,0,0,0,0,0,0,0,0,0,128],z=[17,67,16,1,0,0,0,0,0,0,0,0,0,0,0,0,128],C=new i;this.setCurrent=function(e){C.setCurrent(e)},this.getCurrent=function(){return C.getCurrent()},this.stem=function(){var r=C.cursor;return e(),C.cursor=r,o(),C.limit_backward=r,C.cursor=C.limit,d(),C.cursor=C.limit_backward,s(),!0}};return function(e){return"function"==typeof e.update?e.update(function(e){return n.setCurrent(e),n.stem(),n.getCurrent()}):(n.setCurrent(e),n.stem(),n.getCurrent())}}(),e.Pipeline.registerFunction(e.du.stemmer,"stemmer-du"),e.du.stopWordFilter=e.generateStopWordFilter(" aan al alles als altijd andere ben bij daar dan dat de der deze die dit doch doen door dus een eens en er ge geen geweest haar had heb hebben heeft hem het hier hij hoe hun iemand iets ik in is ja je kan kon kunnen maar me meer men met mij mijn moet na naar niet niets nog nu of om omdat onder ons ook op over reeds te tegen toch toen tot u uit uw van veel voor want waren was wat werd wezen wie wil worden wordt zal ze zelf zich zij zijn zo zonder zou".split(" ")),e.Pipeline.registerFunction(e.du.stopWordFilter,"stopWordFilter-du")}}); \ No newline at end of file diff --git a/en/2021.7/assets/javascripts/lunr/min/lunr.es.min.js b/en/2021.7/assets/javascripts/lunr/min/lunr.es.min.js new file mode 100644 index 000000000..2989d3426 --- /dev/null +++ b/en/2021.7/assets/javascripts/lunr/min/lunr.es.min.js @@ -0,0 +1,18 @@ +/*! + * Lunr languages, `Spanish` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +!function(e,s){"function"==typeof define&&define.amd?define(s):"object"==typeof exports?module.exports=s():s()(e.lunr)}(this,function(){return function(e){if(void 0===e)throw new Error("Lunr is not present. Please include / require Lunr before this script.");if(void 0===e.stemmerSupport)throw new Error("Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.");e.es=function(){this.pipeline.reset(),this.pipeline.add(e.es.trimmer,e.es.stopWordFilter,e.es.stemmer),this.searchPipeline&&(this.searchPipeline.reset(),this.searchPipeline.add(e.es.stemmer))},e.es.wordCharacters="A-Za-zªºÀ-ÖØ-öø-ʸˠ-ˤᴀ-ᴥᴬ-ᵜᵢ-ᵥᵫ-ᵷᵹ-ᶾḀ-ỿⁱⁿₐ-ₜKÅℲⅎⅠ-ↈⱠ-ⱿꜢ-ꞇꞋ-ꞭꞰ-ꞷꟷ-ꟿꬰ-ꭚꭜ-ꭤff-stA-Za-z",e.es.trimmer=e.trimmerSupport.generateTrimmer(e.es.wordCharacters),e.Pipeline.registerFunction(e.es.trimmer,"trimmer-es"),e.es.stemmer=function(){var s=e.stemmerSupport.Among,r=e.stemmerSupport.SnowballProgram,n=new function(){function e(){if(A.out_grouping(x,97,252)){for(;!A.in_grouping(x,97,252);){if(A.cursor>=A.limit)return!0;A.cursor++}return!1}return!0}function n(){if(A.in_grouping(x,97,252)){var s=A.cursor;if(e()){if(A.cursor=s,!A.in_grouping(x,97,252))return!0;for(;!A.out_grouping(x,97,252);){if(A.cursor>=A.limit)return!0;A.cursor++}}return!1}return!0}function i(){var s,r=A.cursor;if(n()){if(A.cursor=r,!A.out_grouping(x,97,252))return;if(s=A.cursor,e()){if(A.cursor=s,!A.in_grouping(x,97,252)||A.cursor>=A.limit)return;A.cursor++}}g=A.cursor}function a(){for(;!A.in_grouping(x,97,252);){if(A.cursor>=A.limit)return!1;A.cursor++}for(;!A.out_grouping(x,97,252);){if(A.cursor>=A.limit)return!1;A.cursor++}return!0}function t(){var e=A.cursor;g=A.limit,p=g,v=g,i(),A.cursor=e,a()&&(p=A.cursor,a()&&(v=A.cursor))}function o(){for(var e;;){if(A.bra=A.cursor,e=A.find_among(k,6))switch(A.ket=A.cursor,e){case 1:A.slice_from("a");continue;case 2:A.slice_from("e");continue;case 3:A.slice_from("i");continue;case 4:A.slice_from("o");continue;case 5:A.slice_from("u");continue;case 6:if(A.cursor>=A.limit)break;A.cursor++;continue}break}}function u(){return g<=A.cursor}function w(){return p<=A.cursor}function c(){return v<=A.cursor}function m(){var e;if(A.ket=A.cursor,A.find_among_b(y,13)&&(A.bra=A.cursor,(e=A.find_among_b(q,11))&&u()))switch(e){case 1:A.bra=A.cursor,A.slice_from("iendo");break;case 2:A.bra=A.cursor,A.slice_from("ando");break;case 3:A.bra=A.cursor,A.slice_from("ar");break;case 4:A.bra=A.cursor,A.slice_from("er");break;case 5:A.bra=A.cursor,A.slice_from("ir");break;case 6:A.slice_del();break;case 7:A.eq_s_b(1,"u")&&A.slice_del()}}function l(e,s){if(!c())return!0;A.slice_del(),A.ket=A.cursor;var r=A.find_among_b(e,s);return r&&(A.bra=A.cursor,1==r&&c()&&A.slice_del()),!1}function d(e){return!c()||(A.slice_del(),A.ket=A.cursor,A.eq_s_b(2,e)&&(A.bra=A.cursor,c()&&A.slice_del()),!1)}function b(){var e;if(A.ket=A.cursor,e=A.find_among_b(S,46)){switch(A.bra=A.cursor,e){case 1:if(!c())return!1;A.slice_del();break;case 2:if(d("ic"))return!1;break;case 3:if(!c())return!1;A.slice_from("log");break;case 4:if(!c())return!1;A.slice_from("u");break;case 5:if(!c())return!1;A.slice_from("ente");break;case 6:if(!w())return!1;A.slice_del(),A.ket=A.cursor,e=A.find_among_b(C,4),e&&(A.bra=A.cursor,c()&&(A.slice_del(),1==e&&(A.ket=A.cursor,A.eq_s_b(2,"at")&&(A.bra=A.cursor,c()&&A.slice_del()))));break;case 7:if(l(P,3))return!1;break;case 8:if(l(F,3))return!1;break;case 9:if(d("at"))return!1}return!0}return!1}function f(){var e,s;if(A.cursor>=g&&(s=A.limit_backward,A.limit_backward=g,A.ket=A.cursor,e=A.find_among_b(W,12),A.limit_backward=s,e)){if(A.bra=A.cursor,1==e){if(!A.eq_s_b(1,"u"))return!1;A.slice_del()}return!0}return!1}function _(){var e,s,r,n;if(A.cursor>=g&&(s=A.limit_backward,A.limit_backward=g,A.ket=A.cursor,e=A.find_among_b(L,96),A.limit_backward=s,e))switch(A.bra=A.cursor,e){case 1:r=A.limit-A.cursor,A.eq_s_b(1,"u")?(n=A.limit-A.cursor,A.eq_s_b(1,"g")?A.cursor=A.limit-n:A.cursor=A.limit-r):A.cursor=A.limit-r,A.bra=A.cursor;case 2:A.slice_del()}}function h(){var e,s;if(A.ket=A.cursor,e=A.find_among_b(z,8))switch(A.bra=A.cursor,e){case 1:u()&&A.slice_del();break;case 2:u()&&(A.slice_del(),A.ket=A.cursor,A.eq_s_b(1,"u")&&(A.bra=A.cursor,s=A.limit-A.cursor,A.eq_s_b(1,"g")&&(A.cursor=A.limit-s,u()&&A.slice_del())))}}var v,p,g,k=[new s("",-1,6),new s("á",0,1),new s("é",0,2),new s("í",0,3),new s("ó",0,4),new s("ú",0,5)],y=[new s("la",-1,-1),new s("sela",0,-1),new s("le",-1,-1),new s("me",-1,-1),new s("se",-1,-1),new s("lo",-1,-1),new s("selo",5,-1),new s("las",-1,-1),new s("selas",7,-1),new s("les",-1,-1),new s("los",-1,-1),new s("selos",10,-1),new s("nos",-1,-1)],q=[new s("ando",-1,6),new s("iendo",-1,6),new s("yendo",-1,7),new s("ándo",-1,2),new s("iéndo",-1,1),new s("ar",-1,6),new s("er",-1,6),new s("ir",-1,6),new s("ár",-1,3),new s("ér",-1,4),new s("ír",-1,5)],C=[new s("ic",-1,-1),new s("ad",-1,-1),new s("os",-1,-1),new s("iv",-1,1)],P=[new s("able",-1,1),new s("ible",-1,1),new s("ante",-1,1)],F=[new s("ic",-1,1),new s("abil",-1,1),new s("iv",-1,1)],S=[new s("ica",-1,1),new s("ancia",-1,2),new s("encia",-1,5),new s("adora",-1,2),new s("osa",-1,1),new s("ista",-1,1),new s("iva",-1,9),new s("anza",-1,1),new s("logía",-1,3),new s("idad",-1,8),new s("able",-1,1),new s("ible",-1,1),new s("ante",-1,2),new s("mente",-1,7),new s("amente",13,6),new s("ación",-1,2),new s("ución",-1,4),new s("ico",-1,1),new s("ismo",-1,1),new s("oso",-1,1),new s("amiento",-1,1),new s("imiento",-1,1),new s("ivo",-1,9),new s("ador",-1,2),new s("icas",-1,1),new s("ancias",-1,2),new s("encias",-1,5),new s("adoras",-1,2),new s("osas",-1,1),new s("istas",-1,1),new s("ivas",-1,9),new s("anzas",-1,1),new s("logías",-1,3),new s("idades",-1,8),new s("ables",-1,1),new s("ibles",-1,1),new s("aciones",-1,2),new s("uciones",-1,4),new s("adores",-1,2),new s("antes",-1,2),new s("icos",-1,1),new s("ismos",-1,1),new s("osos",-1,1),new s("amientos",-1,1),new s("imientos",-1,1),new s("ivos",-1,9)],W=[new s("ya",-1,1),new s("ye",-1,1),new s("yan",-1,1),new s("yen",-1,1),new s("yeron",-1,1),new s("yendo",-1,1),new s("yo",-1,1),new s("yas",-1,1),new s("yes",-1,1),new s("yais",-1,1),new s("yamos",-1,1),new s("yó",-1,1)],L=[new s("aba",-1,2),new s("ada",-1,2),new s("ida",-1,2),new s("ara",-1,2),new s("iera",-1,2),new s("ía",-1,2),new s("aría",5,2),new s("ería",5,2),new s("iría",5,2),new s("ad",-1,2),new s("ed",-1,2),new s("id",-1,2),new s("ase",-1,2),new s("iese",-1,2),new s("aste",-1,2),new s("iste",-1,2),new s("an",-1,2),new s("aban",16,2),new s("aran",16,2),new s("ieran",16,2),new s("ían",16,2),new s("arían",20,2),new s("erían",20,2),new s("irían",20,2),new s("en",-1,1),new s("asen",24,2),new s("iesen",24,2),new s("aron",-1,2),new s("ieron",-1,2),new s("arán",-1,2),new s("erán",-1,2),new s("irán",-1,2),new s("ado",-1,2),new s("ido",-1,2),new s("ando",-1,2),new s("iendo",-1,2),new s("ar",-1,2),new s("er",-1,2),new s("ir",-1,2),new s("as",-1,2),new s("abas",39,2),new s("adas",39,2),new s("idas",39,2),new s("aras",39,2),new s("ieras",39,2),new s("ías",39,2),new s("arías",45,2),new s("erías",45,2),new s("irías",45,2),new s("es",-1,1),new s("ases",49,2),new s("ieses",49,2),new s("abais",-1,2),new s("arais",-1,2),new s("ierais",-1,2),new s("íais",-1,2),new s("aríais",55,2),new s("eríais",55,2),new s("iríais",55,2),new s("aseis",-1,2),new s("ieseis",-1,2),new s("asteis",-1,2),new s("isteis",-1,2),new s("áis",-1,2),new s("éis",-1,1),new s("aréis",64,2),new s("eréis",64,2),new s("iréis",64,2),new s("ados",-1,2),new s("idos",-1,2),new s("amos",-1,2),new s("ábamos",70,2),new s("áramos",70,2),new s("iéramos",70,2),new s("íamos",70,2),new s("aríamos",74,2),new s("eríamos",74,2),new s("iríamos",74,2),new s("emos",-1,1),new s("aremos",78,2),new s("eremos",78,2),new s("iremos",78,2),new s("ásemos",78,2),new s("iésemos",78,2),new s("imos",-1,2),new s("arás",-1,2),new s("erás",-1,2),new s("irás",-1,2),new s("ís",-1,2),new s("ará",-1,2),new s("erá",-1,2),new s("irá",-1,2),new s("aré",-1,2),new s("eré",-1,2),new s("iré",-1,2),new s("ió",-1,2)],z=[new s("a",-1,1),new s("e",-1,2),new s("o",-1,1),new s("os",-1,1),new s("á",-1,1),new s("é",-1,2),new s("í",-1,1),new s("ó",-1,1)],x=[17,65,16,0,0,0,0,0,0,0,0,0,0,0,0,0,1,17,4,10],A=new r;this.setCurrent=function(e){A.setCurrent(e)},this.getCurrent=function(){return A.getCurrent()},this.stem=function(){var e=A.cursor;return t(),A.limit_backward=e,A.cursor=A.limit,m(),A.cursor=A.limit,b()||(A.cursor=A.limit,f()||(A.cursor=A.limit,_())),A.cursor=A.limit,h(),A.cursor=A.limit_backward,o(),!0}};return function(e){return"function"==typeof e.update?e.update(function(e){return n.setCurrent(e),n.stem(),n.getCurrent()}):(n.setCurrent(e),n.stem(),n.getCurrent())}}(),e.Pipeline.registerFunction(e.es.stemmer,"stemmer-es"),e.es.stopWordFilter=e.generateStopWordFilter("a al algo algunas algunos ante antes como con contra cual cuando de del desde donde durante e el ella ellas ellos en entre era erais eran eras eres es esa esas ese eso esos esta estaba estabais estaban estabas estad estada estadas estado estados estamos estando estar estaremos estará estarán estarás estaré estaréis estaría estaríais estaríamos estarían estarías estas este estemos esto estos estoy estuve estuviera estuvierais estuvieran estuvieras estuvieron estuviese estuvieseis estuviesen estuvieses estuvimos estuviste estuvisteis estuviéramos estuviésemos estuvo está estábamos estáis están estás esté estéis estén estés fue fuera fuerais fueran fueras fueron fuese fueseis fuesen fueses fui fuimos fuiste fuisteis fuéramos fuésemos ha habida habidas habido habidos habiendo habremos habrá habrán habrás habré habréis habría habríais habríamos habrían habrías habéis había habíais habíamos habían habías han has hasta hay haya hayamos hayan hayas hayáis he hemos hube hubiera hubierais hubieran hubieras hubieron hubiese hubieseis hubiesen hubieses hubimos hubiste hubisteis hubiéramos hubiésemos hubo la las le les lo los me mi mis mucho muchos muy más mí mía mías mío míos nada ni no nos nosotras nosotros nuestra nuestras nuestro nuestros o os otra otras otro otros para pero poco por porque que quien quienes qué se sea seamos sean seas seremos será serán serás seré seréis sería seríais seríamos serían serías seáis sido siendo sin sobre sois somos son soy su sus suya suyas suyo suyos sí también tanto te tendremos tendrá tendrán tendrás tendré tendréis tendría tendríais tendríamos tendrían tendrías tened tenemos tenga tengamos tengan tengas tengo tengáis tenida tenidas tenido tenidos teniendo tenéis tenía teníais teníamos tenían tenías ti tiene tienen tienes todo todos tu tus tuve tuviera tuvierais tuvieran tuvieras tuvieron tuviese tuvieseis tuviesen tuvieses tuvimos tuviste tuvisteis tuviéramos tuviésemos tuvo tuya tuyas tuyo tuyos tú un una uno unos vosotras vosotros vuestra vuestras vuestro vuestros y ya yo él éramos".split(" ")),e.Pipeline.registerFunction(e.es.stopWordFilter,"stopWordFilter-es")}}); \ No newline at end of file diff --git a/en/2021.7/assets/javascripts/lunr/min/lunr.fi.min.js b/en/2021.7/assets/javascripts/lunr/min/lunr.fi.min.js new file mode 100644 index 000000000..29f5dfcea --- /dev/null +++ b/en/2021.7/assets/javascripts/lunr/min/lunr.fi.min.js @@ -0,0 +1,18 @@ +/*! + * Lunr languages, `Finnish` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +!function(i,e){"function"==typeof define&&define.amd?define(e):"object"==typeof exports?module.exports=e():e()(i.lunr)}(this,function(){return function(i){if(void 0===i)throw new Error("Lunr is not present. Please include / require Lunr before this script.");if(void 0===i.stemmerSupport)throw new Error("Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.");i.fi=function(){this.pipeline.reset(),this.pipeline.add(i.fi.trimmer,i.fi.stopWordFilter,i.fi.stemmer),this.searchPipeline&&(this.searchPipeline.reset(),this.searchPipeline.add(i.fi.stemmer))},i.fi.wordCharacters="A-Za-zªºÀ-ÖØ-öø-ʸˠ-ˤᴀ-ᴥᴬ-ᵜᵢ-ᵥᵫ-ᵷᵹ-ᶾḀ-ỿⁱⁿₐ-ₜKÅℲⅎⅠ-ↈⱠ-ⱿꜢ-ꞇꞋ-ꞭꞰ-ꞷꟷ-ꟿꬰ-ꭚꭜ-ꭤff-stA-Za-z",i.fi.trimmer=i.trimmerSupport.generateTrimmer(i.fi.wordCharacters),i.Pipeline.registerFunction(i.fi.trimmer,"trimmer-fi"),i.fi.stemmer=function(){var e=i.stemmerSupport.Among,r=i.stemmerSupport.SnowballProgram,n=new function(){function i(){f=A.limit,d=f,n()||(f=A.cursor,n()||(d=A.cursor))}function n(){for(var i;;){if(i=A.cursor,A.in_grouping(W,97,246))break;if(A.cursor=i,i>=A.limit)return!0;A.cursor++}for(A.cursor=i;!A.out_grouping(W,97,246);){if(A.cursor>=A.limit)return!0;A.cursor++}return!1}function t(){return d<=A.cursor}function s(){var i,e;if(A.cursor>=f)if(e=A.limit_backward,A.limit_backward=f,A.ket=A.cursor,i=A.find_among_b(h,10)){switch(A.bra=A.cursor,A.limit_backward=e,i){case 1:if(!A.in_grouping_b(x,97,246))return;break;case 2:if(!t())return}A.slice_del()}else A.limit_backward=e}function o(){var i,e,r;if(A.cursor>=f)if(e=A.limit_backward,A.limit_backward=f,A.ket=A.cursor,i=A.find_among_b(v,9))switch(A.bra=A.cursor,A.limit_backward=e,i){case 1:r=A.limit-A.cursor,A.eq_s_b(1,"k")||(A.cursor=A.limit-r,A.slice_del());break;case 2:A.slice_del(),A.ket=A.cursor,A.eq_s_b(3,"kse")&&(A.bra=A.cursor,A.slice_from("ksi"));break;case 3:A.slice_del();break;case 4:A.find_among_b(p,6)&&A.slice_del();break;case 5:A.find_among_b(g,6)&&A.slice_del();break;case 6:A.find_among_b(j,2)&&A.slice_del()}else A.limit_backward=e}function l(){return A.find_among_b(q,7)}function a(){return A.eq_s_b(1,"i")&&A.in_grouping_b(L,97,246)}function u(){var i,e,r;if(A.cursor>=f)if(e=A.limit_backward,A.limit_backward=f,A.ket=A.cursor,i=A.find_among_b(C,30)){switch(A.bra=A.cursor,A.limit_backward=e,i){case 1:if(!A.eq_s_b(1,"a"))return;break;case 2:case 9:if(!A.eq_s_b(1,"e"))return;break;case 3:if(!A.eq_s_b(1,"i"))return;break;case 4:if(!A.eq_s_b(1,"o"))return;break;case 5:if(!A.eq_s_b(1,"ä"))return;break;case 6:if(!A.eq_s_b(1,"ö"))return;break;case 7:if(r=A.limit-A.cursor,!l()&&(A.cursor=A.limit-r,!A.eq_s_b(2,"ie"))){A.cursor=A.limit-r;break}if(A.cursor=A.limit-r,A.cursor<=A.limit_backward){A.cursor=A.limit-r;break}A.cursor--,A.bra=A.cursor;break;case 8:if(!A.in_grouping_b(W,97,246)||!A.out_grouping_b(W,97,246))return}A.slice_del(),k=!0}else A.limit_backward=e}function c(){var i,e,r;if(A.cursor>=d)if(e=A.limit_backward,A.limit_backward=d,A.ket=A.cursor,i=A.find_among_b(P,14)){if(A.bra=A.cursor,A.limit_backward=e,1==i){if(r=A.limit-A.cursor,A.eq_s_b(2,"po"))return;A.cursor=A.limit-r}A.slice_del()}else A.limit_backward=e}function m(){var i;A.cursor>=f&&(i=A.limit_backward,A.limit_backward=f,A.ket=A.cursor,A.find_among_b(F,2)?(A.bra=A.cursor,A.limit_backward=i,A.slice_del()):A.limit_backward=i)}function w(){var i,e,r,n,t,s;if(A.cursor>=f){if(e=A.limit_backward,A.limit_backward=f,A.ket=A.cursor,A.eq_s_b(1,"t")&&(A.bra=A.cursor,r=A.limit-A.cursor,A.in_grouping_b(W,97,246)&&(A.cursor=A.limit-r,A.slice_del(),A.limit_backward=e,n=A.limit-A.cursor,A.cursor>=d&&(A.cursor=d,t=A.limit_backward,A.limit_backward=A.cursor,A.cursor=A.limit-n,A.ket=A.cursor,i=A.find_among_b(S,2))))){if(A.bra=A.cursor,A.limit_backward=t,1==i){if(s=A.limit-A.cursor,A.eq_s_b(2,"po"))return;A.cursor=A.limit-s}return void A.slice_del()}A.limit_backward=e}}function _(){var i,e,r,n;if(A.cursor>=f){for(i=A.limit_backward,A.limit_backward=f,e=A.limit-A.cursor,l()&&(A.cursor=A.limit-e,A.ket=A.cursor,A.cursor>A.limit_backward&&(A.cursor--,A.bra=A.cursor,A.slice_del())),A.cursor=A.limit-e,A.ket=A.cursor,A.in_grouping_b(y,97,228)&&(A.bra=A.cursor,A.out_grouping_b(W,97,246)&&A.slice_del()),A.cursor=A.limit-e,A.ket=A.cursor,A.eq_s_b(1,"j")&&(A.bra=A.cursor,r=A.limit-A.cursor,A.eq_s_b(1,"o")?A.slice_del():(A.cursor=A.limit-r,A.eq_s_b(1,"u")&&A.slice_del())),A.cursor=A.limit-e,A.ket=A.cursor,A.eq_s_b(1,"o")&&(A.bra=A.cursor,A.eq_s_b(1,"j")&&A.slice_del()),A.cursor=A.limit-e,A.limit_backward=i;;){if(n=A.limit-A.cursor,A.out_grouping_b(W,97,246)){A.cursor=A.limit-n;break}if(A.cursor=A.limit-n,A.cursor<=A.limit_backward)return;A.cursor--}A.ket=A.cursor,A.cursor>A.limit_backward&&(A.cursor--,A.bra=A.cursor,b=A.slice_to(),A.eq_v_b(b)&&A.slice_del())}}var k,b,d,f,h=[new e("pa",-1,1),new e("sti",-1,2),new e("kaan",-1,1),new e("han",-1,1),new e("kin",-1,1),new e("hän",-1,1),new e("kään",-1,1),new e("ko",-1,1),new e("pä",-1,1),new e("kö",-1,1)],p=[new e("lla",-1,-1),new e("na",-1,-1),new e("ssa",-1,-1),new e("ta",-1,-1),new e("lta",3,-1),new e("sta",3,-1)],g=[new e("llä",-1,-1),new e("nä",-1,-1),new e("ssä",-1,-1),new e("tä",-1,-1),new e("ltä",3,-1),new e("stä",3,-1)],j=[new e("lle",-1,-1),new e("ine",-1,-1)],v=[new e("nsa",-1,3),new e("mme",-1,3),new e("nne",-1,3),new e("ni",-1,2),new e("si",-1,1),new e("an",-1,4),new e("en",-1,6),new e("än",-1,5),new e("nsä",-1,3)],q=[new e("aa",-1,-1),new e("ee",-1,-1),new e("ii",-1,-1),new e("oo",-1,-1),new e("uu",-1,-1),new e("ää",-1,-1),new e("öö",-1,-1)],C=[new e("a",-1,8),new e("lla",0,-1),new e("na",0,-1),new e("ssa",0,-1),new e("ta",0,-1),new e("lta",4,-1),new e("sta",4,-1),new e("tta",4,9),new e("lle",-1,-1),new e("ine",-1,-1),new e("ksi",-1,-1),new e("n",-1,7),new e("han",11,1),new e("den",11,-1,a),new e("seen",11,-1,l),new e("hen",11,2),new e("tten",11,-1,a),new e("hin",11,3),new e("siin",11,-1,a),new e("hon",11,4),new e("hän",11,5),new e("hön",11,6),new e("ä",-1,8),new e("llä",22,-1),new e("nä",22,-1),new e("ssä",22,-1),new e("tä",22,-1),new e("ltä",26,-1),new e("stä",26,-1),new e("ttä",26,9)],P=[new e("eja",-1,-1),new e("mma",-1,1),new e("imma",1,-1),new e("mpa",-1,1),new e("impa",3,-1),new e("mmi",-1,1),new e("immi",5,-1),new e("mpi",-1,1),new e("impi",7,-1),new e("ejä",-1,-1),new e("mmä",-1,1),new e("immä",10,-1),new e("mpä",-1,1),new e("impä",12,-1)],F=[new e("i",-1,-1),new e("j",-1,-1)],S=[new e("mma",-1,1),new e("imma",0,-1)],y=[17,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8],W=[17,65,16,1,0,0,0,0,0,0,0,0,0,0,0,0,8,0,32],L=[17,65,16,0,0,0,0,0,0,0,0,0,0,0,0,0,8,0,32],x=[17,97,24,1,0,0,0,0,0,0,0,0,0,0,0,0,8,0,32],A=new r;this.setCurrent=function(i){A.setCurrent(i)},this.getCurrent=function(){return A.getCurrent()},this.stem=function(){var e=A.cursor;return i(),k=!1,A.limit_backward=e,A.cursor=A.limit,s(),A.cursor=A.limit,o(),A.cursor=A.limit,u(),A.cursor=A.limit,c(),A.cursor=A.limit,k?(m(),A.cursor=A.limit):(A.cursor=A.limit,w(),A.cursor=A.limit),_(),!0}};return function(i){return"function"==typeof i.update?i.update(function(i){return n.setCurrent(i),n.stem(),n.getCurrent()}):(n.setCurrent(i),n.stem(),n.getCurrent())}}(),i.Pipeline.registerFunction(i.fi.stemmer,"stemmer-fi"),i.fi.stopWordFilter=i.generateStopWordFilter("ei eivät emme en et ette että he heidän heidät heihin heille heillä heiltä heissä heistä heitä hän häneen hänelle hänellä häneltä hänen hänessä hänestä hänet häntä itse ja johon joiden joihin joiksi joilla joille joilta joina joissa joista joita joka joksi jolla jolle jolta jona jonka jos jossa josta jota jotka kanssa keiden keihin keiksi keille keillä keiltä keinä keissä keistä keitä keneen keneksi kenelle kenellä keneltä kenen kenenä kenessä kenestä kenet ketkä ketkä ketä koska kuin kuka kun me meidän meidät meihin meille meillä meiltä meissä meistä meitä mihin miksi mikä mille millä miltä minkä minkä minua minulla minulle minulta minun minussa minusta minut minuun minä minä missä mistä mitkä mitä mukaan mutta ne niiden niihin niiksi niille niillä niiltä niin niin niinä niissä niistä niitä noiden noihin noiksi noilla noille noilta noin noina noissa noista noita nuo nyt näiden näihin näiksi näille näillä näiltä näinä näissä näistä näitä nämä ole olemme olen olet olette oli olimme olin olisi olisimme olisin olisit olisitte olisivat olit olitte olivat olla olleet ollut on ovat poikki se sekä sen siihen siinä siitä siksi sille sillä sillä siltä sinua sinulla sinulle sinulta sinun sinussa sinusta sinut sinuun sinä sinä sitä tai te teidän teidät teihin teille teillä teiltä teissä teistä teitä tuo tuohon tuoksi tuolla tuolle tuolta tuon tuona tuossa tuosta tuota tähän täksi tälle tällä tältä tämä tämän tänä tässä tästä tätä vaan vai vaikka yli".split(" ")),i.Pipeline.registerFunction(i.fi.stopWordFilter,"stopWordFilter-fi")}}); \ No newline at end of file diff --git a/en/2021.7/assets/javascripts/lunr/min/lunr.fr.min.js b/en/2021.7/assets/javascripts/lunr/min/lunr.fr.min.js new file mode 100644 index 000000000..68cd0094a --- /dev/null +++ b/en/2021.7/assets/javascripts/lunr/min/lunr.fr.min.js @@ -0,0 +1,18 @@ +/*! + * Lunr languages, `French` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +!function(e,r){"function"==typeof define&&define.amd?define(r):"object"==typeof exports?module.exports=r():r()(e.lunr)}(this,function(){return function(e){if(void 0===e)throw new Error("Lunr is not present. Please include / require Lunr before this script.");if(void 0===e.stemmerSupport)throw new Error("Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.");e.fr=function(){this.pipeline.reset(),this.pipeline.add(e.fr.trimmer,e.fr.stopWordFilter,e.fr.stemmer),this.searchPipeline&&(this.searchPipeline.reset(),this.searchPipeline.add(e.fr.stemmer))},e.fr.wordCharacters="A-Za-zªºÀ-ÖØ-öø-ʸˠ-ˤᴀ-ᴥᴬ-ᵜᵢ-ᵥᵫ-ᵷᵹ-ᶾḀ-ỿⁱⁿₐ-ₜKÅℲⅎⅠ-ↈⱠ-ⱿꜢ-ꞇꞋ-ꞭꞰ-ꞷꟷ-ꟿꬰ-ꭚꭜ-ꭤff-stA-Za-z",e.fr.trimmer=e.trimmerSupport.generateTrimmer(e.fr.wordCharacters),e.Pipeline.registerFunction(e.fr.trimmer,"trimmer-fr"),e.fr.stemmer=function(){var r=e.stemmerSupport.Among,s=e.stemmerSupport.SnowballProgram,i=new function(){function e(e,r,s){return!(!W.eq_s(1,e)||(W.ket=W.cursor,!W.in_grouping(F,97,251)))&&(W.slice_from(r),W.cursor=s,!0)}function i(e,r,s){return!!W.eq_s(1,e)&&(W.ket=W.cursor,W.slice_from(r),W.cursor=s,!0)}function n(){for(var r,s;;){if(r=W.cursor,W.in_grouping(F,97,251)){if(W.bra=W.cursor,s=W.cursor,e("u","U",r))continue;if(W.cursor=s,e("i","I",r))continue;if(W.cursor=s,i("y","Y",r))continue}if(W.cursor=r,W.bra=r,!e("y","Y",r)){if(W.cursor=r,W.eq_s(1,"q")&&(W.bra=W.cursor,i("u","U",r)))continue;if(W.cursor=r,r>=W.limit)return;W.cursor++}}}function t(){for(;!W.in_grouping(F,97,251);){if(W.cursor>=W.limit)return!0;W.cursor++}for(;!W.out_grouping(F,97,251);){if(W.cursor>=W.limit)return!0;W.cursor++}return!1}function u(){var e=W.cursor;if(q=W.limit,g=q,p=q,W.in_grouping(F,97,251)&&W.in_grouping(F,97,251)&&W.cursor=W.limit){W.cursor=q;break}W.cursor++}while(!W.in_grouping(F,97,251))}q=W.cursor,W.cursor=e,t()||(g=W.cursor,t()||(p=W.cursor))}function o(){for(var e,r;;){if(r=W.cursor,W.bra=r,!(e=W.find_among(h,4)))break;switch(W.ket=W.cursor,e){case 1:W.slice_from("i");break;case 2:W.slice_from("u");break;case 3:W.slice_from("y");break;case 4:if(W.cursor>=W.limit)return;W.cursor++}}}function c(){return q<=W.cursor}function a(){return g<=W.cursor}function l(){return p<=W.cursor}function w(){var e,r;if(W.ket=W.cursor,e=W.find_among_b(C,43)){switch(W.bra=W.cursor,e){case 1:if(!l())return!1;W.slice_del();break;case 2:if(!l())return!1;W.slice_del(),W.ket=W.cursor,W.eq_s_b(2,"ic")&&(W.bra=W.cursor,l()?W.slice_del():W.slice_from("iqU"));break;case 3:if(!l())return!1;W.slice_from("log");break;case 4:if(!l())return!1;W.slice_from("u");break;case 5:if(!l())return!1;W.slice_from("ent");break;case 6:if(!c())return!1;if(W.slice_del(),W.ket=W.cursor,e=W.find_among_b(z,6))switch(W.bra=W.cursor,e){case 1:l()&&(W.slice_del(),W.ket=W.cursor,W.eq_s_b(2,"at")&&(W.bra=W.cursor,l()&&W.slice_del()));break;case 2:l()?W.slice_del():a()&&W.slice_from("eux");break;case 3:l()&&W.slice_del();break;case 4:c()&&W.slice_from("i")}break;case 7:if(!l())return!1;if(W.slice_del(),W.ket=W.cursor,e=W.find_among_b(y,3))switch(W.bra=W.cursor,e){case 1:l()?W.slice_del():W.slice_from("abl");break;case 2:l()?W.slice_del():W.slice_from("iqU");break;case 3:l()&&W.slice_del()}break;case 8:if(!l())return!1;if(W.slice_del(),W.ket=W.cursor,W.eq_s_b(2,"at")&&(W.bra=W.cursor,l()&&(W.slice_del(),W.ket=W.cursor,W.eq_s_b(2,"ic")))){W.bra=W.cursor,l()?W.slice_del():W.slice_from("iqU");break}break;case 9:W.slice_from("eau");break;case 10:if(!a())return!1;W.slice_from("al");break;case 11:if(l())W.slice_del();else{if(!a())return!1;W.slice_from("eux")}break;case 12:if(!a()||!W.out_grouping_b(F,97,251))return!1;W.slice_del();break;case 13:return c()&&W.slice_from("ant"),!1;case 14:return c()&&W.slice_from("ent"),!1;case 15:return r=W.limit-W.cursor,W.in_grouping_b(F,97,251)&&c()&&(W.cursor=W.limit-r,W.slice_del()),!1}return!0}return!1}function f(){var e,r;if(W.cursor=q){if(s=W.limit_backward,W.limit_backward=q,W.ket=W.cursor,e=W.find_among_b(P,7))switch(W.bra=W.cursor,e){case 1:if(l()){if(i=W.limit-W.cursor,!W.eq_s_b(1,"s")&&(W.cursor=W.limit-i,!W.eq_s_b(1,"t")))break;W.slice_del()}break;case 2:W.slice_from("i");break;case 3:W.slice_del();break;case 4:W.eq_s_b(2,"gu")&&W.slice_del()}W.limit_backward=s}}function b(){var e=W.limit-W.cursor;W.find_among_b(U,5)&&(W.cursor=W.limit-e,W.ket=W.cursor,W.cursor>W.limit_backward&&(W.cursor--,W.bra=W.cursor,W.slice_del()))}function d(){for(var e,r=1;W.out_grouping_b(F,97,251);)r--;if(r<=0){if(W.ket=W.cursor,e=W.limit-W.cursor,!W.eq_s_b(1,"é")&&(W.cursor=W.limit-e,!W.eq_s_b(1,"è")))return;W.bra=W.cursor,W.slice_from("e")}}function k(){if(!w()&&(W.cursor=W.limit,!f()&&(W.cursor=W.limit,!m())))return W.cursor=W.limit,void _();W.cursor=W.limit,W.ket=W.cursor,W.eq_s_b(1,"Y")?(W.bra=W.cursor,W.slice_from("i")):(W.cursor=W.limit,W.eq_s_b(1,"ç")&&(W.bra=W.cursor,W.slice_from("c")))}var p,g,q,v=[new r("col",-1,-1),new r("par",-1,-1),new r("tap",-1,-1)],h=[new r("",-1,4),new r("I",0,1),new r("U",0,2),new r("Y",0,3)],z=[new r("iqU",-1,3),new r("abl",-1,3),new r("Ièr",-1,4),new r("ièr",-1,4),new r("eus",-1,2),new r("iv",-1,1)],y=[new r("ic",-1,2),new r("abil",-1,1),new r("iv",-1,3)],C=[new r("iqUe",-1,1),new r("atrice",-1,2),new r("ance",-1,1),new r("ence",-1,5),new r("logie",-1,3),new r("able",-1,1),new r("isme",-1,1),new r("euse",-1,11),new r("iste",-1,1),new r("ive",-1,8),new r("if",-1,8),new r("usion",-1,4),new r("ation",-1,2),new r("ution",-1,4),new r("ateur",-1,2),new r("iqUes",-1,1),new r("atrices",-1,2),new r("ances",-1,1),new r("ences",-1,5),new r("logies",-1,3),new r("ables",-1,1),new r("ismes",-1,1),new r("euses",-1,11),new r("istes",-1,1),new r("ives",-1,8),new r("ifs",-1,8),new r("usions",-1,4),new r("ations",-1,2),new r("utions",-1,4),new r("ateurs",-1,2),new r("ments",-1,15),new r("ements",30,6),new r("issements",31,12),new r("ités",-1,7),new r("ment",-1,15),new r("ement",34,6),new r("issement",35,12),new r("amment",34,13),new r("emment",34,14),new r("aux",-1,10),new r("eaux",39,9),new r("eux",-1,1),new r("ité",-1,7)],x=[new r("ira",-1,1),new r("ie",-1,1),new r("isse",-1,1),new r("issante",-1,1),new r("i",-1,1),new r("irai",4,1),new r("ir",-1,1),new r("iras",-1,1),new r("ies",-1,1),new r("îmes",-1,1),new r("isses",-1,1),new r("issantes",-1,1),new r("îtes",-1,1),new r("is",-1,1),new r("irais",13,1),new r("issais",13,1),new r("irions",-1,1),new r("issions",-1,1),new r("irons",-1,1),new r("issons",-1,1),new r("issants",-1,1),new r("it",-1,1),new r("irait",21,1),new r("issait",21,1),new r("issant",-1,1),new r("iraIent",-1,1),new r("issaIent",-1,1),new r("irent",-1,1),new r("issent",-1,1),new r("iront",-1,1),new r("ît",-1,1),new r("iriez",-1,1),new r("issiez",-1,1),new r("irez",-1,1),new r("issez",-1,1)],I=[new r("a",-1,3),new r("era",0,2),new r("asse",-1,3),new r("ante",-1,3),new r("ée",-1,2),new r("ai",-1,3),new r("erai",5,2),new r("er",-1,2),new r("as",-1,3),new r("eras",8,2),new r("âmes",-1,3),new r("asses",-1,3),new r("antes",-1,3),new r("âtes",-1,3),new r("ées",-1,2),new r("ais",-1,3),new r("erais",15,2),new r("ions",-1,1),new r("erions",17,2),new r("assions",17,3),new r("erons",-1,2),new r("ants",-1,3),new r("és",-1,2),new r("ait",-1,3),new r("erait",23,2),new r("ant",-1,3),new r("aIent",-1,3),new r("eraIent",26,2),new r("èrent",-1,2),new r("assent",-1,3),new r("eront",-1,2),new r("ât",-1,3),new r("ez",-1,2),new r("iez",32,2),new r("eriez",33,2),new r("assiez",33,3),new r("erez",32,2),new r("é",-1,2)],P=[new r("e",-1,3),new r("Ière",0,2),new r("ière",0,2),new r("ion",-1,1),new r("Ier",-1,2),new r("ier",-1,2),new r("ë",-1,4)],U=[new r("ell",-1,-1),new r("eill",-1,-1),new r("enn",-1,-1),new r("onn",-1,-1),new r("ett",-1,-1)],F=[17,65,16,1,0,0,0,0,0,0,0,0,0,0,0,128,130,103,8,5],S=[1,65,20,0,0,0,0,0,0,0,0,0,0,0,0,0,128],W=new s;this.setCurrent=function(e){W.setCurrent(e)},this.getCurrent=function(){return W.getCurrent()},this.stem=function(){var e=W.cursor;return n(),W.cursor=e,u(),W.limit_backward=e,W.cursor=W.limit,k(),W.cursor=W.limit,b(),W.cursor=W.limit,d(),W.cursor=W.limit_backward,o(),!0}};return function(e){return"function"==typeof e.update?e.update(function(e){return i.setCurrent(e),i.stem(),i.getCurrent()}):(i.setCurrent(e),i.stem(),i.getCurrent())}}(),e.Pipeline.registerFunction(e.fr.stemmer,"stemmer-fr"),e.fr.stopWordFilter=e.generateStopWordFilter("ai aie aient aies ait as au aura aurai auraient aurais aurait auras aurez auriez aurions aurons auront aux avaient avais avait avec avez aviez avions avons ayant ayez ayons c ce ceci celà ces cet cette d dans de des du elle en es est et eu eue eues eurent eus eusse eussent eusses eussiez eussions eut eux eûmes eût eûtes furent fus fusse fussent fusses fussiez fussions fut fûmes fût fûtes ici il ils j je l la le les leur leurs lui m ma mais me mes moi mon même n ne nos notre nous on ont ou par pas pour qu que quel quelle quelles quels qui s sa sans se sera serai seraient serais serait seras serez seriez serions serons seront ses soi soient sois soit sommes son sont soyez soyons suis sur t ta te tes toi ton tu un une vos votre vous y à étaient étais était étant étiez étions été étée étées étés êtes".split(" ")),e.Pipeline.registerFunction(e.fr.stopWordFilter,"stopWordFilter-fr")}}); \ No newline at end of file diff --git a/en/2021.7/assets/javascripts/lunr/min/lunr.hi.min.js b/en/2021.7/assets/javascripts/lunr/min/lunr.hi.min.js new file mode 100644 index 000000000..7dbc41402 --- /dev/null +++ b/en/2021.7/assets/javascripts/lunr/min/lunr.hi.min.js @@ -0,0 +1 @@ +!function(e,r){"function"==typeof define&&define.amd?define(r):"object"==typeof exports?module.exports=r():r()(e.lunr)}(this,function(){return function(e){if(void 0===e)throw new Error("Lunr is not present. Please include / require Lunr before this script.");if(void 0===e.stemmerSupport)throw new Error("Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.");e.hi=function(){this.pipeline.reset(),this.pipeline.add(e.hi.trimmer,e.hi.stopWordFilter,e.hi.stemmer),this.searchPipeline&&(this.searchPipeline.reset(),this.searchPipeline.add(e.hi.stemmer))},e.hi.wordCharacters="ऀ-ःऄ-एऐ-टठ-यर-िी-ॏॐ-य़ॠ-९॰-ॿa-zA-Za-zA-Z0-90-9",e.hi.trimmer=e.trimmerSupport.generateTrimmer(e.hi.wordCharacters),e.Pipeline.registerFunction(e.hi.trimmer,"trimmer-hi"),e.hi.stopWordFilter=e.generateStopWordFilter("अत अपना अपनी अपने अभी अंदर आदि आप इत्यादि इन इनका इन्हीं इन्हें इन्हों इस इसका इसकी इसके इसमें इसी इसे उन उनका उनकी उनके उनको उन्हीं उन्हें उन्हों उस उसके उसी उसे एक एवं एस ऐसे और कई कर करता करते करना करने करें कहते कहा का काफ़ी कि कितना किन्हें किन्हों किया किर किस किसी किसे की कुछ कुल के को कोई कौन कौनसा गया घर जब जहाँ जा जितना जिन जिन्हें जिन्हों जिस जिसे जीधर जैसा जैसे जो तक तब तरह तिन तिन्हें तिन्हों तिस तिसे तो था थी थे दबारा दिया दुसरा दूसरे दो द्वारा न नके नहीं ना निहायत नीचे ने पर पहले पूरा पे फिर बनी बही बहुत बाद बाला बिलकुल भी भीतर मगर मानो मे में यदि यह यहाँ यही या यिह ये रखें रहा रहे ऱ्वासा लिए लिये लेकिन व वग़ैरह वर्ग वह वहाँ वहीं वाले वुह वे वो सकता सकते सबसे सभी साथ साबुत साभ सारा से सो संग ही हुआ हुई हुए है हैं हो होता होती होते होना होने".split(" ")),e.hi.stemmer=function(){return function(e){return"function"==typeof e.update?e.update(function(e){return e}):e}}();var r=e.wordcut;r.init(),e.hi.tokenizer=function(i){if(!arguments.length||null==i||void 0==i)return[];if(Array.isArray(i))return i.map(function(r){return isLunr2?new e.Token(r.toLowerCase()):r.toLowerCase()});var t=i.toString().toLowerCase().replace(/^\s+/,"");return r.cut(t).split("|")},e.Pipeline.registerFunction(e.hi.stemmer,"stemmer-hi"),e.Pipeline.registerFunction(e.hi.stopWordFilter,"stopWordFilter-hi")}}); \ No newline at end of file diff --git a/en/2021.7/assets/javascripts/lunr/min/lunr.hu.min.js b/en/2021.7/assets/javascripts/lunr/min/lunr.hu.min.js new file mode 100644 index 000000000..ed9d909f7 --- /dev/null +++ b/en/2021.7/assets/javascripts/lunr/min/lunr.hu.min.js @@ -0,0 +1,18 @@ +/*! + * Lunr languages, `Hungarian` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +!function(e,n){"function"==typeof define&&define.amd?define(n):"object"==typeof exports?module.exports=n():n()(e.lunr)}(this,function(){return function(e){if(void 0===e)throw new Error("Lunr is not present. Please include / require Lunr before this script.");if(void 0===e.stemmerSupport)throw new Error("Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.");e.hu=function(){this.pipeline.reset(),this.pipeline.add(e.hu.trimmer,e.hu.stopWordFilter,e.hu.stemmer),this.searchPipeline&&(this.searchPipeline.reset(),this.searchPipeline.add(e.hu.stemmer))},e.hu.wordCharacters="A-Za-zªºÀ-ÖØ-öø-ʸˠ-ˤᴀ-ᴥᴬ-ᵜᵢ-ᵥᵫ-ᵷᵹ-ᶾḀ-ỿⁱⁿₐ-ₜKÅℲⅎⅠ-ↈⱠ-ⱿꜢ-ꞇꞋ-ꞭꞰ-ꞷꟷ-ꟿꬰ-ꭚꭜ-ꭤff-stA-Za-z",e.hu.trimmer=e.trimmerSupport.generateTrimmer(e.hu.wordCharacters),e.Pipeline.registerFunction(e.hu.trimmer,"trimmer-hu"),e.hu.stemmer=function(){var n=e.stemmerSupport.Among,r=e.stemmerSupport.SnowballProgram,i=new function(){function e(){var e,n=L.cursor;if(d=L.limit,L.in_grouping(W,97,252))for(;;){if(e=L.cursor,L.out_grouping(W,97,252))return L.cursor=e,L.find_among(g,8)||(L.cursor=e,e=L.limit)return void(d=e);L.cursor++}if(L.cursor=n,L.out_grouping(W,97,252)){for(;!L.in_grouping(W,97,252);){if(L.cursor>=L.limit)return;L.cursor++}d=L.cursor}}function i(){return d<=L.cursor}function a(){var e;if(L.ket=L.cursor,(e=L.find_among_b(h,2))&&(L.bra=L.cursor,i()))switch(e){case 1:L.slice_from("a");break;case 2:L.slice_from("e")}}function t(){var e=L.limit-L.cursor;return!!L.find_among_b(p,23)&&(L.cursor=L.limit-e,!0)}function s(){if(L.cursor>L.limit_backward){L.cursor--,L.ket=L.cursor;var e=L.cursor-1;L.limit_backward<=e&&e<=L.limit&&(L.cursor=e,L.bra=e,L.slice_del())}}function c(){var e;if(L.ket=L.cursor,(e=L.find_among_b(_,2))&&(L.bra=L.cursor,i())){if((1==e||2==e)&&!t())return;L.slice_del(),s()}}function o(){L.ket=L.cursor,L.find_among_b(v,44)&&(L.bra=L.cursor,i()&&(L.slice_del(),a()))}function w(){var e;if(L.ket=L.cursor,(e=L.find_among_b(z,3))&&(L.bra=L.cursor,i()))switch(e){case 1:L.slice_from("e");break;case 2:case 3:L.slice_from("a")}}function l(){var e;if(L.ket=L.cursor,(e=L.find_among_b(y,6))&&(L.bra=L.cursor,i()))switch(e){case 1:case 2:L.slice_del();break;case 3:L.slice_from("a");break;case 4:L.slice_from("e")}}function u(){var e;if(L.ket=L.cursor,(e=L.find_among_b(j,2))&&(L.bra=L.cursor,i())){if((1==e||2==e)&&!t())return;L.slice_del(),s()}}function m(){var e;if(L.ket=L.cursor,(e=L.find_among_b(C,7))&&(L.bra=L.cursor,i()))switch(e){case 1:L.slice_from("a");break;case 2:L.slice_from("e");break;case 3:case 4:case 5:case 6:case 7:L.slice_del()}}function k(){var e;if(L.ket=L.cursor,(e=L.find_among_b(P,12))&&(L.bra=L.cursor,i()))switch(e){case 1:case 4:case 7:case 9:L.slice_del();break;case 2:case 5:case 8:L.slice_from("e");break;case 3:case 6:L.slice_from("a")}}function f(){var e;if(L.ket=L.cursor,(e=L.find_among_b(F,31))&&(L.bra=L.cursor,i()))switch(e){case 1:case 4:case 7:case 8:case 9:case 12:case 13:case 16:case 17:case 18:L.slice_del();break;case 2:case 5:case 10:case 14:case 19:L.slice_from("a");break;case 3:case 6:case 11:case 15:case 20:L.slice_from("e")}}function b(){var e;if(L.ket=L.cursor,(e=L.find_among_b(S,42))&&(L.bra=L.cursor,i()))switch(e){case 1:case 4:case 5:case 6:case 9:case 10:case 11:case 14:case 15:case 16:case 17:case 20:case 21:case 24:case 25:case 26:case 29:L.slice_del();break;case 2:case 7:case 12:case 18:case 22:case 27:L.slice_from("a");break;case 3:case 8:case 13:case 19:case 23:case 28:L.slice_from("e")}}var d,g=[new n("cs",-1,-1),new n("dzs",-1,-1),new n("gy",-1,-1),new n("ly",-1,-1),new n("ny",-1,-1),new n("sz",-1,-1),new n("ty",-1,-1),new n("zs",-1,-1)],h=[new n("á",-1,1),new n("é",-1,2)],p=[new n("bb",-1,-1),new n("cc",-1,-1),new n("dd",-1,-1),new n("ff",-1,-1),new n("gg",-1,-1),new n("jj",-1,-1),new n("kk",-1,-1),new n("ll",-1,-1),new n("mm",-1,-1),new n("nn",-1,-1),new n("pp",-1,-1),new n("rr",-1,-1),new n("ccs",-1,-1),new n("ss",-1,-1),new n("zzs",-1,-1),new n("tt",-1,-1),new n("vv",-1,-1),new n("ggy",-1,-1),new n("lly",-1,-1),new n("nny",-1,-1),new n("tty",-1,-1),new n("ssz",-1,-1),new n("zz",-1,-1)],_=[new n("al",-1,1),new n("el",-1,2)],v=[new n("ba",-1,-1),new n("ra",-1,-1),new n("be",-1,-1),new n("re",-1,-1),new n("ig",-1,-1),new n("nak",-1,-1),new n("nek",-1,-1),new n("val",-1,-1),new n("vel",-1,-1),new n("ul",-1,-1),new n("nál",-1,-1),new n("nél",-1,-1),new n("ból",-1,-1),new n("ról",-1,-1),new n("tól",-1,-1),new n("bõl",-1,-1),new n("rõl",-1,-1),new n("tõl",-1,-1),new n("ül",-1,-1),new n("n",-1,-1),new n("an",19,-1),new n("ban",20,-1),new n("en",19,-1),new n("ben",22,-1),new n("képpen",22,-1),new n("on",19,-1),new n("ön",19,-1),new n("képp",-1,-1),new n("kor",-1,-1),new n("t",-1,-1),new n("at",29,-1),new n("et",29,-1),new n("ként",29,-1),new n("anként",32,-1),new n("enként",32,-1),new n("onként",32,-1),new n("ot",29,-1),new n("ért",29,-1),new n("öt",29,-1),new n("hez",-1,-1),new n("hoz",-1,-1),new n("höz",-1,-1),new n("vá",-1,-1),new n("vé",-1,-1)],z=[new n("án",-1,2),new n("én",-1,1),new n("ánként",-1,3)],y=[new n("stul",-1,2),new n("astul",0,1),new n("ástul",0,3),new n("stül",-1,2),new n("estül",3,1),new n("éstül",3,4)],j=[new n("á",-1,1),new n("é",-1,2)],C=[new n("k",-1,7),new n("ak",0,4),new n("ek",0,6),new n("ok",0,5),new n("ák",0,1),new n("ék",0,2),new n("ök",0,3)],P=[new n("éi",-1,7),new n("áéi",0,6),new n("ééi",0,5),new n("é",-1,9),new n("ké",3,4),new n("aké",4,1),new n("eké",4,1),new n("oké",4,1),new n("áké",4,3),new n("éké",4,2),new n("öké",4,1),new n("éé",3,8)],F=[new n("a",-1,18),new n("ja",0,17),new n("d",-1,16),new n("ad",2,13),new n("ed",2,13),new n("od",2,13),new n("ád",2,14),new n("éd",2,15),new n("öd",2,13),new n("e",-1,18),new n("je",9,17),new n("nk",-1,4),new n("unk",11,1),new n("ánk",11,2),new n("énk",11,3),new n("ünk",11,1),new n("uk",-1,8),new n("juk",16,7),new n("ájuk",17,5),new n("ük",-1,8),new n("jük",19,7),new n("éjük",20,6),new n("m",-1,12),new n("am",22,9),new n("em",22,9),new n("om",22,9),new n("ám",22,10),new n("ém",22,11),new n("o",-1,18),new n("á",-1,19),new n("é",-1,20)],S=[new n("id",-1,10),new n("aid",0,9),new n("jaid",1,6),new n("eid",0,9),new n("jeid",3,6),new n("áid",0,7),new n("éid",0,8),new n("i",-1,15),new n("ai",7,14),new n("jai",8,11),new n("ei",7,14),new n("jei",10,11),new n("ái",7,12),new n("éi",7,13),new n("itek",-1,24),new n("eitek",14,21),new n("jeitek",15,20),new n("éitek",14,23),new n("ik",-1,29),new n("aik",18,26),new n("jaik",19,25),new n("eik",18,26),new n("jeik",21,25),new n("áik",18,27),new n("éik",18,28),new n("ink",-1,20),new n("aink",25,17),new n("jaink",26,16),new n("eink",25,17),new n("jeink",28,16),new n("áink",25,18),new n("éink",25,19),new n("aitok",-1,21),new n("jaitok",32,20),new n("áitok",-1,22),new n("im",-1,5),new n("aim",35,4),new n("jaim",36,1),new n("eim",35,4),new n("jeim",38,1),new n("áim",35,2),new n("éim",35,3)],W=[17,65,16,0,0,0,0,0,0,0,0,0,0,0,0,0,1,17,52,14],L=new r;this.setCurrent=function(e){L.setCurrent(e)},this.getCurrent=function(){return L.getCurrent()},this.stem=function(){var n=L.cursor;return e(),L.limit_backward=n,L.cursor=L.limit,c(),L.cursor=L.limit,o(),L.cursor=L.limit,w(),L.cursor=L.limit,l(),L.cursor=L.limit,u(),L.cursor=L.limit,k(),L.cursor=L.limit,f(),L.cursor=L.limit,b(),L.cursor=L.limit,m(),!0}};return function(e){return"function"==typeof e.update?e.update(function(e){return i.setCurrent(e),i.stem(),i.getCurrent()}):(i.setCurrent(e),i.stem(),i.getCurrent())}}(),e.Pipeline.registerFunction(e.hu.stemmer,"stemmer-hu"),e.hu.stopWordFilter=e.generateStopWordFilter("a abban ahhoz ahogy ahol aki akik akkor alatt amely amelyek amelyekben amelyeket amelyet amelynek ami amikor amit amolyan amíg annak arra arról az azok azon azonban azt aztán azután azzal azért be belül benne bár cikk cikkek cikkeket csak de e ebben eddig egy egyes egyetlen egyik egyre egyéb egész ehhez ekkor el ellen elsõ elég elõ elõször elõtt emilyen ennek erre ez ezek ezen ezt ezzel ezért fel felé hanem hiszen hogy hogyan igen ill ill. illetve ilyen ilyenkor ismét ison itt jobban jó jól kell kellett keressünk keresztül ki kívül között közül legalább legyen lehet lehetett lenne lenni lesz lett maga magát majd majd meg mellett mely melyek mert mi mikor milyen minden mindenki mindent mindig mint mintha mit mivel miért most már más másik még míg nagy nagyobb nagyon ne nekem neki nem nincs néha néhány nélkül olyan ott pedig persze rá s saját sem semmi sok sokat sokkal szemben szerint szinte számára talán tehát teljes tovább továbbá több ugyanis utolsó után utána vagy vagyis vagyok valaki valami valamint való van vannak vele vissza viszont volna volt voltak voltam voltunk által általában át én éppen és így õ õk õket össze úgy új újabb újra".split(" ")),e.Pipeline.registerFunction(e.hu.stopWordFilter,"stopWordFilter-hu")}}); \ No newline at end of file diff --git a/en/2021.7/assets/javascripts/lunr/min/lunr.it.min.js b/en/2021.7/assets/javascripts/lunr/min/lunr.it.min.js new file mode 100644 index 000000000..344b6a3c0 --- /dev/null +++ b/en/2021.7/assets/javascripts/lunr/min/lunr.it.min.js @@ -0,0 +1,18 @@ +/*! + * Lunr languages, `Italian` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +!function(e,r){"function"==typeof define&&define.amd?define(r):"object"==typeof exports?module.exports=r():r()(e.lunr)}(this,function(){return function(e){if(void 0===e)throw new Error("Lunr is not present. Please include / require Lunr before this script.");if(void 0===e.stemmerSupport)throw new Error("Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.");e.it=function(){this.pipeline.reset(),this.pipeline.add(e.it.trimmer,e.it.stopWordFilter,e.it.stemmer),this.searchPipeline&&(this.searchPipeline.reset(),this.searchPipeline.add(e.it.stemmer))},e.it.wordCharacters="A-Za-zªºÀ-ÖØ-öø-ʸˠ-ˤᴀ-ᴥᴬ-ᵜᵢ-ᵥᵫ-ᵷᵹ-ᶾḀ-ỿⁱⁿₐ-ₜKÅℲⅎⅠ-ↈⱠ-ⱿꜢ-ꞇꞋ-ꞭꞰ-ꞷꟷ-ꟿꬰ-ꭚꭜ-ꭤff-stA-Za-z",e.it.trimmer=e.trimmerSupport.generateTrimmer(e.it.wordCharacters),e.Pipeline.registerFunction(e.it.trimmer,"trimmer-it"),e.it.stemmer=function(){var r=e.stemmerSupport.Among,n=e.stemmerSupport.SnowballProgram,i=new function(){function e(e,r,n){return!(!x.eq_s(1,e)||(x.ket=x.cursor,!x.in_grouping(L,97,249)))&&(x.slice_from(r),x.cursor=n,!0)}function i(){for(var r,n,i,o,t=x.cursor;;){if(x.bra=x.cursor,r=x.find_among(h,7))switch(x.ket=x.cursor,r){case 1:x.slice_from("à");continue;case 2:x.slice_from("è");continue;case 3:x.slice_from("ì");continue;case 4:x.slice_from("ò");continue;case 5:x.slice_from("ù");continue;case 6:x.slice_from("qU");continue;case 7:if(x.cursor>=x.limit)break;x.cursor++;continue}break}for(x.cursor=t;;)for(n=x.cursor;;){if(i=x.cursor,x.in_grouping(L,97,249)){if(x.bra=x.cursor,o=x.cursor,e("u","U",i))break;if(x.cursor=o,e("i","I",i))break}if(x.cursor=i,x.cursor>=x.limit)return void(x.cursor=n);x.cursor++}}function o(e){if(x.cursor=e,!x.in_grouping(L,97,249))return!1;for(;!x.out_grouping(L,97,249);){if(x.cursor>=x.limit)return!1;x.cursor++}return!0}function t(){if(x.in_grouping(L,97,249)){var e=x.cursor;if(x.out_grouping(L,97,249)){for(;!x.in_grouping(L,97,249);){if(x.cursor>=x.limit)return o(e);x.cursor++}return!0}return o(e)}return!1}function s(){var e,r=x.cursor;if(!t()){if(x.cursor=r,!x.out_grouping(L,97,249))return;if(e=x.cursor,x.out_grouping(L,97,249)){for(;!x.in_grouping(L,97,249);){if(x.cursor>=x.limit)return x.cursor=e,void(x.in_grouping(L,97,249)&&x.cursor=x.limit)return;x.cursor++}k=x.cursor}function a(){for(;!x.in_grouping(L,97,249);){if(x.cursor>=x.limit)return!1;x.cursor++}for(;!x.out_grouping(L,97,249);){if(x.cursor>=x.limit)return!1;x.cursor++}return!0}function u(){var e=x.cursor;k=x.limit,p=k,g=k,s(),x.cursor=e,a()&&(p=x.cursor,a()&&(g=x.cursor))}function c(){for(var e;;){if(x.bra=x.cursor,!(e=x.find_among(q,3)))break;switch(x.ket=x.cursor,e){case 1:x.slice_from("i");break;case 2:x.slice_from("u");break;case 3:if(x.cursor>=x.limit)return;x.cursor++}}}function w(){return k<=x.cursor}function l(){return p<=x.cursor}function m(){return g<=x.cursor}function f(){var e;if(x.ket=x.cursor,x.find_among_b(C,37)&&(x.bra=x.cursor,(e=x.find_among_b(z,5))&&w()))switch(e){case 1:x.slice_del();break;case 2:x.slice_from("e")}}function v(){var e;if(x.ket=x.cursor,!(e=x.find_among_b(S,51)))return!1;switch(x.bra=x.cursor,e){case 1:if(!m())return!1;x.slice_del();break;case 2:if(!m())return!1;x.slice_del(),x.ket=x.cursor,x.eq_s_b(2,"ic")&&(x.bra=x.cursor,m()&&x.slice_del());break;case 3:if(!m())return!1;x.slice_from("log");break;case 4:if(!m())return!1;x.slice_from("u");break;case 5:if(!m())return!1;x.slice_from("ente");break;case 6:if(!w())return!1;x.slice_del();break;case 7:if(!l())return!1;x.slice_del(),x.ket=x.cursor,e=x.find_among_b(P,4),e&&(x.bra=x.cursor,m()&&(x.slice_del(),1==e&&(x.ket=x.cursor,x.eq_s_b(2,"at")&&(x.bra=x.cursor,m()&&x.slice_del()))));break;case 8:if(!m())return!1;x.slice_del(),x.ket=x.cursor,e=x.find_among_b(F,3),e&&(x.bra=x.cursor,1==e&&m()&&x.slice_del());break;case 9:if(!m())return!1;x.slice_del(),x.ket=x.cursor,x.eq_s_b(2,"at")&&(x.bra=x.cursor,m()&&(x.slice_del(),x.ket=x.cursor,x.eq_s_b(2,"ic")&&(x.bra=x.cursor,m()&&x.slice_del())))}return!0}function b(){var e,r;x.cursor>=k&&(r=x.limit_backward,x.limit_backward=k,x.ket=x.cursor,e=x.find_among_b(W,87),e&&(x.bra=x.cursor,1==e&&x.slice_del()),x.limit_backward=r)}function d(){var e=x.limit-x.cursor;if(x.ket=x.cursor,x.in_grouping_b(y,97,242)&&(x.bra=x.cursor,w()&&(x.slice_del(),x.ket=x.cursor,x.eq_s_b(1,"i")&&(x.bra=x.cursor,w()))))return void x.slice_del();x.cursor=x.limit-e}function _(){d(),x.ket=x.cursor,x.eq_s_b(1,"h")&&(x.bra=x.cursor,x.in_grouping_b(U,99,103)&&w()&&x.slice_del())}var g,p,k,h=[new r("",-1,7),new r("qu",0,6),new r("á",0,1),new r("é",0,2),new r("í",0,3),new r("ó",0,4),new r("ú",0,5)],q=[new r("",-1,3),new r("I",0,1),new r("U",0,2)],C=[new r("la",-1,-1),new r("cela",0,-1),new r("gliela",0,-1),new r("mela",0,-1),new r("tela",0,-1),new r("vela",0,-1),new r("le",-1,-1),new r("cele",6,-1),new r("gliele",6,-1),new r("mele",6,-1),new r("tele",6,-1),new r("vele",6,-1),new r("ne",-1,-1),new r("cene",12,-1),new r("gliene",12,-1),new r("mene",12,-1),new r("sene",12,-1),new r("tene",12,-1),new r("vene",12,-1),new r("ci",-1,-1),new r("li",-1,-1),new r("celi",20,-1),new r("glieli",20,-1),new r("meli",20,-1),new r("teli",20,-1),new r("veli",20,-1),new r("gli",20,-1),new r("mi",-1,-1),new r("si",-1,-1),new r("ti",-1,-1),new r("vi",-1,-1),new r("lo",-1,-1),new r("celo",31,-1),new r("glielo",31,-1),new r("melo",31,-1),new r("telo",31,-1),new r("velo",31,-1)],z=[new r("ando",-1,1),new r("endo",-1,1),new r("ar",-1,2),new r("er",-1,2),new r("ir",-1,2)],P=[new r("ic",-1,-1),new r("abil",-1,-1),new r("os",-1,-1),new r("iv",-1,1)],F=[new r("ic",-1,1),new r("abil",-1,1),new r("iv",-1,1)],S=[new r("ica",-1,1),new r("logia",-1,3),new r("osa",-1,1),new r("ista",-1,1),new r("iva",-1,9),new r("anza",-1,1),new r("enza",-1,5),new r("ice",-1,1),new r("atrice",7,1),new r("iche",-1,1),new r("logie",-1,3),new r("abile",-1,1),new r("ibile",-1,1),new r("usione",-1,4),new r("azione",-1,2),new r("uzione",-1,4),new r("atore",-1,2),new r("ose",-1,1),new r("ante",-1,1),new r("mente",-1,1),new r("amente",19,7),new r("iste",-1,1),new r("ive",-1,9),new r("anze",-1,1),new r("enze",-1,5),new r("ici",-1,1),new r("atrici",25,1),new r("ichi",-1,1),new r("abili",-1,1),new r("ibili",-1,1),new r("ismi",-1,1),new r("usioni",-1,4),new r("azioni",-1,2),new r("uzioni",-1,4),new r("atori",-1,2),new r("osi",-1,1),new r("anti",-1,1),new r("amenti",-1,6),new r("imenti",-1,6),new r("isti",-1,1),new r("ivi",-1,9),new r("ico",-1,1),new r("ismo",-1,1),new r("oso",-1,1),new r("amento",-1,6),new r("imento",-1,6),new r("ivo",-1,9),new r("ità",-1,8),new r("istà",-1,1),new r("istè",-1,1),new r("istì",-1,1)],W=[new r("isca",-1,1),new r("enda",-1,1),new r("ata",-1,1),new r("ita",-1,1),new r("uta",-1,1),new r("ava",-1,1),new r("eva",-1,1),new r("iva",-1,1),new r("erebbe",-1,1),new r("irebbe",-1,1),new r("isce",-1,1),new r("ende",-1,1),new r("are",-1,1),new r("ere",-1,1),new r("ire",-1,1),new r("asse",-1,1),new r("ate",-1,1),new r("avate",16,1),new r("evate",16,1),new r("ivate",16,1),new r("ete",-1,1),new r("erete",20,1),new r("irete",20,1),new r("ite",-1,1),new r("ereste",-1,1),new r("ireste",-1,1),new r("ute",-1,1),new r("erai",-1,1),new r("irai",-1,1),new r("isci",-1,1),new r("endi",-1,1),new r("erei",-1,1),new r("irei",-1,1),new r("assi",-1,1),new r("ati",-1,1),new r("iti",-1,1),new r("eresti",-1,1),new r("iresti",-1,1),new r("uti",-1,1),new r("avi",-1,1),new r("evi",-1,1),new r("ivi",-1,1),new r("isco",-1,1),new r("ando",-1,1),new r("endo",-1,1),new r("Yamo",-1,1),new r("iamo",-1,1),new r("avamo",-1,1),new r("evamo",-1,1),new r("ivamo",-1,1),new r("eremo",-1,1),new r("iremo",-1,1),new r("assimo",-1,1),new r("ammo",-1,1),new r("emmo",-1,1),new r("eremmo",54,1),new r("iremmo",54,1),new r("immo",-1,1),new r("ano",-1,1),new r("iscano",58,1),new r("avano",58,1),new r("evano",58,1),new r("ivano",58,1),new r("eranno",-1,1),new r("iranno",-1,1),new r("ono",-1,1),new r("iscono",65,1),new r("arono",65,1),new r("erono",65,1),new r("irono",65,1),new r("erebbero",-1,1),new r("irebbero",-1,1),new r("assero",-1,1),new r("essero",-1,1),new r("issero",-1,1),new r("ato",-1,1),new r("ito",-1,1),new r("uto",-1,1),new r("avo",-1,1),new r("evo",-1,1),new r("ivo",-1,1),new r("ar",-1,1),new r("ir",-1,1),new r("erà",-1,1),new r("irà",-1,1),new r("erò",-1,1),new r("irò",-1,1)],L=[17,65,16,0,0,0,0,0,0,0,0,0,0,0,0,128,128,8,2,1],y=[17,65,0,0,0,0,0,0,0,0,0,0,0,0,0,128,128,8,2],U=[17],x=new n;this.setCurrent=function(e){x.setCurrent(e)},this.getCurrent=function(){return x.getCurrent()},this.stem=function(){var e=x.cursor;return i(),x.cursor=e,u(),x.limit_backward=e,x.cursor=x.limit,f(),x.cursor=x.limit,v()||(x.cursor=x.limit,b()),x.cursor=x.limit,_(),x.cursor=x.limit_backward,c(),!0}};return function(e){return"function"==typeof e.update?e.update(function(e){return i.setCurrent(e),i.stem(),i.getCurrent()}):(i.setCurrent(e),i.stem(),i.getCurrent())}}(),e.Pipeline.registerFunction(e.it.stemmer,"stemmer-it"),e.it.stopWordFilter=e.generateStopWordFilter("a abbia abbiamo abbiano abbiate ad agl agli ai al all alla alle allo anche avemmo avendo avesse avessero avessi avessimo aveste avesti avete aveva avevamo avevano avevate avevi avevo avrai avranno avrebbe avrebbero avrei avremmo avremo avreste avresti avrete avrà avrò avuta avute avuti avuto c che chi ci coi col come con contro cui da dagl dagli dai dal dall dalla dalle dallo degl degli dei del dell della delle dello di dov dove e ebbe ebbero ebbi ed era erano eravamo eravate eri ero essendo faccia facciamo facciano facciate faccio facemmo facendo facesse facessero facessi facessimo faceste facesti faceva facevamo facevano facevate facevi facevo fai fanno farai faranno farebbe farebbero farei faremmo faremo fareste faresti farete farà farò fece fecero feci fosse fossero fossi fossimo foste fosti fu fui fummo furono gli ha hai hanno ho i il in io l la le lei li lo loro lui ma mi mia mie miei mio ne negl negli nei nel nell nella nelle nello noi non nostra nostre nostri nostro o per perché più quale quanta quante quanti quanto quella quelle quelli quello questa queste questi questo sarai saranno sarebbe sarebbero sarei saremmo saremo sareste saresti sarete sarà sarò se sei si sia siamo siano siate siete sono sta stai stando stanno starai staranno starebbe starebbero starei staremmo staremo stareste staresti starete starà starò stava stavamo stavano stavate stavi stavo stemmo stesse stessero stessi stessimo steste stesti stette stettero stetti stia stiamo stiano stiate sto su sua sue sugl sugli sui sul sull sulla sulle sullo suo suoi ti tra tu tua tue tuo tuoi tutti tutto un una uno vi voi vostra vostre vostri vostro è".split(" ")),e.Pipeline.registerFunction(e.it.stopWordFilter,"stopWordFilter-it")}}); \ No newline at end of file diff --git a/en/2021.7/assets/javascripts/lunr/min/lunr.ja.min.js b/en/2021.7/assets/javascripts/lunr/min/lunr.ja.min.js new file mode 100644 index 000000000..5f254ebe9 --- /dev/null +++ b/en/2021.7/assets/javascripts/lunr/min/lunr.ja.min.js @@ -0,0 +1 @@ +!function(e,r){"function"==typeof define&&define.amd?define(r):"object"==typeof exports?module.exports=r():r()(e.lunr)}(this,function(){return function(e){if(void 0===e)throw new Error("Lunr is not present. Please include / require Lunr before this script.");if(void 0===e.stemmerSupport)throw new Error("Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.");var r="2"==e.version[0];e.ja=function(){this.pipeline.reset(),this.pipeline.add(e.ja.trimmer,e.ja.stopWordFilter,e.ja.stemmer),r?this.tokenizer=e.ja.tokenizer:(e.tokenizer&&(e.tokenizer=e.ja.tokenizer),this.tokenizerFn&&(this.tokenizerFn=e.ja.tokenizer))};var t=new e.TinySegmenter;e.ja.tokenizer=function(i){var n,o,s,p,a,u,m,l,c,f;if(!arguments.length||null==i||void 0==i)return[];if(Array.isArray(i))return i.map(function(t){return r?new e.Token(t.toLowerCase()):t.toLowerCase()});for(o=i.toString().toLowerCase().replace(/^\s+/,""),n=o.length-1;n>=0;n--)if(/\S/.test(o.charAt(n))){o=o.substring(0,n+1);break}for(a=[],s=o.length,c=0,l=0;c<=s;c++)if(u=o.charAt(c),m=c-l,u.match(/\s/)||c==s){if(m>0)for(p=t.segment(o.slice(l,c)).filter(function(e){return!!e}),f=l,n=0;n=C.limit)break;C.cursor++;continue}break}for(C.cursor=o,C.bra=o,C.eq_s(1,"y")?(C.ket=C.cursor,C.slice_from("Y")):C.cursor=o;;)if(e=C.cursor,C.in_grouping(q,97,232)){if(i=C.cursor,C.bra=i,C.eq_s(1,"i"))C.ket=C.cursor,C.in_grouping(q,97,232)&&(C.slice_from("I"),C.cursor=e);else if(C.cursor=i,C.eq_s(1,"y"))C.ket=C.cursor,C.slice_from("Y"),C.cursor=e;else if(n(e))break}else if(n(e))break}function n(r){return C.cursor=r,r>=C.limit||(C.cursor++,!1)}function o(){_=C.limit,d=_,t()||(_=C.cursor,_<3&&(_=3),t()||(d=C.cursor))}function t(){for(;!C.in_grouping(q,97,232);){if(C.cursor>=C.limit)return!0;C.cursor++}for(;!C.out_grouping(q,97,232);){if(C.cursor>=C.limit)return!0;C.cursor++}return!1}function s(){for(var r;;)if(C.bra=C.cursor,r=C.find_among(p,3))switch(C.ket=C.cursor,r){case 1:C.slice_from("y");break;case 2:C.slice_from("i");break;case 3:if(C.cursor>=C.limit)return;C.cursor++}}function u(){return _<=C.cursor}function c(){return d<=C.cursor}function a(){var r=C.limit-C.cursor;C.find_among_b(g,3)&&(C.cursor=C.limit-r,C.ket=C.cursor,C.cursor>C.limit_backward&&(C.cursor--,C.bra=C.cursor,C.slice_del()))}function l(){var r;w=!1,C.ket=C.cursor,C.eq_s_b(1,"e")&&(C.bra=C.cursor,u()&&(r=C.limit-C.cursor,C.out_grouping_b(q,97,232)&&(C.cursor=C.limit-r,C.slice_del(),w=!0,a())))}function m(){var r;u()&&(r=C.limit-C.cursor,C.out_grouping_b(q,97,232)&&(C.cursor=C.limit-r,C.eq_s_b(3,"gem")||(C.cursor=C.limit-r,C.slice_del(),a())))}function f(){var r,e,i,n,o,t,s=C.limit-C.cursor;if(C.ket=C.cursor,r=C.find_among_b(h,5))switch(C.bra=C.cursor,r){case 1:u()&&C.slice_from("heid");break;case 2:m();break;case 3:u()&&C.out_grouping_b(j,97,232)&&C.slice_del()}if(C.cursor=C.limit-s,l(),C.cursor=C.limit-s,C.ket=C.cursor,C.eq_s_b(4,"heid")&&(C.bra=C.cursor,c()&&(e=C.limit-C.cursor,C.eq_s_b(1,"c")||(C.cursor=C.limit-e,C.slice_del(),C.ket=C.cursor,C.eq_s_b(2,"en")&&(C.bra=C.cursor,m())))),C.cursor=C.limit-s,C.ket=C.cursor,r=C.find_among_b(k,6))switch(C.bra=C.cursor,r){case 1:if(c()){if(C.slice_del(),i=C.limit-C.cursor,C.ket=C.cursor,C.eq_s_b(2,"ig")&&(C.bra=C.cursor,c()&&(n=C.limit-C.cursor,!C.eq_s_b(1,"e")))){C.cursor=C.limit-n,C.slice_del();break}C.cursor=C.limit-i,a()}break;case 2:c()&&(o=C.limit-C.cursor,C.eq_s_b(1,"e")||(C.cursor=C.limit-o,C.slice_del()));break;case 3:c()&&(C.slice_del(),l());break;case 4:c()&&C.slice_del();break;case 5:c()&&w&&C.slice_del()}C.cursor=C.limit-s,C.out_grouping_b(z,73,232)&&(t=C.limit-C.cursor,C.find_among_b(v,4)&&C.out_grouping_b(q,97,232)&&(C.cursor=C.limit-t,C.ket=C.cursor,C.cursor>C.limit_backward&&(C.cursor--,C.bra=C.cursor,C.slice_del())))}var d,_,w,b=[new e("",-1,6),new e("á",0,1),new e("ä",0,1),new e("é",0,2),new e("ë",0,2),new e("í",0,3),new e("ï",0,3),new e("ó",0,4),new e("ö",0,4),new e("ú",0,5),new e("ü",0,5)],p=[new e("",-1,3),new e("I",0,2),new e("Y",0,1)],g=[new e("dd",-1,-1),new e("kk",-1,-1),new e("tt",-1,-1)],h=[new e("ene",-1,2),new e("se",-1,3),new e("en",-1,2),new e("heden",2,1),new e("s",-1,3)],k=[new e("end",-1,1),new e("ig",-1,2),new e("ing",-1,1),new e("lijk",-1,3),new e("baar",-1,4),new e("bar",-1,5)],v=[new e("aa",-1,-1),new e("ee",-1,-1),new e("oo",-1,-1),new e("uu",-1,-1)],q=[17,65,16,1,0,0,0,0,0,0,0,0,0,0,0,0,128],z=[1,0,0,17,65,16,1,0,0,0,0,0,0,0,0,0,0,0,0,128],j=[17,67,16,1,0,0,0,0,0,0,0,0,0,0,0,0,128],C=new i;this.setCurrent=function(r){C.setCurrent(r)},this.getCurrent=function(){return C.getCurrent()},this.stem=function(){var e=C.cursor;return r(),C.cursor=e,o(),C.limit_backward=e,C.cursor=C.limit,f(),C.cursor=C.limit_backward,s(),!0}};return function(r){return"function"==typeof r.update?r.update(function(r){return n.setCurrent(r),n.stem(),n.getCurrent()}):(n.setCurrent(r),n.stem(),n.getCurrent())}}(),r.Pipeline.registerFunction(r.nl.stemmer,"stemmer-nl"),r.nl.stopWordFilter=r.generateStopWordFilter(" aan al alles als altijd andere ben bij daar dan dat de der deze die dit doch doen door dus een eens en er ge geen geweest haar had heb hebben heeft hem het hier hij hoe hun iemand iets ik in is ja je kan kon kunnen maar me meer men met mij mijn moet na naar niet niets nog nu of om omdat onder ons ook op over reeds te tegen toch toen tot u uit uw van veel voor want waren was wat werd wezen wie wil worden wordt zal ze zelf zich zij zijn zo zonder zou".split(" ")),r.Pipeline.registerFunction(r.nl.stopWordFilter,"stopWordFilter-nl")}}); \ No newline at end of file diff --git a/en/2021.7/assets/javascripts/lunr/min/lunr.no.min.js b/en/2021.7/assets/javascripts/lunr/min/lunr.no.min.js new file mode 100644 index 000000000..92bc7e4e8 --- /dev/null +++ b/en/2021.7/assets/javascripts/lunr/min/lunr.no.min.js @@ -0,0 +1,18 @@ +/*! + * Lunr languages, `Norwegian` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +!function(e,r){"function"==typeof define&&define.amd?define(r):"object"==typeof exports?module.exports=r():r()(e.lunr)}(this,function(){return function(e){if(void 0===e)throw new Error("Lunr is not present. Please include / require Lunr before this script.");if(void 0===e.stemmerSupport)throw new Error("Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.");e.no=function(){this.pipeline.reset(),this.pipeline.add(e.no.trimmer,e.no.stopWordFilter,e.no.stemmer),this.searchPipeline&&(this.searchPipeline.reset(),this.searchPipeline.add(e.no.stemmer))},e.no.wordCharacters="A-Za-zªºÀ-ÖØ-öø-ʸˠ-ˤᴀ-ᴥᴬ-ᵜᵢ-ᵥᵫ-ᵷᵹ-ᶾḀ-ỿⁱⁿₐ-ₜKÅℲⅎⅠ-ↈⱠ-ⱿꜢ-ꞇꞋ-ꞭꞰ-ꞷꟷ-ꟿꬰ-ꭚꭜ-ꭤff-stA-Za-z",e.no.trimmer=e.trimmerSupport.generateTrimmer(e.no.wordCharacters),e.Pipeline.registerFunction(e.no.trimmer,"trimmer-no"),e.no.stemmer=function(){var r=e.stemmerSupport.Among,n=e.stemmerSupport.SnowballProgram,i=new function(){function e(){var e,r=w.cursor+3;if(a=w.limit,0<=r||r<=w.limit){for(s=r;;){if(e=w.cursor,w.in_grouping(d,97,248)){w.cursor=e;break}if(e>=w.limit)return;w.cursor=e+1}for(;!w.out_grouping(d,97,248);){if(w.cursor>=w.limit)return;w.cursor++}a=w.cursor,a=a&&(r=w.limit_backward,w.limit_backward=a,w.ket=w.cursor,e=w.find_among_b(m,29),w.limit_backward=r,e))switch(w.bra=w.cursor,e){case 1:w.slice_del();break;case 2:n=w.limit-w.cursor,w.in_grouping_b(c,98,122)?w.slice_del():(w.cursor=w.limit-n,w.eq_s_b(1,"k")&&w.out_grouping_b(d,97,248)&&w.slice_del());break;case 3:w.slice_from("er")}}function t(){var e,r=w.limit-w.cursor;w.cursor>=a&&(e=w.limit_backward,w.limit_backward=a,w.ket=w.cursor,w.find_among_b(u,2)?(w.bra=w.cursor,w.limit_backward=e,w.cursor=w.limit-r,w.cursor>w.limit_backward&&(w.cursor--,w.bra=w.cursor,w.slice_del())):w.limit_backward=e)}function o(){var e,r;w.cursor>=a&&(r=w.limit_backward,w.limit_backward=a,w.ket=w.cursor,e=w.find_among_b(l,11),e?(w.bra=w.cursor,w.limit_backward=r,1==e&&w.slice_del()):w.limit_backward=r)}var s,a,m=[new r("a",-1,1),new r("e",-1,1),new r("ede",1,1),new r("ande",1,1),new r("ende",1,1),new r("ane",1,1),new r("ene",1,1),new r("hetene",6,1),new r("erte",1,3),new r("en",-1,1),new r("heten",9,1),new r("ar",-1,1),new r("er",-1,1),new r("heter",12,1),new r("s",-1,2),new r("as",14,1),new r("es",14,1),new r("edes",16,1),new r("endes",16,1),new r("enes",16,1),new r("hetenes",19,1),new r("ens",14,1),new r("hetens",21,1),new r("ers",14,1),new r("ets",14,1),new r("et",-1,1),new r("het",25,1),new r("ert",-1,3),new r("ast",-1,1)],u=[new r("dt",-1,-1),new r("vt",-1,-1)],l=[new r("leg",-1,1),new r("eleg",0,1),new r("ig",-1,1),new r("eig",2,1),new r("lig",2,1),new r("elig",4,1),new r("els",-1,1),new r("lov",-1,1),new r("elov",7,1),new r("slov",7,1),new r("hetslov",9,1)],d=[17,65,16,1,0,0,0,0,0,0,0,0,0,0,0,0,48,0,128],c=[119,125,149,1],w=new n;this.setCurrent=function(e){w.setCurrent(e)},this.getCurrent=function(){return w.getCurrent()},this.stem=function(){var r=w.cursor;return e(),w.limit_backward=r,w.cursor=w.limit,i(),w.cursor=w.limit,t(),w.cursor=w.limit,o(),!0}};return function(e){return"function"==typeof e.update?e.update(function(e){return i.setCurrent(e),i.stem(),i.getCurrent()}):(i.setCurrent(e),i.stem(),i.getCurrent())}}(),e.Pipeline.registerFunction(e.no.stemmer,"stemmer-no"),e.no.stopWordFilter=e.generateStopWordFilter("alle at av bare begge ble blei bli blir blitt både båe da de deg dei deim deira deires dem den denne der dere deres det dette di din disse ditt du dykk dykkar då eg ein eit eitt eller elles en enn er et ett etter for fordi fra før ha hadde han hans har hennar henne hennes her hjå ho hoe honom hoss hossen hun hva hvem hver hvilke hvilken hvis hvor hvordan hvorfor i ikke ikkje ikkje ingen ingi inkje inn inni ja jeg kan kom korleis korso kun kunne kva kvar kvarhelst kven kvi kvifor man mange me med medan meg meget mellom men mi min mine mitt mot mykje ned no noe noen noka noko nokon nokor nokre nå når og også om opp oss over på samme seg selv si si sia sidan siden sin sine sitt sjøl skal skulle slik so som som somme somt så sånn til um upp ut uten var vart varte ved vere verte vi vil ville vore vors vort vår være være vært å".split(" ")),e.Pipeline.registerFunction(e.no.stopWordFilter,"stopWordFilter-no")}}); \ No newline at end of file diff --git a/en/2021.7/assets/javascripts/lunr/min/lunr.pt.min.js b/en/2021.7/assets/javascripts/lunr/min/lunr.pt.min.js new file mode 100644 index 000000000..6c16996d6 --- /dev/null +++ b/en/2021.7/assets/javascripts/lunr/min/lunr.pt.min.js @@ -0,0 +1,18 @@ +/*! + * Lunr languages, `Portuguese` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +!function(e,r){"function"==typeof define&&define.amd?define(r):"object"==typeof exports?module.exports=r():r()(e.lunr)}(this,function(){return function(e){if(void 0===e)throw new Error("Lunr is not present. Please include / require Lunr before this script.");if(void 0===e.stemmerSupport)throw new Error("Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.");e.pt=function(){this.pipeline.reset(),this.pipeline.add(e.pt.trimmer,e.pt.stopWordFilter,e.pt.stemmer),this.searchPipeline&&(this.searchPipeline.reset(),this.searchPipeline.add(e.pt.stemmer))},e.pt.wordCharacters="A-Za-zªºÀ-ÖØ-öø-ʸˠ-ˤᴀ-ᴥᴬ-ᵜᵢ-ᵥᵫ-ᵷᵹ-ᶾḀ-ỿⁱⁿₐ-ₜKÅℲⅎⅠ-ↈⱠ-ⱿꜢ-ꞇꞋ-ꞭꞰ-ꞷꟷ-ꟿꬰ-ꭚꭜ-ꭤff-stA-Za-z",e.pt.trimmer=e.trimmerSupport.generateTrimmer(e.pt.wordCharacters),e.Pipeline.registerFunction(e.pt.trimmer,"trimmer-pt"),e.pt.stemmer=function(){var r=e.stemmerSupport.Among,s=e.stemmerSupport.SnowballProgram,n=new function(){function e(){for(var e;;){if(z.bra=z.cursor,e=z.find_among(k,3))switch(z.ket=z.cursor,e){case 1:z.slice_from("a~");continue;case 2:z.slice_from("o~");continue;case 3:if(z.cursor>=z.limit)break;z.cursor++;continue}break}}function n(){if(z.out_grouping(y,97,250)){for(;!z.in_grouping(y,97,250);){if(z.cursor>=z.limit)return!0;z.cursor++}return!1}return!0}function i(){if(z.in_grouping(y,97,250))for(;!z.out_grouping(y,97,250);){if(z.cursor>=z.limit)return!1;z.cursor++}return g=z.cursor,!0}function o(){var e,r,s=z.cursor;if(z.in_grouping(y,97,250))if(e=z.cursor,n()){if(z.cursor=e,i())return}else g=z.cursor;if(z.cursor=s,z.out_grouping(y,97,250)){if(r=z.cursor,n()){if(z.cursor=r,!z.in_grouping(y,97,250)||z.cursor>=z.limit)return;z.cursor++}g=z.cursor}}function t(){for(;!z.in_grouping(y,97,250);){if(z.cursor>=z.limit)return!1;z.cursor++}for(;!z.out_grouping(y,97,250);){if(z.cursor>=z.limit)return!1;z.cursor++}return!0}function a(){var e=z.cursor;g=z.limit,b=g,h=g,o(),z.cursor=e,t()&&(b=z.cursor,t()&&(h=z.cursor))}function u(){for(var e;;){if(z.bra=z.cursor,e=z.find_among(q,3))switch(z.ket=z.cursor,e){case 1:z.slice_from("ã");continue;case 2:z.slice_from("õ");continue;case 3:if(z.cursor>=z.limit)break;z.cursor++;continue}break}}function w(){return g<=z.cursor}function m(){return b<=z.cursor}function c(){return h<=z.cursor}function l(){var e;if(z.ket=z.cursor,!(e=z.find_among_b(F,45)))return!1;switch(z.bra=z.cursor,e){case 1:if(!c())return!1;z.slice_del();break;case 2:if(!c())return!1;z.slice_from("log");break;case 3:if(!c())return!1;z.slice_from("u");break;case 4:if(!c())return!1;z.slice_from("ente");break;case 5:if(!m())return!1;z.slice_del(),z.ket=z.cursor,e=z.find_among_b(j,4),e&&(z.bra=z.cursor,c()&&(z.slice_del(),1==e&&(z.ket=z.cursor,z.eq_s_b(2,"at")&&(z.bra=z.cursor,c()&&z.slice_del()))));break;case 6:if(!c())return!1;z.slice_del(),z.ket=z.cursor,e=z.find_among_b(C,3),e&&(z.bra=z.cursor,1==e&&c()&&z.slice_del());break;case 7:if(!c())return!1;z.slice_del(),z.ket=z.cursor,e=z.find_among_b(P,3),e&&(z.bra=z.cursor,1==e&&c()&&z.slice_del());break;case 8:if(!c())return!1;z.slice_del(),z.ket=z.cursor,z.eq_s_b(2,"at")&&(z.bra=z.cursor,c()&&z.slice_del());break;case 9:if(!w()||!z.eq_s_b(1,"e"))return!1;z.slice_from("ir")}return!0}function f(){var e,r;if(z.cursor>=g){if(r=z.limit_backward,z.limit_backward=g,z.ket=z.cursor,e=z.find_among_b(S,120))return z.bra=z.cursor,1==e&&z.slice_del(),z.limit_backward=r,!0;z.limit_backward=r}return!1}function d(){var e;z.ket=z.cursor,(e=z.find_among_b(W,7))&&(z.bra=z.cursor,1==e&&w()&&z.slice_del())}function v(e,r){if(z.eq_s_b(1,e)){z.bra=z.cursor;var s=z.limit-z.cursor;if(z.eq_s_b(1,r))return z.cursor=z.limit-s,w()&&z.slice_del(),!1}return!0}function p(){var e;if(z.ket=z.cursor,e=z.find_among_b(L,4))switch(z.bra=z.cursor,e){case 1:w()&&(z.slice_del(),z.ket=z.cursor,z.limit-z.cursor,v("u","g")&&v("i","c"));break;case 2:z.slice_from("c")}}function _(){if(!l()&&(z.cursor=z.limit,!f()))return z.cursor=z.limit,void d();z.cursor=z.limit,z.ket=z.cursor,z.eq_s_b(1,"i")&&(z.bra=z.cursor,z.eq_s_b(1,"c")&&(z.cursor=z.limit,w()&&z.slice_del()))}var h,b,g,k=[new r("",-1,3),new r("ã",0,1),new r("õ",0,2)],q=[new r("",-1,3),new r("a~",0,1),new r("o~",0,2)],j=[new r("ic",-1,-1),new r("ad",-1,-1),new r("os",-1,-1),new r("iv",-1,1)],C=[new r("ante",-1,1),new r("avel",-1,1),new r("ível",-1,1)],P=[new r("ic",-1,1),new r("abil",-1,1),new r("iv",-1,1)],F=[new r("ica",-1,1),new r("ância",-1,1),new r("ência",-1,4),new r("ira",-1,9),new r("adora",-1,1),new r("osa",-1,1),new r("ista",-1,1),new r("iva",-1,8),new r("eza",-1,1),new r("logía",-1,2),new r("idade",-1,7),new r("ante",-1,1),new r("mente",-1,6),new r("amente",12,5),new r("ável",-1,1),new r("ível",-1,1),new r("ución",-1,3),new r("ico",-1,1),new r("ismo",-1,1),new r("oso",-1,1),new r("amento",-1,1),new r("imento",-1,1),new r("ivo",-1,8),new r("aça~o",-1,1),new r("ador",-1,1),new r("icas",-1,1),new r("ências",-1,4),new r("iras",-1,9),new r("adoras",-1,1),new r("osas",-1,1),new r("istas",-1,1),new r("ivas",-1,8),new r("ezas",-1,1),new r("logías",-1,2),new r("idades",-1,7),new r("uciones",-1,3),new r("adores",-1,1),new r("antes",-1,1),new r("aço~es",-1,1),new r("icos",-1,1),new r("ismos",-1,1),new r("osos",-1,1),new r("amentos",-1,1),new r("imentos",-1,1),new r("ivos",-1,8)],S=[new r("ada",-1,1),new r("ida",-1,1),new r("ia",-1,1),new r("aria",2,1),new r("eria",2,1),new r("iria",2,1),new r("ara",-1,1),new r("era",-1,1),new r("ira",-1,1),new r("ava",-1,1),new r("asse",-1,1),new r("esse",-1,1),new r("isse",-1,1),new r("aste",-1,1),new r("este",-1,1),new r("iste",-1,1),new r("ei",-1,1),new r("arei",16,1),new r("erei",16,1),new r("irei",16,1),new r("am",-1,1),new r("iam",20,1),new r("ariam",21,1),new r("eriam",21,1),new r("iriam",21,1),new r("aram",20,1),new r("eram",20,1),new r("iram",20,1),new r("avam",20,1),new r("em",-1,1),new r("arem",29,1),new r("erem",29,1),new r("irem",29,1),new r("assem",29,1),new r("essem",29,1),new r("issem",29,1),new r("ado",-1,1),new r("ido",-1,1),new r("ando",-1,1),new r("endo",-1,1),new r("indo",-1,1),new r("ara~o",-1,1),new r("era~o",-1,1),new r("ira~o",-1,1),new r("ar",-1,1),new r("er",-1,1),new r("ir",-1,1),new r("as",-1,1),new r("adas",47,1),new r("idas",47,1),new r("ias",47,1),new r("arias",50,1),new r("erias",50,1),new r("irias",50,1),new r("aras",47,1),new r("eras",47,1),new r("iras",47,1),new r("avas",47,1),new r("es",-1,1),new r("ardes",58,1),new r("erdes",58,1),new r("irdes",58,1),new r("ares",58,1),new r("eres",58,1),new r("ires",58,1),new r("asses",58,1),new r("esses",58,1),new r("isses",58,1),new r("astes",58,1),new r("estes",58,1),new r("istes",58,1),new r("is",-1,1),new r("ais",71,1),new r("eis",71,1),new r("areis",73,1),new r("ereis",73,1),new r("ireis",73,1),new r("áreis",73,1),new r("éreis",73,1),new r("íreis",73,1),new r("ásseis",73,1),new r("ésseis",73,1),new r("ísseis",73,1),new r("áveis",73,1),new r("íeis",73,1),new r("aríeis",84,1),new r("eríeis",84,1),new r("iríeis",84,1),new r("ados",-1,1),new r("idos",-1,1),new r("amos",-1,1),new r("áramos",90,1),new r("éramos",90,1),new r("íramos",90,1),new r("ávamos",90,1),new r("íamos",90,1),new r("aríamos",95,1),new r("eríamos",95,1),new r("iríamos",95,1),new r("emos",-1,1),new r("aremos",99,1),new r("eremos",99,1),new r("iremos",99,1),new r("ássemos",99,1),new r("êssemos",99,1),new r("íssemos",99,1),new r("imos",-1,1),new r("armos",-1,1),new r("ermos",-1,1),new r("irmos",-1,1),new r("ámos",-1,1),new r("arás",-1,1),new r("erás",-1,1),new r("irás",-1,1),new r("eu",-1,1),new r("iu",-1,1),new r("ou",-1,1),new r("ará",-1,1),new r("erá",-1,1),new r("irá",-1,1)],W=[new r("a",-1,1),new r("i",-1,1),new r("o",-1,1),new r("os",-1,1),new r("á",-1,1),new r("í",-1,1),new r("ó",-1,1)],L=[new r("e",-1,1),new r("ç",-1,2),new r("é",-1,1),new r("ê",-1,1)],y=[17,65,16,0,0,0,0,0,0,0,0,0,0,0,0,0,3,19,12,2],z=new s;this.setCurrent=function(e){z.setCurrent(e)},this.getCurrent=function(){return z.getCurrent()},this.stem=function(){var r=z.cursor;return e(),z.cursor=r,a(),z.limit_backward=r,z.cursor=z.limit,_(),z.cursor=z.limit,p(),z.cursor=z.limit_backward,u(),!0}};return function(e){return"function"==typeof e.update?e.update(function(e){return n.setCurrent(e),n.stem(),n.getCurrent()}):(n.setCurrent(e),n.stem(),n.getCurrent())}}(),e.Pipeline.registerFunction(e.pt.stemmer,"stemmer-pt"),e.pt.stopWordFilter=e.generateStopWordFilter("a ao aos aquela aquelas aquele aqueles aquilo as até com como da das de dela delas dele deles depois do dos e ela elas ele eles em entre era eram essa essas esse esses esta estamos estas estava estavam este esteja estejam estejamos estes esteve estive estivemos estiver estivera estiveram estiverem estivermos estivesse estivessem estivéramos estivéssemos estou está estávamos estão eu foi fomos for fora foram forem formos fosse fossem fui fôramos fôssemos haja hajam hajamos havemos hei houve houvemos houver houvera houveram houverei houverem houveremos houveria houveriam houvermos houverá houverão houveríamos houvesse houvessem houvéramos houvéssemos há hão isso isto já lhe lhes mais mas me mesmo meu meus minha minhas muito na nas nem no nos nossa nossas nosso nossos num numa não nós o os ou para pela pelas pelo pelos por qual quando que quem se seja sejam sejamos sem serei seremos seria seriam será serão seríamos seu seus somos sou sua suas são só também te tem temos tenha tenham tenhamos tenho terei teremos teria teriam terá terão teríamos teu teus teve tinha tinham tive tivemos tiver tivera tiveram tiverem tivermos tivesse tivessem tivéramos tivéssemos tu tua tuas tém tínhamos um uma você vocês vos à às éramos".split(" ")),e.Pipeline.registerFunction(e.pt.stopWordFilter,"stopWordFilter-pt")}}); \ No newline at end of file diff --git a/en/2021.7/assets/javascripts/lunr/min/lunr.ro.min.js b/en/2021.7/assets/javascripts/lunr/min/lunr.ro.min.js new file mode 100644 index 000000000..727714018 --- /dev/null +++ b/en/2021.7/assets/javascripts/lunr/min/lunr.ro.min.js @@ -0,0 +1,18 @@ +/*! + * Lunr languages, `Romanian` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +!function(e,i){"function"==typeof define&&define.amd?define(i):"object"==typeof exports?module.exports=i():i()(e.lunr)}(this,function(){return function(e){if(void 0===e)throw new Error("Lunr is not present. Please include / require Lunr before this script.");if(void 0===e.stemmerSupport)throw new Error("Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.");e.ro=function(){this.pipeline.reset(),this.pipeline.add(e.ro.trimmer,e.ro.stopWordFilter,e.ro.stemmer),this.searchPipeline&&(this.searchPipeline.reset(),this.searchPipeline.add(e.ro.stemmer))},e.ro.wordCharacters="A-Za-zªºÀ-ÖØ-öø-ʸˠ-ˤᴀ-ᴥᴬ-ᵜᵢ-ᵥᵫ-ᵷᵹ-ᶾḀ-ỿⁱⁿₐ-ₜKÅℲⅎⅠ-ↈⱠ-ⱿꜢ-ꞇꞋ-ꞭꞰ-ꞷꟷ-ꟿꬰ-ꭚꭜ-ꭤff-stA-Za-z",e.ro.trimmer=e.trimmerSupport.generateTrimmer(e.ro.wordCharacters),e.Pipeline.registerFunction(e.ro.trimmer,"trimmer-ro"),e.ro.stemmer=function(){var i=e.stemmerSupport.Among,r=e.stemmerSupport.SnowballProgram,n=new function(){function e(e,i){L.eq_s(1,e)&&(L.ket=L.cursor,L.in_grouping(W,97,259)&&L.slice_from(i))}function n(){for(var i,r;;){if(i=L.cursor,L.in_grouping(W,97,259)&&(r=L.cursor,L.bra=r,e("u","U"),L.cursor=r,e("i","I")),L.cursor=i,L.cursor>=L.limit)break;L.cursor++}}function t(){if(L.out_grouping(W,97,259)){for(;!L.in_grouping(W,97,259);){if(L.cursor>=L.limit)return!0;L.cursor++}return!1}return!0}function a(){if(L.in_grouping(W,97,259))for(;!L.out_grouping(W,97,259);){if(L.cursor>=L.limit)return!0;L.cursor++}return!1}function o(){var e,i,r=L.cursor;if(L.in_grouping(W,97,259)){if(e=L.cursor,!t())return void(h=L.cursor);if(L.cursor=e,!a())return void(h=L.cursor)}L.cursor=r,L.out_grouping(W,97,259)&&(i=L.cursor,t()&&(L.cursor=i,L.in_grouping(W,97,259)&&L.cursor=L.limit)return!1;L.cursor++}for(;!L.out_grouping(W,97,259);){if(L.cursor>=L.limit)return!1;L.cursor++}return!0}function c(){var e=L.cursor;h=L.limit,k=h,g=h,o(),L.cursor=e,u()&&(k=L.cursor,u()&&(g=L.cursor))}function s(){for(var e;;){if(L.bra=L.cursor,e=L.find_among(z,3))switch(L.ket=L.cursor,e){case 1:L.slice_from("i");continue;case 2:L.slice_from("u");continue;case 3:if(L.cursor>=L.limit)break;L.cursor++;continue}break}}function w(){return h<=L.cursor}function m(){return k<=L.cursor}function l(){return g<=L.cursor}function f(){var e,i;if(L.ket=L.cursor,(e=L.find_among_b(C,16))&&(L.bra=L.cursor,m()))switch(e){case 1:L.slice_del();break;case 2:L.slice_from("a");break;case 3:L.slice_from("e");break;case 4:L.slice_from("i");break;case 5:i=L.limit-L.cursor,L.eq_s_b(2,"ab")||(L.cursor=L.limit-i,L.slice_from("i"));break;case 6:L.slice_from("at");break;case 7:L.slice_from("aţi")}}function p(){var e,i=L.limit-L.cursor;if(L.ket=L.cursor,(e=L.find_among_b(P,46))&&(L.bra=L.cursor,m())){switch(e){case 1:L.slice_from("abil");break;case 2:L.slice_from("ibil");break;case 3:L.slice_from("iv");break;case 4:L.slice_from("ic");break;case 5:L.slice_from("at");break;case 6:L.slice_from("it")}return _=!0,L.cursor=L.limit-i,!0}return!1}function d(){var e,i;for(_=!1;;)if(i=L.limit-L.cursor,!p()){L.cursor=L.limit-i;break}if(L.ket=L.cursor,(e=L.find_among_b(F,62))&&(L.bra=L.cursor,l())){switch(e){case 1:L.slice_del();break;case 2:L.eq_s_b(1,"ţ")&&(L.bra=L.cursor,L.slice_from("t"));break;case 3:L.slice_from("ist")}_=!0}}function b(){var e,i,r;if(L.cursor>=h){if(i=L.limit_backward,L.limit_backward=h,L.ket=L.cursor,e=L.find_among_b(q,94))switch(L.bra=L.cursor,e){case 1:if(r=L.limit-L.cursor,!L.out_grouping_b(W,97,259)&&(L.cursor=L.limit-r,!L.eq_s_b(1,"u")))break;case 2:L.slice_del()}L.limit_backward=i}}function v(){var e;L.ket=L.cursor,(e=L.find_among_b(S,5))&&(L.bra=L.cursor,w()&&1==e&&L.slice_del())}var _,g,k,h,z=[new i("",-1,3),new i("I",0,1),new i("U",0,2)],C=[new i("ea",-1,3),new i("aţia",-1,7),new i("aua",-1,2),new i("iua",-1,4),new i("aţie",-1,7),new i("ele",-1,3),new i("ile",-1,5),new i("iile",6,4),new i("iei",-1,4),new i("atei",-1,6),new i("ii",-1,4),new i("ului",-1,1),new i("ul",-1,1),new i("elor",-1,3),new i("ilor",-1,4),new i("iilor",14,4)],P=[new i("icala",-1,4),new i("iciva",-1,4),new i("ativa",-1,5),new i("itiva",-1,6),new i("icale",-1,4),new i("aţiune",-1,5),new i("iţiune",-1,6),new i("atoare",-1,5),new i("itoare",-1,6),new i("ătoare",-1,5),new i("icitate",-1,4),new i("abilitate",-1,1),new i("ibilitate",-1,2),new i("ivitate",-1,3),new i("icive",-1,4),new i("ative",-1,5),new i("itive",-1,6),new i("icali",-1,4),new i("atori",-1,5),new i("icatori",18,4),new i("itori",-1,6),new i("ători",-1,5),new i("icitati",-1,4),new i("abilitati",-1,1),new i("ivitati",-1,3),new i("icivi",-1,4),new i("ativi",-1,5),new i("itivi",-1,6),new i("icităi",-1,4),new i("abilităi",-1,1),new i("ivităi",-1,3),new i("icităţi",-1,4),new i("abilităţi",-1,1),new i("ivităţi",-1,3),new i("ical",-1,4),new i("ator",-1,5),new i("icator",35,4),new i("itor",-1,6),new i("ător",-1,5),new i("iciv",-1,4),new i("ativ",-1,5),new i("itiv",-1,6),new i("icală",-1,4),new i("icivă",-1,4),new i("ativă",-1,5),new i("itivă",-1,6)],F=[new i("ica",-1,1),new i("abila",-1,1),new i("ibila",-1,1),new i("oasa",-1,1),new i("ata",-1,1),new i("ita",-1,1),new i("anta",-1,1),new i("ista",-1,3),new i("uta",-1,1),new i("iva",-1,1),new i("ic",-1,1),new i("ice",-1,1),new i("abile",-1,1),new i("ibile",-1,1),new i("isme",-1,3),new i("iune",-1,2),new i("oase",-1,1),new i("ate",-1,1),new i("itate",17,1),new i("ite",-1,1),new i("ante",-1,1),new i("iste",-1,3),new i("ute",-1,1),new i("ive",-1,1),new i("ici",-1,1),new i("abili",-1,1),new i("ibili",-1,1),new i("iuni",-1,2),new i("atori",-1,1),new i("osi",-1,1),new i("ati",-1,1),new i("itati",30,1),new i("iti",-1,1),new i("anti",-1,1),new i("isti",-1,3),new i("uti",-1,1),new i("işti",-1,3),new i("ivi",-1,1),new i("ităi",-1,1),new i("oşi",-1,1),new i("ităţi",-1,1),new i("abil",-1,1),new i("ibil",-1,1),new i("ism",-1,3),new i("ator",-1,1),new i("os",-1,1),new i("at",-1,1),new i("it",-1,1),new i("ant",-1,1),new i("ist",-1,3),new i("ut",-1,1),new i("iv",-1,1),new i("ică",-1,1),new i("abilă",-1,1),new i("ibilă",-1,1),new i("oasă",-1,1),new i("ată",-1,1),new i("ită",-1,1),new i("antă",-1,1),new i("istă",-1,3),new i("ută",-1,1),new i("ivă",-1,1)],q=[new i("ea",-1,1),new i("ia",-1,1),new i("esc",-1,1),new i("ăsc",-1,1),new i("ind",-1,1),new i("ând",-1,1),new i("are",-1,1),new i("ere",-1,1),new i("ire",-1,1),new i("âre",-1,1),new i("se",-1,2),new i("ase",10,1),new i("sese",10,2),new i("ise",10,1),new i("use",10,1),new i("âse",10,1),new i("eşte",-1,1),new i("ăşte",-1,1),new i("eze",-1,1),new i("ai",-1,1),new i("eai",19,1),new i("iai",19,1),new i("sei",-1,2),new i("eşti",-1,1),new i("ăşti",-1,1),new i("ui",-1,1),new i("ezi",-1,1),new i("âi",-1,1),new i("aşi",-1,1),new i("seşi",-1,2),new i("aseşi",29,1),new i("seseşi",29,2),new i("iseşi",29,1),new i("useşi",29,1),new i("âseşi",29,1),new i("işi",-1,1),new i("uşi",-1,1),new i("âşi",-1,1),new i("aţi",-1,2),new i("eaţi",38,1),new i("iaţi",38,1),new i("eţi",-1,2),new i("iţi",-1,2),new i("âţi",-1,2),new i("arăţi",-1,1),new i("serăţi",-1,2),new i("aserăţi",45,1),new i("seserăţi",45,2),new i("iserăţi",45,1),new i("userăţi",45,1),new i("âserăţi",45,1),new i("irăţi",-1,1),new i("urăţi",-1,1),new i("ârăţi",-1,1),new i("am",-1,1),new i("eam",54,1),new i("iam",54,1),new i("em",-1,2),new i("asem",57,1),new i("sesem",57,2),new i("isem",57,1),new i("usem",57,1),new i("âsem",57,1),new i("im",-1,2),new i("âm",-1,2),new i("ăm",-1,2),new i("arăm",65,1),new i("serăm",65,2),new i("aserăm",67,1),new i("seserăm",67,2),new i("iserăm",67,1),new i("userăm",67,1),new i("âserăm",67,1),new i("irăm",65,1),new i("urăm",65,1),new i("ârăm",65,1),new i("au",-1,1),new i("eau",76,1),new i("iau",76,1),new i("indu",-1,1),new i("ându",-1,1),new i("ez",-1,1),new i("ească",-1,1),new i("ară",-1,1),new i("seră",-1,2),new i("aseră",84,1),new i("seseră",84,2),new i("iseră",84,1),new i("useră",84,1),new i("âseră",84,1),new i("iră",-1,1),new i("ură",-1,1),new i("âră",-1,1),new i("ează",-1,1)],S=[new i("a",-1,1),new i("e",-1,1),new i("ie",1,1),new i("i",-1,1),new i("ă",-1,1)],W=[17,65,16,0,0,0,0,0,0,0,0,0,0,0,0,0,2,32,0,0,4],L=new r;this.setCurrent=function(e){L.setCurrent(e)},this.getCurrent=function(){return L.getCurrent()},this.stem=function(){var e=L.cursor;return n(),L.cursor=e,c(),L.limit_backward=e,L.cursor=L.limit,f(),L.cursor=L.limit,d(),L.cursor=L.limit,_||(L.cursor=L.limit,b(),L.cursor=L.limit),v(),L.cursor=L.limit_backward,s(),!0}};return function(e){return"function"==typeof e.update?e.update(function(e){return n.setCurrent(e),n.stem(),n.getCurrent()}):(n.setCurrent(e),n.stem(),n.getCurrent())}}(),e.Pipeline.registerFunction(e.ro.stemmer,"stemmer-ro"),e.ro.stopWordFilter=e.generateStopWordFilter("acea aceasta această aceea acei aceia acel acela acele acelea acest acesta aceste acestea aceşti aceştia acolo acord acum ai aia aibă aici al ale alea altceva altcineva am ar are asemenea asta astea astăzi asupra au avea avem aveţi azi aş aşadar aţi bine bucur bună ca care caut ce cel ceva chiar cinci cine cineva contra cu cum cumva curând curînd când cât câte câtva câţi cînd cît cîte cîtva cîţi că căci cărei căror cărui către da dacă dar datorită dată dau de deci deja deoarece departe deşi din dinaintea dintr- dintre doi doilea două drept după dă ea ei el ele eram este eu eşti face fata fi fie fiecare fii fim fiu fiţi frumos fără graţie halbă iar ieri la le li lor lui lângă lîngă mai mea mei mele mereu meu mi mie mine mult multă mulţi mulţumesc mâine mîine mă ne nevoie nici nicăieri nimeni nimeri nimic nişte noastre noastră noi noroc nostru nouă noştri nu opt ori oricare orice oricine oricum oricând oricât oricînd oricît oriunde patra patru patrulea pe pentru peste pic poate pot prea prima primul prin puţin puţina puţină până pînă rog sa sale sau se spate spre sub sunt suntem sunteţi sută sînt sîntem sînteţi să săi său ta tale te timp tine toate toată tot totuşi toţi trei treia treilea tu tăi tău un una unde undeva unei uneia unele uneori unii unor unora unu unui unuia unul vi voastre voastră voi vostru vouă voştri vreme vreo vreun vă zece zero zi zice îi îl îmi împotriva în înainte înaintea încotro încât încît între întrucât întrucît îţi ăla ălea ăsta ăstea ăştia şapte şase şi ştiu ţi ţie".split(" ")),e.Pipeline.registerFunction(e.ro.stopWordFilter,"stopWordFilter-ro")}}); \ No newline at end of file diff --git a/en/2021.7/assets/javascripts/lunr/min/lunr.ru.min.js b/en/2021.7/assets/javascripts/lunr/min/lunr.ru.min.js new file mode 100644 index 000000000..186cc485c --- /dev/null +++ b/en/2021.7/assets/javascripts/lunr/min/lunr.ru.min.js @@ -0,0 +1,18 @@ +/*! + * Lunr languages, `Russian` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +!function(e,n){"function"==typeof define&&define.amd?define(n):"object"==typeof exports?module.exports=n():n()(e.lunr)}(this,function(){return function(e){if(void 0===e)throw new Error("Lunr is not present. Please include / require Lunr before this script.");if(void 0===e.stemmerSupport)throw new Error("Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.");e.ru=function(){this.pipeline.reset(),this.pipeline.add(e.ru.trimmer,e.ru.stopWordFilter,e.ru.stemmer),this.searchPipeline&&(this.searchPipeline.reset(),this.searchPipeline.add(e.ru.stemmer))},e.ru.wordCharacters="Ѐ-҄҇-ԯᴫᵸⷠ-ⷿꙀ-ꚟ︮︯",e.ru.trimmer=e.trimmerSupport.generateTrimmer(e.ru.wordCharacters),e.Pipeline.registerFunction(e.ru.trimmer,"trimmer-ru"),e.ru.stemmer=function(){var n=e.stemmerSupport.Among,r=e.stemmerSupport.SnowballProgram,t=new function(){function e(){for(;!W.in_grouping(S,1072,1103);){if(W.cursor>=W.limit)return!1;W.cursor++}return!0}function t(){for(;!W.out_grouping(S,1072,1103);){if(W.cursor>=W.limit)return!1;W.cursor++}return!0}function w(){b=W.limit,_=b,e()&&(b=W.cursor,t()&&e()&&t()&&(_=W.cursor))}function i(){return _<=W.cursor}function u(e,n){var r,t;if(W.ket=W.cursor,r=W.find_among_b(e,n)){switch(W.bra=W.cursor,r){case 1:if(t=W.limit-W.cursor,!W.eq_s_b(1,"а")&&(W.cursor=W.limit-t,!W.eq_s_b(1,"я")))return!1;case 2:W.slice_del()}return!0}return!1}function o(){return u(h,9)}function s(e,n){var r;return W.ket=W.cursor,!!(r=W.find_among_b(e,n))&&(W.bra=W.cursor,1==r&&W.slice_del(),!0)}function c(){return s(g,26)}function m(){return!!c()&&(u(C,8),!0)}function f(){return s(k,2)}function l(){return u(P,46)}function a(){s(v,36)}function p(){var e;W.ket=W.cursor,(e=W.find_among_b(F,2))&&(W.bra=W.cursor,i()&&1==e&&W.slice_del())}function d(){var e;if(W.ket=W.cursor,e=W.find_among_b(q,4))switch(W.bra=W.cursor,e){case 1:if(W.slice_del(),W.ket=W.cursor,!W.eq_s_b(1,"н"))break;W.bra=W.cursor;case 2:if(!W.eq_s_b(1,"н"))break;case 3:W.slice_del()}}var _,b,h=[new n("в",-1,1),new n("ив",0,2),new n("ыв",0,2),new n("вши",-1,1),new n("ивши",3,2),new n("ывши",3,2),new n("вшись",-1,1),new n("ившись",6,2),new n("ывшись",6,2)],g=[new n("ее",-1,1),new n("ие",-1,1),new n("ое",-1,1),new n("ые",-1,1),new n("ими",-1,1),new n("ыми",-1,1),new n("ей",-1,1),new n("ий",-1,1),new n("ой",-1,1),new n("ый",-1,1),new n("ем",-1,1),new n("им",-1,1),new n("ом",-1,1),new n("ым",-1,1),new n("его",-1,1),new n("ого",-1,1),new n("ему",-1,1),new n("ому",-1,1),new n("их",-1,1),new n("ых",-1,1),new n("ею",-1,1),new n("ою",-1,1),new n("ую",-1,1),new n("юю",-1,1),new n("ая",-1,1),new n("яя",-1,1)],C=[new n("ем",-1,1),new n("нн",-1,1),new n("вш",-1,1),new n("ивш",2,2),new n("ывш",2,2),new n("щ",-1,1),new n("ющ",5,1),new n("ующ",6,2)],k=[new n("сь",-1,1),new n("ся",-1,1)],P=[new n("ла",-1,1),new n("ила",0,2),new n("ыла",0,2),new n("на",-1,1),new n("ена",3,2),new n("ете",-1,1),new n("ите",-1,2),new n("йте",-1,1),new n("ейте",7,2),new n("уйте",7,2),new n("ли",-1,1),new n("или",10,2),new n("ыли",10,2),new n("й",-1,1),new n("ей",13,2),new n("уй",13,2),new n("л",-1,1),new n("ил",16,2),new n("ыл",16,2),new n("ем",-1,1),new n("им",-1,2),new n("ым",-1,2),new n("н",-1,1),new n("ен",22,2),new n("ло",-1,1),new n("ило",24,2),new n("ыло",24,2),new n("но",-1,1),new n("ено",27,2),new n("нно",27,1),new n("ет",-1,1),new n("ует",30,2),new n("ит",-1,2),new n("ыт",-1,2),new n("ют",-1,1),new n("уют",34,2),new n("ят",-1,2),new n("ны",-1,1),new n("ены",37,2),new n("ть",-1,1),new n("ить",39,2),new n("ыть",39,2),new n("ешь",-1,1),new n("ишь",-1,2),new n("ю",-1,2),new n("ую",44,2)],v=[new n("а",-1,1),new n("ев",-1,1),new n("ов",-1,1),new n("е",-1,1),new n("ие",3,1),new n("ье",3,1),new n("и",-1,1),new n("еи",6,1),new n("ии",6,1),new n("ами",6,1),new n("ями",6,1),new n("иями",10,1),new n("й",-1,1),new n("ей",12,1),new n("ией",13,1),new n("ий",12,1),new n("ой",12,1),new n("ам",-1,1),new n("ем",-1,1),new n("ием",18,1),new n("ом",-1,1),new n("ям",-1,1),new n("иям",21,1),new n("о",-1,1),new n("у",-1,1),new n("ах",-1,1),new n("ях",-1,1),new n("иях",26,1),new n("ы",-1,1),new n("ь",-1,1),new n("ю",-1,1),new n("ию",30,1),new n("ью",30,1),new n("я",-1,1),new n("ия",33,1),new n("ья",33,1)],F=[new n("ост",-1,1),new n("ость",-1,1)],q=[new n("ейше",-1,1),new n("н",-1,2),new n("ейш",-1,1),new n("ь",-1,3)],S=[33,65,8,232],W=new r;this.setCurrent=function(e){W.setCurrent(e)},this.getCurrent=function(){return W.getCurrent()},this.stem=function(){return w(),W.cursor=W.limit,!(W.cursor=i&&(e-=i,t[e>>3]&1<<(7&e)))return this.cursor++,!0}return!1},in_grouping_b:function(t,i,s){if(this.cursor>this.limit_backward){var e=r.charCodeAt(this.cursor-1);if(e<=s&&e>=i&&(e-=i,t[e>>3]&1<<(7&e)))return this.cursor--,!0}return!1},out_grouping:function(t,i,s){if(this.cursors||e>3]&1<<(7&e)))return this.cursor++,!0}return!1},out_grouping_b:function(t,i,s){if(this.cursor>this.limit_backward){var e=r.charCodeAt(this.cursor-1);if(e>s||e>3]&1<<(7&e)))return this.cursor--,!0}return!1},eq_s:function(t,i){if(this.limit-this.cursor>1),f=0,l=o0||e==s||c)break;c=!0}}for(;;){var _=t[s];if(o>=_.s_size){if(this.cursor=n+_.s_size,!_.method)return _.result;var b=_.method();if(this.cursor=n+_.s_size,b)return _.result}if((s=_.substring_i)<0)return 0}},find_among_b:function(t,i){for(var s=0,e=i,n=this.cursor,u=this.limit_backward,o=0,h=0,c=!1;;){for(var a=s+(e-s>>1),f=0,l=o=0;m--){if(n-l==u){f=-1;break}if(f=r.charCodeAt(n-1-l)-_.s[m])break;l++}if(f<0?(e=a,h=l):(s=a,o=l),e-s<=1){if(s>0||e==s||c)break;c=!0}}for(;;){var _=t[s];if(o>=_.s_size){if(this.cursor=n-_.s_size,!_.method)return _.result;var b=_.method();if(this.cursor=n-_.s_size,b)return _.result}if((s=_.substring_i)<0)return 0}},replace_s:function(t,i,s){var e=s.length-(i-t),n=r.substring(0,t),u=r.substring(i);return r=n+s+u,this.limit+=e,this.cursor>=i?this.cursor+=e:this.cursor>t&&(this.cursor=t),e},slice_check:function(){if(this.bra<0||this.bra>this.ket||this.ket>this.limit||this.limit>r.length)throw"faulty slice operation"},slice_from:function(r){this.slice_check(),this.replace_s(this.bra,this.ket,r)},slice_del:function(){this.slice_from("")},insert:function(r,t,i){var s=this.replace_s(r,t,i);r<=this.bra&&(this.bra+=s),r<=this.ket&&(this.ket+=s)},slice_to:function(){return this.slice_check(),r.substring(this.bra,this.ket)},eq_v_b:function(r){return this.eq_s_b(r.length,r)}}}},r.trimmerSupport={generateTrimmer:function(r){var t=new RegExp("^[^"+r+"]+"),i=new RegExp("[^"+r+"]+$");return function(r){return"function"==typeof r.update?r.update(function(r){return r.replace(t,"").replace(i,"")}):r.replace(t,"").replace(i,"")}}}}}); \ No newline at end of file diff --git a/en/2021.7/assets/javascripts/lunr/min/lunr.sv.min.js b/en/2021.7/assets/javascripts/lunr/min/lunr.sv.min.js new file mode 100644 index 000000000..3e5eb6400 --- /dev/null +++ b/en/2021.7/assets/javascripts/lunr/min/lunr.sv.min.js @@ -0,0 +1,18 @@ +/*! + * Lunr languages, `Swedish` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +!function(e,r){"function"==typeof define&&define.amd?define(r):"object"==typeof exports?module.exports=r():r()(e.lunr)}(this,function(){return function(e){if(void 0===e)throw new Error("Lunr is not present. Please include / require Lunr before this script.");if(void 0===e.stemmerSupport)throw new Error("Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.");e.sv=function(){this.pipeline.reset(),this.pipeline.add(e.sv.trimmer,e.sv.stopWordFilter,e.sv.stemmer),this.searchPipeline&&(this.searchPipeline.reset(),this.searchPipeline.add(e.sv.stemmer))},e.sv.wordCharacters="A-Za-zªºÀ-ÖØ-öø-ʸˠ-ˤᴀ-ᴥᴬ-ᵜᵢ-ᵥᵫ-ᵷᵹ-ᶾḀ-ỿⁱⁿₐ-ₜKÅℲⅎⅠ-ↈⱠ-ⱿꜢ-ꞇꞋ-ꞭꞰ-ꞷꟷ-ꟿꬰ-ꭚꭜ-ꭤff-stA-Za-z",e.sv.trimmer=e.trimmerSupport.generateTrimmer(e.sv.wordCharacters),e.Pipeline.registerFunction(e.sv.trimmer,"trimmer-sv"),e.sv.stemmer=function(){var r=e.stemmerSupport.Among,n=e.stemmerSupport.SnowballProgram,t=new function(){function e(){var e,r=w.cursor+3;if(o=w.limit,0<=r||r<=w.limit){for(a=r;;){if(e=w.cursor,w.in_grouping(l,97,246)){w.cursor=e;break}if(w.cursor=e,w.cursor>=w.limit)return;w.cursor++}for(;!w.out_grouping(l,97,246);){if(w.cursor>=w.limit)return;w.cursor++}o=w.cursor,o=o&&(w.limit_backward=o,w.cursor=w.limit,w.ket=w.cursor,e=w.find_among_b(u,37),w.limit_backward=r,e))switch(w.bra=w.cursor,e){case 1:w.slice_del();break;case 2:w.in_grouping_b(d,98,121)&&w.slice_del()}}function i(){var e=w.limit_backward;w.cursor>=o&&(w.limit_backward=o,w.cursor=w.limit,w.find_among_b(c,7)&&(w.cursor=w.limit,w.ket=w.cursor,w.cursor>w.limit_backward&&(w.bra=--w.cursor,w.slice_del())),w.limit_backward=e)}function s(){var e,r;if(w.cursor>=o){if(r=w.limit_backward,w.limit_backward=o,w.cursor=w.limit,w.ket=w.cursor,e=w.find_among_b(m,5))switch(w.bra=w.cursor,e){case 1:w.slice_del();break;case 2:w.slice_from("lös");break;case 3:w.slice_from("full")}w.limit_backward=r}}var a,o,u=[new r("a",-1,1),new r("arna",0,1),new r("erna",0,1),new r("heterna",2,1),new r("orna",0,1),new r("ad",-1,1),new r("e",-1,1),new r("ade",6,1),new r("ande",6,1),new r("arne",6,1),new r("are",6,1),new r("aste",6,1),new r("en",-1,1),new r("anden",12,1),new r("aren",12,1),new r("heten",12,1),new r("ern",-1,1),new r("ar",-1,1),new r("er",-1,1),new r("heter",18,1),new r("or",-1,1),new r("s",-1,2),new r("as",21,1),new r("arnas",22,1),new r("ernas",22,1),new r("ornas",22,1),new r("es",21,1),new r("ades",26,1),new r("andes",26,1),new r("ens",21,1),new r("arens",29,1),new r("hetens",29,1),new r("erns",21,1),new r("at",-1,1),new r("andet",-1,1),new r("het",-1,1),new r("ast",-1,1)],c=[new r("dd",-1,-1),new r("gd",-1,-1),new r("nn",-1,-1),new r("dt",-1,-1),new r("gt",-1,-1),new r("kt",-1,-1),new r("tt",-1,-1)],m=[new r("ig",-1,1),new r("lig",0,1),new r("els",-1,1),new r("fullt",-1,3),new r("löst",-1,2)],l=[17,65,16,1,0,0,0,0,0,0,0,0,0,0,0,0,24,0,32],d=[119,127,149],w=new n;this.setCurrent=function(e){w.setCurrent(e)},this.getCurrent=function(){return w.getCurrent()},this.stem=function(){var r=w.cursor;return e(),w.limit_backward=r,w.cursor=w.limit,t(),w.cursor=w.limit,i(),w.cursor=w.limit,s(),!0}};return function(e){return"function"==typeof e.update?e.update(function(e){return t.setCurrent(e),t.stem(),t.getCurrent()}):(t.setCurrent(e),t.stem(),t.getCurrent())}}(),e.Pipeline.registerFunction(e.sv.stemmer,"stemmer-sv"),e.sv.stopWordFilter=e.generateStopWordFilter("alla allt att av blev bli blir blivit de dem den denna deras dess dessa det detta dig din dina ditt du där då efter ej eller en er era ert ett från för ha hade han hans har henne hennes hon honom hur här i icke ingen inom inte jag ju kan kunde man med mellan men mig min mina mitt mot mycket ni nu när någon något några och om oss på samma sedan sig sin sina sitta själv skulle som så sådan sådana sådant till under upp ut utan vad var vara varför varit varje vars vart vem vi vid vilka vilkas vilken vilket vår våra vårt än är åt över".split(" ")),e.Pipeline.registerFunction(e.sv.stopWordFilter,"stopWordFilter-sv")}}); \ No newline at end of file diff --git a/en/2021.7/assets/javascripts/lunr/min/lunr.th.min.js b/en/2021.7/assets/javascripts/lunr/min/lunr.th.min.js new file mode 100644 index 000000000..dee3aac6e --- /dev/null +++ b/en/2021.7/assets/javascripts/lunr/min/lunr.th.min.js @@ -0,0 +1 @@ +!function(e,r){"function"==typeof define&&define.amd?define(r):"object"==typeof exports?module.exports=r():r()(e.lunr)}(this,function(){return function(e){if(void 0===e)throw new Error("Lunr is not present. Please include / require Lunr before this script.");if(void 0===e.stemmerSupport)throw new Error("Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.");var r="2"==e.version[0];e.th=function(){this.pipeline.reset(),this.pipeline.add(e.th.trimmer),r?this.tokenizer=e.th.tokenizer:(e.tokenizer&&(e.tokenizer=e.th.tokenizer),this.tokenizerFn&&(this.tokenizerFn=e.th.tokenizer))},e.th.wordCharacters="[฀-๿]",e.th.trimmer=e.trimmerSupport.generateTrimmer(e.th.wordCharacters),e.Pipeline.registerFunction(e.th.trimmer,"trimmer-th");var t=e.wordcut;t.init(),e.th.tokenizer=function(i){if(!arguments.length||null==i||void 0==i)return[];if(Array.isArray(i))return i.map(function(t){return r?new e.Token(t):t});var n=i.toString().replace(/^\s+/,"");return t.cut(n).split("|")}}}); \ No newline at end of file diff --git a/en/2021.7/assets/javascripts/lunr/min/lunr.tr.min.js b/en/2021.7/assets/javascripts/lunr/min/lunr.tr.min.js new file mode 100644 index 000000000..563f6ec1f --- /dev/null +++ b/en/2021.7/assets/javascripts/lunr/min/lunr.tr.min.js @@ -0,0 +1,18 @@ +/*! + * Lunr languages, `Turkish` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +!function(r,i){"function"==typeof define&&define.amd?define(i):"object"==typeof exports?module.exports=i():i()(r.lunr)}(this,function(){return function(r){if(void 0===r)throw new Error("Lunr is not present. Please include / require Lunr before this script.");if(void 0===r.stemmerSupport)throw new Error("Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.");r.tr=function(){this.pipeline.reset(),this.pipeline.add(r.tr.trimmer,r.tr.stopWordFilter,r.tr.stemmer),this.searchPipeline&&(this.searchPipeline.reset(),this.searchPipeline.add(r.tr.stemmer))},r.tr.wordCharacters="A-Za-zªºÀ-ÖØ-öø-ʸˠ-ˤᴀ-ᴥᴬ-ᵜᵢ-ᵥᵫ-ᵷᵹ-ᶾḀ-ỿⁱⁿₐ-ₜKÅℲⅎⅠ-ↈⱠ-ⱿꜢ-ꞇꞋ-ꞭꞰ-ꞷꟷ-ꟿꬰ-ꭚꭜ-ꭤff-stA-Za-z",r.tr.trimmer=r.trimmerSupport.generateTrimmer(r.tr.wordCharacters),r.Pipeline.registerFunction(r.tr.trimmer,"trimmer-tr"),r.tr.stemmer=function(){var i=r.stemmerSupport.Among,e=r.stemmerSupport.SnowballProgram,n=new function(){function r(r,i,e){for(;;){var n=Dr.limit-Dr.cursor;if(Dr.in_grouping_b(r,i,e)){Dr.cursor=Dr.limit-n;break}if(Dr.cursor=Dr.limit-n,Dr.cursor<=Dr.limit_backward)return!1;Dr.cursor--}return!0}function n(){var i,e;i=Dr.limit-Dr.cursor,r(Wr,97,305);for(var n=0;nDr.limit_backward&&(Dr.cursor--,e=Dr.limit-Dr.cursor,i()))?(Dr.cursor=Dr.limit-e,!0):(Dr.cursor=Dr.limit-n,r()?(Dr.cursor=Dr.limit-n,!1):(Dr.cursor=Dr.limit-n,!(Dr.cursor<=Dr.limit_backward)&&(Dr.cursor--,!!i()&&(Dr.cursor=Dr.limit-n,!0))))}function u(r){return t(r,function(){return Dr.in_grouping_b(Wr,97,305)})}function o(){return u(function(){return Dr.eq_s_b(1,"n")})}function s(){return u(function(){return Dr.eq_s_b(1,"s")})}function c(){return u(function(){return Dr.eq_s_b(1,"y")})}function l(){return t(function(){return Dr.in_grouping_b(Lr,105,305)},function(){return Dr.out_grouping_b(Wr,97,305)})}function a(){return Dr.find_among_b(ur,10)&&l()}function m(){return n()&&Dr.in_grouping_b(Lr,105,305)&&s()}function d(){return Dr.find_among_b(or,2)}function f(){return n()&&Dr.in_grouping_b(Lr,105,305)&&c()}function b(){return n()&&Dr.find_among_b(sr,4)}function w(){return n()&&Dr.find_among_b(cr,4)&&o()}function _(){return n()&&Dr.find_among_b(lr,2)&&c()}function k(){return n()&&Dr.find_among_b(ar,2)}function p(){return n()&&Dr.find_among_b(mr,4)}function g(){return n()&&Dr.find_among_b(dr,2)}function y(){return n()&&Dr.find_among_b(fr,4)}function z(){return n()&&Dr.find_among_b(br,2)}function v(){return n()&&Dr.find_among_b(wr,2)&&c()}function h(){return Dr.eq_s_b(2,"ki")}function q(){return n()&&Dr.find_among_b(_r,2)&&o()}function C(){return n()&&Dr.find_among_b(kr,4)&&c()}function P(){return n()&&Dr.find_among_b(pr,4)}function F(){return n()&&Dr.find_among_b(gr,4)&&c()}function S(){return Dr.find_among_b(yr,4)}function W(){return n()&&Dr.find_among_b(zr,2)}function L(){return n()&&Dr.find_among_b(vr,4)}function x(){return n()&&Dr.find_among_b(hr,8)}function A(){return Dr.find_among_b(qr,2)}function E(){return n()&&Dr.find_among_b(Cr,32)&&c()}function j(){return Dr.find_among_b(Pr,8)&&c()}function T(){return n()&&Dr.find_among_b(Fr,4)&&c()}function Z(){return Dr.eq_s_b(3,"ken")&&c()}function B(){var r=Dr.limit-Dr.cursor;return!(T()||(Dr.cursor=Dr.limit-r,E()||(Dr.cursor=Dr.limit-r,j()||(Dr.cursor=Dr.limit-r,Z()))))}function D(){if(A()){var r=Dr.limit-Dr.cursor;if(S()||(Dr.cursor=Dr.limit-r,W()||(Dr.cursor=Dr.limit-r,C()||(Dr.cursor=Dr.limit-r,P()||(Dr.cursor=Dr.limit-r,F()||(Dr.cursor=Dr.limit-r))))),T())return!1}return!0}function G(){if(W()){Dr.bra=Dr.cursor,Dr.slice_del();var r=Dr.limit-Dr.cursor;return Dr.ket=Dr.cursor,x()||(Dr.cursor=Dr.limit-r,E()||(Dr.cursor=Dr.limit-r,j()||(Dr.cursor=Dr.limit-r,T()||(Dr.cursor=Dr.limit-r)))),nr=!1,!1}return!0}function H(){if(!L())return!0;var r=Dr.limit-Dr.cursor;return!E()&&(Dr.cursor=Dr.limit-r,!j())}function I(){var r,i=Dr.limit-Dr.cursor;return!(S()||(Dr.cursor=Dr.limit-i,F()||(Dr.cursor=Dr.limit-i,P()||(Dr.cursor=Dr.limit-i,C()))))||(Dr.bra=Dr.cursor,Dr.slice_del(),r=Dr.limit-Dr.cursor,Dr.ket=Dr.cursor,T()||(Dr.cursor=Dr.limit-r),!1)}function J(){var r,i=Dr.limit-Dr.cursor;if(Dr.ket=Dr.cursor,nr=!0,B()&&(Dr.cursor=Dr.limit-i,D()&&(Dr.cursor=Dr.limit-i,G()&&(Dr.cursor=Dr.limit-i,H()&&(Dr.cursor=Dr.limit-i,I()))))){if(Dr.cursor=Dr.limit-i,!x())return;Dr.bra=Dr.cursor,Dr.slice_del(),Dr.ket=Dr.cursor,r=Dr.limit-Dr.cursor,S()||(Dr.cursor=Dr.limit-r,W()||(Dr.cursor=Dr.limit-r,C()||(Dr.cursor=Dr.limit-r,P()||(Dr.cursor=Dr.limit-r,F()||(Dr.cursor=Dr.limit-r))))),T()||(Dr.cursor=Dr.limit-r)}Dr.bra=Dr.cursor,Dr.slice_del()}function K(){var r,i,e,n;if(Dr.ket=Dr.cursor,h()){if(r=Dr.limit-Dr.cursor,p())return Dr.bra=Dr.cursor,Dr.slice_del(),i=Dr.limit-Dr.cursor,Dr.ket=Dr.cursor,W()?(Dr.bra=Dr.cursor,Dr.slice_del(),K()):(Dr.cursor=Dr.limit-i,a()&&(Dr.bra=Dr.cursor,Dr.slice_del(),Dr.ket=Dr.cursor,W()&&(Dr.bra=Dr.cursor,Dr.slice_del(),K()))),!0;if(Dr.cursor=Dr.limit-r,w()){if(Dr.bra=Dr.cursor,Dr.slice_del(),Dr.ket=Dr.cursor,e=Dr.limit-Dr.cursor,d())Dr.bra=Dr.cursor,Dr.slice_del();else{if(Dr.cursor=Dr.limit-e,Dr.ket=Dr.cursor,!a()&&(Dr.cursor=Dr.limit-e,!m()&&(Dr.cursor=Dr.limit-e,!K())))return!0;Dr.bra=Dr.cursor,Dr.slice_del(),Dr.ket=Dr.cursor,W()&&(Dr.bra=Dr.cursor,Dr.slice_del(),K())}return!0}if(Dr.cursor=Dr.limit-r,g()){if(n=Dr.limit-Dr.cursor,d())Dr.bra=Dr.cursor,Dr.slice_del();else if(Dr.cursor=Dr.limit-n,m())Dr.bra=Dr.cursor,Dr.slice_del(),Dr.ket=Dr.cursor,W()&&(Dr.bra=Dr.cursor,Dr.slice_del(),K());else if(Dr.cursor=Dr.limit-n,!K())return!1;return!0}}return!1}function M(r){if(Dr.ket=Dr.cursor,!g()&&(Dr.cursor=Dr.limit-r,!k()))return!1;var i=Dr.limit-Dr.cursor;if(d())Dr.bra=Dr.cursor,Dr.slice_del();else if(Dr.cursor=Dr.limit-i,m())Dr.bra=Dr.cursor,Dr.slice_del(),Dr.ket=Dr.cursor,W()&&(Dr.bra=Dr.cursor,Dr.slice_del(),K());else if(Dr.cursor=Dr.limit-i,!K())return!1;return!0}function N(r){if(Dr.ket=Dr.cursor,!z()&&(Dr.cursor=Dr.limit-r,!b()))return!1;var i=Dr.limit-Dr.cursor;return!(!m()&&(Dr.cursor=Dr.limit-i,!d()))&&(Dr.bra=Dr.cursor,Dr.slice_del(),Dr.ket=Dr.cursor,W()&&(Dr.bra=Dr.cursor,Dr.slice_del(),K()),!0)}function O(){var r,i=Dr.limit-Dr.cursor;return Dr.ket=Dr.cursor,!(!w()&&(Dr.cursor=Dr.limit-i,!v()))&&(Dr.bra=Dr.cursor,Dr.slice_del(),r=Dr.limit-Dr.cursor,Dr.ket=Dr.cursor,!(!W()||(Dr.bra=Dr.cursor,Dr.slice_del(),!K()))||(Dr.cursor=Dr.limit-r,Dr.ket=Dr.cursor,!(a()||(Dr.cursor=Dr.limit-r,m()||(Dr.cursor=Dr.limit-r,K())))||(Dr.bra=Dr.cursor,Dr.slice_del(),Dr.ket=Dr.cursor,W()&&(Dr.bra=Dr.cursor,Dr.slice_del(),K()),!0)))}function Q(){var r,i,e=Dr.limit-Dr.cursor;if(Dr.ket=Dr.cursor,!p()&&(Dr.cursor=Dr.limit-e,!f()&&(Dr.cursor=Dr.limit-e,!_())))return!1;if(Dr.bra=Dr.cursor,Dr.slice_del(),Dr.ket=Dr.cursor,r=Dr.limit-Dr.cursor,a())Dr.bra=Dr.cursor,Dr.slice_del(),i=Dr.limit-Dr.cursor,Dr.ket=Dr.cursor,W()||(Dr.cursor=Dr.limit-i);else if(Dr.cursor=Dr.limit-r,!W())return!0;return Dr.bra=Dr.cursor,Dr.slice_del(),Dr.ket=Dr.cursor,K(),!0}function R(){var r,i,e=Dr.limit-Dr.cursor;if(Dr.ket=Dr.cursor,W())return Dr.bra=Dr.cursor,Dr.slice_del(),void K();if(Dr.cursor=Dr.limit-e,Dr.ket=Dr.cursor,q())if(Dr.bra=Dr.cursor,Dr.slice_del(),r=Dr.limit-Dr.cursor,Dr.ket=Dr.cursor,d())Dr.bra=Dr.cursor,Dr.slice_del();else{if(Dr.cursor=Dr.limit-r,Dr.ket=Dr.cursor,!a()&&(Dr.cursor=Dr.limit-r,!m())){if(Dr.cursor=Dr.limit-r,Dr.ket=Dr.cursor,!W())return;if(Dr.bra=Dr.cursor,Dr.slice_del(),!K())return}Dr.bra=Dr.cursor,Dr.slice_del(),Dr.ket=Dr.cursor,W()&&(Dr.bra=Dr.cursor,Dr.slice_del(),K())}else if(Dr.cursor=Dr.limit-e,!M(e)&&(Dr.cursor=Dr.limit-e,!N(e))){if(Dr.cursor=Dr.limit-e,Dr.ket=Dr.cursor,y())return Dr.bra=Dr.cursor,Dr.slice_del(),Dr.ket=Dr.cursor,i=Dr.limit-Dr.cursor,void(a()?(Dr.bra=Dr.cursor,Dr.slice_del(),Dr.ket=Dr.cursor,W()&&(Dr.bra=Dr.cursor,Dr.slice_del(),K())):(Dr.cursor=Dr.limit-i,W()?(Dr.bra=Dr.cursor,Dr.slice_del(),K()):(Dr.cursor=Dr.limit-i,K())));if(Dr.cursor=Dr.limit-e,!O()){if(Dr.cursor=Dr.limit-e,d())return Dr.bra=Dr.cursor,void Dr.slice_del();Dr.cursor=Dr.limit-e,K()||(Dr.cursor=Dr.limit-e,Q()||(Dr.cursor=Dr.limit-e,Dr.ket=Dr.cursor,(a()||(Dr.cursor=Dr.limit-e,m()))&&(Dr.bra=Dr.cursor,Dr.slice_del(),Dr.ket=Dr.cursor,W()&&(Dr.bra=Dr.cursor,Dr.slice_del(),K()))))}}}function U(){var r;if(Dr.ket=Dr.cursor,r=Dr.find_among_b(Sr,4))switch(Dr.bra=Dr.cursor,r){case 1:Dr.slice_from("p");break;case 2:Dr.slice_from("ç");break;case 3:Dr.slice_from("t");break;case 4:Dr.slice_from("k")}}function V(){for(;;){var r=Dr.limit-Dr.cursor;if(Dr.in_grouping_b(Wr,97,305)){Dr.cursor=Dr.limit-r;break}if(Dr.cursor=Dr.limit-r,Dr.cursor<=Dr.limit_backward)return!1;Dr.cursor--}return!0}function X(r,i,e){if(Dr.cursor=Dr.limit-r,V()){var n=Dr.limit-Dr.cursor;if(!Dr.eq_s_b(1,i)&&(Dr.cursor=Dr.limit-n,!Dr.eq_s_b(1,e)))return!0;Dr.cursor=Dr.limit-r;var t=Dr.cursor;return Dr.insert(Dr.cursor,Dr.cursor,e),Dr.cursor=t,!1}return!0}function Y(){var r=Dr.limit-Dr.cursor;(Dr.eq_s_b(1,"d")||(Dr.cursor=Dr.limit-r,Dr.eq_s_b(1,"g")))&&X(r,"a","ı")&&X(r,"e","i")&&X(r,"o","u")&&X(r,"ö","ü")}function $(){for(var r,i=Dr.cursor,e=2;;){for(r=Dr.cursor;!Dr.in_grouping(Wr,97,305);){if(Dr.cursor>=Dr.limit)return Dr.cursor=r,!(e>0)&&(Dr.cursor=i,!0);Dr.cursor++}e--}}function rr(r,i,e){for(;!Dr.eq_s(i,e);){if(Dr.cursor>=Dr.limit)return!0;Dr.cursor++}return(tr=i)!=Dr.limit||(Dr.cursor=r,!1)}function ir(){var r=Dr.cursor;return!rr(r,2,"ad")||(Dr.cursor=r,!rr(r,5,"soyad"))}function er(){var r=Dr.cursor;return!ir()&&(Dr.limit_backward=r,Dr.cursor=Dr.limit,Y(),Dr.cursor=Dr.limit,U(),!0)}var nr,tr,ur=[new i("m",-1,-1),new i("n",-1,-1),new i("miz",-1,-1),new i("niz",-1,-1),new i("muz",-1,-1),new i("nuz",-1,-1),new i("müz",-1,-1),new i("nüz",-1,-1),new i("mız",-1,-1),new i("nız",-1,-1)],or=[new i("leri",-1,-1),new i("ları",-1,-1)],sr=[new i("ni",-1,-1),new i("nu",-1,-1),new i("nü",-1,-1),new i("nı",-1,-1)],cr=[new i("in",-1,-1),new i("un",-1,-1),new i("ün",-1,-1),new i("ın",-1,-1)],lr=[new i("a",-1,-1),new i("e",-1,-1)],ar=[new i("na",-1,-1),new i("ne",-1,-1)],mr=[new i("da",-1,-1),new i("ta",-1,-1),new i("de",-1,-1),new i("te",-1,-1)],dr=[new i("nda",-1,-1),new i("nde",-1,-1)],fr=[new i("dan",-1,-1),new i("tan",-1,-1),new i("den",-1,-1),new i("ten",-1,-1)],br=[new i("ndan",-1,-1),new i("nden",-1,-1)],wr=[new i("la",-1,-1),new i("le",-1,-1)],_r=[new i("ca",-1,-1),new i("ce",-1,-1)],kr=[new i("im",-1,-1),new i("um",-1,-1),new i("üm",-1,-1),new i("ım",-1,-1)],pr=[new i("sin",-1,-1),new i("sun",-1,-1),new i("sün",-1,-1),new i("sın",-1,-1)],gr=[new i("iz",-1,-1),new i("uz",-1,-1),new i("üz",-1,-1),new i("ız",-1,-1)],yr=[new i("siniz",-1,-1),new i("sunuz",-1,-1),new i("sünüz",-1,-1),new i("sınız",-1,-1)],zr=[new i("lar",-1,-1),new i("ler",-1,-1)],vr=[new i("niz",-1,-1),new i("nuz",-1,-1),new i("nüz",-1,-1),new i("nız",-1,-1)],hr=[new i("dir",-1,-1),new i("tir",-1,-1),new i("dur",-1,-1),new i("tur",-1,-1),new i("dür",-1,-1),new i("tür",-1,-1),new i("dır",-1,-1),new i("tır",-1,-1)],qr=[new i("casına",-1,-1),new i("cesine",-1,-1)],Cr=[new i("di",-1,-1),new i("ti",-1,-1),new i("dik",-1,-1),new i("tik",-1,-1),new i("duk",-1,-1),new i("tuk",-1,-1),new i("dük",-1,-1),new i("tük",-1,-1),new i("dık",-1,-1),new i("tık",-1,-1),new i("dim",-1,-1),new i("tim",-1,-1),new i("dum",-1,-1),new i("tum",-1,-1),new i("düm",-1,-1),new i("tüm",-1,-1),new i("dım",-1,-1),new i("tım",-1,-1),new i("din",-1,-1),new i("tin",-1,-1),new i("dun",-1,-1),new i("tun",-1,-1),new i("dün",-1,-1),new i("tün",-1,-1),new i("dın",-1,-1),new i("tın",-1,-1),new i("du",-1,-1),new i("tu",-1,-1),new i("dü",-1,-1),new i("tü",-1,-1),new i("dı",-1,-1),new i("tı",-1,-1)],Pr=[new i("sa",-1,-1),new i("se",-1,-1),new i("sak",-1,-1),new i("sek",-1,-1),new i("sam",-1,-1),new i("sem",-1,-1),new i("san",-1,-1),new i("sen",-1,-1)],Fr=[new i("miş",-1,-1),new i("muş",-1,-1),new i("müş",-1,-1),new i("mış",-1,-1)],Sr=[new i("b",-1,1),new i("c",-1,2),new i("d",-1,3),new i("ğ",-1,4)],Wr=[17,65,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,8,0,0,0,0,0,0,1],Lr=[1,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,1],xr=[1,64,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],Ar=[17,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,130],Er=[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],jr=[17],Tr=[65],Zr=[65],Br=[["a",xr,97,305],["e",Ar,101,252],["ı",Er,97,305],["i",jr,101,105],["o",Tr,111,117],["ö",Zr,246,252],["u",Tr,111,117]],Dr=new e;this.setCurrent=function(r){Dr.setCurrent(r)},this.getCurrent=function(){return Dr.getCurrent()},this.stem=function(){return!!($()&&(Dr.limit_backward=Dr.cursor,Dr.cursor=Dr.limit,J(),Dr.cursor=Dr.limit,nr&&(R(),Dr.cursor=Dr.limit_backward,er())))}};return function(r){return"function"==typeof r.update?r.update(function(r){return n.setCurrent(r),n.stem(),n.getCurrent()}):(n.setCurrent(r),n.stem(),n.getCurrent())}}(),r.Pipeline.registerFunction(r.tr.stemmer,"stemmer-tr"),r.tr.stopWordFilter=r.generateStopWordFilter("acaba altmış altı ama ancak arada aslında ayrıca bana bazı belki ben benden beni benim beri beş bile bin bir biri birkaç birkez birçok birşey birşeyi biz bizden bize bizi bizim bu buna bunda bundan bunlar bunları bunların bunu bunun burada böyle böylece da daha dahi de defa değil diye diğer doksan dokuz dolayı dolayısıyla dört edecek eden ederek edilecek ediliyor edilmesi ediyor elli en etmesi etti ettiği ettiğini eğer gibi göre halen hangi hatta hem henüz hep hepsi her herhangi herkesin hiç hiçbir iki ile ilgili ise itibaren itibariyle için işte kadar karşın katrilyon kendi kendilerine kendini kendisi kendisine kendisini kez ki kim kimden kime kimi kimse kırk milyar milyon mu mü mı nasıl ne neden nedenle nerde nerede nereye niye niçin o olan olarak oldu olduklarını olduğu olduğunu olmadı olmadığı olmak olması olmayan olmaz olsa olsun olup olur olursa oluyor on ona ondan onlar onlardan onları onların onu onun otuz oysa pek rağmen sadece sanki sekiz seksen sen senden seni senin siz sizden sizi sizin tarafından trilyon tüm var vardı ve veya ya yani yapacak yapmak yaptı yaptıkları yaptığı yaptığını yapılan yapılması yapıyor yedi yerine yetmiş yine yirmi yoksa yüz zaten çok çünkü öyle üzere üç şey şeyden şeyi şeyler şu şuna şunda şundan şunları şunu şöyle".split(" ")),r.Pipeline.registerFunction(r.tr.stopWordFilter,"stopWordFilter-tr")}}); \ No newline at end of file diff --git a/en/2021.7/assets/javascripts/lunr/min/lunr.vi.min.js b/en/2021.7/assets/javascripts/lunr/min/lunr.vi.min.js new file mode 100644 index 000000000..22aed28c4 --- /dev/null +++ b/en/2021.7/assets/javascripts/lunr/min/lunr.vi.min.js @@ -0,0 +1 @@ +!function(e,r){"function"==typeof define&&define.amd?define(r):"object"==typeof exports?module.exports=r():r()(e.lunr)}(this,function(){return function(e){if(void 0===e)throw new Error("Lunr is not present. Please include / require Lunr before this script.");if(void 0===e.stemmerSupport)throw new Error("Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.");e.vi=function(){this.pipeline.reset(),this.pipeline.add(e.vi.stopWordFilter,e.vi.trimmer)},e.vi.wordCharacters="[A-Za-ẓ̀͐́͑̉̃̓ÂâÊêÔôĂ-ăĐ-đƠ-ơƯ-ư]",e.vi.trimmer=e.trimmerSupport.generateTrimmer(e.vi.wordCharacters),e.Pipeline.registerFunction(e.vi.trimmer,"trimmer-vi"),e.vi.stopWordFilter=e.generateStopWordFilter("là cái nhưng mà".split(" "))}}); \ No newline at end of file diff --git a/en/2021.7/assets/javascripts/lunr/min/lunr.zh.min.js b/en/2021.7/assets/javascripts/lunr/min/lunr.zh.min.js new file mode 100644 index 000000000..7727bbe24 --- /dev/null +++ b/en/2021.7/assets/javascripts/lunr/min/lunr.zh.min.js @@ -0,0 +1 @@ +!function(e,r){"function"==typeof define&&define.amd?define(r):"object"==typeof exports?module.exports=r(require("nodejieba")):r()(e.lunr)}(this,function(e){return function(r,t){if(void 0===r)throw new Error("Lunr is not present. Please include / require Lunr before this script.");if(void 0===r.stemmerSupport)throw new Error("Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.");var i="2"==r.version[0];r.zh=function(){this.pipeline.reset(),this.pipeline.add(r.zh.trimmer,r.zh.stopWordFilter,r.zh.stemmer),i?this.tokenizer=r.zh.tokenizer:(r.tokenizer&&(r.tokenizer=r.zh.tokenizer),this.tokenizerFn&&(this.tokenizerFn=r.zh.tokenizer))},r.zh.tokenizer=function(n){if(!arguments.length||null==n||void 0==n)return[];if(Array.isArray(n))return n.map(function(e){return i?new r.Token(e.toLowerCase()):e.toLowerCase()});t&&e.load(t);var o=n.toString().trim().toLowerCase(),s=[];e.cut(o,!0).forEach(function(e){s=s.concat(e.split(" "))}),s=s.filter(function(e){return!!e});var u=0;return s.map(function(e,t){if(i){var n=o.indexOf(e,u),s={};return s.position=[n,e.length],s.index=t,u=n,new r.Token(e,s)}return e})},r.zh.wordCharacters="\\w一-龥",r.zh.trimmer=r.trimmerSupport.generateTrimmer(r.zh.wordCharacters),r.Pipeline.registerFunction(r.zh.trimmer,"trimmer-zh"),r.zh.stemmer=function(){return function(e){return e}}(),r.Pipeline.registerFunction(r.zh.stemmer,"stemmer-zh"),r.zh.stopWordFilter=r.generateStopWordFilter("的 一 不 在 人 有 是 为 以 于 上 他 而 后 之 来 及 了 因 下 可 到 由 这 与 也 此 但 并 个 其 已 无 小 我 们 起 最 再 今 去 好 只 又 或 很 亦 某 把 那 你 乃 它 吧 被 比 别 趁 当 从 到 得 打 凡 儿 尔 该 各 给 跟 和 何 还 即 几 既 看 据 距 靠 啦 了 另 么 每 们 嘛 拿 哪 那 您 凭 且 却 让 仍 啥 如 若 使 谁 虽 随 同 所 她 哇 嗡 往 哪 些 向 沿 哟 用 于 咱 则 怎 曾 至 致 着 诸 自".split(" ")),r.Pipeline.registerFunction(r.zh.stopWordFilter,"stopWordFilter-zh")}}); \ No newline at end of file diff --git a/en/2021.7/assets/javascripts/lunr/tinyseg.js b/en/2021.7/assets/javascripts/lunr/tinyseg.js new file mode 100644 index 000000000..167fa6dd6 --- /dev/null +++ b/en/2021.7/assets/javascripts/lunr/tinyseg.js @@ -0,0 +1,206 @@ +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +;(function (root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function () { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + + return function(lunr) { + // TinySegmenter 0.1 -- Super compact Japanese tokenizer in Javascript + // (c) 2008 Taku Kudo + // TinySegmenter is freely distributable under the terms of a new BSD licence. + // For details, see http://chasen.org/~taku/software/TinySegmenter/LICENCE.txt + + function TinySegmenter() { + var patterns = { + "[一二三四五六七八九十百千万億兆]":"M", + "[一-龠々〆ヵヶ]":"H", + "[ぁ-ん]":"I", + "[ァ-ヴーア-ン゙ー]":"K", + "[a-zA-Za-zA-Z]":"A", + "[0-90-9]":"N" + } + this.chartype_ = []; + for (var i in patterns) { + var regexp = new RegExp(i); + this.chartype_.push([regexp, patterns[i]]); + } + + this.BIAS__ = -332 + this.BC1__ = {"HH":6,"II":2461,"KH":406,"OH":-1378}; + this.BC2__ = {"AA":-3267,"AI":2744,"AN":-878,"HH":-4070,"HM":-1711,"HN":4012,"HO":3761,"IA":1327,"IH":-1184,"II":-1332,"IK":1721,"IO":5492,"KI":3831,"KK":-8741,"MH":-3132,"MK":3334,"OO":-2920}; + this.BC3__ = {"HH":996,"HI":626,"HK":-721,"HN":-1307,"HO":-836,"IH":-301,"KK":2762,"MK":1079,"MM":4034,"OA":-1652,"OH":266}; + this.BP1__ = {"BB":295,"OB":304,"OO":-125,"UB":352}; + this.BP2__ = {"BO":60,"OO":-1762}; + this.BQ1__ = {"BHH":1150,"BHM":1521,"BII":-1158,"BIM":886,"BMH":1208,"BNH":449,"BOH":-91,"BOO":-2597,"OHI":451,"OIH":-296,"OKA":1851,"OKH":-1020,"OKK":904,"OOO":2965}; + this.BQ2__ = {"BHH":118,"BHI":-1159,"BHM":466,"BIH":-919,"BKK":-1720,"BKO":864,"OHH":-1139,"OHM":-181,"OIH":153,"UHI":-1146}; + this.BQ3__ = {"BHH":-792,"BHI":2664,"BII":-299,"BKI":419,"BMH":937,"BMM":8335,"BNN":998,"BOH":775,"OHH":2174,"OHM":439,"OII":280,"OKH":1798,"OKI":-793,"OKO":-2242,"OMH":-2402,"OOO":11699}; + this.BQ4__ = {"BHH":-3895,"BIH":3761,"BII":-4654,"BIK":1348,"BKK":-1806,"BMI":-3385,"BOO":-12396,"OAH":926,"OHH":266,"OHK":-2036,"ONN":-973}; + this.BW1__ = {",と":660,",同":727,"B1あ":1404,"B1同":542,"、と":660,"、同":727,"」と":1682,"あっ":1505,"いう":1743,"いっ":-2055,"いる":672,"うし":-4817,"うん":665,"から":3472,"がら":600,"こう":-790,"こと":2083,"こん":-1262,"さら":-4143,"さん":4573,"した":2641,"して":1104,"すで":-3399,"そこ":1977,"それ":-871,"たち":1122,"ため":601,"った":3463,"つい":-802,"てい":805,"てき":1249,"でき":1127,"です":3445,"では":844,"とい":-4915,"とみ":1922,"どこ":3887,"ない":5713,"なっ":3015,"など":7379,"なん":-1113,"にし":2468,"には":1498,"にも":1671,"に対":-912,"の一":-501,"の中":741,"ませ":2448,"まで":1711,"まま":2600,"まる":-2155,"やむ":-1947,"よっ":-2565,"れた":2369,"れで":-913,"をし":1860,"を見":731,"亡く":-1886,"京都":2558,"取り":-2784,"大き":-2604,"大阪":1497,"平方":-2314,"引き":-1336,"日本":-195,"本当":-2423,"毎日":-2113,"目指":-724,"B1あ":1404,"B1同":542,"」と":1682}; + this.BW2__ = {"..":-11822,"11":-669,"――":-5730,"−−":-13175,"いう":-1609,"うか":2490,"かし":-1350,"かも":-602,"から":-7194,"かれ":4612,"がい":853,"がら":-3198,"きた":1941,"くな":-1597,"こと":-8392,"この":-4193,"させ":4533,"され":13168,"さん":-3977,"しい":-1819,"しか":-545,"した":5078,"して":972,"しな":939,"その":-3744,"たい":-1253,"たた":-662,"ただ":-3857,"たち":-786,"たと":1224,"たは":-939,"った":4589,"って":1647,"っと":-2094,"てい":6144,"てき":3640,"てく":2551,"ては":-3110,"ても":-3065,"でい":2666,"でき":-1528,"でし":-3828,"です":-4761,"でも":-4203,"とい":1890,"とこ":-1746,"とと":-2279,"との":720,"とみ":5168,"とも":-3941,"ない":-2488,"なが":-1313,"など":-6509,"なの":2614,"なん":3099,"にお":-1615,"にし":2748,"にな":2454,"によ":-7236,"に対":-14943,"に従":-4688,"に関":-11388,"のか":2093,"ので":-7059,"のに":-6041,"のの":-6125,"はい":1073,"はが":-1033,"はず":-2532,"ばれ":1813,"まし":-1316,"まで":-6621,"まれ":5409,"めて":-3153,"もい":2230,"もの":-10713,"らか":-944,"らし":-1611,"らに":-1897,"りし":651,"りま":1620,"れた":4270,"れて":849,"れば":4114,"ろう":6067,"われ":7901,"を通":-11877,"んだ":728,"んな":-4115,"一人":602,"一方":-1375,"一日":970,"一部":-1051,"上が":-4479,"会社":-1116,"出て":2163,"分の":-7758,"同党":970,"同日":-913,"大阪":-2471,"委員":-1250,"少な":-1050,"年度":-8669,"年間":-1626,"府県":-2363,"手権":-1982,"新聞":-4066,"日新":-722,"日本":-7068,"日米":3372,"曜日":-601,"朝鮮":-2355,"本人":-2697,"東京":-1543,"然と":-1384,"社会":-1276,"立て":-990,"第に":-1612,"米国":-4268,"11":-669}; + this.BW3__ = {"あた":-2194,"あり":719,"ある":3846,"い.":-1185,"い。":-1185,"いい":5308,"いえ":2079,"いく":3029,"いた":2056,"いっ":1883,"いる":5600,"いわ":1527,"うち":1117,"うと":4798,"えと":1454,"か.":2857,"か。":2857,"かけ":-743,"かっ":-4098,"かに":-669,"から":6520,"かり":-2670,"が,":1816,"が、":1816,"がき":-4855,"がけ":-1127,"がっ":-913,"がら":-4977,"がり":-2064,"きた":1645,"けど":1374,"こと":7397,"この":1542,"ころ":-2757,"さい":-714,"さを":976,"し,":1557,"し、":1557,"しい":-3714,"した":3562,"して":1449,"しな":2608,"しま":1200,"す.":-1310,"す。":-1310,"する":6521,"ず,":3426,"ず、":3426,"ずに":841,"そう":428,"た.":8875,"た。":8875,"たい":-594,"たの":812,"たり":-1183,"たる":-853,"だ.":4098,"だ。":4098,"だっ":1004,"った":-4748,"って":300,"てい":6240,"てお":855,"ても":302,"です":1437,"でに":-1482,"では":2295,"とう":-1387,"とし":2266,"との":541,"とも":-3543,"どう":4664,"ない":1796,"なく":-903,"など":2135,"に,":-1021,"に、":-1021,"にし":1771,"にな":1906,"には":2644,"の,":-724,"の、":-724,"の子":-1000,"は,":1337,"は、":1337,"べき":2181,"まし":1113,"ます":6943,"まっ":-1549,"まで":6154,"まれ":-793,"らし":1479,"られ":6820,"るる":3818,"れ,":854,"れ、":854,"れた":1850,"れて":1375,"れば":-3246,"れる":1091,"われ":-605,"んだ":606,"んで":798,"カ月":990,"会議":860,"入り":1232,"大会":2217,"始め":1681,"市":965,"新聞":-5055,"日,":974,"日、":974,"社会":2024,"カ月":990}; + this.TC1__ = {"AAA":1093,"HHH":1029,"HHM":580,"HII":998,"HOH":-390,"HOM":-331,"IHI":1169,"IOH":-142,"IOI":-1015,"IOM":467,"MMH":187,"OOI":-1832}; + this.TC2__ = {"HHO":2088,"HII":-1023,"HMM":-1154,"IHI":-1965,"KKH":703,"OII":-2649}; + this.TC3__ = {"AAA":-294,"HHH":346,"HHI":-341,"HII":-1088,"HIK":731,"HOH":-1486,"IHH":128,"IHI":-3041,"IHO":-1935,"IIH":-825,"IIM":-1035,"IOI":-542,"KHH":-1216,"KKA":491,"KKH":-1217,"KOK":-1009,"MHH":-2694,"MHM":-457,"MHO":123,"MMH":-471,"NNH":-1689,"NNO":662,"OHO":-3393}; + this.TC4__ = {"HHH":-203,"HHI":1344,"HHK":365,"HHM":-122,"HHN":182,"HHO":669,"HIH":804,"HII":679,"HOH":446,"IHH":695,"IHO":-2324,"IIH":321,"III":1497,"IIO":656,"IOO":54,"KAK":4845,"KKA":3386,"KKK":3065,"MHH":-405,"MHI":201,"MMH":-241,"MMM":661,"MOM":841}; + this.TQ1__ = {"BHHH":-227,"BHHI":316,"BHIH":-132,"BIHH":60,"BIII":1595,"BNHH":-744,"BOHH":225,"BOOO":-908,"OAKK":482,"OHHH":281,"OHIH":249,"OIHI":200,"OIIH":-68}; + this.TQ2__ = {"BIHH":-1401,"BIII":-1033,"BKAK":-543,"BOOO":-5591}; + this.TQ3__ = {"BHHH":478,"BHHM":-1073,"BHIH":222,"BHII":-504,"BIIH":-116,"BIII":-105,"BMHI":-863,"BMHM":-464,"BOMH":620,"OHHH":346,"OHHI":1729,"OHII":997,"OHMH":481,"OIHH":623,"OIIH":1344,"OKAK":2792,"OKHH":587,"OKKA":679,"OOHH":110,"OOII":-685}; + this.TQ4__ = {"BHHH":-721,"BHHM":-3604,"BHII":-966,"BIIH":-607,"BIII":-2181,"OAAA":-2763,"OAKK":180,"OHHH":-294,"OHHI":2446,"OHHO":480,"OHIH":-1573,"OIHH":1935,"OIHI":-493,"OIIH":626,"OIII":-4007,"OKAK":-8156}; + this.TW1__ = {"につい":-4681,"東京都":2026}; + this.TW2__ = {"ある程":-2049,"いった":-1256,"ころが":-2434,"しょう":3873,"その後":-4430,"だって":-1049,"ていた":1833,"として":-4657,"ともに":-4517,"もので":1882,"一気に":-792,"初めて":-1512,"同時に":-8097,"大きな":-1255,"対して":-2721,"社会党":-3216}; + this.TW3__ = {"いただ":-1734,"してい":1314,"として":-4314,"につい":-5483,"にとっ":-5989,"に当た":-6247,"ので,":-727,"ので、":-727,"のもの":-600,"れから":-3752,"十二月":-2287}; + this.TW4__ = {"いう.":8576,"いう。":8576,"からな":-2348,"してい":2958,"たが,":1516,"たが、":1516,"ている":1538,"という":1349,"ました":5543,"ません":1097,"ようと":-4258,"よると":5865}; + this.UC1__ = {"A":484,"K":93,"M":645,"O":-505}; + this.UC2__ = {"A":819,"H":1059,"I":409,"M":3987,"N":5775,"O":646}; + this.UC3__ = {"A":-1370,"I":2311}; + this.UC4__ = {"A":-2643,"H":1809,"I":-1032,"K":-3450,"M":3565,"N":3876,"O":6646}; + this.UC5__ = {"H":313,"I":-1238,"K":-799,"M":539,"O":-831}; + this.UC6__ = {"H":-506,"I":-253,"K":87,"M":247,"O":-387}; + this.UP1__ = {"O":-214}; + this.UP2__ = {"B":69,"O":935}; + this.UP3__ = {"B":189}; + this.UQ1__ = {"BH":21,"BI":-12,"BK":-99,"BN":142,"BO":-56,"OH":-95,"OI":477,"OK":410,"OO":-2422}; + this.UQ2__ = {"BH":216,"BI":113,"OK":1759}; + this.UQ3__ = {"BA":-479,"BH":42,"BI":1913,"BK":-7198,"BM":3160,"BN":6427,"BO":14761,"OI":-827,"ON":-3212}; + this.UW1__ = {",":156,"、":156,"「":-463,"あ":-941,"う":-127,"が":-553,"き":121,"こ":505,"で":-201,"と":-547,"ど":-123,"に":-789,"の":-185,"は":-847,"も":-466,"や":-470,"よ":182,"ら":-292,"り":208,"れ":169,"を":-446,"ん":-137,"・":-135,"主":-402,"京":-268,"区":-912,"午":871,"国":-460,"大":561,"委":729,"市":-411,"日":-141,"理":361,"生":-408,"県":-386,"都":-718,"「":-463,"・":-135}; + this.UW2__ = {",":-829,"、":-829,"〇":892,"「":-645,"」":3145,"あ":-538,"い":505,"う":134,"お":-502,"か":1454,"が":-856,"く":-412,"こ":1141,"さ":878,"ざ":540,"し":1529,"す":-675,"せ":300,"そ":-1011,"た":188,"だ":1837,"つ":-949,"て":-291,"で":-268,"と":-981,"ど":1273,"な":1063,"に":-1764,"の":130,"は":-409,"ひ":-1273,"べ":1261,"ま":600,"も":-1263,"や":-402,"よ":1639,"り":-579,"る":-694,"れ":571,"を":-2516,"ん":2095,"ア":-587,"カ":306,"キ":568,"ッ":831,"三":-758,"不":-2150,"世":-302,"中":-968,"主":-861,"事":492,"人":-123,"会":978,"保":362,"入":548,"初":-3025,"副":-1566,"北":-3414,"区":-422,"大":-1769,"天":-865,"太":-483,"子":-1519,"学":760,"実":1023,"小":-2009,"市":-813,"年":-1060,"強":1067,"手":-1519,"揺":-1033,"政":1522,"文":-1355,"新":-1682,"日":-1815,"明":-1462,"最":-630,"朝":-1843,"本":-1650,"東":-931,"果":-665,"次":-2378,"民":-180,"気":-1740,"理":752,"発":529,"目":-1584,"相":-242,"県":-1165,"立":-763,"第":810,"米":509,"自":-1353,"行":838,"西":-744,"見":-3874,"調":1010,"議":1198,"込":3041,"開":1758,"間":-1257,"「":-645,"」":3145,"ッ":831,"ア":-587,"カ":306,"キ":568}; + this.UW3__ = {",":4889,"1":-800,"−":-1723,"、":4889,"々":-2311,"〇":5827,"」":2670,"〓":-3573,"あ":-2696,"い":1006,"う":2342,"え":1983,"お":-4864,"か":-1163,"が":3271,"く":1004,"け":388,"げ":401,"こ":-3552,"ご":-3116,"さ":-1058,"し":-395,"す":584,"せ":3685,"そ":-5228,"た":842,"ち":-521,"っ":-1444,"つ":-1081,"て":6167,"で":2318,"と":1691,"ど":-899,"な":-2788,"に":2745,"の":4056,"は":4555,"ひ":-2171,"ふ":-1798,"へ":1199,"ほ":-5516,"ま":-4384,"み":-120,"め":1205,"も":2323,"や":-788,"よ":-202,"ら":727,"り":649,"る":5905,"れ":2773,"わ":-1207,"を":6620,"ん":-518,"ア":551,"グ":1319,"ス":874,"ッ":-1350,"ト":521,"ム":1109,"ル":1591,"ロ":2201,"ン":278,"・":-3794,"一":-1619,"下":-1759,"世":-2087,"両":3815,"中":653,"主":-758,"予":-1193,"二":974,"人":2742,"今":792,"他":1889,"以":-1368,"低":811,"何":4265,"作":-361,"保":-2439,"元":4858,"党":3593,"全":1574,"公":-3030,"六":755,"共":-1880,"円":5807,"再":3095,"分":457,"初":2475,"別":1129,"前":2286,"副":4437,"力":365,"動":-949,"務":-1872,"化":1327,"北":-1038,"区":4646,"千":-2309,"午":-783,"協":-1006,"口":483,"右":1233,"各":3588,"合":-241,"同":3906,"和":-837,"員":4513,"国":642,"型":1389,"場":1219,"外":-241,"妻":2016,"学":-1356,"安":-423,"実":-1008,"家":1078,"小":-513,"少":-3102,"州":1155,"市":3197,"平":-1804,"年":2416,"広":-1030,"府":1605,"度":1452,"建":-2352,"当":-3885,"得":1905,"思":-1291,"性":1822,"戸":-488,"指":-3973,"政":-2013,"教":-1479,"数":3222,"文":-1489,"新":1764,"日":2099,"旧":5792,"昨":-661,"時":-1248,"曜":-951,"最":-937,"月":4125,"期":360,"李":3094,"村":364,"東":-805,"核":5156,"森":2438,"業":484,"氏":2613,"民":-1694,"決":-1073,"法":1868,"海":-495,"無":979,"物":461,"特":-3850,"生":-273,"用":914,"町":1215,"的":7313,"直":-1835,"省":792,"県":6293,"知":-1528,"私":4231,"税":401,"立":-960,"第":1201,"米":7767,"系":3066,"約":3663,"級":1384,"統":-4229,"総":1163,"線":1255,"者":6457,"能":725,"自":-2869,"英":785,"見":1044,"調":-562,"財":-733,"費":1777,"車":1835,"軍":1375,"込":-1504,"通":-1136,"選":-681,"郎":1026,"郡":4404,"部":1200,"金":2163,"長":421,"開":-1432,"間":1302,"関":-1282,"雨":2009,"電":-1045,"非":2066,"駅":1620,"1":-800,"」":2670,"・":-3794,"ッ":-1350,"ア":551,"グ":1319,"ス":874,"ト":521,"ム":1109,"ル":1591,"ロ":2201,"ン":278}; + this.UW4__ = {",":3930,".":3508,"―":-4841,"、":3930,"。":3508,"〇":4999,"「":1895,"」":3798,"〓":-5156,"あ":4752,"い":-3435,"う":-640,"え":-2514,"お":2405,"か":530,"が":6006,"き":-4482,"ぎ":-3821,"く":-3788,"け":-4376,"げ":-4734,"こ":2255,"ご":1979,"さ":2864,"し":-843,"じ":-2506,"す":-731,"ず":1251,"せ":181,"そ":4091,"た":5034,"だ":5408,"ち":-3654,"っ":-5882,"つ":-1659,"て":3994,"で":7410,"と":4547,"な":5433,"に":6499,"ぬ":1853,"ね":1413,"の":7396,"は":8578,"ば":1940,"ひ":4249,"び":-4134,"ふ":1345,"へ":6665,"べ":-744,"ほ":1464,"ま":1051,"み":-2082,"む":-882,"め":-5046,"も":4169,"ゃ":-2666,"や":2795,"ょ":-1544,"よ":3351,"ら":-2922,"り":-9726,"る":-14896,"れ":-2613,"ろ":-4570,"わ":-1783,"を":13150,"ん":-2352,"カ":2145,"コ":1789,"セ":1287,"ッ":-724,"ト":-403,"メ":-1635,"ラ":-881,"リ":-541,"ル":-856,"ン":-3637,"・":-4371,"ー":-11870,"一":-2069,"中":2210,"予":782,"事":-190,"井":-1768,"人":1036,"以":544,"会":950,"体":-1286,"作":530,"側":4292,"先":601,"党":-2006,"共":-1212,"内":584,"円":788,"初":1347,"前":1623,"副":3879,"力":-302,"動":-740,"務":-2715,"化":776,"区":4517,"協":1013,"参":1555,"合":-1834,"和":-681,"員":-910,"器":-851,"回":1500,"国":-619,"園":-1200,"地":866,"場":-1410,"塁":-2094,"士":-1413,"多":1067,"大":571,"子":-4802,"学":-1397,"定":-1057,"寺":-809,"小":1910,"屋":-1328,"山":-1500,"島":-2056,"川":-2667,"市":2771,"年":374,"庁":-4556,"後":456,"性":553,"感":916,"所":-1566,"支":856,"改":787,"政":2182,"教":704,"文":522,"方":-856,"日":1798,"時":1829,"最":845,"月":-9066,"木":-485,"来":-442,"校":-360,"業":-1043,"氏":5388,"民":-2716,"気":-910,"沢":-939,"済":-543,"物":-735,"率":672,"球":-1267,"生":-1286,"産":-1101,"田":-2900,"町":1826,"的":2586,"目":922,"省":-3485,"県":2997,"空":-867,"立":-2112,"第":788,"米":2937,"系":786,"約":2171,"経":1146,"統":-1169,"総":940,"線":-994,"署":749,"者":2145,"能":-730,"般":-852,"行":-792,"規":792,"警":-1184,"議":-244,"谷":-1000,"賞":730,"車":-1481,"軍":1158,"輪":-1433,"込":-3370,"近":929,"道":-1291,"選":2596,"郎":-4866,"都":1192,"野":-1100,"銀":-2213,"長":357,"間":-2344,"院":-2297,"際":-2604,"電":-878,"領":-1659,"題":-792,"館":-1984,"首":1749,"高":2120,"「":1895,"」":3798,"・":-4371,"ッ":-724,"ー":-11870,"カ":2145,"コ":1789,"セ":1287,"ト":-403,"メ":-1635,"ラ":-881,"リ":-541,"ル":-856,"ン":-3637}; + this.UW5__ = {",":465,".":-299,"1":-514,"E2":-32768,"]":-2762,"、":465,"。":-299,"「":363,"あ":1655,"い":331,"う":-503,"え":1199,"お":527,"か":647,"が":-421,"き":1624,"ぎ":1971,"く":312,"げ":-983,"さ":-1537,"し":-1371,"す":-852,"だ":-1186,"ち":1093,"っ":52,"つ":921,"て":-18,"で":-850,"と":-127,"ど":1682,"な":-787,"に":-1224,"の":-635,"は":-578,"べ":1001,"み":502,"め":865,"ゃ":3350,"ょ":854,"り":-208,"る":429,"れ":504,"わ":419,"を":-1264,"ん":327,"イ":241,"ル":451,"ン":-343,"中":-871,"京":722,"会":-1153,"党":-654,"務":3519,"区":-901,"告":848,"員":2104,"大":-1296,"学":-548,"定":1785,"嵐":-1304,"市":-2991,"席":921,"年":1763,"思":872,"所":-814,"挙":1618,"新":-1682,"日":218,"月":-4353,"査":932,"格":1356,"機":-1508,"氏":-1347,"田":240,"町":-3912,"的":-3149,"相":1319,"省":-1052,"県":-4003,"研":-997,"社":-278,"空":-813,"統":1955,"者":-2233,"表":663,"語":-1073,"議":1219,"選":-1018,"郎":-368,"長":786,"間":1191,"題":2368,"館":-689,"1":-514,"E2":-32768,"「":363,"イ":241,"ル":451,"ン":-343}; + this.UW6__ = {",":227,".":808,"1":-270,"E1":306,"、":227,"。":808,"あ":-307,"う":189,"か":241,"が":-73,"く":-121,"こ":-200,"じ":1782,"す":383,"た":-428,"っ":573,"て":-1014,"で":101,"と":-105,"な":-253,"に":-149,"の":-417,"は":-236,"も":-206,"り":187,"る":-135,"を":195,"ル":-673,"ン":-496,"一":-277,"中":201,"件":-800,"会":624,"前":302,"区":1792,"員":-1212,"委":798,"学":-960,"市":887,"広":-695,"後":535,"業":-697,"相":753,"社":-507,"福":974,"空":-822,"者":1811,"連":463,"郎":1082,"1":-270,"E1":306,"ル":-673,"ン":-496}; + + return this; + } + TinySegmenter.prototype.ctype_ = function(str) { + for (var i in this.chartype_) { + if (str.match(this.chartype_[i][0])) { + return this.chartype_[i][1]; + } + } + return "O"; + } + + TinySegmenter.prototype.ts_ = function(v) { + if (v) { return v; } + return 0; + } + + TinySegmenter.prototype.segment = function(input) { + if (input == null || input == undefined || input == "") { + return []; + } + var result = []; + var seg = ["B3","B2","B1"]; + var ctype = ["O","O","O"]; + var o = input.split(""); + for (i = 0; i < o.length; ++i) { + seg.push(o[i]); + ctype.push(this.ctype_(o[i])) + } + seg.push("E1"); + seg.push("E2"); + seg.push("E3"); + ctype.push("O"); + ctype.push("O"); + ctype.push("O"); + var word = seg[3]; + var p1 = "U"; + var p2 = "U"; + var p3 = "U"; + for (var i = 4; i < seg.length - 3; ++i) { + var score = this.BIAS__; + var w1 = seg[i-3]; + var w2 = seg[i-2]; + var w3 = seg[i-1]; + var w4 = seg[i]; + var w5 = seg[i+1]; + var w6 = seg[i+2]; + var c1 = ctype[i-3]; + var c2 = ctype[i-2]; + var c3 = ctype[i-1]; + var c4 = ctype[i]; + var c5 = ctype[i+1]; + var c6 = ctype[i+2]; + score += this.ts_(this.UP1__[p1]); + score += this.ts_(this.UP2__[p2]); + score += this.ts_(this.UP3__[p3]); + score += this.ts_(this.BP1__[p1 + p2]); + score += this.ts_(this.BP2__[p2 + p3]); + score += this.ts_(this.UW1__[w1]); + score += this.ts_(this.UW2__[w2]); + score += this.ts_(this.UW3__[w3]); + score += this.ts_(this.UW4__[w4]); + score += this.ts_(this.UW5__[w5]); + score += this.ts_(this.UW6__[w6]); + score += this.ts_(this.BW1__[w2 + w3]); + score += this.ts_(this.BW2__[w3 + w4]); + score += this.ts_(this.BW3__[w4 + w5]); + score += this.ts_(this.TW1__[w1 + w2 + w3]); + score += this.ts_(this.TW2__[w2 + w3 + w4]); + score += this.ts_(this.TW3__[w3 + w4 + w5]); + score += this.ts_(this.TW4__[w4 + w5 + w6]); + score += this.ts_(this.UC1__[c1]); + score += this.ts_(this.UC2__[c2]); + score += this.ts_(this.UC3__[c3]); + score += this.ts_(this.UC4__[c4]); + score += this.ts_(this.UC5__[c5]); + score += this.ts_(this.UC6__[c6]); + score += this.ts_(this.BC1__[c2 + c3]); + score += this.ts_(this.BC2__[c3 + c4]); + score += this.ts_(this.BC3__[c4 + c5]); + score += this.ts_(this.TC1__[c1 + c2 + c3]); + score += this.ts_(this.TC2__[c2 + c3 + c4]); + score += this.ts_(this.TC3__[c3 + c4 + c5]); + score += this.ts_(this.TC4__[c4 + c5 + c6]); + // score += this.ts_(this.TC5__[c4 + c5 + c6]); + score += this.ts_(this.UQ1__[p1 + c1]); + score += this.ts_(this.UQ2__[p2 + c2]); + score += this.ts_(this.UQ3__[p3 + c3]); + score += this.ts_(this.BQ1__[p2 + c2 + c3]); + score += this.ts_(this.BQ2__[p2 + c3 + c4]); + score += this.ts_(this.BQ3__[p3 + c2 + c3]); + score += this.ts_(this.BQ4__[p3 + c3 + c4]); + score += this.ts_(this.TQ1__[p2 + c1 + c2 + c3]); + score += this.ts_(this.TQ2__[p2 + c2 + c3 + c4]); + score += this.ts_(this.TQ3__[p3 + c1 + c2 + c3]); + score += this.ts_(this.TQ4__[p3 + c2 + c3 + c4]); + var p = "O"; + if (score > 0) { + result.push(word); + word = ""; + p = "B"; + } + p1 = p2; + p2 = p3; + p3 = p; + word += seg[i]; + } + result.push(word); + + return result; + } + + lunr.TinySegmenter = TinySegmenter; + }; + +})); \ No newline at end of file diff --git a/en/2021.7/assets/javascripts/lunr/wordcut.js b/en/2021.7/assets/javascripts/lunr/wordcut.js new file mode 100644 index 000000000..146f4b44b --- /dev/null +++ b/en/2021.7/assets/javascripts/lunr/wordcut.js @@ -0,0 +1,6708 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}(g.lunr || (g.lunr = {})).wordcut = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 1; + }) + this.addWords(words, false) + } + if(finalize){ + this.finalizeDict(); + } + }, + + dictSeek: function (l, r, ch, strOffset, pos) { + var ans = null; + while (l <= r) { + var m = Math.floor((l + r) / 2), + dict_item = this.dict[m], + len = dict_item.length; + if (len <= strOffset) { + l = m + 1; + } else { + var ch_ = dict_item[strOffset]; + if (ch_ < ch) { + l = m + 1; + } else if (ch_ > ch) { + r = m - 1; + } else { + ans = m; + if (pos == LEFT) { + r = m - 1; + } else { + l = m + 1; + } + } + } + } + return ans; + }, + + isFinal: function (acceptor) { + return this.dict[acceptor.l].length == acceptor.strOffset; + }, + + createAcceptor: function () { + return { + l: 0, + r: this.dict.length - 1, + strOffset: 0, + isFinal: false, + dict: this, + transit: function (ch) { + return this.dict.transit(this, ch); + }, + isError: false, + tag: "DICT", + w: 1, + type: "DICT" + }; + }, + + transit: function (acceptor, ch) { + var l = this.dictSeek(acceptor.l, + acceptor.r, + ch, + acceptor.strOffset, + LEFT); + if (l !== null) { + var r = this.dictSeek(l, + acceptor.r, + ch, + acceptor.strOffset, + RIGHT); + acceptor.l = l; + acceptor.r = r; + acceptor.strOffset++; + acceptor.isFinal = this.isFinal(acceptor); + } else { + acceptor.isError = true; + } + return acceptor; + }, + + sortuniq: function(a){ + return a.sort().filter(function(item, pos, arr){ + return !pos || item != arr[pos - 1]; + }) + }, + + flatten: function(a){ + //[[1,2],[3]] -> [1,2,3] + return [].concat.apply([], a); + } +}; +module.exports = WordcutDict; + +}).call(this,"/dist/tmp") +},{"glob":16,"path":22}],3:[function(require,module,exports){ +var WordRule = { + createAcceptor: function(tag) { + if (tag["WORD_RULE"]) + return null; + + return {strOffset: 0, + isFinal: false, + transit: function(ch) { + var lch = ch.toLowerCase(); + if (lch >= "a" && lch <= "z") { + this.isFinal = true; + this.strOffset++; + } else { + this.isError = true; + } + return this; + }, + isError: false, + tag: "WORD_RULE", + type: "WORD_RULE", + w: 1}; + } +}; + +var NumberRule = { + createAcceptor: function(tag) { + if (tag["NUMBER_RULE"]) + return null; + + return {strOffset: 0, + isFinal: false, + transit: function(ch) { + if (ch >= "0" && ch <= "9") { + this.isFinal = true; + this.strOffset++; + } else { + this.isError = true; + } + return this; + }, + isError: false, + tag: "NUMBER_RULE", + type: "NUMBER_RULE", + w: 1}; + } +}; + +var SpaceRule = { + tag: "SPACE_RULE", + createAcceptor: function(tag) { + + if (tag["SPACE_RULE"]) + return null; + + return {strOffset: 0, + isFinal: false, + transit: function(ch) { + if (ch == " " || ch == "\t" || ch == "\r" || ch == "\n" || + ch == "\u00A0" || ch=="\u2003"//nbsp and emsp + ) { + this.isFinal = true; + this.strOffset++; + } else { + this.isError = true; + } + return this; + }, + isError: false, + tag: SpaceRule.tag, + w: 1, + type: "SPACE_RULE"}; + } +} + +var SingleSymbolRule = { + tag: "SINSYM", + createAcceptor: function(tag) { + return {strOffset: 0, + isFinal: false, + transit: function(ch) { + if (this.strOffset == 0 && ch.match(/^[\@\(\)\/\,\-\."`]$/)) { + this.isFinal = true; + this.strOffset++; + } else { + this.isError = true; + } + return this; + }, + isError: false, + tag: "SINSYM", + w: 1, + type: "SINSYM"}; + } +} + + +var LatinRules = [WordRule, SpaceRule, SingleSymbolRule, NumberRule]; + +module.exports = LatinRules; + +},{}],4:[function(require,module,exports){ +var _ = require("underscore") + , WordcutCore = require("./wordcut_core"); +var PathInfoBuilder = { + + /* + buildByPartAcceptors: function(path, acceptors, i) { + var + var genInfos = partAcceptors.reduce(function(genInfos, acceptor) { + + }, []); + + return genInfos; + } + */ + + buildByAcceptors: function(path, finalAcceptors, i) { + var self = this; + var infos = finalAcceptors.map(function(acceptor) { + var p = i - acceptor.strOffset + 1 + , _info = path[p]; + + var info = {p: p, + mw: _info.mw + (acceptor.mw === undefined ? 0 : acceptor.mw), + w: acceptor.w + _info.w, + unk: (acceptor.unk ? acceptor.unk : 0) + _info.unk, + type: acceptor.type}; + + if (acceptor.type == "PART") { + for(var j = p + 1; j <= i; j++) { + path[j].merge = p; + } + info.merge = p; + } + + return info; + }); + return infos.filter(function(info) { return info; }); + }, + + fallback: function(path, leftBoundary, text, i) { + var _info = path[leftBoundary]; + if (text[i].match(/[\u0E48-\u0E4E]/)) { + if (leftBoundary != 0) + leftBoundary = path[leftBoundary].p; + return {p: leftBoundary, + mw: 0, + w: 1 + _info.w, + unk: 1 + _info.unk, + type: "UNK"}; +/* } else if(leftBoundary > 0 && path[leftBoundary].type !== "UNK") { + leftBoundary = path[leftBoundary].p; + return {p: leftBoundary, + w: 1 + _info.w, + unk: 1 + _info.unk, + type: "UNK"}; */ + } else { + return {p: leftBoundary, + mw: _info.mw, + w: 1 + _info.w, + unk: 1 + _info.unk, + type: "UNK"}; + } + }, + + build: function(path, finalAcceptors, i, leftBoundary, text) { + var basicPathInfos = this.buildByAcceptors(path, finalAcceptors, i); + if (basicPathInfos.length > 0) { + return basicPathInfos; + } else { + return [this.fallback(path, leftBoundary, text, i)]; + } + } +}; + +module.exports = function() { + return _.clone(PathInfoBuilder); +} + +},{"./wordcut_core":8,"underscore":25}],5:[function(require,module,exports){ +var _ = require("underscore"); + + +var PathSelector = { + selectPath: function(paths) { + var path = paths.reduce(function(selectedPath, path) { + if (selectedPath == null) { + return path; + } else { + if (path.unk < selectedPath.unk) + return path; + if (path.unk == selectedPath.unk) { + if (path.mw < selectedPath.mw) + return path + if (path.mw == selectedPath.mw) { + if (path.w < selectedPath.w) + return path; + } + } + return selectedPath; + } + }, null); + return path; + }, + + createPath: function() { + return [{p:null, w:0, unk:0, type: "INIT", mw:0}]; + } +}; + +module.exports = function() { + return _.clone(PathSelector); +}; + +},{"underscore":25}],6:[function(require,module,exports){ +function isMatch(pat, offset, ch) { + if (pat.length <= offset) + return false; + var _ch = pat[offset]; + return _ch == ch || + (_ch.match(/[กข]/) && ch.match(/[ก-ฮ]/)) || + (_ch.match(/[มบ]/) && ch.match(/[ก-ฮ]/)) || + (_ch.match(/\u0E49/) && ch.match(/[\u0E48-\u0E4B]/)); +} + +var Rule0 = { + pat: "เหก็ม", + createAcceptor: function(tag) { + return {strOffset: 0, + isFinal: false, + transit: function(ch) { + if (isMatch(Rule0.pat, this.strOffset,ch)) { + this.isFinal = (this.strOffset + 1 == Rule0.pat.length); + this.strOffset++; + } else { + this.isError = true; + } + return this; + }, + isError: false, + tag: "THAI_RULE", + type: "THAI_RULE", + w: 1}; + } +}; + +var PartRule = { + createAcceptor: function(tag) { + return {strOffset: 0, + patterns: [ + "แก", "เก", "ก้", "กก์", "กา", "กี", "กิ", "กืก" + ], + isFinal: false, + transit: function(ch) { + var offset = this.strOffset; + this.patterns = this.patterns.filter(function(pat) { + return isMatch(pat, offset, ch); + }); + + if (this.patterns.length > 0) { + var len = 1 + offset; + this.isFinal = this.patterns.some(function(pat) { + return pat.length == len; + }); + this.strOffset++; + } else { + this.isError = true; + } + return this; + }, + isError: false, + tag: "PART", + type: "PART", + unk: 1, + w: 1}; + } +}; + +var ThaiRules = [Rule0, PartRule]; + +module.exports = ThaiRules; + +},{}],7:[function(require,module,exports){ +var sys = require("sys") + , WordcutDict = require("./dict") + , WordcutCore = require("./wordcut_core") + , PathInfoBuilder = require("./path_info_builder") + , PathSelector = require("./path_selector") + , Acceptors = require("./acceptors") + , latinRules = require("./latin_rules") + , thaiRules = require("./thai_rules") + , _ = require("underscore"); + + +var Wordcut = Object.create(WordcutCore); +Wordcut.defaultPathInfoBuilder = PathInfoBuilder; +Wordcut.defaultPathSelector = PathSelector; +Wordcut.defaultAcceptors = Acceptors; +Wordcut.defaultLatinRules = latinRules; +Wordcut.defaultThaiRules = thaiRules; +Wordcut.defaultDict = WordcutDict; + + +Wordcut.initNoDict = function(dict_path) { + var self = this; + self.pathInfoBuilder = new self.defaultPathInfoBuilder; + self.pathSelector = new self.defaultPathSelector; + self.acceptors = new self.defaultAcceptors; + self.defaultLatinRules.forEach(function(rule) { + self.acceptors.creators.push(rule); + }); + self.defaultThaiRules.forEach(function(rule) { + self.acceptors.creators.push(rule); + }); +}; + +Wordcut.init = function(dict_path, withDefault, additionalWords) { + withDefault = withDefault || false; + this.initNoDict(); + var dict = _.clone(this.defaultDict); + dict.init(dict_path, withDefault, additionalWords); + this.acceptors.creators.push(dict); +}; + +module.exports = Wordcut; + +},{"./acceptors":1,"./dict":2,"./latin_rules":3,"./path_info_builder":4,"./path_selector":5,"./thai_rules":6,"./wordcut_core":8,"sys":28,"underscore":25}],8:[function(require,module,exports){ +var WordcutCore = { + + buildPath: function(text) { + var self = this + , path = self.pathSelector.createPath() + , leftBoundary = 0; + self.acceptors.reset(); + for (var i = 0; i < text.length; i++) { + var ch = text[i]; + self.acceptors.transit(ch); + + var possiblePathInfos = self + .pathInfoBuilder + .build(path, + self.acceptors.getFinalAcceptors(), + i, + leftBoundary, + text); + var selectedPath = self.pathSelector.selectPath(possiblePathInfos) + + path.push(selectedPath); + if (selectedPath.type !== "UNK") { + leftBoundary = i; + } + } + return path; + }, + + pathToRanges: function(path) { + var e = path.length - 1 + , ranges = []; + + while (e > 0) { + var info = path[e] + , s = info.p; + + if (info.merge !== undefined && ranges.length > 0) { + var r = ranges[ranges.length - 1]; + r.s = info.merge; + s = r.s; + } else { + ranges.push({s:s, e:e}); + } + e = s; + } + return ranges.reverse(); + }, + + rangesToText: function(text, ranges, delimiter) { + return ranges.map(function(r) { + return text.substring(r.s, r.e); + }).join(delimiter); + }, + + cut: function(text, delimiter) { + var path = this.buildPath(text) + , ranges = this.pathToRanges(path); + return this + .rangesToText(text, ranges, + (delimiter === undefined ? "|" : delimiter)); + }, + + cutIntoRanges: function(text, noText) { + var path = this.buildPath(text) + , ranges = this.pathToRanges(path); + + if (!noText) { + ranges.forEach(function(r) { + r.text = text.substring(r.s, r.e); + }); + } + return ranges; + }, + + cutIntoArray: function(text) { + var path = this.buildPath(text) + , ranges = this.pathToRanges(path); + + return ranges.map(function(r) { + return text.substring(r.s, r.e) + }); + } +}; + +module.exports = WordcutCore; + +},{}],9:[function(require,module,exports){ +// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 +// +// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! +// +// Originally from narwhal.js (http://narwhaljs.org) +// Copyright (c) 2009 Thomas Robinson <280north.com> +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the 'Software'), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +// when used in node, this will actually load the util module we depend on +// versus loading the builtin util module as happens otherwise +// this is a bug in node module loading as far as I am concerned +var util = require('util/'); + +var pSlice = Array.prototype.slice; +var hasOwn = Object.prototype.hasOwnProperty; + +// 1. The assert module provides functions that throw +// AssertionError's when particular conditions are not met. The +// assert module must conform to the following interface. + +var assert = module.exports = ok; + +// 2. The AssertionError is defined in assert. +// new assert.AssertionError({ message: message, +// actual: actual, +// expected: expected }) + +assert.AssertionError = function AssertionError(options) { + this.name = 'AssertionError'; + this.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + if (options.message) { + this.message = options.message; + this.generatedMessage = false; + } else { + this.message = getMessage(this); + this.generatedMessage = true; + } + var stackStartFunction = options.stackStartFunction || fail; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, stackStartFunction); + } + else { + // non v8 browsers so we can have a stacktrace + var err = new Error(); + if (err.stack) { + var out = err.stack; + + // try to strip useless frames + var fn_name = stackStartFunction.name; + var idx = out.indexOf('\n' + fn_name); + if (idx >= 0) { + // once we have located the function frame + // we need to strip out everything before it (and its line) + var next_line = out.indexOf('\n', idx + 1); + out = out.substring(next_line + 1); + } + + this.stack = out; + } + } +}; + +// assert.AssertionError instanceof Error +util.inherits(assert.AssertionError, Error); + +function replacer(key, value) { + if (util.isUndefined(value)) { + return '' + value; + } + if (util.isNumber(value) && !isFinite(value)) { + return value.toString(); + } + if (util.isFunction(value) || util.isRegExp(value)) { + return value.toString(); + } + return value; +} + +function truncate(s, n) { + if (util.isString(s)) { + return s.length < n ? s : s.slice(0, n); + } else { + return s; + } +} + +function getMessage(self) { + return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + + self.operator + ' ' + + truncate(JSON.stringify(self.expected, replacer), 128); +} + +// At present only the three keys mentioned above are used and +// understood by the spec. Implementations or sub modules can pass +// other keys to the AssertionError's constructor - they will be +// ignored. + +// 3. All of the following functions must throw an AssertionError +// when a corresponding condition is not met, with a message that +// may be undefined if not provided. All assertion methods provide +// both the actual and expected values to the assertion error for +// display purposes. + +function fail(actual, expected, message, operator, stackStartFunction) { + throw new assert.AssertionError({ + message: message, + actual: actual, + expected: expected, + operator: operator, + stackStartFunction: stackStartFunction + }); +} + +// EXTENSION! allows for well behaved errors defined elsewhere. +assert.fail = fail; + +// 4. Pure assertion tests whether a value is truthy, as determined +// by !!guard. +// assert.ok(guard, message_opt); +// This statement is equivalent to assert.equal(true, !!guard, +// message_opt);. To test strictly for the value true, use +// assert.strictEqual(true, guard, message_opt);. + +function ok(value, message) { + if (!value) fail(value, true, message, '==', assert.ok); +} +assert.ok = ok; + +// 5. The equality assertion tests shallow, coercive equality with +// ==. +// assert.equal(actual, expected, message_opt); + +assert.equal = function equal(actual, expected, message) { + if (actual != expected) fail(actual, expected, message, '==', assert.equal); +}; + +// 6. The non-equality assertion tests for whether two objects are not equal +// with != assert.notEqual(actual, expected, message_opt); + +assert.notEqual = function notEqual(actual, expected, message) { + if (actual == expected) { + fail(actual, expected, message, '!=', assert.notEqual); + } +}; + +// 7. The equivalence assertion tests a deep equality relation. +// assert.deepEqual(actual, expected, message_opt); + +assert.deepEqual = function deepEqual(actual, expected, message) { + if (!_deepEqual(actual, expected)) { + fail(actual, expected, message, 'deepEqual', assert.deepEqual); + } +}; + +function _deepEqual(actual, expected) { + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + + } else if (util.isBuffer(actual) && util.isBuffer(expected)) { + if (actual.length != expected.length) return false; + + for (var i = 0; i < actual.length; i++) { + if (actual[i] !== expected[i]) return false; + } + + return true; + + // 7.2. If the expected value is a Date object, the actual value is + // equivalent if it is also a Date object that refers to the same time. + } else if (util.isDate(actual) && util.isDate(expected)) { + return actual.getTime() === expected.getTime(); + + // 7.3 If the expected value is a RegExp object, the actual value is + // equivalent if it is also a RegExp object with the same source and + // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). + } else if (util.isRegExp(actual) && util.isRegExp(expected)) { + return actual.source === expected.source && + actual.global === expected.global && + actual.multiline === expected.multiline && + actual.lastIndex === expected.lastIndex && + actual.ignoreCase === expected.ignoreCase; + + // 7.4. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if (!util.isObject(actual) && !util.isObject(expected)) { + return actual == expected; + + // 7.5 For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else { + return objEquiv(actual, expected); + } +} + +function isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; +} + +function objEquiv(a, b) { + if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) + return false; + // an identical 'prototype' property. + if (a.prototype !== b.prototype) return false; + // if one is a primitive, the other must be same + if (util.isPrimitive(a) || util.isPrimitive(b)) { + return a === b; + } + var aIsArgs = isArguments(a), + bIsArgs = isArguments(b); + if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) + return false; + if (aIsArgs) { + a = pSlice.call(a); + b = pSlice.call(b); + return _deepEqual(a, b); + } + var ka = objectKeys(a), + kb = objectKeys(b), + key, i; + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length != kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] != kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!_deepEqual(a[key], b[key])) return false; + } + return true; +} + +// 8. The non-equivalence assertion tests for any deep inequality. +// assert.notDeepEqual(actual, expected, message_opt); + +assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (_deepEqual(actual, expected)) { + fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); + } +}; + +// 9. The strict equality assertion tests strict equality, as determined by ===. +// assert.strictEqual(actual, expected, message_opt); + +assert.strictEqual = function strictEqual(actual, expected, message) { + if (actual !== expected) { + fail(actual, expected, message, '===', assert.strictEqual); + } +}; + +// 10. The strict non-equality assertion tests for strict inequality, as +// determined by !==. assert.notStrictEqual(actual, expected, message_opt); + +assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (actual === expected) { + fail(actual, expected, message, '!==', assert.notStrictEqual); + } +}; + +function expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } + + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } else if (actual instanceof expected) { + return true; + } else if (expected.call({}, actual) === true) { + return true; + } + + return false; +} + +function _throws(shouldThrow, block, expected, message) { + var actual; + + if (util.isString(expected)) { + message = expected; + expected = null; + } + + try { + block(); + } catch (e) { + actual = e; + } + + message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + + (message ? ' ' + message : '.'); + + if (shouldThrow && !actual) { + fail(actual, expected, 'Missing expected exception' + message); + } + + if (!shouldThrow && expectedException(actual, expected)) { + fail(actual, expected, 'Got unwanted exception' + message); + } + + if ((shouldThrow && actual && expected && + !expectedException(actual, expected)) || (!shouldThrow && actual)) { + throw actual; + } +} + +// 11. Expected to throw an error: +// assert.throws(block, Error_opt, message_opt); + +assert.throws = function(block, /*optional*/error, /*optional*/message) { + _throws.apply(this, [true].concat(pSlice.call(arguments))); +}; + +// EXTENSION! This is annoying to write outside this module. +assert.doesNotThrow = function(block, /*optional*/message) { + _throws.apply(this, [false].concat(pSlice.call(arguments))); +}; + +assert.ifError = function(err) { if (err) {throw err;}}; + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + if (hasOwn.call(obj, key)) keys.push(key); + } + return keys; +}; + +},{"util/":28}],10:[function(require,module,exports){ +'use strict'; +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + + var r = range(a, b, str); + + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} + +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} + +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; + + if (ai >= 0 && bi > 0) { + begs = []; + left = str.length; + + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } + + bi = str.indexOf(b, i + 1); + } + + i = ai < bi && ai >= 0 ? ai : bi; + } + + if (begs.length) { + result = [ left, right ]; + } + } + + return result; +} + +},{}],11:[function(require,module,exports){ +var concatMap = require('concat-map'); +var balanced = require('balanced-match'); + +module.exports = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function identity(e) { + return e; +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + + return expansions; +} + + +},{"balanced-match":10,"concat-map":13}],12:[function(require,module,exports){ + +},{}],13:[function(require,module,exports){ +module.exports = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],14:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; + +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; + + if (!this._events) + this._events = {}; + + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } + throw TypeError('Uncaught, unspecified "error" event.'); + } + } + + handler = this._events[type]; + + if (isUndefined(handler)) + return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + len = arguments.length; + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + handler.apply(this, args); + } + } else if (isObject(handler)) { + len = arguments.length; + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } + + return true; +}; + +EventEmitter.prototype.addListener = function(type, listener) { + var m; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events) + this._events = {}; + + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); + + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + var m; + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } + + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } + + return this; +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + var fired = false; + + function g() { + this.removeListener(type, g); + + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } + + g.listener = listener; + this.on(type, g); + + return this; +}; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events || !this._events[type]) + return this; + + list = this._events[type]; + length = list.length; + position = -1; + + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } + + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } + + return this; +}; + +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; + + if (!this._events) + return this; + + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } + + listeners = this._events[type]; + + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; + + return this; +}; + +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; + +EventEmitter.listenerCount = function(emitter, type) { + var ret; + if (!emitter._events || !emitter._events[type]) + ret = 0; + else if (isFunction(emitter._events[type])) + ret = 1; + else + ret = emitter._events[type].length; + return ret; +}; + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isUndefined(arg) { + return arg === void 0; +} + +},{}],15:[function(require,module,exports){ +(function (process){ +exports.alphasort = alphasort +exports.alphasorti = alphasorti +exports.setopts = setopts +exports.ownProp = ownProp +exports.makeAbs = makeAbs +exports.finish = finish +exports.mark = mark +exports.isIgnored = isIgnored +exports.childrenIgnored = childrenIgnored + +function ownProp (obj, field) { + return Object.prototype.hasOwnProperty.call(obj, field) +} + +var path = require("path") +var minimatch = require("minimatch") +var isAbsolute = require("path-is-absolute") +var Minimatch = minimatch.Minimatch + +function alphasorti (a, b) { + return a.toLowerCase().localeCompare(b.toLowerCase()) +} + +function alphasort (a, b) { + return a.localeCompare(b) +} + +function setupIgnores (self, options) { + self.ignore = options.ignore || [] + + if (!Array.isArray(self.ignore)) + self.ignore = [self.ignore] + + if (self.ignore.length) { + self.ignore = self.ignore.map(ignoreMap) + } +} + +function ignoreMap (pattern) { + var gmatcher = null + if (pattern.slice(-3) === '/**') { + var gpattern = pattern.replace(/(\/\*\*)+$/, '') + gmatcher = new Minimatch(gpattern) + } + + return { + matcher: new Minimatch(pattern), + gmatcher: gmatcher + } +} + +function setopts (self, pattern, options) { + if (!options) + options = {} + + // base-matching: just use globstar for that. + if (options.matchBase && -1 === pattern.indexOf("/")) { + if (options.noglobstar) { + throw new Error("base matching requires globstar") + } + pattern = "**/" + pattern + } + + self.silent = !!options.silent + self.pattern = pattern + self.strict = options.strict !== false + self.realpath = !!options.realpath + self.realpathCache = options.realpathCache || Object.create(null) + self.follow = !!options.follow + self.dot = !!options.dot + self.mark = !!options.mark + self.nodir = !!options.nodir + if (self.nodir) + self.mark = true + self.sync = !!options.sync + self.nounique = !!options.nounique + self.nonull = !!options.nonull + self.nosort = !!options.nosort + self.nocase = !!options.nocase + self.stat = !!options.stat + self.noprocess = !!options.noprocess + + self.maxLength = options.maxLength || Infinity + self.cache = options.cache || Object.create(null) + self.statCache = options.statCache || Object.create(null) + self.symlinks = options.symlinks || Object.create(null) + + setupIgnores(self, options) + + self.changedCwd = false + var cwd = process.cwd() + if (!ownProp(options, "cwd")) + self.cwd = cwd + else { + self.cwd = options.cwd + self.changedCwd = path.resolve(options.cwd) !== cwd + } + + self.root = options.root || path.resolve(self.cwd, "/") + self.root = path.resolve(self.root) + if (process.platform === "win32") + self.root = self.root.replace(/\\/g, "/") + + self.nomount = !!options.nomount + + // disable comments and negation unless the user explicitly + // passes in false as the option. + options.nonegate = options.nonegate === false ? false : true + options.nocomment = options.nocomment === false ? false : true + deprecationWarning(options) + + self.minimatch = new Minimatch(pattern, options) + self.options = self.minimatch.options +} + +// TODO(isaacs): remove entirely in v6 +// exported to reset in tests +exports.deprecationWarned +function deprecationWarning(options) { + if (!options.nonegate || !options.nocomment) { + if (process.noDeprecation !== true && !exports.deprecationWarned) { + var msg = 'glob WARNING: comments and negation will be disabled in v6' + if (process.throwDeprecation) + throw new Error(msg) + else if (process.traceDeprecation) + console.trace(msg) + else + console.error(msg) + + exports.deprecationWarned = true + } + } +} + +function finish (self) { + var nou = self.nounique + var all = nou ? [] : Object.create(null) + + for (var i = 0, l = self.matches.length; i < l; i ++) { + var matches = self.matches[i] + if (!matches || Object.keys(matches).length === 0) { + if (self.nonull) { + // do like the shell, and spit out the literal glob + var literal = self.minimatch.globSet[i] + if (nou) + all.push(literal) + else + all[literal] = true + } + } else { + // had matches + var m = Object.keys(matches) + if (nou) + all.push.apply(all, m) + else + m.forEach(function (m) { + all[m] = true + }) + } + } + + if (!nou) + all = Object.keys(all) + + if (!self.nosort) + all = all.sort(self.nocase ? alphasorti : alphasort) + + // at *some* point we statted all of these + if (self.mark) { + for (var i = 0; i < all.length; i++) { + all[i] = self._mark(all[i]) + } + if (self.nodir) { + all = all.filter(function (e) { + return !(/\/$/.test(e)) + }) + } + } + + if (self.ignore.length) + all = all.filter(function(m) { + return !isIgnored(self, m) + }) + + self.found = all +} + +function mark (self, p) { + var abs = makeAbs(self, p) + var c = self.cache[abs] + var m = p + if (c) { + var isDir = c === 'DIR' || Array.isArray(c) + var slash = p.slice(-1) === '/' + + if (isDir && !slash) + m += '/' + else if (!isDir && slash) + m = m.slice(0, -1) + + if (m !== p) { + var mabs = makeAbs(self, m) + self.statCache[mabs] = self.statCache[abs] + self.cache[mabs] = self.cache[abs] + } + } + + return m +} + +// lotta situps... +function makeAbs (self, f) { + var abs = f + if (f.charAt(0) === '/') { + abs = path.join(self.root, f) + } else if (isAbsolute(f) || f === '') { + abs = f + } else if (self.changedCwd) { + abs = path.resolve(self.cwd, f) + } else { + abs = path.resolve(f) + } + return abs +} + + +// Return true, if pattern ends with globstar '**', for the accompanying parent directory. +// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents +function isIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) + }) +} + +function childrenIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return !!(item.gmatcher && item.gmatcher.match(path)) + }) +} + +}).call(this,require('_process')) +},{"_process":24,"minimatch":20,"path":22,"path-is-absolute":23}],16:[function(require,module,exports){ +(function (process){ +// Approach: +// +// 1. Get the minimatch set +// 2. For each pattern in the set, PROCESS(pattern, false) +// 3. Store matches per-set, then uniq them +// +// PROCESS(pattern, inGlobStar) +// Get the first [n] items from pattern that are all strings +// Join these together. This is PREFIX. +// If there is no more remaining, then stat(PREFIX) and +// add to matches if it succeeds. END. +// +// If inGlobStar and PREFIX is symlink and points to dir +// set ENTRIES = [] +// else readdir(PREFIX) as ENTRIES +// If fail, END +// +// with ENTRIES +// If pattern[n] is GLOBSTAR +// // handle the case where the globstar match is empty +// // by pruning it out, and testing the resulting pattern +// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) +// // handle other cases. +// for ENTRY in ENTRIES (not dotfiles) +// // attach globstar + tail onto the entry +// // Mark that this entry is a globstar match +// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) +// +// else // not globstar +// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) +// Test ENTRY against pattern[n] +// If fails, continue +// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) +// +// Caveat: +// Cache all stats and readdirs results to minimize syscall. Since all +// we ever care about is existence and directory-ness, we can just keep +// `true` for files, and [children,...] for directories, or `false` for +// things that don't exist. + +module.exports = glob + +var fs = require('fs') +var minimatch = require('minimatch') +var Minimatch = minimatch.Minimatch +var inherits = require('inherits') +var EE = require('events').EventEmitter +var path = require('path') +var assert = require('assert') +var isAbsolute = require('path-is-absolute') +var globSync = require('./sync.js') +var common = require('./common.js') +var alphasort = common.alphasort +var alphasorti = common.alphasorti +var setopts = common.setopts +var ownProp = common.ownProp +var inflight = require('inflight') +var util = require('util') +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored + +var once = require('once') + +function glob (pattern, options, cb) { + if (typeof options === 'function') cb = options, options = {} + if (!options) options = {} + + if (options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return globSync(pattern, options) + } + + return new Glob(pattern, options, cb) +} + +glob.sync = globSync +var GlobSync = glob.GlobSync = globSync.GlobSync + +// old api surface +glob.glob = glob + +glob.hasMagic = function (pattern, options_) { + var options = util._extend({}, options_) + options.noprocess = true + + var g = new Glob(pattern, options) + var set = g.minimatch.set + if (set.length > 1) + return true + + for (var j = 0; j < set[0].length; j++) { + if (typeof set[0][j] !== 'string') + return true + } + + return false +} + +glob.Glob = Glob +inherits(Glob, EE) +function Glob (pattern, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + + if (options && options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return new GlobSync(pattern, options) + } + + if (!(this instanceof Glob)) + return new Glob(pattern, options, cb) + + setopts(this, pattern, options) + this._didRealPath = false + + // process each pattern in the minimatch set + var n = this.minimatch.set.length + + // The matches are stored as {: true,...} so that + // duplicates are automagically pruned. + // Later, we do an Object.keys() on these. + // Keep them as a list so we can fill in when nonull is set. + this.matches = new Array(n) + + if (typeof cb === 'function') { + cb = once(cb) + this.on('error', cb) + this.on('end', function (matches) { + cb(null, matches) + }) + } + + var self = this + var n = this.minimatch.set.length + this._processing = 0 + this.matches = new Array(n) + + this._emitQueue = [] + this._processQueue = [] + this.paused = false + + if (this.noprocess) + return this + + if (n === 0) + return done() + + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false, done) + } + + function done () { + --self._processing + if (self._processing <= 0) + self._finish() + } +} + +Glob.prototype._finish = function () { + assert(this instanceof Glob) + if (this.aborted) + return + + if (this.realpath && !this._didRealpath) + return this._realpath() + + common.finish(this) + this.emit('end', this.found) +} + +Glob.prototype._realpath = function () { + if (this._didRealpath) + return + + this._didRealpath = true + + var n = this.matches.length + if (n === 0) + return this._finish() + + var self = this + for (var i = 0; i < this.matches.length; i++) + this._realpathSet(i, next) + + function next () { + if (--n === 0) + self._finish() + } +} + +Glob.prototype._realpathSet = function (index, cb) { + var matchset = this.matches[index] + if (!matchset) + return cb() + + var found = Object.keys(matchset) + var self = this + var n = found.length + + if (n === 0) + return cb() + + var set = this.matches[index] = Object.create(null) + found.forEach(function (p, i) { + // If there's a problem with the stat, then it means that + // one or more of the links in the realpath couldn't be + // resolved. just return the abs value in that case. + p = self._makeAbs(p) + fs.realpath(p, self.realpathCache, function (er, real) { + if (!er) + set[real] = true + else if (er.syscall === 'stat') + set[p] = true + else + self.emit('error', er) // srsly wtf right here + + if (--n === 0) { + self.matches[index] = set + cb() + } + }) + }) +} + +Glob.prototype._mark = function (p) { + return common.mark(this, p) +} + +Glob.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} + +Glob.prototype.abort = function () { + this.aborted = true + this.emit('abort') +} + +Glob.prototype.pause = function () { + if (!this.paused) { + this.paused = true + this.emit('pause') + } +} + +Glob.prototype.resume = function () { + if (this.paused) { + this.emit('resume') + this.paused = false + if (this._emitQueue.length) { + var eq = this._emitQueue.slice(0) + this._emitQueue.length = 0 + for (var i = 0; i < eq.length; i ++) { + var e = eq[i] + this._emitMatch(e[0], e[1]) + } + } + if (this._processQueue.length) { + var pq = this._processQueue.slice(0) + this._processQueue.length = 0 + for (var i = 0; i < pq.length; i ++) { + var p = pq[i] + this._processing-- + this._process(p[0], p[1], p[2], p[3]) + } + } + } +} + +Glob.prototype._process = function (pattern, index, inGlobStar, cb) { + assert(this instanceof Glob) + assert(typeof cb === 'function') + + if (this.aborted) + return + + this._processing++ + if (this.paused) { + this._processQueue.push([pattern, index, inGlobStar, cb]) + return + } + + //console.error('PROCESS %d', this._processing, pattern) + + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ + } + // now n is the index of the first one that is *not* a string. + + // see if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index, cb) + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } + + var remain = pattern.slice(n) + + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix + + var abs = this._makeAbs(read) + + //if ignored, skip _processing + if (childrenIgnored(this, read)) + return cb() + + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) +} + +Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} + +Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return cb() + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } + + //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) + + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return cb() + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) + } + // This was the last one, and no stats were needed + return cb() + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + this._process([e].concat(remain), index, inGlobStar, cb) + } + cb() +} + +Glob.prototype._emitMatch = function (index, e) { + if (this.aborted) + return + + if (this.matches[index][e]) + return + + if (isIgnored(this, e)) + return + + if (this.paused) { + this._emitQueue.push([index, e]) + return + } + + var abs = this._makeAbs(e) + + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return + } + + if (this.mark) + e = this._mark(e) + + this.matches[index][e] = true + + var st = this.statCache[abs] + if (st) + this.emit('stat', e, st) + + this.emit('match', e) +} + +Glob.prototype._readdirInGlobStar = function (abs, cb) { + if (this.aborted) + return + + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false, cb) + + var lstatkey = 'lstat\0' + abs + var self = this + var lstatcb = inflight(lstatkey, lstatcb_) + + if (lstatcb) + fs.lstat(abs, lstatcb) + + function lstatcb_ (er, lstat) { + if (er) + return cb() + + var isSym = lstat.isSymbolicLink() + self.symlinks[abs] = isSym + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && !lstat.isDirectory()) { + self.cache[abs] = 'FILE' + cb() + } else + self._readdir(abs, false, cb) + } +} + +Glob.prototype._readdir = function (abs, inGlobStar, cb) { + if (this.aborted) + return + + cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) + if (!cb) + return + + //console.error('RD %j %j', +inGlobStar, abs) + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs, cb) + + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return cb() + + if (Array.isArray(c)) + return cb(null, c) + } + + var self = this + fs.readdir(abs, readdirCb(this, abs, cb)) +} + +function readdirCb (self, abs, cb) { + return function (er, entries) { + if (er) + self._readdirError(abs, er, cb) + else + self._readdirEntries(abs, entries, cb) + } +} + +Glob.prototype._readdirEntries = function (abs, entries, cb) { + if (this.aborted) + return + + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } + + this.cache[abs] = entries + return cb(null, entries) +} + +Glob.prototype._readdirError = function (f, er, cb) { + if (this.aborted) + return + + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + this.cache[this._makeAbs(f)] = 'FILE' + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) { + this.emit('error', er) + // If the error is handled, then we abort + // if not, we threw out of here + this.abort() + } + if (!this.silent) + console.error('glob error', er) + break + } + + return cb() +} + +Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} + + +Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + //console.error('pgs2', prefix, remain[0], entries) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return cb() + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false, cb) + + var isSym = this.symlinks[abs] + var len = entries.length + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return cb() + + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true, cb) + + var below = gspref.concat(entries[i], remain) + this._process(below, index, true, cb) + } + + cb() +} + +Glob.prototype._processSimple = function (prefix, index, cb) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var self = this + this._stat(prefix, function (er, exists) { + self._processSimple2(prefix, index, er, exists, cb) + }) +} +Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { + + //console.error('ps2', prefix, exists) + + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return cb() + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') + + // Mark this as a match + this._emitMatch(index, prefix) + cb() +} + +// Returns either 'DIR', 'FILE', or false +Glob.prototype._stat = function (f, cb) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' + + if (f.length > this.maxLength) + return cb() + + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] + + if (Array.isArray(c)) + c = 'DIR' + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return cb(null, c) + + if (needDir && c === 'FILE') + return cb() + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + + var exists + var stat = this.statCache[abs] + if (stat !== undefined) { + if (stat === false) + return cb(null, stat) + else { + var type = stat.isDirectory() ? 'DIR' : 'FILE' + if (needDir && type === 'FILE') + return cb() + else + return cb(null, type, stat) + } + } + + var self = this + var statcb = inflight('stat\0' + abs, lstatcb_) + if (statcb) + fs.lstat(abs, statcb) + + function lstatcb_ (er, lstat) { + if (lstat && lstat.isSymbolicLink()) { + // If it's a symlink, then treat it as the target, unless + // the target does not exist, then treat it as a file. + return fs.stat(abs, function (er, stat) { + if (er) + self._stat2(f, abs, null, lstat, cb) + else + self._stat2(f, abs, er, stat, cb) + }) + } else { + self._stat2(f, abs, er, lstat, cb) + } + } +} + +Glob.prototype._stat2 = function (f, abs, er, stat, cb) { + if (er) { + this.statCache[abs] = false + return cb() + } + + var needDir = f.slice(-1) === '/' + this.statCache[abs] = stat + + if (abs.slice(-1) === '/' && !stat.isDirectory()) + return cb(null, false, stat) + + var c = stat.isDirectory() ? 'DIR' : 'FILE' + this.cache[abs] = this.cache[abs] || c + + if (needDir && c !== 'DIR') + return cb() + + return cb(null, c, stat) +} + +}).call(this,require('_process')) +},{"./common.js":15,"./sync.js":17,"_process":24,"assert":9,"events":14,"fs":12,"inflight":18,"inherits":19,"minimatch":20,"once":21,"path":22,"path-is-absolute":23,"util":28}],17:[function(require,module,exports){ +(function (process){ +module.exports = globSync +globSync.GlobSync = GlobSync + +var fs = require('fs') +var minimatch = require('minimatch') +var Minimatch = minimatch.Minimatch +var Glob = require('./glob.js').Glob +var util = require('util') +var path = require('path') +var assert = require('assert') +var isAbsolute = require('path-is-absolute') +var common = require('./common.js') +var alphasort = common.alphasort +var alphasorti = common.alphasorti +var setopts = common.setopts +var ownProp = common.ownProp +var childrenIgnored = common.childrenIgnored + +function globSync (pattern, options) { + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + return new GlobSync(pattern, options).found +} + +function GlobSync (pattern, options) { + if (!pattern) + throw new Error('must provide pattern') + + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + if (!(this instanceof GlobSync)) + return new GlobSync(pattern, options) + + setopts(this, pattern, options) + + if (this.noprocess) + return this + + var n = this.minimatch.set.length + this.matches = new Array(n) + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false) + } + this._finish() +} + +GlobSync.prototype._finish = function () { + assert(this instanceof GlobSync) + if (this.realpath) { + var self = this + this.matches.forEach(function (matchset, index) { + var set = self.matches[index] = Object.create(null) + for (var p in matchset) { + try { + p = self._makeAbs(p) + var real = fs.realpathSync(p, self.realpathCache) + set[real] = true + } catch (er) { + if (er.syscall === 'stat') + set[self._makeAbs(p)] = true + else + throw er + } + } + }) + } + common.finish(this) +} + + +GlobSync.prototype._process = function (pattern, index, inGlobStar) { + assert(this instanceof GlobSync) + + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ + } + // now n is the index of the first one that is *not* a string. + + // See if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index) + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } + + var remain = pattern.slice(n) + + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix + + var abs = this._makeAbs(read) + + //if ignored, skip processing + if (childrenIgnored(this, read)) + return + + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar) +} + + +GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { + var entries = this._readdir(abs, inGlobStar) + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } + + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix.slice(-1) !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this.matches[index][e] = true + } + // This was the last one, and no stats were needed + return + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) + newPattern = [prefix, e] + else + newPattern = [e] + this._process(newPattern.concat(remain), index, inGlobStar) + } +} + + +GlobSync.prototype._emitMatch = function (index, e) { + var abs = this._makeAbs(e) + if (this.mark) + e = this._mark(e) + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[this._makeAbs(e)] + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true + if (this.stat) + this._stat(e) +} + + +GlobSync.prototype._readdirInGlobStar = function (abs) { + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false) + + var entries + var lstat + var stat + try { + lstat = fs.lstatSync(abs) + } catch (er) { + // lstat failed, doesn't exist + return null + } + + var isSym = lstat.isSymbolicLink() + this.symlinks[abs] = isSym + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && !lstat.isDirectory()) + this.cache[abs] = 'FILE' + else + entries = this._readdir(abs, false) + + return entries +} + +GlobSync.prototype._readdir = function (abs, inGlobStar) { + var entries + + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs) + + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return null + + if (Array.isArray(c)) + return c + } + + try { + return this._readdirEntries(abs, fs.readdirSync(abs)) + } catch (er) { + this._readdirError(abs, er) + return null + } +} + +GlobSync.prototype._readdirEntries = function (abs, entries) { + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } + + this.cache[abs] = entries + + // mark and cache dir-ness + return entries +} + +GlobSync.prototype._readdirError = function (f, er) { + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + this.cache[this._makeAbs(f)] = 'FILE' + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) + throw er + if (!this.silent) + console.error('glob error', er) + break + } +} + +GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { + + var entries = this._readdir(abs, inGlobStar) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false) + + var len = entries.length + var isSym = this.symlinks[abs] + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return + + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true) + + var below = gspref.concat(entries[i], remain) + this._process(below, index, true) + } +} + +GlobSync.prototype._processSimple = function (prefix, index) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var exists = this._stat(prefix) + + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') + + // Mark this as a match + this.matches[index][prefix] = true +} + +// Returns either 'DIR', 'FILE', or false +GlobSync.prototype._stat = function (f) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' + + if (f.length > this.maxLength) + return false + + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] + + if (Array.isArray(c)) + c = 'DIR' + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return c + + if (needDir && c === 'FILE') + return false + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + + var exists + var stat = this.statCache[abs] + if (!stat) { + var lstat + try { + lstat = fs.lstatSync(abs) + } catch (er) { + return false + } + + if (lstat.isSymbolicLink()) { + try { + stat = fs.statSync(abs) + } catch (er) { + stat = lstat + } + } else { + stat = lstat + } + } + + this.statCache[abs] = stat + + var c = stat.isDirectory() ? 'DIR' : 'FILE' + this.cache[abs] = this.cache[abs] || c + + if (needDir && c !== 'DIR') + return false + + return c +} + +GlobSync.prototype._mark = function (p) { + return common.mark(this, p) +} + +GlobSync.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} + +}).call(this,require('_process')) +},{"./common.js":15,"./glob.js":16,"_process":24,"assert":9,"fs":12,"minimatch":20,"path":22,"path-is-absolute":23,"util":28}],18:[function(require,module,exports){ +(function (process){ +var wrappy = require('wrappy') +var reqs = Object.create(null) +var once = require('once') + +module.exports = wrappy(inflight) + +function inflight (key, cb) { + if (reqs[key]) { + reqs[key].push(cb) + return null + } else { + reqs[key] = [cb] + return makeres(key) + } +} + +function makeres (key) { + return once(function RES () { + var cbs = reqs[key] + var len = cbs.length + var args = slice(arguments) + + // XXX It's somewhat ambiguous whether a new callback added in this + // pass should be queued for later execution if something in the + // list of callbacks throws, or if it should just be discarded. + // However, it's such an edge case that it hardly matters, and either + // choice is likely as surprising as the other. + // As it happens, we do go ahead and schedule it for later execution. + try { + for (var i = 0; i < len; i++) { + cbs[i].apply(null, args) + } + } finally { + if (cbs.length > len) { + // added more in the interim. + // de-zalgo, just in case, but don't call again. + cbs.splice(0, len) + process.nextTick(function () { + RES.apply(null, args) + }) + } else { + delete reqs[key] + } + } + }) +} + +function slice (args) { + var length = args.length + var array = [] + + for (var i = 0; i < length; i++) array[i] = args[i] + return array +} + +}).call(this,require('_process')) +},{"_process":24,"once":21,"wrappy":29}],19:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + +},{}],20:[function(require,module,exports){ +module.exports = minimatch +minimatch.Minimatch = Minimatch + +var path = { sep: '/' } +try { + path = require('path') +} catch (er) {} + +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} +var expand = require('brace-expansion') + +var plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +} + +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]' + +// * => any number of characters +var star = qmark + '*?' + +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' + +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' + +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') + +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) +} + +// normalizes slashes. +var slashSplit = /\/+/ + +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} + +function ext (a, b) { + a = a || {} + b = b || {} + var t = {} + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + return t +} + +minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return minimatch + + var orig = minimatch + + var m = function minimatch (p, pattern, options) { + return orig.minimatch(p, pattern, ext(def, options)) + } + + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + } + + return m +} + +Minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return Minimatch + return minimatch.defaults(def).Minimatch +} + +function minimatch (p, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {} + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + + // "" only matches "" + if (pattern.trim() === '') return p === '' + + return new Minimatch(pattern, options).match(p) +} + +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } + + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {} + pattern = pattern.trim() + + // windows support: need to use /, not \ + if (path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') + } + + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + + // make the set of regexps etc. + this.make() +} + +Minimatch.prototype.debug = function () {} + +Minimatch.prototype.make = make +function make () { + // don't do it more than once. + if (this._made) return + + var pattern = this.pattern + var options = this.options + + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } + + // step 1: figure out negation, etc. + this.parseNegate() + + // step 2: expand braces + var set = this.globSet = this.braceExpand() + + if (options.debug) this.debug = console.error + + this.debug(this.pattern, set) + + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }) + + this.debug(this.pattern, set) + + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) + + this.debug(this.pattern, set) + + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }) + + this.debug(this.pattern, set) + + this.set = set +} + +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 + + if (options.nonegate) return + + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ + } + + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate +} + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) +} + +Minimatch.prototype.braceExpand = braceExpand + +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options + } else { + options = {} + } + } + + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern + + if (typeof pattern === 'undefined') { + throw new TypeError('undefined pattern') + } + + if (options.nobrace || + !pattern.match(/\{.*\}/)) { + // shortcut. no need to expand. + return [pattern] + } + + return expand(pattern) +} + +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + if (pattern.length > 1024 * 64) { + throw new TypeError('pattern is too long') + } + + var options = this.options + + // shortcuts + if (!options.noglobstar && pattern === '**') return GLOBSTAR + if (pattern === '') return '' + + var re = '' + var hasMagic = !!options.nocase + var escaping = false + // ? => one single character + var patternListStack = [] + var negativeLists = [] + var stateChar + var inClass = false + var reClassStart = -1 + var classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' + var self = this + + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } + } + + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue + } + + switch (c) { + case '/': + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + + case '\\': + clearStateChar() + escaping = true + continue + + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue + + case '(': + if (inClass) { + re += '(' + continue + } + + if (!stateChar) { + re += '\\(' + continue + } + + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }) + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!(?:' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue + + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } + + clearStateChar() + hasMagic = true + var pl = patternListStack.pop() + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close + if (pl.type === '!') { + negativeLists.push(pl) + } + pl.reEnd = re.length + continue + + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } + + clearStateChar() + re += '|' + continue + + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() + + if (inClass) { + re += '\\' + c + continue + } + + inClass = true + classStart = i + reClassStart = re.length + re += c + continue + + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + escaping = false + continue + } + + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + if (inClass) { + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } + } + + // finish up the class. + hasMagic = true + inClass = false + re += c + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar() + + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } + + re += c + + } // switch + } // for + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } + + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) + + this.debug('tail=%j\n %s', tail, tail, pl, re) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type + + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } + + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } + + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case '.': + case '[': + case '(': addPatternStart = true + } + + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n] + + var nlBefore = re.slice(0, nl.reStart) + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + var nlAfter = re.slice(nl.reEnd) + + nlLast += nlAfter + + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + var openParensBefore = nlBefore.split('(').length - 1 + var cleanAfter = nlAfter + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + } + nlAfter = cleanAfter + + var dollar = '' + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$' + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast + re = newRe + } + + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re + } + + if (addPatternStart) { + re = patternStart + re + } + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + var flags = options.nocase ? 'i' : '' + try { + var regExp = new RegExp('^' + re + '$', flags) + } catch (er) { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') + } + + regExp._glob = pattern + regExp._src = re + + return regExp +} + +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} + +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp + + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set + + if (!set.length) { + this.regexp = false + return this.regexp + } + var options = this.options + + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' + + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' + + try { + this.regexp = new RegExp(re, flags) + } catch (ex) { + this.regexp = false + } + return this.regexp +} + +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list +} + +Minimatch.prototype.match = match +function match (f, partial) { + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' + + if (f === '/' && partial) return true + + var options = this.options + + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } + + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) + + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + var set = this.set + this.debug(this.pattern, 'set', set) + + // Find the basename of the path by looking for the last non-empty segment + var filename + var i + for (i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } + + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} + +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options + + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) + + this.debug('matchOne', file.length, pattern.length) + + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] + + this.debug(pattern, p, f) + + // should be impossible. + // some invalid regexp stuff in the set. + if (p === false) return false + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } + + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } + + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } + + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + if (options.nocase) { + hit = f.toLowerCase() === p.toLowerCase() + } else { + hit = f === p + } + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) + } + + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') + return emptyFileEnd + } + + // should be unreachable. + throw new Error('wtf?') +} + +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} + +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} + +},{"brace-expansion":11,"path":22}],21:[function(require,module,exports){ +var wrappy = require('wrappy') +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) + +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) + +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} + +},{"wrappy":29}],22:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; +}; + + +exports.basename = function(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPath(path)[3]; +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +}).call(this,require('_process')) +},{"_process":24}],23:[function(require,module,exports){ +(function (process){ +'use strict'; + +function posix(path) { + return path.charAt(0) === '/'; +} + +function win32(path) { + // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 + var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; + var result = splitDeviceRe.exec(path); + var device = result[1] || ''; + var isUnc = Boolean(device && device.charAt(1) !== ':'); + + // UNC paths are always absolute + return Boolean(result[2] || isUnc); +} + +module.exports = process.platform === 'win32' ? win32 : posix; +module.exports.posix = posix; +module.exports.win32 = win32; + +}).call(this,require('_process')) +},{"_process":24}],24:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],25:[function(require,module,exports){ +// Underscore.js 1.8.3 +// http://underscorejs.org +// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors +// Underscore may be freely distributed under the MIT license. + +(function() { + + // Baseline setup + // -------------- + + // Establish the root object, `window` in the browser, or `exports` on the server. + var root = this; + + // Save the previous value of the `_` variable. + var previousUnderscore = root._; + + // Save bytes in the minified (but not gzipped) version: + var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; + + // Create quick reference variables for speed access to core prototypes. + var + push = ArrayProto.push, + slice = ArrayProto.slice, + toString = ObjProto.toString, + hasOwnProperty = ObjProto.hasOwnProperty; + + // All **ECMAScript 5** native function implementations that we hope to use + // are declared here. + var + nativeIsArray = Array.isArray, + nativeKeys = Object.keys, + nativeBind = FuncProto.bind, + nativeCreate = Object.create; + + // Naked function reference for surrogate-prototype-swapping. + var Ctor = function(){}; + + // Create a safe reference to the Underscore object for use below. + var _ = function(obj) { + if (obj instanceof _) return obj; + if (!(this instanceof _)) return new _(obj); + this._wrapped = obj; + }; + + // Export the Underscore object for **Node.js**, with + // backwards-compatibility for the old `require()` API. If we're in + // the browser, add `_` as a global object. + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = _; + } + exports._ = _; + } else { + root._ = _; + } + + // Current version. + _.VERSION = '1.8.3'; + + // Internal function that returns an efficient (for current engines) version + // of the passed-in callback, to be repeatedly applied in other Underscore + // functions. + var optimizeCb = function(func, context, argCount) { + if (context === void 0) return func; + switch (argCount == null ? 3 : argCount) { + case 1: return function(value) { + return func.call(context, value); + }; + case 2: return function(value, other) { + return func.call(context, value, other); + }; + case 3: return function(value, index, collection) { + return func.call(context, value, index, collection); + }; + case 4: return function(accumulator, value, index, collection) { + return func.call(context, accumulator, value, index, collection); + }; + } + return function() { + return func.apply(context, arguments); + }; + }; + + // A mostly-internal function to generate callbacks that can be applied + // to each element in a collection, returning the desired result — either + // identity, an arbitrary callback, a property matcher, or a property accessor. + var cb = function(value, context, argCount) { + if (value == null) return _.identity; + if (_.isFunction(value)) return optimizeCb(value, context, argCount); + if (_.isObject(value)) return _.matcher(value); + return _.property(value); + }; + _.iteratee = function(value, context) { + return cb(value, context, Infinity); + }; + + // An internal function for creating assigner functions. + var createAssigner = function(keysFunc, undefinedOnly) { + return function(obj) { + var length = arguments.length; + if (length < 2 || obj == null) return obj; + for (var index = 1; index < length; index++) { + var source = arguments[index], + keys = keysFunc(source), + l = keys.length; + for (var i = 0; i < l; i++) { + var key = keys[i]; + if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key]; + } + } + return obj; + }; + }; + + // An internal function for creating a new object that inherits from another. + var baseCreate = function(prototype) { + if (!_.isObject(prototype)) return {}; + if (nativeCreate) return nativeCreate(prototype); + Ctor.prototype = prototype; + var result = new Ctor; + Ctor.prototype = null; + return result; + }; + + var property = function(key) { + return function(obj) { + return obj == null ? void 0 : obj[key]; + }; + }; + + // Helper for collection methods to determine whether a collection + // should be iterated as an array or as an object + // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength + // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 + var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; + var getLength = property('length'); + var isArrayLike = function(collection) { + var length = getLength(collection); + return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX; + }; + + // Collection Functions + // -------------------- + + // The cornerstone, an `each` implementation, aka `forEach`. + // Handles raw objects in addition to array-likes. Treats all + // sparse array-likes as if they were dense. + _.each = _.forEach = function(obj, iteratee, context) { + iteratee = optimizeCb(iteratee, context); + var i, length; + if (isArrayLike(obj)) { + for (i = 0, length = obj.length; i < length; i++) { + iteratee(obj[i], i, obj); + } + } else { + var keys = _.keys(obj); + for (i = 0, length = keys.length; i < length; i++) { + iteratee(obj[keys[i]], keys[i], obj); + } + } + return obj; + }; + + // Return the results of applying the iteratee to each element. + _.map = _.collect = function(obj, iteratee, context) { + iteratee = cb(iteratee, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length, + results = Array(length); + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + results[index] = iteratee(obj[currentKey], currentKey, obj); + } + return results; + }; + + // Create a reducing function iterating left or right. + function createReduce(dir) { + // Optimized iterator function as using arguments.length + // in the main function will deoptimize the, see #1991. + function iterator(obj, iteratee, memo, keys, index, length) { + for (; index >= 0 && index < length; index += dir) { + var currentKey = keys ? keys[index] : index; + memo = iteratee(memo, obj[currentKey], currentKey, obj); + } + return memo; + } + + return function(obj, iteratee, memo, context) { + iteratee = optimizeCb(iteratee, context, 4); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length, + index = dir > 0 ? 0 : length - 1; + // Determine the initial value if none is provided. + if (arguments.length < 3) { + memo = obj[keys ? keys[index] : index]; + index += dir; + } + return iterator(obj, iteratee, memo, keys, index, length); + }; + } + + // **Reduce** builds up a single result from a list of values, aka `inject`, + // or `foldl`. + _.reduce = _.foldl = _.inject = createReduce(1); + + // The right-associative version of reduce, also known as `foldr`. + _.reduceRight = _.foldr = createReduce(-1); + + // Return the first value which passes a truth test. Aliased as `detect`. + _.find = _.detect = function(obj, predicate, context) { + var key; + if (isArrayLike(obj)) { + key = _.findIndex(obj, predicate, context); + } else { + key = _.findKey(obj, predicate, context); + } + if (key !== void 0 && key !== -1) return obj[key]; + }; + + // Return all the elements that pass a truth test. + // Aliased as `select`. + _.filter = _.select = function(obj, predicate, context) { + var results = []; + predicate = cb(predicate, context); + _.each(obj, function(value, index, list) { + if (predicate(value, index, list)) results.push(value); + }); + return results; + }; + + // Return all the elements for which a truth test fails. + _.reject = function(obj, predicate, context) { + return _.filter(obj, _.negate(cb(predicate)), context); + }; + + // Determine whether all of the elements match a truth test. + // Aliased as `all`. + _.every = _.all = function(obj, predicate, context) { + predicate = cb(predicate, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length; + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + if (!predicate(obj[currentKey], currentKey, obj)) return false; + } + return true; + }; + + // Determine if at least one element in the object matches a truth test. + // Aliased as `any`. + _.some = _.any = function(obj, predicate, context) { + predicate = cb(predicate, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length; + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + if (predicate(obj[currentKey], currentKey, obj)) return true; + } + return false; + }; + + // Determine if the array or object contains a given item (using `===`). + // Aliased as `includes` and `include`. + _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) { + if (!isArrayLike(obj)) obj = _.values(obj); + if (typeof fromIndex != 'number' || guard) fromIndex = 0; + return _.indexOf(obj, item, fromIndex) >= 0; + }; + + // Invoke a method (with arguments) on every item in a collection. + _.invoke = function(obj, method) { + var args = slice.call(arguments, 2); + var isFunc = _.isFunction(method); + return _.map(obj, function(value) { + var func = isFunc ? method : value[method]; + return func == null ? func : func.apply(value, args); + }); + }; + + // Convenience version of a common use case of `map`: fetching a property. + _.pluck = function(obj, key) { + return _.map(obj, _.property(key)); + }; + + // Convenience version of a common use case of `filter`: selecting only objects + // containing specific `key:value` pairs. + _.where = function(obj, attrs) { + return _.filter(obj, _.matcher(attrs)); + }; + + // Convenience version of a common use case of `find`: getting the first object + // containing specific `key:value` pairs. + _.findWhere = function(obj, attrs) { + return _.find(obj, _.matcher(attrs)); + }; + + // Return the maximum element (or element-based computation). + _.max = function(obj, iteratee, context) { + var result = -Infinity, lastComputed = -Infinity, + value, computed; + if (iteratee == null && obj != null) { + obj = isArrayLike(obj) ? obj : _.values(obj); + for (var i = 0, length = obj.length; i < length; i++) { + value = obj[i]; + if (value > result) { + result = value; + } + } + } else { + iteratee = cb(iteratee, context); + _.each(obj, function(value, index, list) { + computed = iteratee(value, index, list); + if (computed > lastComputed || computed === -Infinity && result === -Infinity) { + result = value; + lastComputed = computed; + } + }); + } + return result; + }; + + // Return the minimum element (or element-based computation). + _.min = function(obj, iteratee, context) { + var result = Infinity, lastComputed = Infinity, + value, computed; + if (iteratee == null && obj != null) { + obj = isArrayLike(obj) ? obj : _.values(obj); + for (var i = 0, length = obj.length; i < length; i++) { + value = obj[i]; + if (value < result) { + result = value; + } + } + } else { + iteratee = cb(iteratee, context); + _.each(obj, function(value, index, list) { + computed = iteratee(value, index, list); + if (computed < lastComputed || computed === Infinity && result === Infinity) { + result = value; + lastComputed = computed; + } + }); + } + return result; + }; + + // Shuffle a collection, using the modern version of the + // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). + _.shuffle = function(obj) { + var set = isArrayLike(obj) ? obj : _.values(obj); + var length = set.length; + var shuffled = Array(length); + for (var index = 0, rand; index < length; index++) { + rand = _.random(0, index); + if (rand !== index) shuffled[index] = shuffled[rand]; + shuffled[rand] = set[index]; + } + return shuffled; + }; + + // Sample **n** random values from a collection. + // If **n** is not specified, returns a single random element. + // The internal `guard` argument allows it to work with `map`. + _.sample = function(obj, n, guard) { + if (n == null || guard) { + if (!isArrayLike(obj)) obj = _.values(obj); + return obj[_.random(obj.length - 1)]; + } + return _.shuffle(obj).slice(0, Math.max(0, n)); + }; + + // Sort the object's values by a criterion produced by an iteratee. + _.sortBy = function(obj, iteratee, context) { + iteratee = cb(iteratee, context); + return _.pluck(_.map(obj, function(value, index, list) { + return { + value: value, + index: index, + criteria: iteratee(value, index, list) + }; + }).sort(function(left, right) { + var a = left.criteria; + var b = right.criteria; + if (a !== b) { + if (a > b || a === void 0) return 1; + if (a < b || b === void 0) return -1; + } + return left.index - right.index; + }), 'value'); + }; + + // An internal function used for aggregate "group by" operations. + var group = function(behavior) { + return function(obj, iteratee, context) { + var result = {}; + iteratee = cb(iteratee, context); + _.each(obj, function(value, index) { + var key = iteratee(value, index, obj); + behavior(result, value, key); + }); + return result; + }; + }; + + // Groups the object's values by a criterion. Pass either a string attribute + // to group by, or a function that returns the criterion. + _.groupBy = group(function(result, value, key) { + if (_.has(result, key)) result[key].push(value); else result[key] = [value]; + }); + + // Indexes the object's values by a criterion, similar to `groupBy`, but for + // when you know that your index values will be unique. + _.indexBy = group(function(result, value, key) { + result[key] = value; + }); + + // Counts instances of an object that group by a certain criterion. Pass + // either a string attribute to count by, or a function that returns the + // criterion. + _.countBy = group(function(result, value, key) { + if (_.has(result, key)) result[key]++; else result[key] = 1; + }); + + // Safely create a real, live array from anything iterable. + _.toArray = function(obj) { + if (!obj) return []; + if (_.isArray(obj)) return slice.call(obj); + if (isArrayLike(obj)) return _.map(obj, _.identity); + return _.values(obj); + }; + + // Return the number of elements in an object. + _.size = function(obj) { + if (obj == null) return 0; + return isArrayLike(obj) ? obj.length : _.keys(obj).length; + }; + + // Split a collection into two arrays: one whose elements all satisfy the given + // predicate, and one whose elements all do not satisfy the predicate. + _.partition = function(obj, predicate, context) { + predicate = cb(predicate, context); + var pass = [], fail = []; + _.each(obj, function(value, key, obj) { + (predicate(value, key, obj) ? pass : fail).push(value); + }); + return [pass, fail]; + }; + + // Array Functions + // --------------- + + // Get the first element of an array. Passing **n** will return the first N + // values in the array. Aliased as `head` and `take`. The **guard** check + // allows it to work with `_.map`. + _.first = _.head = _.take = function(array, n, guard) { + if (array == null) return void 0; + if (n == null || guard) return array[0]; + return _.initial(array, array.length - n); + }; + + // Returns everything but the last entry of the array. Especially useful on + // the arguments object. Passing **n** will return all the values in + // the array, excluding the last N. + _.initial = function(array, n, guard) { + return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); + }; + + // Get the last element of an array. Passing **n** will return the last N + // values in the array. + _.last = function(array, n, guard) { + if (array == null) return void 0; + if (n == null || guard) return array[array.length - 1]; + return _.rest(array, Math.max(0, array.length - n)); + }; + + // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. + // Especially useful on the arguments object. Passing an **n** will return + // the rest N values in the array. + _.rest = _.tail = _.drop = function(array, n, guard) { + return slice.call(array, n == null || guard ? 1 : n); + }; + + // Trim out all falsy values from an array. + _.compact = function(array) { + return _.filter(array, _.identity); + }; + + // Internal implementation of a recursive `flatten` function. + var flatten = function(input, shallow, strict, startIndex) { + var output = [], idx = 0; + for (var i = startIndex || 0, length = getLength(input); i < length; i++) { + var value = input[i]; + if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) { + //flatten current level of array or arguments object + if (!shallow) value = flatten(value, shallow, strict); + var j = 0, len = value.length; + output.length += len; + while (j < len) { + output[idx++] = value[j++]; + } + } else if (!strict) { + output[idx++] = value; + } + } + return output; + }; + + // Flatten out an array, either recursively (by default), or just one level. + _.flatten = function(array, shallow) { + return flatten(array, shallow, false); + }; + + // Return a version of the array that does not contain the specified value(s). + _.without = function(array) { + return _.difference(array, slice.call(arguments, 1)); + }; + + // Produce a duplicate-free version of the array. If the array has already + // been sorted, you have the option of using a faster algorithm. + // Aliased as `unique`. + _.uniq = _.unique = function(array, isSorted, iteratee, context) { + if (!_.isBoolean(isSorted)) { + context = iteratee; + iteratee = isSorted; + isSorted = false; + } + if (iteratee != null) iteratee = cb(iteratee, context); + var result = []; + var seen = []; + for (var i = 0, length = getLength(array); i < length; i++) { + var value = array[i], + computed = iteratee ? iteratee(value, i, array) : value; + if (isSorted) { + if (!i || seen !== computed) result.push(value); + seen = computed; + } else if (iteratee) { + if (!_.contains(seen, computed)) { + seen.push(computed); + result.push(value); + } + } else if (!_.contains(result, value)) { + result.push(value); + } + } + return result; + }; + + // Produce an array that contains the union: each distinct element from all of + // the passed-in arrays. + _.union = function() { + return _.uniq(flatten(arguments, true, true)); + }; + + // Produce an array that contains every item shared between all the + // passed-in arrays. + _.intersection = function(array) { + var result = []; + var argsLength = arguments.length; + for (var i = 0, length = getLength(array); i < length; i++) { + var item = array[i]; + if (_.contains(result, item)) continue; + for (var j = 1; j < argsLength; j++) { + if (!_.contains(arguments[j], item)) break; + } + if (j === argsLength) result.push(item); + } + return result; + }; + + // Take the difference between one array and a number of other arrays. + // Only the elements present in just the first array will remain. + _.difference = function(array) { + var rest = flatten(arguments, true, true, 1); + return _.filter(array, function(value){ + return !_.contains(rest, value); + }); + }; + + // Zip together multiple lists into a single array -- elements that share + // an index go together. + _.zip = function() { + return _.unzip(arguments); + }; + + // Complement of _.zip. Unzip accepts an array of arrays and groups + // each array's elements on shared indices + _.unzip = function(array) { + var length = array && _.max(array, getLength).length || 0; + var result = Array(length); + + for (var index = 0; index < length; index++) { + result[index] = _.pluck(array, index); + } + return result; + }; + + // Converts lists into objects. Pass either a single array of `[key, value]` + // pairs, or two parallel arrays of the same length -- one of keys, and one of + // the corresponding values. + _.object = function(list, values) { + var result = {}; + for (var i = 0, length = getLength(list); i < length; i++) { + if (values) { + result[list[i]] = values[i]; + } else { + result[list[i][0]] = list[i][1]; + } + } + return result; + }; + + // Generator function to create the findIndex and findLastIndex functions + function createPredicateIndexFinder(dir) { + return function(array, predicate, context) { + predicate = cb(predicate, context); + var length = getLength(array); + var index = dir > 0 ? 0 : length - 1; + for (; index >= 0 && index < length; index += dir) { + if (predicate(array[index], index, array)) return index; + } + return -1; + }; + } + + // Returns the first index on an array-like that passes a predicate test + _.findIndex = createPredicateIndexFinder(1); + _.findLastIndex = createPredicateIndexFinder(-1); + + // Use a comparator function to figure out the smallest index at which + // an object should be inserted so as to maintain order. Uses binary search. + _.sortedIndex = function(array, obj, iteratee, context) { + iteratee = cb(iteratee, context, 1); + var value = iteratee(obj); + var low = 0, high = getLength(array); + while (low < high) { + var mid = Math.floor((low + high) / 2); + if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; + } + return low; + }; + + // Generator function to create the indexOf and lastIndexOf functions + function createIndexFinder(dir, predicateFind, sortedIndex) { + return function(array, item, idx) { + var i = 0, length = getLength(array); + if (typeof idx == 'number') { + if (dir > 0) { + i = idx >= 0 ? idx : Math.max(idx + length, i); + } else { + length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; + } + } else if (sortedIndex && idx && length) { + idx = sortedIndex(array, item); + return array[idx] === item ? idx : -1; + } + if (item !== item) { + idx = predicateFind(slice.call(array, i, length), _.isNaN); + return idx >= 0 ? idx + i : -1; + } + for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) { + if (array[idx] === item) return idx; + } + return -1; + }; + } + + // Return the position of the first occurrence of an item in an array, + // or -1 if the item is not included in the array. + // If the array is large and already in sort order, pass `true` + // for **isSorted** to use binary search. + _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex); + _.lastIndexOf = createIndexFinder(-1, _.findLastIndex); + + // Generate an integer Array containing an arithmetic progression. A port of + // the native Python `range()` function. See + // [the Python documentation](http://docs.python.org/library/functions.html#range). + _.range = function(start, stop, step) { + if (stop == null) { + stop = start || 0; + start = 0; + } + step = step || 1; + + var length = Math.max(Math.ceil((stop - start) / step), 0); + var range = Array(length); + + for (var idx = 0; idx < length; idx++, start += step) { + range[idx] = start; + } + + return range; + }; + + // Function (ahem) Functions + // ------------------ + + // Determines whether to execute a function as a constructor + // or a normal function with the provided arguments + var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) { + if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); + var self = baseCreate(sourceFunc.prototype); + var result = sourceFunc.apply(self, args); + if (_.isObject(result)) return result; + return self; + }; + + // Create a function bound to a given object (assigning `this`, and arguments, + // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if + // available. + _.bind = function(func, context) { + if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); + if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); + var args = slice.call(arguments, 2); + var bound = function() { + return executeBound(func, bound, context, this, args.concat(slice.call(arguments))); + }; + return bound; + }; + + // Partially apply a function by creating a version that has had some of its + // arguments pre-filled, without changing its dynamic `this` context. _ acts + // as a placeholder, allowing any combination of arguments to be pre-filled. + _.partial = function(func) { + var boundArgs = slice.call(arguments, 1); + var bound = function() { + var position = 0, length = boundArgs.length; + var args = Array(length); + for (var i = 0; i < length; i++) { + args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i]; + } + while (position < arguments.length) args.push(arguments[position++]); + return executeBound(func, bound, this, this, args); + }; + return bound; + }; + + // Bind a number of an object's methods to that object. Remaining arguments + // are the method names to be bound. Useful for ensuring that all callbacks + // defined on an object belong to it. + _.bindAll = function(obj) { + var i, length = arguments.length, key; + if (length <= 1) throw new Error('bindAll must be passed function names'); + for (i = 1; i < length; i++) { + key = arguments[i]; + obj[key] = _.bind(obj[key], obj); + } + return obj; + }; + + // Memoize an expensive function by storing its results. + _.memoize = function(func, hasher) { + var memoize = function(key) { + var cache = memoize.cache; + var address = '' + (hasher ? hasher.apply(this, arguments) : key); + if (!_.has(cache, address)) cache[address] = func.apply(this, arguments); + return cache[address]; + }; + memoize.cache = {}; + return memoize; + }; + + // Delays a function for the given number of milliseconds, and then calls + // it with the arguments supplied. + _.delay = function(func, wait) { + var args = slice.call(arguments, 2); + return setTimeout(function(){ + return func.apply(null, args); + }, wait); + }; + + // Defers a function, scheduling it to run after the current call stack has + // cleared. + _.defer = _.partial(_.delay, _, 1); + + // Returns a function, that, when invoked, will only be triggered at most once + // during a given window of time. Normally, the throttled function will run + // as much as it can, without ever going more than once per `wait` duration; + // but if you'd like to disable the execution on the leading edge, pass + // `{leading: false}`. To disable execution on the trailing edge, ditto. + _.throttle = function(func, wait, options) { + var context, args, result; + var timeout = null; + var previous = 0; + if (!options) options = {}; + var later = function() { + previous = options.leading === false ? 0 : _.now(); + timeout = null; + result = func.apply(context, args); + if (!timeout) context = args = null; + }; + return function() { + var now = _.now(); + if (!previous && options.leading === false) previous = now; + var remaining = wait - (now - previous); + context = this; + args = arguments; + if (remaining <= 0 || remaining > wait) { + if (timeout) { + clearTimeout(timeout); + timeout = null; + } + previous = now; + result = func.apply(context, args); + if (!timeout) context = args = null; + } else if (!timeout && options.trailing !== false) { + timeout = setTimeout(later, remaining); + } + return result; + }; + }; + + // Returns a function, that, as long as it continues to be invoked, will not + // be triggered. The function will be called after it stops being called for + // N milliseconds. If `immediate` is passed, trigger the function on the + // leading edge, instead of the trailing. + _.debounce = function(func, wait, immediate) { + var timeout, args, context, timestamp, result; + + var later = function() { + var last = _.now() - timestamp; + + if (last < wait && last >= 0) { + timeout = setTimeout(later, wait - last); + } else { + timeout = null; + if (!immediate) { + result = func.apply(context, args); + if (!timeout) context = args = null; + } + } + }; + + return function() { + context = this; + args = arguments; + timestamp = _.now(); + var callNow = immediate && !timeout; + if (!timeout) timeout = setTimeout(later, wait); + if (callNow) { + result = func.apply(context, args); + context = args = null; + } + + return result; + }; + }; + + // Returns the first function passed as an argument to the second, + // allowing you to adjust arguments, run code before and after, and + // conditionally execute the original function. + _.wrap = function(func, wrapper) { + return _.partial(wrapper, func); + }; + + // Returns a negated version of the passed-in predicate. + _.negate = function(predicate) { + return function() { + return !predicate.apply(this, arguments); + }; + }; + + // Returns a function that is the composition of a list of functions, each + // consuming the return value of the function that follows. + _.compose = function() { + var args = arguments; + var start = args.length - 1; + return function() { + var i = start; + var result = args[start].apply(this, arguments); + while (i--) result = args[i].call(this, result); + return result; + }; + }; + + // Returns a function that will only be executed on and after the Nth call. + _.after = function(times, func) { + return function() { + if (--times < 1) { + return func.apply(this, arguments); + } + }; + }; + + // Returns a function that will only be executed up to (but not including) the Nth call. + _.before = function(times, func) { + var memo; + return function() { + if (--times > 0) { + memo = func.apply(this, arguments); + } + if (times <= 1) func = null; + return memo; + }; + }; + + // Returns a function that will be executed at most one time, no matter how + // often you call it. Useful for lazy initialization. + _.once = _.partial(_.before, 2); + + // Object Functions + // ---------------- + + // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed. + var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); + var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', + 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; + + function collectNonEnumProps(obj, keys) { + var nonEnumIdx = nonEnumerableProps.length; + var constructor = obj.constructor; + var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto; + + // Constructor is a special case. + var prop = 'constructor'; + if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop); + + while (nonEnumIdx--) { + prop = nonEnumerableProps[nonEnumIdx]; + if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) { + keys.push(prop); + } + } + } + + // Retrieve the names of an object's own properties. + // Delegates to **ECMAScript 5**'s native `Object.keys` + _.keys = function(obj) { + if (!_.isObject(obj)) return []; + if (nativeKeys) return nativeKeys(obj); + var keys = []; + for (var key in obj) if (_.has(obj, key)) keys.push(key); + // Ahem, IE < 9. + if (hasEnumBug) collectNonEnumProps(obj, keys); + return keys; + }; + + // Retrieve all the property names of an object. + _.allKeys = function(obj) { + if (!_.isObject(obj)) return []; + var keys = []; + for (var key in obj) keys.push(key); + // Ahem, IE < 9. + if (hasEnumBug) collectNonEnumProps(obj, keys); + return keys; + }; + + // Retrieve the values of an object's properties. + _.values = function(obj) { + var keys = _.keys(obj); + var length = keys.length; + var values = Array(length); + for (var i = 0; i < length; i++) { + values[i] = obj[keys[i]]; + } + return values; + }; + + // Returns the results of applying the iteratee to each element of the object + // In contrast to _.map it returns an object + _.mapObject = function(obj, iteratee, context) { + iteratee = cb(iteratee, context); + var keys = _.keys(obj), + length = keys.length, + results = {}, + currentKey; + for (var index = 0; index < length; index++) { + currentKey = keys[index]; + results[currentKey] = iteratee(obj[currentKey], currentKey, obj); + } + return results; + }; + + // Convert an object into a list of `[key, value]` pairs. + _.pairs = function(obj) { + var keys = _.keys(obj); + var length = keys.length; + var pairs = Array(length); + for (var i = 0; i < length; i++) { + pairs[i] = [keys[i], obj[keys[i]]]; + } + return pairs; + }; + + // Invert the keys and values of an object. The values must be serializable. + _.invert = function(obj) { + var result = {}; + var keys = _.keys(obj); + for (var i = 0, length = keys.length; i < length; i++) { + result[obj[keys[i]]] = keys[i]; + } + return result; + }; + + // Return a sorted list of the function names available on the object. + // Aliased as `methods` + _.functions = _.methods = function(obj) { + var names = []; + for (var key in obj) { + if (_.isFunction(obj[key])) names.push(key); + } + return names.sort(); + }; + + // Extend a given object with all the properties in passed-in object(s). + _.extend = createAssigner(_.allKeys); + + // Assigns a given object with all the own properties in the passed-in object(s) + // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) + _.extendOwn = _.assign = createAssigner(_.keys); + + // Returns the first key on an object that passes a predicate test + _.findKey = function(obj, predicate, context) { + predicate = cb(predicate, context); + var keys = _.keys(obj), key; + for (var i = 0, length = keys.length; i < length; i++) { + key = keys[i]; + if (predicate(obj[key], key, obj)) return key; + } + }; + + // Return a copy of the object only containing the whitelisted properties. + _.pick = function(object, oiteratee, context) { + var result = {}, obj = object, iteratee, keys; + if (obj == null) return result; + if (_.isFunction(oiteratee)) { + keys = _.allKeys(obj); + iteratee = optimizeCb(oiteratee, context); + } else { + keys = flatten(arguments, false, false, 1); + iteratee = function(value, key, obj) { return key in obj; }; + obj = Object(obj); + } + for (var i = 0, length = keys.length; i < length; i++) { + var key = keys[i]; + var value = obj[key]; + if (iteratee(value, key, obj)) result[key] = value; + } + return result; + }; + + // Return a copy of the object without the blacklisted properties. + _.omit = function(obj, iteratee, context) { + if (_.isFunction(iteratee)) { + iteratee = _.negate(iteratee); + } else { + var keys = _.map(flatten(arguments, false, false, 1), String); + iteratee = function(value, key) { + return !_.contains(keys, key); + }; + } + return _.pick(obj, iteratee, context); + }; + + // Fill in a given object with default properties. + _.defaults = createAssigner(_.allKeys, true); + + // Creates an object that inherits from the given prototype object. + // If additional properties are provided then they will be added to the + // created object. + _.create = function(prototype, props) { + var result = baseCreate(prototype); + if (props) _.extendOwn(result, props); + return result; + }; + + // Create a (shallow-cloned) duplicate of an object. + _.clone = function(obj) { + if (!_.isObject(obj)) return obj; + return _.isArray(obj) ? obj.slice() : _.extend({}, obj); + }; + + // Invokes interceptor with the obj, and then returns obj. + // The primary purpose of this method is to "tap into" a method chain, in + // order to perform operations on intermediate results within the chain. + _.tap = function(obj, interceptor) { + interceptor(obj); + return obj; + }; + + // Returns whether an object has a given set of `key:value` pairs. + _.isMatch = function(object, attrs) { + var keys = _.keys(attrs), length = keys.length; + if (object == null) return !length; + var obj = Object(object); + for (var i = 0; i < length; i++) { + var key = keys[i]; + if (attrs[key] !== obj[key] || !(key in obj)) return false; + } + return true; + }; + + + // Internal recursive comparison function for `isEqual`. + var eq = function(a, b, aStack, bStack) { + // Identical objects are equal. `0 === -0`, but they aren't identical. + // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). + if (a === b) return a !== 0 || 1 / a === 1 / b; + // A strict comparison is necessary because `null == undefined`. + if (a == null || b == null) return a === b; + // Unwrap any wrapped objects. + if (a instanceof _) a = a._wrapped; + if (b instanceof _) b = b._wrapped; + // Compare `[[Class]]` names. + var className = toString.call(a); + if (className !== toString.call(b)) return false; + switch (className) { + // Strings, numbers, regular expressions, dates, and booleans are compared by value. + case '[object RegExp]': + // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') + case '[object String]': + // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is + // equivalent to `new String("5")`. + return '' + a === '' + b; + case '[object Number]': + // `NaN`s are equivalent, but non-reflexive. + // Object(NaN) is equivalent to NaN + if (+a !== +a) return +b !== +b; + // An `egal` comparison is performed for other numeric values. + return +a === 0 ? 1 / +a === 1 / b : +a === +b; + case '[object Date]': + case '[object Boolean]': + // Coerce dates and booleans to numeric primitive values. Dates are compared by their + // millisecond representations. Note that invalid dates with millisecond representations + // of `NaN` are not equivalent. + return +a === +b; + } + + var areArrays = className === '[object Array]'; + if (!areArrays) { + if (typeof a != 'object' || typeof b != 'object') return false; + + // Objects with different constructors are not equivalent, but `Object`s or `Array`s + // from different frames are. + var aCtor = a.constructor, bCtor = b.constructor; + if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor && + _.isFunction(bCtor) && bCtor instanceof bCtor) + && ('constructor' in a && 'constructor' in b)) { + return false; + } + } + // Assume equality for cyclic structures. The algorithm for detecting cyclic + // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. + + // Initializing stack of traversed objects. + // It's done here since we only need them for objects and arrays comparison. + aStack = aStack || []; + bStack = bStack || []; + var length = aStack.length; + while (length--) { + // Linear search. Performance is inversely proportional to the number of + // unique nested structures. + if (aStack[length] === a) return bStack[length] === b; + } + + // Add the first object to the stack of traversed objects. + aStack.push(a); + bStack.push(b); + + // Recursively compare objects and arrays. + if (areArrays) { + // Compare array lengths to determine if a deep comparison is necessary. + length = a.length; + if (length !== b.length) return false; + // Deep compare the contents, ignoring non-numeric properties. + while (length--) { + if (!eq(a[length], b[length], aStack, bStack)) return false; + } + } else { + // Deep compare objects. + var keys = _.keys(a), key; + length = keys.length; + // Ensure that both objects contain the same number of properties before comparing deep equality. + if (_.keys(b).length !== length) return false; + while (length--) { + // Deep compare each member + key = keys[length]; + if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false; + } + } + // Remove the first object from the stack of traversed objects. + aStack.pop(); + bStack.pop(); + return true; + }; + + // Perform a deep comparison to check if two objects are equal. + _.isEqual = function(a, b) { + return eq(a, b); + }; + + // Is a given array, string, or object empty? + // An "empty" object has no enumerable own-properties. + _.isEmpty = function(obj) { + if (obj == null) return true; + if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0; + return _.keys(obj).length === 0; + }; + + // Is a given value a DOM element? + _.isElement = function(obj) { + return !!(obj && obj.nodeType === 1); + }; + + // Is a given value an array? + // Delegates to ECMA5's native Array.isArray + _.isArray = nativeIsArray || function(obj) { + return toString.call(obj) === '[object Array]'; + }; + + // Is a given variable an object? + _.isObject = function(obj) { + var type = typeof obj; + return type === 'function' || type === 'object' && !!obj; + }; + + // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError. + _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) { + _['is' + name] = function(obj) { + return toString.call(obj) === '[object ' + name + ']'; + }; + }); + + // Define a fallback version of the method in browsers (ahem, IE < 9), where + // there isn't any inspectable "Arguments" type. + if (!_.isArguments(arguments)) { + _.isArguments = function(obj) { + return _.has(obj, 'callee'); + }; + } + + // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8, + // IE 11 (#1621), and in Safari 8 (#1929). + if (typeof /./ != 'function' && typeof Int8Array != 'object') { + _.isFunction = function(obj) { + return typeof obj == 'function' || false; + }; + } + + // Is a given object a finite number? + _.isFinite = function(obj) { + return isFinite(obj) && !isNaN(parseFloat(obj)); + }; + + // Is the given value `NaN`? (NaN is the only number which does not equal itself). + _.isNaN = function(obj) { + return _.isNumber(obj) && obj !== +obj; + }; + + // Is a given value a boolean? + _.isBoolean = function(obj) { + return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; + }; + + // Is a given value equal to null? + _.isNull = function(obj) { + return obj === null; + }; + + // Is a given variable undefined? + _.isUndefined = function(obj) { + return obj === void 0; + }; + + // Shortcut function for checking if an object has a given property directly + // on itself (in other words, not on a prototype). + _.has = function(obj, key) { + return obj != null && hasOwnProperty.call(obj, key); + }; + + // Utility Functions + // ----------------- + + // Run Underscore.js in *noConflict* mode, returning the `_` variable to its + // previous owner. Returns a reference to the Underscore object. + _.noConflict = function() { + root._ = previousUnderscore; + return this; + }; + + // Keep the identity function around for default iteratees. + _.identity = function(value) { + return value; + }; + + // Predicate-generating functions. Often useful outside of Underscore. + _.constant = function(value) { + return function() { + return value; + }; + }; + + _.noop = function(){}; + + _.property = property; + + // Generates a function for a given object that returns a given property. + _.propertyOf = function(obj) { + return obj == null ? function(){} : function(key) { + return obj[key]; + }; + }; + + // Returns a predicate for checking whether an object has a given set of + // `key:value` pairs. + _.matcher = _.matches = function(attrs) { + attrs = _.extendOwn({}, attrs); + return function(obj) { + return _.isMatch(obj, attrs); + }; + }; + + // Run a function **n** times. + _.times = function(n, iteratee, context) { + var accum = Array(Math.max(0, n)); + iteratee = optimizeCb(iteratee, context, 1); + for (var i = 0; i < n; i++) accum[i] = iteratee(i); + return accum; + }; + + // Return a random integer between min and max (inclusive). + _.random = function(min, max) { + if (max == null) { + max = min; + min = 0; + } + return min + Math.floor(Math.random() * (max - min + 1)); + }; + + // A (possibly faster) way to get the current timestamp as an integer. + _.now = Date.now || function() { + return new Date().getTime(); + }; + + // List of HTML entities for escaping. + var escapeMap = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', + '`': '`' + }; + var unescapeMap = _.invert(escapeMap); + + // Functions for escaping and unescaping strings to/from HTML interpolation. + var createEscaper = function(map) { + var escaper = function(match) { + return map[match]; + }; + // Regexes for identifying a key that needs to be escaped + var source = '(?:' + _.keys(map).join('|') + ')'; + var testRegexp = RegExp(source); + var replaceRegexp = RegExp(source, 'g'); + return function(string) { + string = string == null ? '' : '' + string; + return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; + }; + }; + _.escape = createEscaper(escapeMap); + _.unescape = createEscaper(unescapeMap); + + // If the value of the named `property` is a function then invoke it with the + // `object` as context; otherwise, return it. + _.result = function(object, property, fallback) { + var value = object == null ? void 0 : object[property]; + if (value === void 0) { + value = fallback; + } + return _.isFunction(value) ? value.call(object) : value; + }; + + // Generate a unique integer id (unique within the entire client session). + // Useful for temporary DOM ids. + var idCounter = 0; + _.uniqueId = function(prefix) { + var id = ++idCounter + ''; + return prefix ? prefix + id : id; + }; + + // By default, Underscore uses ERB-style template delimiters, change the + // following template settings to use alternative delimiters. + _.templateSettings = { + evaluate : /<%([\s\S]+?)%>/g, + interpolate : /<%=([\s\S]+?)%>/g, + escape : /<%-([\s\S]+?)%>/g + }; + + // When customizing `templateSettings`, if you don't want to define an + // interpolation, evaluation or escaping regex, we need one that is + // guaranteed not to match. + var noMatch = /(.)^/; + + // Certain characters need to be escaped so that they can be put into a + // string literal. + var escapes = { + "'": "'", + '\\': '\\', + '\r': 'r', + '\n': 'n', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + var escaper = /\\|'|\r|\n|\u2028|\u2029/g; + + var escapeChar = function(match) { + return '\\' + escapes[match]; + }; + + // JavaScript micro-templating, similar to John Resig's implementation. + // Underscore templating handles arbitrary delimiters, preserves whitespace, + // and correctly escapes quotes within interpolated code. + // NB: `oldSettings` only exists for backwards compatibility. + _.template = function(text, settings, oldSettings) { + if (!settings && oldSettings) settings = oldSettings; + settings = _.defaults({}, settings, _.templateSettings); + + // Combine delimiters into one regular expression via alternation. + var matcher = RegExp([ + (settings.escape || noMatch).source, + (settings.interpolate || noMatch).source, + (settings.evaluate || noMatch).source + ].join('|') + '|$', 'g'); + + // Compile the template source, escaping string literals appropriately. + var index = 0; + var source = "__p+='"; + text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { + source += text.slice(index, offset).replace(escaper, escapeChar); + index = offset + match.length; + + if (escape) { + source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; + } else if (interpolate) { + source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; + } else if (evaluate) { + source += "';\n" + evaluate + "\n__p+='"; + } + + // Adobe VMs need the match returned to produce the correct offest. + return match; + }); + source += "';\n"; + + // If a variable is not specified, place data values in local scope. + if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; + + source = "var __t,__p='',__j=Array.prototype.join," + + "print=function(){__p+=__j.call(arguments,'');};\n" + + source + 'return __p;\n'; + + try { + var render = new Function(settings.variable || 'obj', '_', source); + } catch (e) { + e.source = source; + throw e; + } + + var template = function(data) { + return render.call(this, data, _); + }; + + // Provide the compiled source as a convenience for precompilation. + var argument = settings.variable || 'obj'; + template.source = 'function(' + argument + '){\n' + source + '}'; + + return template; + }; + + // Add a "chain" function. Start chaining a wrapped Underscore object. + _.chain = function(obj) { + var instance = _(obj); + instance._chain = true; + return instance; + }; + + // OOP + // --------------- + // If Underscore is called as a function, it returns a wrapped object that + // can be used OO-style. This wrapper holds altered versions of all the + // underscore functions. Wrapped objects may be chained. + + // Helper function to continue chaining intermediate results. + var result = function(instance, obj) { + return instance._chain ? _(obj).chain() : obj; + }; + + // Add your own custom functions to the Underscore object. + _.mixin = function(obj) { + _.each(_.functions(obj), function(name) { + var func = _[name] = obj[name]; + _.prototype[name] = function() { + var args = [this._wrapped]; + push.apply(args, arguments); + return result(this, func.apply(_, args)); + }; + }); + }; + + // Add all of the Underscore functions to the wrapper object. + _.mixin(_); + + // Add all mutator Array functions to the wrapper. + _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { + var method = ArrayProto[name]; + _.prototype[name] = function() { + var obj = this._wrapped; + method.apply(obj, arguments); + if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; + return result(this, obj); + }; + }); + + // Add all accessor Array functions to the wrapper. + _.each(['concat', 'join', 'slice'], function(name) { + var method = ArrayProto[name]; + _.prototype[name] = function() { + return result(this, method.apply(this._wrapped, arguments)); + }; + }); + + // Extracts the result from a wrapped and chained object. + _.prototype.value = function() { + return this._wrapped; + }; + + // Provide unwrapping proxy for some methods used in engine operations + // such as arithmetic and JSON stringification. + _.prototype.valueOf = _.prototype.toJSON = _.prototype.value; + + _.prototype.toString = function() { + return '' + this._wrapped; + }; + + // AMD registration happens at the end for compatibility with AMD loaders + // that may not enforce next-turn semantics on modules. Even though general + // practice for AMD registration is to be anonymous, underscore registers + // as a named module because, like jQuery, it is a base library that is + // popular enough to be bundled in a third party lib, but not be part of + // an AMD load request. Those cases could generate an error when an + // anonymous define() is called outside of a loader request. + if (typeof define === 'function' && define.amd) { + define('underscore', [], function() { + return _; + }); + } +}.call(this)); + +},{}],26:[function(require,module,exports){ +arguments[4][19][0].apply(exports,arguments) +},{"dup":19}],27:[function(require,module,exports){ +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} +},{}],28:[function(require,module,exports){ +(function (process,global){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnviron; +exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = require('./support/isBuffer'); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = require('inherits'); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./support/isBuffer":27,"_process":24,"inherits":26}],29:[function(require,module,exports){ +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +module.exports = wrappy +function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k] + }) + + return wrapper + + function wrapper() { + var args = new Array(arguments.length) + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + var ret = fn.apply(this, args) + var cb = args[args.length-1] + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k] + }) + } + return ret + } +} + +},{}]},{},[7])(7) +}); \ No newline at end of file diff --git a/en/2021.7/assets/javascripts/workers/search.53c85856.min.js b/en/2021.7/assets/javascripts/workers/search.53c85856.min.js new file mode 100644 index 000000000..cec2cff2e --- /dev/null +++ b/en/2021.7/assets/javascripts/workers/search.53c85856.min.js @@ -0,0 +1,48 @@ +(()=>{var pe=Object.create;var z=Object.defineProperty;var ge=Object.getOwnPropertyDescriptor;var ye=Object.getOwnPropertyNames,H=Object.getOwnPropertySymbols,me=Object.getPrototypeOf,Y=Object.prototype.hasOwnProperty,ve=Object.prototype.propertyIsEnumerable;var G=(t,e,r)=>e in t?z(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,J=(t,e)=>{for(var r in e||(e={}))Y.call(e,r)&&G(t,r,e[r]);if(H)for(var r of H(e))ve.call(e,r)&&G(t,r,e[r]);return t};var xe=t=>z(t,"__esModule",{value:!0});var X=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Se=(t,e,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ye(e))!Y.call(t,n)&&n!=="default"&&z(t,n,{get:()=>e[n],enumerable:!(r=ge(e,n))||r.enumerable});return t},Z=t=>Se(xe(z(t!=null?pe(me(t)):{},"default",t&&t.__esModule&&"default"in t?{get:()=>t.default,enumerable:!0}:{value:t,enumerable:!0})),t);var U=(t,e,r)=>new Promise((n,i)=>{var s=u=>{try{a(r.next(u))}catch(c){i(c)}},o=u=>{try{a(r.throw(u))}catch(c){i(c)}},a=u=>u.done?n(u.value):Promise.resolve(u.value).then(s,o);a((r=r.apply(t,e)).next())});var te=X((K,ee)=>{/** + * lunr - http://lunrjs.com - A bit like Solr, but much smaller and not as bright - 2.3.9 + * Copyright (C) 2020 Oliver Nightingale + * @license MIT + */(function(){var t=function(e){var r=new t.Builder;return r.pipeline.add(t.trimmer,t.stopWordFilter,t.stemmer),r.searchPipeline.add(t.stemmer),e.call(r,r),r.build()};t.version="2.3.9";/*! + * lunr.utils + * Copyright (C) 2020 Oliver Nightingale + */t.utils={},t.utils.warn=function(e){return function(r){e.console&&console.warn&&console.warn(r)}}(this),t.utils.asString=function(e){return e==null?"":e.toString()},t.utils.clone=function(e){if(e==null)return e;for(var r=Object.create(null),n=Object.keys(e),i=0;i0){var h=t.utils.clone(r)||{};h.position=[a,c],h.index=s.length,s.push(new t.Token(n.slice(a,o),h))}a=o+1}}return s},t.tokenizer.separator=/[\s\-]+/;/*! + * lunr.Pipeline + * Copyright (C) 2020 Oliver Nightingale + */t.Pipeline=function(){this._stack=[]},t.Pipeline.registeredFunctions=Object.create(null),t.Pipeline.registerFunction=function(e,r){r in this.registeredFunctions&&t.utils.warn("Overwriting existing registered function: "+r),e.label=r,t.Pipeline.registeredFunctions[e.label]=e},t.Pipeline.warnIfFunctionNotRegistered=function(e){var r=e.label&&e.label in this.registeredFunctions;r||t.utils.warn(`Function is not registered with pipeline. This may cause problems when serialising the index. +`,e)},t.Pipeline.load=function(e){var r=new t.Pipeline;return e.forEach(function(n){var i=t.Pipeline.registeredFunctions[n];if(i)r.add(i);else throw new Error("Cannot load unregistered function: "+n)}),r},t.Pipeline.prototype.add=function(){var e=Array.prototype.slice.call(arguments);e.forEach(function(r){t.Pipeline.warnIfFunctionNotRegistered(r),this._stack.push(r)},this)},t.Pipeline.prototype.after=function(e,r){t.Pipeline.warnIfFunctionNotRegistered(r);var n=this._stack.indexOf(e);if(n==-1)throw new Error("Cannot find existingFn");n=n+1,this._stack.splice(n,0,r)},t.Pipeline.prototype.before=function(e,r){t.Pipeline.warnIfFunctionNotRegistered(r);var n=this._stack.indexOf(e);if(n==-1)throw new Error("Cannot find existingFn");this._stack.splice(n,0,r)},t.Pipeline.prototype.remove=function(e){var r=this._stack.indexOf(e);r!=-1&&this._stack.splice(r,1)},t.Pipeline.prototype.run=function(e){for(var r=this._stack.length,n=0;n1&&(oe&&(n=s),o!=e);)i=n-r,s=r+Math.floor(i/2),o=this.elements[s*2];if(o==e||o>e)return s*2;if(ou?h+=2:a==u&&(r+=n[c+1]*i[h+1],c+=2,h+=2);return r},t.Vector.prototype.similarity=function(e){return this.dot(e)/this.magnitude()||0},t.Vector.prototype.toArray=function(){for(var e=new Array(this.elements.length/2),r=1,n=0;r0){var o=s.str.charAt(0),a;o in s.node.edges?a=s.node.edges[o]:(a=new t.TokenSet,s.node.edges[o]=a),s.str.length==1&&(a.final=!0),i.push({node:a,editsRemaining:s.editsRemaining,str:s.str.slice(1)})}if(s.editsRemaining!=0){if("*"in s.node.edges)var u=s.node.edges["*"];else{var u=new t.TokenSet;s.node.edges["*"]=u}if(s.str.length==0&&(u.final=!0),i.push({node:u,editsRemaining:s.editsRemaining-1,str:s.str}),s.str.length>1&&i.push({node:s.node,editsRemaining:s.editsRemaining-1,str:s.str.slice(1)}),s.str.length==1&&(s.node.final=!0),s.str.length>=1){if("*"in s.node.edges)var c=s.node.edges["*"];else{var c=new t.TokenSet;s.node.edges["*"]=c}s.str.length==1&&(c.final=!0),i.push({node:c,editsRemaining:s.editsRemaining-1,str:s.str.slice(1)})}if(s.str.length>1){var h=s.str.charAt(0),y=s.str.charAt(1),g;y in s.node.edges?g=s.node.edges[y]:(g=new t.TokenSet,s.node.edges[y]=g),s.str.length==1&&(g.final=!0),i.push({node:g,editsRemaining:s.editsRemaining-1,str:h+s.str.slice(2)})}}}return n},t.TokenSet.fromString=function(e){for(var r=new t.TokenSet,n=r,i=0,s=e.length;i=e;r--){var n=this.uncheckedNodes[r],i=n.child.toString();i in this.minimizedNodes?n.parent.edges[n.char]=this.minimizedNodes[i]:(n.child._str=i,this.minimizedNodes[i]=n.child),this.uncheckedNodes.pop()}};/*! + * lunr.Index + * Copyright (C) 2020 Oliver Nightingale + */t.Index=function(e){this.invertedIndex=e.invertedIndex,this.fieldVectors=e.fieldVectors,this.tokenSet=e.tokenSet,this.fields=e.fields,this.pipeline=e.pipeline},t.Index.prototype.search=function(e){return this.query(function(r){var n=new t.QueryParser(e,r);n.parse()})},t.Index.prototype.query=function(e){for(var r=new t.Query(this.fields),n=Object.create(null),i=Object.create(null),s=Object.create(null),o=Object.create(null),a=Object.create(null),u=0;u1?this._b=1:this._b=e},t.Builder.prototype.k1=function(e){this._k1=e},t.Builder.prototype.add=function(e,r){var n=e[this._ref],i=Object.keys(this._fields);this._documents[n]=r||{},this.documentCount+=1;for(var s=0;s=this.length)return t.QueryLexer.EOS;var e=this.str.charAt(this.pos);return this.pos+=1,e},t.QueryLexer.prototype.width=function(){return this.pos-this.start},t.QueryLexer.prototype.ignore=function(){this.start==this.pos&&(this.pos+=1),this.start=this.pos},t.QueryLexer.prototype.backup=function(){this.pos-=1},t.QueryLexer.prototype.acceptDigitRun=function(){var e,r;do e=this.next(),r=e.charCodeAt(0);while(r>47&&r<58);e!=t.QueryLexer.EOS&&this.backup()},t.QueryLexer.prototype.more=function(){return this.pos1&&(e.backup(),e.emit(t.QueryLexer.TERM)),e.ignore(),e.more())return t.QueryLexer.lexText},t.QueryLexer.lexEditDistance=function(e){return e.ignore(),e.acceptDigitRun(),e.emit(t.QueryLexer.EDIT_DISTANCE),t.QueryLexer.lexText},t.QueryLexer.lexBoost=function(e){return e.ignore(),e.acceptDigitRun(),e.emit(t.QueryLexer.BOOST),t.QueryLexer.lexText},t.QueryLexer.lexEOS=function(e){e.width()>0&&e.emit(t.QueryLexer.TERM)},t.QueryLexer.termSeparator=t.tokenizer.separator,t.QueryLexer.lexText=function(e){for(;;){var r=e.next();if(r==t.QueryLexer.EOS)return t.QueryLexer.lexEOS;if(r.charCodeAt(0)==92){e.escapeCharacter();continue}if(r==":")return t.QueryLexer.lexField;if(r=="~")return e.backup(),e.width()>0&&e.emit(t.QueryLexer.TERM),t.QueryLexer.lexEditDistance;if(r=="^")return e.backup(),e.width()>0&&e.emit(t.QueryLexer.TERM),t.QueryLexer.lexBoost;if(r=="+"&&e.width()===1||r=="-"&&e.width()===1)return e.emit(t.QueryLexer.PRESENCE),t.QueryLexer.lexText;if(r.match(t.QueryLexer.termSeparator))return t.QueryLexer.lexTerm}},t.QueryParser=function(e,r){this.lexer=new t.QueryLexer(e),this.query=r,this.currentClause={},this.lexemeIdx=0},t.QueryParser.prototype.parse=function(){this.lexer.run(),this.lexemes=this.lexer.lexemes;for(var e=t.QueryParser.parseClause;e;)e=e(this);return this.query},t.QueryParser.prototype.peekLexeme=function(){return this.lexemes[this.lexemeIdx]},t.QueryParser.prototype.consumeLexeme=function(){var e=this.peekLexeme();return this.lexemeIdx+=1,e},t.QueryParser.prototype.nextClause=function(){var e=this.currentClause;this.query.clause(e),this.currentClause={}},t.QueryParser.parseClause=function(e){var r=e.peekLexeme();if(r!=null)switch(r.type){case t.QueryLexer.PRESENCE:return t.QueryParser.parsePresence;case t.QueryLexer.FIELD:return t.QueryParser.parseField;case t.QueryLexer.TERM:return t.QueryParser.parseTerm;default:var n="expected either a field or a term, found "+r.type;throw r.str.length>=1&&(n+=" with value '"+r.str+"'"),new t.QueryParseError(n,r.start,r.end)}},t.QueryParser.parsePresence=function(e){var r=e.consumeLexeme();if(r!=null){switch(r.str){case"-":e.currentClause.presence=t.Query.presence.PROHIBITED;break;case"+":e.currentClause.presence=t.Query.presence.REQUIRED;break;default:var n="unrecognised presence operator'"+r.str+"'";throw new t.QueryParseError(n,r.start,r.end)}var i=e.peekLexeme();if(i==null){var n="expecting term or field, found nothing";throw new t.QueryParseError(n,r.start,r.end)}switch(i.type){case t.QueryLexer.FIELD:return t.QueryParser.parseField;case t.QueryLexer.TERM:return t.QueryParser.parseTerm;default:var n="expecting term or field, found '"+i.type+"'";throw new t.QueryParseError(n,i.start,i.end)}}},t.QueryParser.parseField=function(e){var r=e.consumeLexeme();if(r!=null){if(e.query.allFields.indexOf(r.str)==-1){var n=e.query.allFields.map(function(o){return"'"+o+"'"}).join(", "),i="unrecognised field '"+r.str+"', possible fields: "+n;throw new t.QueryParseError(i,r.start,r.end)}e.currentClause.fields=[r.str];var s=e.peekLexeme();if(s==null){var i="expecting term, found nothing";throw new t.QueryParseError(i,r.start,r.end)}switch(s.type){case t.QueryLexer.TERM:return t.QueryParser.parseTerm;default:var i="expecting term, found '"+s.type+"'";throw new t.QueryParseError(i,s.start,s.end)}}},t.QueryParser.parseTerm=function(e){var r=e.consumeLexeme();if(r!=null){e.currentClause.term=r.str.toLowerCase(),r.str.indexOf("*")!=-1&&(e.currentClause.usePipeline=!1);var n=e.peekLexeme();if(n==null){e.nextClause();return}switch(n.type){case t.QueryLexer.TERM:return e.nextClause(),t.QueryParser.parseTerm;case t.QueryLexer.FIELD:return e.nextClause(),t.QueryParser.parseField;case t.QueryLexer.EDIT_DISTANCE:return t.QueryParser.parseEditDistance;case t.QueryLexer.BOOST:return t.QueryParser.parseBoost;case t.QueryLexer.PRESENCE:return e.nextClause(),t.QueryParser.parsePresence;default:var i="Unexpected lexeme type '"+n.type+"'";throw new t.QueryParseError(i,n.start,n.end)}}},t.QueryParser.parseEditDistance=function(e){var r=e.consumeLexeme();if(r!=null){var n=parseInt(r.str,10);if(isNaN(n)){var i="edit distance must be numeric";throw new t.QueryParseError(i,r.start,r.end)}e.currentClause.editDistance=n;var s=e.peekLexeme();if(s==null){e.nextClause();return}switch(s.type){case t.QueryLexer.TERM:return e.nextClause(),t.QueryParser.parseTerm;case t.QueryLexer.FIELD:return e.nextClause(),t.QueryParser.parseField;case t.QueryLexer.EDIT_DISTANCE:return t.QueryParser.parseEditDistance;case t.QueryLexer.BOOST:return t.QueryParser.parseBoost;case t.QueryLexer.PRESENCE:return e.nextClause(),t.QueryParser.parsePresence;default:var i="Unexpected lexeme type '"+s.type+"'";throw new t.QueryParseError(i,s.start,s.end)}}},t.QueryParser.parseBoost=function(e){var r=e.consumeLexeme();if(r!=null){var n=parseInt(r.str,10);if(isNaN(n)){var i="boost must be numeric";throw new t.QueryParseError(i,r.start,r.end)}e.currentClause.boost=n;var s=e.peekLexeme();if(s==null){e.nextClause();return}switch(s.type){case t.QueryLexer.TERM:return e.nextClause(),t.QueryParser.parseTerm;case t.QueryLexer.FIELD:return e.nextClause(),t.QueryParser.parseField;case t.QueryLexer.EDIT_DISTANCE:return t.QueryParser.parseEditDistance;case t.QueryLexer.BOOST:return t.QueryParser.parseBoost;case t.QueryLexer.PRESENCE:return e.nextClause(),t.QueryParser.parsePresence;default:var i="Unexpected lexeme type '"+s.type+"'";throw new t.QueryParseError(i,s.start,s.end)}}},function(e,r){typeof define=="function"&&define.amd?define(r):typeof K=="object"?ee.exports=r():e.lunr=r()}(this,function(){return t})})()});var ne=X((Pe,re)=>{/*! + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu + * MIT Licensed + */"use strict";var Qe=/["'&<>]/;re.exports=be;function be(t){var e=""+t,r=Qe.exec(e);if(!r)return e;var n,i="",s=0,o=0;for(s=r.index;s`${i}${s}`;return n=>{n=n.replace(/[\s*+\-:~^]+/g," ").trim();let i=new RegExp(`(^|${t.separator})(${n.replace(/[|\\{}()[\]^$+*?.-]/g,"\\$&").replace(e,"|")})`,"img");return s=>s.replace(i,r).replace(/<\/mark>(\s+)]*>/img,"$1")}}function ae(t){let e=new lunr.Query(["title","text"]);return new lunr.QueryParser(t,e).parse(),e.clauses}function ue(t,e){let r=new Set(t),n={};for(let i=0;i!n.has(i)))]}var W=class{constructor({config:e,docs:r,index:n,options:i}){this.options=i,this.documents=se(r),this.highlight=oe(e),lunr.tokenizer.separator=new RegExp(e.separator),typeof n=="undefined"?this.index=lunr(function(){e.lang.length===1&&e.lang[0]!=="en"?this.use(lunr[e.lang[0]]):e.lang.length>1&&this.use(lunr.multiLanguage(...e.lang));let s=we(["trimmer","stopWordFilter","stemmer"],i.pipeline);for(let o of e.lang.map(a=>a==="en"?lunr:lunr[a]))for(let a of s)this.pipeline.remove(o[a]),this.searchPipeline.remove(o[a]);this.ref("location"),this.field("title",{boost:1e3}),this.field("text");for(let o of r)this.add(o)}):this.index=lunr.Index.load(n)}search(e){if(e)try{let r=this.highlight(e),n=ae(e).filter(o=>o.presence!==lunr.Query.presence.PROHIBITED),i=this.index.search(`${e}*`).reduce((o,{ref:a,score:u,matchData:c})=>{let h=this.documents.get(a);if(typeof h!="undefined"){let{location:y,title:g,text:b,parent:v}=h,Q=ue(n,Object.keys(c.metadata)),f=+!v+ +Object.values(Q).every(p=>p);o.push({location:y,title:r(g),text:r(b),score:u*(1+f),terms:Q})}return o},[]).sort((o,a)=>a.score-o.score).reduce((o,a)=>{let u=this.documents.get(a.location);if(typeof u!="undefined"){let c="parent"in u?u.parent.location:u.location;o.set(c,[...o.get(c)||[],a])}return o},new Map),s;if(this.options.suggestions){let o=this.index.query(a=>{for(let u of n)a.term(u.term,{fields:["title"],presence:lunr.Query.presence.REQUIRED,wildcard:lunr.Query.wildcard.TRAILING})});s=o.length?Object.keys(o[0].matchData.metadata):[]}return J({items:[...i.values()]},typeof s!="undefined"&&{suggestions:s})}catch(r){console.warn(`Invalid query: ${e} \u2013 see https://bit.ly/2s3ChXG`)}return{items:[]}}};var T;(function(i){i[i.SETUP=0]="SETUP",i[i.READY=1]="READY",i[i.QUERY=2]="QUERY",i[i.RESULT=3]="RESULT"})(T||(T={}));var q;function Le(t){return U(this,null,function*(){let e="../lunr";if(typeof parent!="undefined"&&"IFrameWorker"in parent){let n=document.querySelector("script[src]"),[i]=n.src.split("/worker");e=e.replace("..",i)}let r=[];for(let n of t.lang){switch(n){case"ja":r.push(`${e}/tinyseg.js`);break;case"hi":case"th":r.push(`${e}/wordcut.js`);break}n!=="en"&&r.push(`${e}/min/lunr.${n}.min.js`)}t.lang.length>1&&r.push(`${e}/min/lunr.multi.min.js`),r.length&&(yield importScripts(`${e}/min/lunr.stemmer.support.min.js`,...r))})}function Ee(t){return U(this,null,function*(){switch(t.type){case T.SETUP:return yield Le(t.data.config),q=new W(t.data),{type:T.READY};case T.QUERY:return{type:T.RESULT,data:q?q.search(t.data):{items:[]}};default:throw new TypeError("Invalid message type")}})}self.lunr=ce.default;addEventListener("message",t=>U(void 0,null,function*(){postMessage(yield Ee(t.data))}));})(); +//# sourceMappingURL=search.53c85856.min.js.map + diff --git a/en/2021.7/assets/javascripts/workers/search.53c85856.min.js.map b/en/2021.7/assets/javascripts/workers/search.53c85856.min.js.map new file mode 100644 index 000000000..e21cedc5e --- /dev/null +++ b/en/2021.7/assets/javascripts/workers/search.53c85856.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["node_modules/lunr/lunr.js", "node_modules/escape-html/index.js", "src/assets/javascripts/integrations/search/worker/main/index.ts", "src/assets/javascripts/integrations/search/document/index.ts", "src/assets/javascripts/integrations/search/highlighter/index.ts", "src/assets/javascripts/integrations/search/query/_/index.ts", "src/assets/javascripts/integrations/search/_/index.ts", "src/assets/javascripts/integrations/search/worker/message/index.ts"], + "sourcesContent": ["/**\n * lunr - http://lunrjs.com - A bit like Solr, but much smaller and not as bright - 2.3.9\n * Copyright (C) 2020 Oliver Nightingale\n * @license MIT\n */\n\n;(function(){\n\n/**\n * A convenience function for configuring and constructing\n * a new lunr Index.\n *\n * A lunr.Builder instance is created and the pipeline setup\n * with a trimmer, stop word filter and stemmer.\n *\n * This builder object is yielded to the configuration function\n * that is passed as a parameter, allowing the list of fields\n * and other builder parameters to be customised.\n *\n * All documents _must_ be added within the passed config function.\n *\n * @example\n * var idx = lunr(function () {\n * this.field('title')\n * this.field('body')\n * this.ref('id')\n *\n * documents.forEach(function (doc) {\n * this.add(doc)\n * }, this)\n * })\n *\n * @see {@link lunr.Builder}\n * @see {@link lunr.Pipeline}\n * @see {@link lunr.trimmer}\n * @see {@link lunr.stopWordFilter}\n * @see {@link lunr.stemmer}\n * @namespace {function} lunr\n */\nvar lunr = function (config) {\n var builder = new lunr.Builder\n\n builder.pipeline.add(\n lunr.trimmer,\n lunr.stopWordFilter,\n lunr.stemmer\n )\n\n builder.searchPipeline.add(\n lunr.stemmer\n )\n\n config.call(builder, builder)\n return builder.build()\n}\n\nlunr.version = \"2.3.9\"\n/*!\n * lunr.utils\n * Copyright (C) 2020 Oliver Nightingale\n */\n\n/**\n * A namespace containing utils for the rest of the lunr library\n * @namespace lunr.utils\n */\nlunr.utils = {}\n\n/**\n * Print a warning message to the console.\n *\n * @param {String} message The message to be printed.\n * @memberOf lunr.utils\n * @function\n */\nlunr.utils.warn = (function (global) {\n /* eslint-disable no-console */\n return function (message) {\n if (global.console && console.warn) {\n console.warn(message)\n }\n }\n /* eslint-enable no-console */\n})(this)\n\n/**\n * Convert an object to a string.\n *\n * In the case of `null` and `undefined` the function returns\n * the empty string, in all other cases the result of calling\n * `toString` on the passed object is returned.\n *\n * @param {Any} obj The object to convert to a string.\n * @return {String} string representation of the passed object.\n * @memberOf lunr.utils\n */\nlunr.utils.asString = function (obj) {\n if (obj === void 0 || obj === null) {\n return \"\"\n } else {\n return obj.toString()\n }\n}\n\n/**\n * Clones an object.\n *\n * Will create a copy of an existing object such that any mutations\n * on the copy cannot affect the original.\n *\n * Only shallow objects are supported, passing a nested object to this\n * function will cause a TypeError.\n *\n * Objects with primitives, and arrays of primitives are supported.\n *\n * @param {Object} obj The object to clone.\n * @return {Object} a clone of the passed object.\n * @throws {TypeError} when a nested object is passed.\n * @memberOf Utils\n */\nlunr.utils.clone = function (obj) {\n if (obj === null || obj === undefined) {\n return obj\n }\n\n var clone = Object.create(null),\n keys = Object.keys(obj)\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i],\n val = obj[key]\n\n if (Array.isArray(val)) {\n clone[key] = val.slice()\n continue\n }\n\n if (typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean') {\n clone[key] = val\n continue\n }\n\n throw new TypeError(\"clone is not deep and does not support nested objects\")\n }\n\n return clone\n}\nlunr.FieldRef = function (docRef, fieldName, stringValue) {\n this.docRef = docRef\n this.fieldName = fieldName\n this._stringValue = stringValue\n}\n\nlunr.FieldRef.joiner = \"/\"\n\nlunr.FieldRef.fromString = function (s) {\n var n = s.indexOf(lunr.FieldRef.joiner)\n\n if (n === -1) {\n throw \"malformed field ref string\"\n }\n\n var fieldRef = s.slice(0, n),\n docRef = s.slice(n + 1)\n\n return new lunr.FieldRef (docRef, fieldRef, s)\n}\n\nlunr.FieldRef.prototype.toString = function () {\n if (this._stringValue == undefined) {\n this._stringValue = this.fieldName + lunr.FieldRef.joiner + this.docRef\n }\n\n return this._stringValue\n}\n/*!\n * lunr.Set\n * Copyright (C) 2020 Oliver Nightingale\n */\n\n/**\n * A lunr set.\n *\n * @constructor\n */\nlunr.Set = function (elements) {\n this.elements = Object.create(null)\n\n if (elements) {\n this.length = elements.length\n\n for (var i = 0; i < this.length; i++) {\n this.elements[elements[i]] = true\n }\n } else {\n this.length = 0\n }\n}\n\n/**\n * A complete set that contains all elements.\n *\n * @static\n * @readonly\n * @type {lunr.Set}\n */\nlunr.Set.complete = {\n intersect: function (other) {\n return other\n },\n\n union: function () {\n return this\n },\n\n contains: function () {\n return true\n }\n}\n\n/**\n * An empty set that contains no elements.\n *\n * @static\n * @readonly\n * @type {lunr.Set}\n */\nlunr.Set.empty = {\n intersect: function () {\n return this\n },\n\n union: function (other) {\n return other\n },\n\n contains: function () {\n return false\n }\n}\n\n/**\n * Returns true if this set contains the specified object.\n *\n * @param {object} object - Object whose presence in this set is to be tested.\n * @returns {boolean} - True if this set contains the specified object.\n */\nlunr.Set.prototype.contains = function (object) {\n return !!this.elements[object]\n}\n\n/**\n * Returns a new set containing only the elements that are present in both\n * this set and the specified set.\n *\n * @param {lunr.Set} other - set to intersect with this set.\n * @returns {lunr.Set} a new set that is the intersection of this and the specified set.\n */\n\nlunr.Set.prototype.intersect = function (other) {\n var a, b, elements, intersection = []\n\n if (other === lunr.Set.complete) {\n return this\n }\n\n if (other === lunr.Set.empty) {\n return other\n }\n\n if (this.length < other.length) {\n a = this\n b = other\n } else {\n a = other\n b = this\n }\n\n elements = Object.keys(a.elements)\n\n for (var i = 0; i < elements.length; i++) {\n var element = elements[i]\n if (element in b.elements) {\n intersection.push(element)\n }\n }\n\n return new lunr.Set (intersection)\n}\n\n/**\n * Returns a new set combining the elements of this and the specified set.\n *\n * @param {lunr.Set} other - set to union with this set.\n * @return {lunr.Set} a new set that is the union of this and the specified set.\n */\n\nlunr.Set.prototype.union = function (other) {\n if (other === lunr.Set.complete) {\n return lunr.Set.complete\n }\n\n if (other === lunr.Set.empty) {\n return this\n }\n\n return new lunr.Set(Object.keys(this.elements).concat(Object.keys(other.elements)))\n}\n/**\n * A function to calculate the inverse document frequency for\n * a posting. This is shared between the builder and the index\n *\n * @private\n * @param {object} posting - The posting for a given term\n * @param {number} documentCount - The total number of documents.\n */\nlunr.idf = function (posting, documentCount) {\n var documentsWithTerm = 0\n\n for (var fieldName in posting) {\n if (fieldName == '_index') continue // Ignore the term index, its not a field\n documentsWithTerm += Object.keys(posting[fieldName]).length\n }\n\n var x = (documentCount - documentsWithTerm + 0.5) / (documentsWithTerm + 0.5)\n\n return Math.log(1 + Math.abs(x))\n}\n\n/**\n * A token wraps a string representation of a token\n * as it is passed through the text processing pipeline.\n *\n * @constructor\n * @param {string} [str=''] - The string token being wrapped.\n * @param {object} [metadata={}] - Metadata associated with this token.\n */\nlunr.Token = function (str, metadata) {\n this.str = str || \"\"\n this.metadata = metadata || {}\n}\n\n/**\n * Returns the token string that is being wrapped by this object.\n *\n * @returns {string}\n */\nlunr.Token.prototype.toString = function () {\n return this.str\n}\n\n/**\n * A token update function is used when updating or optionally\n * when cloning a token.\n *\n * @callback lunr.Token~updateFunction\n * @param {string} str - The string representation of the token.\n * @param {Object} metadata - All metadata associated with this token.\n */\n\n/**\n * Applies the given function to the wrapped string token.\n *\n * @example\n * token.update(function (str, metadata) {\n * return str.toUpperCase()\n * })\n *\n * @param {lunr.Token~updateFunction} fn - A function to apply to the token string.\n * @returns {lunr.Token}\n */\nlunr.Token.prototype.update = function (fn) {\n this.str = fn(this.str, this.metadata)\n return this\n}\n\n/**\n * Creates a clone of this token. Optionally a function can be\n * applied to the cloned token.\n *\n * @param {lunr.Token~updateFunction} [fn] - An optional function to apply to the cloned token.\n * @returns {lunr.Token}\n */\nlunr.Token.prototype.clone = function (fn) {\n fn = fn || function (s) { return s }\n return new lunr.Token (fn(this.str, this.metadata), this.metadata)\n}\n/*!\n * lunr.tokenizer\n * Copyright (C) 2020 Oliver Nightingale\n */\n\n/**\n * A function for splitting a string into tokens ready to be inserted into\n * the search index. Uses `lunr.tokenizer.separator` to split strings, change\n * the value of this property to change how strings are split into tokens.\n *\n * This tokenizer will convert its parameter to a string by calling `toString` and\n * then will split this string on the character in `lunr.tokenizer.separator`.\n * Arrays will have their elements converted to strings and wrapped in a lunr.Token.\n *\n * Optional metadata can be passed to the tokenizer, this metadata will be cloned and\n * added as metadata to every token that is created from the object to be tokenized.\n *\n * @static\n * @param {?(string|object|object[])} obj - The object to convert into tokens\n * @param {?object} metadata - Optional metadata to associate with every token\n * @returns {lunr.Token[]}\n * @see {@link lunr.Pipeline}\n */\nlunr.tokenizer = function (obj, metadata) {\n if (obj == null || obj == undefined) {\n return []\n }\n\n if (Array.isArray(obj)) {\n return obj.map(function (t) {\n return new lunr.Token(\n lunr.utils.asString(t).toLowerCase(),\n lunr.utils.clone(metadata)\n )\n })\n }\n\n var str = obj.toString().toLowerCase(),\n len = str.length,\n tokens = []\n\n for (var sliceEnd = 0, sliceStart = 0; sliceEnd <= len; sliceEnd++) {\n var char = str.charAt(sliceEnd),\n sliceLength = sliceEnd - sliceStart\n\n if ((char.match(lunr.tokenizer.separator) || sliceEnd == len)) {\n\n if (sliceLength > 0) {\n var tokenMetadata = lunr.utils.clone(metadata) || {}\n tokenMetadata[\"position\"] = [sliceStart, sliceLength]\n tokenMetadata[\"index\"] = tokens.length\n\n tokens.push(\n new lunr.Token (\n str.slice(sliceStart, sliceEnd),\n tokenMetadata\n )\n )\n }\n\n sliceStart = sliceEnd + 1\n }\n\n }\n\n return tokens\n}\n\n/**\n * The separator used to split a string into tokens. Override this property to change the behaviour of\n * `lunr.tokenizer` behaviour when tokenizing strings. By default this splits on whitespace and hyphens.\n *\n * @static\n * @see lunr.tokenizer\n */\nlunr.tokenizer.separator = /[\\s\\-]+/\n/*!\n * lunr.Pipeline\n * Copyright (C) 2020 Oliver Nightingale\n */\n\n/**\n * lunr.Pipelines maintain an ordered list of functions to be applied to all\n * tokens in documents entering the search index and queries being ran against\n * the index.\n *\n * An instance of lunr.Index created with the lunr shortcut will contain a\n * pipeline with a stop word filter and an English language stemmer. Extra\n * functions can be added before or after either of these functions or these\n * default functions can be removed.\n *\n * When run the pipeline will call each function in turn, passing a token, the\n * index of that token in the original list of all tokens and finally a list of\n * all the original tokens.\n *\n * The output of functions in the pipeline will be passed to the next function\n * in the pipeline. To exclude a token from entering the index the function\n * should return undefined, the rest of the pipeline will not be called with\n * this token.\n *\n * For serialisation of pipelines to work, all functions used in an instance of\n * a pipeline should be registered with lunr.Pipeline. Registered functions can\n * then be loaded. If trying to load a serialised pipeline that uses functions\n * that are not registered an error will be thrown.\n *\n * If not planning on serialising the pipeline then registering pipeline functions\n * is not necessary.\n *\n * @constructor\n */\nlunr.Pipeline = function () {\n this._stack = []\n}\n\nlunr.Pipeline.registeredFunctions = Object.create(null)\n\n/**\n * A pipeline function maps lunr.Token to lunr.Token. A lunr.Token contains the token\n * string as well as all known metadata. A pipeline function can mutate the token string\n * or mutate (or add) metadata for a given token.\n *\n * A pipeline function can indicate that the passed token should be discarded by returning\n * null, undefined or an empty string. This token will not be passed to any downstream pipeline\n * functions and will not be added to the index.\n *\n * Multiple tokens can be returned by returning an array of tokens. Each token will be passed\n * to any downstream pipeline functions and all will returned tokens will be added to the index.\n *\n * Any number of pipeline functions may be chained together using a lunr.Pipeline.\n *\n * @interface lunr.PipelineFunction\n * @param {lunr.Token} token - A token from the document being processed.\n * @param {number} i - The index of this token in the complete list of tokens for this document/field.\n * @param {lunr.Token[]} tokens - All tokens for this document/field.\n * @returns {(?lunr.Token|lunr.Token[])}\n */\n\n/**\n * Register a function with the pipeline.\n *\n * Functions that are used in the pipeline should be registered if the pipeline\n * needs to be serialised, or a serialised pipeline needs to be loaded.\n *\n * Registering a function does not add it to a pipeline, functions must still be\n * added to instances of the pipeline for them to be used when running a pipeline.\n *\n * @param {lunr.PipelineFunction} fn - The function to check for.\n * @param {String} label - The label to register this function with\n */\nlunr.Pipeline.registerFunction = function (fn, label) {\n if (label in this.registeredFunctions) {\n lunr.utils.warn('Overwriting existing registered function: ' + label)\n }\n\n fn.label = label\n lunr.Pipeline.registeredFunctions[fn.label] = fn\n}\n\n/**\n * Warns if the function is not registered as a Pipeline function.\n *\n * @param {lunr.PipelineFunction} fn - The function to check for.\n * @private\n */\nlunr.Pipeline.warnIfFunctionNotRegistered = function (fn) {\n var isRegistered = fn.label && (fn.label in this.registeredFunctions)\n\n if (!isRegistered) {\n lunr.utils.warn('Function is not registered with pipeline. This may cause problems when serialising the index.\\n', fn)\n }\n}\n\n/**\n * Loads a previously serialised pipeline.\n *\n * All functions to be loaded must already be registered with lunr.Pipeline.\n * If any function from the serialised data has not been registered then an\n * error will be thrown.\n *\n * @param {Object} serialised - The serialised pipeline to load.\n * @returns {lunr.Pipeline}\n */\nlunr.Pipeline.load = function (serialised) {\n var pipeline = new lunr.Pipeline\n\n serialised.forEach(function (fnName) {\n var fn = lunr.Pipeline.registeredFunctions[fnName]\n\n if (fn) {\n pipeline.add(fn)\n } else {\n throw new Error('Cannot load unregistered function: ' + fnName)\n }\n })\n\n return pipeline\n}\n\n/**\n * Adds new functions to the end of the pipeline.\n *\n * Logs a warning if the function has not been registered.\n *\n * @param {lunr.PipelineFunction[]} functions - Any number of functions to add to the pipeline.\n */\nlunr.Pipeline.prototype.add = function () {\n var fns = Array.prototype.slice.call(arguments)\n\n fns.forEach(function (fn) {\n lunr.Pipeline.warnIfFunctionNotRegistered(fn)\n this._stack.push(fn)\n }, this)\n}\n\n/**\n * Adds a single function after a function that already exists in the\n * pipeline.\n *\n * Logs a warning if the function has not been registered.\n *\n * @param {lunr.PipelineFunction} existingFn - A function that already exists in the pipeline.\n * @param {lunr.PipelineFunction} newFn - The new function to add to the pipeline.\n */\nlunr.Pipeline.prototype.after = function (existingFn, newFn) {\n lunr.Pipeline.warnIfFunctionNotRegistered(newFn)\n\n var pos = this._stack.indexOf(existingFn)\n if (pos == -1) {\n throw new Error('Cannot find existingFn')\n }\n\n pos = pos + 1\n this._stack.splice(pos, 0, newFn)\n}\n\n/**\n * Adds a single function before a function that already exists in the\n * pipeline.\n *\n * Logs a warning if the function has not been registered.\n *\n * @param {lunr.PipelineFunction} existingFn - A function that already exists in the pipeline.\n * @param {lunr.PipelineFunction} newFn - The new function to add to the pipeline.\n */\nlunr.Pipeline.prototype.before = function (existingFn, newFn) {\n lunr.Pipeline.warnIfFunctionNotRegistered(newFn)\n\n var pos = this._stack.indexOf(existingFn)\n if (pos == -1) {\n throw new Error('Cannot find existingFn')\n }\n\n this._stack.splice(pos, 0, newFn)\n}\n\n/**\n * Removes a function from the pipeline.\n *\n * @param {lunr.PipelineFunction} fn The function to remove from the pipeline.\n */\nlunr.Pipeline.prototype.remove = function (fn) {\n var pos = this._stack.indexOf(fn)\n if (pos == -1) {\n return\n }\n\n this._stack.splice(pos, 1)\n}\n\n/**\n * Runs the current list of functions that make up the pipeline against the\n * passed tokens.\n *\n * @param {Array} tokens The tokens to run through the pipeline.\n * @returns {Array}\n */\nlunr.Pipeline.prototype.run = function (tokens) {\n var stackLength = this._stack.length\n\n for (var i = 0; i < stackLength; i++) {\n var fn = this._stack[i]\n var memo = []\n\n for (var j = 0; j < tokens.length; j++) {\n var result = fn(tokens[j], j, tokens)\n\n if (result === null || result === void 0 || result === '') continue\n\n if (Array.isArray(result)) {\n for (var k = 0; k < result.length; k++) {\n memo.push(result[k])\n }\n } else {\n memo.push(result)\n }\n }\n\n tokens = memo\n }\n\n return tokens\n}\n\n/**\n * Convenience method for passing a string through a pipeline and getting\n * strings out. This method takes care of wrapping the passed string in a\n * token and mapping the resulting tokens back to strings.\n *\n * @param {string} str - The string to pass through the pipeline.\n * @param {?object} metadata - Optional metadata to associate with the token\n * passed to the pipeline.\n * @returns {string[]}\n */\nlunr.Pipeline.prototype.runString = function (str, metadata) {\n var token = new lunr.Token (str, metadata)\n\n return this.run([token]).map(function (t) {\n return t.toString()\n })\n}\n\n/**\n * Resets the pipeline by removing any existing processors.\n *\n */\nlunr.Pipeline.prototype.reset = function () {\n this._stack = []\n}\n\n/**\n * Returns a representation of the pipeline ready for serialisation.\n *\n * Logs a warning if the function has not been registered.\n *\n * @returns {Array}\n */\nlunr.Pipeline.prototype.toJSON = function () {\n return this._stack.map(function (fn) {\n lunr.Pipeline.warnIfFunctionNotRegistered(fn)\n\n return fn.label\n })\n}\n/*!\n * lunr.Vector\n * Copyright (C) 2020 Oliver Nightingale\n */\n\n/**\n * A vector is used to construct the vector space of documents and queries. These\n * vectors support operations to determine the similarity between two documents or\n * a document and a query.\n *\n * Normally no parameters are required for initializing a vector, but in the case of\n * loading a previously dumped vector the raw elements can be provided to the constructor.\n *\n * For performance reasons vectors are implemented with a flat array, where an elements\n * index is immediately followed by its value. E.g. [index, value, index, value]. This\n * allows the underlying array to be as sparse as possible and still offer decent\n * performance when being used for vector calculations.\n *\n * @constructor\n * @param {Number[]} [elements] - The flat list of element index and element value pairs.\n */\nlunr.Vector = function (elements) {\n this._magnitude = 0\n this.elements = elements || []\n}\n\n\n/**\n * Calculates the position within the vector to insert a given index.\n *\n * This is used internally by insert and upsert. If there are duplicate indexes then\n * the position is returned as if the value for that index were to be updated, but it\n * is the callers responsibility to check whether there is a duplicate at that index\n *\n * @param {Number} insertIdx - The index at which the element should be inserted.\n * @returns {Number}\n */\nlunr.Vector.prototype.positionForIndex = function (index) {\n // For an empty vector the tuple can be inserted at the beginning\n if (this.elements.length == 0) {\n return 0\n }\n\n var start = 0,\n end = this.elements.length / 2,\n sliceLength = end - start,\n pivotPoint = Math.floor(sliceLength / 2),\n pivotIndex = this.elements[pivotPoint * 2]\n\n while (sliceLength > 1) {\n if (pivotIndex < index) {\n start = pivotPoint\n }\n\n if (pivotIndex > index) {\n end = pivotPoint\n }\n\n if (pivotIndex == index) {\n break\n }\n\n sliceLength = end - start\n pivotPoint = start + Math.floor(sliceLength / 2)\n pivotIndex = this.elements[pivotPoint * 2]\n }\n\n if (pivotIndex == index) {\n return pivotPoint * 2\n }\n\n if (pivotIndex > index) {\n return pivotPoint * 2\n }\n\n if (pivotIndex < index) {\n return (pivotPoint + 1) * 2\n }\n}\n\n/**\n * Inserts an element at an index within the vector.\n *\n * Does not allow duplicates, will throw an error if there is already an entry\n * for this index.\n *\n * @param {Number} insertIdx - The index at which the element should be inserted.\n * @param {Number} val - The value to be inserted into the vector.\n */\nlunr.Vector.prototype.insert = function (insertIdx, val) {\n this.upsert(insertIdx, val, function () {\n throw \"duplicate index\"\n })\n}\n\n/**\n * Inserts or updates an existing index within the vector.\n *\n * @param {Number} insertIdx - The index at which the element should be inserted.\n * @param {Number} val - The value to be inserted into the vector.\n * @param {function} fn - A function that is called for updates, the existing value and the\n * requested value are passed as arguments\n */\nlunr.Vector.prototype.upsert = function (insertIdx, val, fn) {\n this._magnitude = 0\n var position = this.positionForIndex(insertIdx)\n\n if (this.elements[position] == insertIdx) {\n this.elements[position + 1] = fn(this.elements[position + 1], val)\n } else {\n this.elements.splice(position, 0, insertIdx, val)\n }\n}\n\n/**\n * Calculates the magnitude of this vector.\n *\n * @returns {Number}\n */\nlunr.Vector.prototype.magnitude = function () {\n if (this._magnitude) return this._magnitude\n\n var sumOfSquares = 0,\n elementsLength = this.elements.length\n\n for (var i = 1; i < elementsLength; i += 2) {\n var val = this.elements[i]\n sumOfSquares += val * val\n }\n\n return this._magnitude = Math.sqrt(sumOfSquares)\n}\n\n/**\n * Calculates the dot product of this vector and another vector.\n *\n * @param {lunr.Vector} otherVector - The vector to compute the dot product with.\n * @returns {Number}\n */\nlunr.Vector.prototype.dot = function (otherVector) {\n var dotProduct = 0,\n a = this.elements, b = otherVector.elements,\n aLen = a.length, bLen = b.length,\n aVal = 0, bVal = 0,\n i = 0, j = 0\n\n while (i < aLen && j < bLen) {\n aVal = a[i], bVal = b[j]\n if (aVal < bVal) {\n i += 2\n } else if (aVal > bVal) {\n j += 2\n } else if (aVal == bVal) {\n dotProduct += a[i + 1] * b[j + 1]\n i += 2\n j += 2\n }\n }\n\n return dotProduct\n}\n\n/**\n * Calculates the similarity between this vector and another vector.\n *\n * @param {lunr.Vector} otherVector - The other vector to calculate the\n * similarity with.\n * @returns {Number}\n */\nlunr.Vector.prototype.similarity = function (otherVector) {\n return this.dot(otherVector) / this.magnitude() || 0\n}\n\n/**\n * Converts the vector to an array of the elements within the vector.\n *\n * @returns {Number[]}\n */\nlunr.Vector.prototype.toArray = function () {\n var output = new Array (this.elements.length / 2)\n\n for (var i = 1, j = 0; i < this.elements.length; i += 2, j++) {\n output[j] = this.elements[i]\n }\n\n return output\n}\n\n/**\n * A JSON serializable representation of the vector.\n *\n * @returns {Number[]}\n */\nlunr.Vector.prototype.toJSON = function () {\n return this.elements\n}\n/* eslint-disable */\n/*!\n * lunr.stemmer\n * Copyright (C) 2020 Oliver Nightingale\n * Includes code from - http://tartarus.org/~martin/PorterStemmer/js.txt\n */\n\n/**\n * lunr.stemmer is an english language stemmer, this is a JavaScript\n * implementation of the PorterStemmer taken from http://tartarus.org/~martin\n *\n * @static\n * @implements {lunr.PipelineFunction}\n * @param {lunr.Token} token - The string to stem\n * @returns {lunr.Token}\n * @see {@link lunr.Pipeline}\n * @function\n */\nlunr.stemmer = (function(){\n var step2list = {\n \"ational\" : \"ate\",\n \"tional\" : \"tion\",\n \"enci\" : \"ence\",\n \"anci\" : \"ance\",\n \"izer\" : \"ize\",\n \"bli\" : \"ble\",\n \"alli\" : \"al\",\n \"entli\" : \"ent\",\n \"eli\" : \"e\",\n \"ousli\" : \"ous\",\n \"ization\" : \"ize\",\n \"ation\" : \"ate\",\n \"ator\" : \"ate\",\n \"alism\" : \"al\",\n \"iveness\" : \"ive\",\n \"fulness\" : \"ful\",\n \"ousness\" : \"ous\",\n \"aliti\" : \"al\",\n \"iviti\" : \"ive\",\n \"biliti\" : \"ble\",\n \"logi\" : \"log\"\n },\n\n step3list = {\n \"icate\" : \"ic\",\n \"ative\" : \"\",\n \"alize\" : \"al\",\n \"iciti\" : \"ic\",\n \"ical\" : \"ic\",\n \"ful\" : \"\",\n \"ness\" : \"\"\n },\n\n c = \"[^aeiou]\", // consonant\n v = \"[aeiouy]\", // vowel\n C = c + \"[^aeiouy]*\", // consonant sequence\n V = v + \"[aeiou]*\", // vowel sequence\n\n mgr0 = \"^(\" + C + \")?\" + V + C, // [C]VC... is m>0\n meq1 = \"^(\" + C + \")?\" + V + C + \"(\" + V + \")?$\", // [C]VC[V] is m=1\n mgr1 = \"^(\" + C + \")?\" + V + C + V + C, // [C]VCVC... is m>1\n s_v = \"^(\" + C + \")?\" + v; // vowel in stem\n\n var re_mgr0 = new RegExp(mgr0);\n var re_mgr1 = new RegExp(mgr1);\n var re_meq1 = new RegExp(meq1);\n var re_s_v = new RegExp(s_v);\n\n var re_1a = /^(.+?)(ss|i)es$/;\n var re2_1a = /^(.+?)([^s])s$/;\n var re_1b = /^(.+?)eed$/;\n var re2_1b = /^(.+?)(ed|ing)$/;\n var re_1b_2 = /.$/;\n var re2_1b_2 = /(at|bl|iz)$/;\n var re3_1b_2 = new RegExp(\"([^aeiouylsz])\\\\1$\");\n var re4_1b_2 = new RegExp(\"^\" + C + v + \"[^aeiouwxy]$\");\n\n var re_1c = /^(.+?[^aeiou])y$/;\n var re_2 = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/;\n\n var re_3 = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/;\n\n var re_4 = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/;\n var re2_4 = /^(.+?)(s|t)(ion)$/;\n\n var re_5 = /^(.+?)e$/;\n var re_5_1 = /ll$/;\n var re3_5 = new RegExp(\"^\" + C + v + \"[^aeiouwxy]$\");\n\n var porterStemmer = function porterStemmer(w) {\n var stem,\n suffix,\n firstch,\n re,\n re2,\n re3,\n re4;\n\n if (w.length < 3) { return w; }\n\n firstch = w.substr(0,1);\n if (firstch == \"y\") {\n w = firstch.toUpperCase() + w.substr(1);\n }\n\n // Step 1a\n re = re_1a\n re2 = re2_1a;\n\n if (re.test(w)) { w = w.replace(re,\"$1$2\"); }\n else if (re2.test(w)) { w = w.replace(re2,\"$1$2\"); }\n\n // Step 1b\n re = re_1b;\n re2 = re2_1b;\n if (re.test(w)) {\n var fp = re.exec(w);\n re = re_mgr0;\n if (re.test(fp[1])) {\n re = re_1b_2;\n w = w.replace(re,\"\");\n }\n } else if (re2.test(w)) {\n var fp = re2.exec(w);\n stem = fp[1];\n re2 = re_s_v;\n if (re2.test(stem)) {\n w = stem;\n re2 = re2_1b_2;\n re3 = re3_1b_2;\n re4 = re4_1b_2;\n if (re2.test(w)) { w = w + \"e\"; }\n else if (re3.test(w)) { re = re_1b_2; w = w.replace(re,\"\"); }\n else if (re4.test(w)) { w = w + \"e\"; }\n }\n }\n\n // Step 1c - replace suffix y or Y by i if preceded by a non-vowel which is not the first letter of the word (so cry -> cri, by -> by, say -> say)\n re = re_1c;\n if (re.test(w)) {\n var fp = re.exec(w);\n stem = fp[1];\n w = stem + \"i\";\n }\n\n // Step 2\n re = re_2;\n if (re.test(w)) {\n var fp = re.exec(w);\n stem = fp[1];\n suffix = fp[2];\n re = re_mgr0;\n if (re.test(stem)) {\n w = stem + step2list[suffix];\n }\n }\n\n // Step 3\n re = re_3;\n if (re.test(w)) {\n var fp = re.exec(w);\n stem = fp[1];\n suffix = fp[2];\n re = re_mgr0;\n if (re.test(stem)) {\n w = stem + step3list[suffix];\n }\n }\n\n // Step 4\n re = re_4;\n re2 = re2_4;\n if (re.test(w)) {\n var fp = re.exec(w);\n stem = fp[1];\n re = re_mgr1;\n if (re.test(stem)) {\n w = stem;\n }\n } else if (re2.test(w)) {\n var fp = re2.exec(w);\n stem = fp[1] + fp[2];\n re2 = re_mgr1;\n if (re2.test(stem)) {\n w = stem;\n }\n }\n\n // Step 5\n re = re_5;\n if (re.test(w)) {\n var fp = re.exec(w);\n stem = fp[1];\n re = re_mgr1;\n re2 = re_meq1;\n re3 = re3_5;\n if (re.test(stem) || (re2.test(stem) && !(re3.test(stem)))) {\n w = stem;\n }\n }\n\n re = re_5_1;\n re2 = re_mgr1;\n if (re.test(w) && re2.test(w)) {\n re = re_1b_2;\n w = w.replace(re,\"\");\n }\n\n // and turn initial Y back to y\n\n if (firstch == \"y\") {\n w = firstch.toLowerCase() + w.substr(1);\n }\n\n return w;\n };\n\n return function (token) {\n return token.update(porterStemmer);\n }\n})();\n\nlunr.Pipeline.registerFunction(lunr.stemmer, 'stemmer')\n/*!\n * lunr.stopWordFilter\n * Copyright (C) 2020 Oliver Nightingale\n */\n\n/**\n * lunr.generateStopWordFilter builds a stopWordFilter function from the provided\n * list of stop words.\n *\n * The built in lunr.stopWordFilter is built using this generator and can be used\n * to generate custom stopWordFilters for applications or non English languages.\n *\n * @function\n * @param {Array} token The token to pass through the filter\n * @returns {lunr.PipelineFunction}\n * @see lunr.Pipeline\n * @see lunr.stopWordFilter\n */\nlunr.generateStopWordFilter = function (stopWords) {\n var words = stopWords.reduce(function (memo, stopWord) {\n memo[stopWord] = stopWord\n return memo\n }, {})\n\n return function (token) {\n if (token && words[token.toString()] !== token.toString()) return token\n }\n}\n\n/**\n * lunr.stopWordFilter is an English language stop word list filter, any words\n * contained in the list will not be passed through the filter.\n *\n * This is intended to be used in the Pipeline. If the token does not pass the\n * filter then undefined will be returned.\n *\n * @function\n * @implements {lunr.PipelineFunction}\n * @params {lunr.Token} token - A token to check for being a stop word.\n * @returns {lunr.Token}\n * @see {@link lunr.Pipeline}\n */\nlunr.stopWordFilter = lunr.generateStopWordFilter([\n 'a',\n 'able',\n 'about',\n 'across',\n 'after',\n 'all',\n 'almost',\n 'also',\n 'am',\n 'among',\n 'an',\n 'and',\n 'any',\n 'are',\n 'as',\n 'at',\n 'be',\n 'because',\n 'been',\n 'but',\n 'by',\n 'can',\n 'cannot',\n 'could',\n 'dear',\n 'did',\n 'do',\n 'does',\n 'either',\n 'else',\n 'ever',\n 'every',\n 'for',\n 'from',\n 'get',\n 'got',\n 'had',\n 'has',\n 'have',\n 'he',\n 'her',\n 'hers',\n 'him',\n 'his',\n 'how',\n 'however',\n 'i',\n 'if',\n 'in',\n 'into',\n 'is',\n 'it',\n 'its',\n 'just',\n 'least',\n 'let',\n 'like',\n 'likely',\n 'may',\n 'me',\n 'might',\n 'most',\n 'must',\n 'my',\n 'neither',\n 'no',\n 'nor',\n 'not',\n 'of',\n 'off',\n 'often',\n 'on',\n 'only',\n 'or',\n 'other',\n 'our',\n 'own',\n 'rather',\n 'said',\n 'say',\n 'says',\n 'she',\n 'should',\n 'since',\n 'so',\n 'some',\n 'than',\n 'that',\n 'the',\n 'their',\n 'them',\n 'then',\n 'there',\n 'these',\n 'they',\n 'this',\n 'tis',\n 'to',\n 'too',\n 'twas',\n 'us',\n 'wants',\n 'was',\n 'we',\n 'were',\n 'what',\n 'when',\n 'where',\n 'which',\n 'while',\n 'who',\n 'whom',\n 'why',\n 'will',\n 'with',\n 'would',\n 'yet',\n 'you',\n 'your'\n])\n\nlunr.Pipeline.registerFunction(lunr.stopWordFilter, 'stopWordFilter')\n/*!\n * lunr.trimmer\n * Copyright (C) 2020 Oliver Nightingale\n */\n\n/**\n * lunr.trimmer is a pipeline function for trimming non word\n * characters from the beginning and end of tokens before they\n * enter the index.\n *\n * This implementation may not work correctly for non latin\n * characters and should either be removed or adapted for use\n * with languages with non-latin characters.\n *\n * @static\n * @implements {lunr.PipelineFunction}\n * @param {lunr.Token} token The token to pass through the filter\n * @returns {lunr.Token}\n * @see lunr.Pipeline\n */\nlunr.trimmer = function (token) {\n return token.update(function (s) {\n return s.replace(/^\\W+/, '').replace(/\\W+$/, '')\n })\n}\n\nlunr.Pipeline.registerFunction(lunr.trimmer, 'trimmer')\n/*!\n * lunr.TokenSet\n * Copyright (C) 2020 Oliver Nightingale\n */\n\n/**\n * A token set is used to store the unique list of all tokens\n * within an index. Token sets are also used to represent an\n * incoming query to the index, this query token set and index\n * token set are then intersected to find which tokens to look\n * up in the inverted index.\n *\n * A token set can hold multiple tokens, as in the case of the\n * index token set, or it can hold a single token as in the\n * case of a simple query token set.\n *\n * Additionally token sets are used to perform wildcard matching.\n * Leading, contained and trailing wildcards are supported, and\n * from this edit distance matching can also be provided.\n *\n * Token sets are implemented as a minimal finite state automata,\n * where both common prefixes and suffixes are shared between tokens.\n * This helps to reduce the space used for storing the token set.\n *\n * @constructor\n */\nlunr.TokenSet = function () {\n this.final = false\n this.edges = {}\n this.id = lunr.TokenSet._nextId\n lunr.TokenSet._nextId += 1\n}\n\n/**\n * Keeps track of the next, auto increment, identifier to assign\n * to a new tokenSet.\n *\n * TokenSets require a unique identifier to be correctly minimised.\n *\n * @private\n */\nlunr.TokenSet._nextId = 1\n\n/**\n * Creates a TokenSet instance from the given sorted array of words.\n *\n * @param {String[]} arr - A sorted array of strings to create the set from.\n * @returns {lunr.TokenSet}\n * @throws Will throw an error if the input array is not sorted.\n */\nlunr.TokenSet.fromArray = function (arr) {\n var builder = new lunr.TokenSet.Builder\n\n for (var i = 0, len = arr.length; i < len; i++) {\n builder.insert(arr[i])\n }\n\n builder.finish()\n return builder.root\n}\n\n/**\n * Creates a token set from a query clause.\n *\n * @private\n * @param {Object} clause - A single clause from lunr.Query.\n * @param {string} clause.term - The query clause term.\n * @param {number} [clause.editDistance] - The optional edit distance for the term.\n * @returns {lunr.TokenSet}\n */\nlunr.TokenSet.fromClause = function (clause) {\n if ('editDistance' in clause) {\n return lunr.TokenSet.fromFuzzyString(clause.term, clause.editDistance)\n } else {\n return lunr.TokenSet.fromString(clause.term)\n }\n}\n\n/**\n * Creates a token set representing a single string with a specified\n * edit distance.\n *\n * Insertions, deletions, substitutions and transpositions are each\n * treated as an edit distance of 1.\n *\n * Increasing the allowed edit distance will have a dramatic impact\n * on the performance of both creating and intersecting these TokenSets.\n * It is advised to keep the edit distance less than 3.\n *\n * @param {string} str - The string to create the token set from.\n * @param {number} editDistance - The allowed edit distance to match.\n * @returns {lunr.Vector}\n */\nlunr.TokenSet.fromFuzzyString = function (str, editDistance) {\n var root = new lunr.TokenSet\n\n var stack = [{\n node: root,\n editsRemaining: editDistance,\n str: str\n }]\n\n while (stack.length) {\n var frame = stack.pop()\n\n // no edit\n if (frame.str.length > 0) {\n var char = frame.str.charAt(0),\n noEditNode\n\n if (char in frame.node.edges) {\n noEditNode = frame.node.edges[char]\n } else {\n noEditNode = new lunr.TokenSet\n frame.node.edges[char] = noEditNode\n }\n\n if (frame.str.length == 1) {\n noEditNode.final = true\n }\n\n stack.push({\n node: noEditNode,\n editsRemaining: frame.editsRemaining,\n str: frame.str.slice(1)\n })\n }\n\n if (frame.editsRemaining == 0) {\n continue\n }\n\n // insertion\n if (\"*\" in frame.node.edges) {\n var insertionNode = frame.node.edges[\"*\"]\n } else {\n var insertionNode = new lunr.TokenSet\n frame.node.edges[\"*\"] = insertionNode\n }\n\n if (frame.str.length == 0) {\n insertionNode.final = true\n }\n\n stack.push({\n node: insertionNode,\n editsRemaining: frame.editsRemaining - 1,\n str: frame.str\n })\n\n // deletion\n // can only do a deletion if we have enough edits remaining\n // and if there are characters left to delete in the string\n if (frame.str.length > 1) {\n stack.push({\n node: frame.node,\n editsRemaining: frame.editsRemaining - 1,\n str: frame.str.slice(1)\n })\n }\n\n // deletion\n // just removing the last character from the str\n if (frame.str.length == 1) {\n frame.node.final = true\n }\n\n // substitution\n // can only do a substitution if we have enough edits remaining\n // and if there are characters left to substitute\n if (frame.str.length >= 1) {\n if (\"*\" in frame.node.edges) {\n var substitutionNode = frame.node.edges[\"*\"]\n } else {\n var substitutionNode = new lunr.TokenSet\n frame.node.edges[\"*\"] = substitutionNode\n }\n\n if (frame.str.length == 1) {\n substitutionNode.final = true\n }\n\n stack.push({\n node: substitutionNode,\n editsRemaining: frame.editsRemaining - 1,\n str: frame.str.slice(1)\n })\n }\n\n // transposition\n // can only do a transposition if there are edits remaining\n // and there are enough characters to transpose\n if (frame.str.length > 1) {\n var charA = frame.str.charAt(0),\n charB = frame.str.charAt(1),\n transposeNode\n\n if (charB in frame.node.edges) {\n transposeNode = frame.node.edges[charB]\n } else {\n transposeNode = new lunr.TokenSet\n frame.node.edges[charB] = transposeNode\n }\n\n if (frame.str.length == 1) {\n transposeNode.final = true\n }\n\n stack.push({\n node: transposeNode,\n editsRemaining: frame.editsRemaining - 1,\n str: charA + frame.str.slice(2)\n })\n }\n }\n\n return root\n}\n\n/**\n * Creates a TokenSet from a string.\n *\n * The string may contain one or more wildcard characters (*)\n * that will allow wildcard matching when intersecting with\n * another TokenSet.\n *\n * @param {string} str - The string to create a TokenSet from.\n * @returns {lunr.TokenSet}\n */\nlunr.TokenSet.fromString = function (str) {\n var node = new lunr.TokenSet,\n root = node\n\n /*\n * Iterates through all characters within the passed string\n * appending a node for each character.\n *\n * When a wildcard character is found then a self\n * referencing edge is introduced to continually match\n * any number of any characters.\n */\n for (var i = 0, len = str.length; i < len; i++) {\n var char = str[i],\n final = (i == len - 1)\n\n if (char == \"*\") {\n node.edges[char] = node\n node.final = final\n\n } else {\n var next = new lunr.TokenSet\n next.final = final\n\n node.edges[char] = next\n node = next\n }\n }\n\n return root\n}\n\n/**\n * Converts this TokenSet into an array of strings\n * contained within the TokenSet.\n *\n * This is not intended to be used on a TokenSet that\n * contains wildcards, in these cases the results are\n * undefined and are likely to cause an infinite loop.\n *\n * @returns {string[]}\n */\nlunr.TokenSet.prototype.toArray = function () {\n var words = []\n\n var stack = [{\n prefix: \"\",\n node: this\n }]\n\n while (stack.length) {\n var frame = stack.pop(),\n edges = Object.keys(frame.node.edges),\n len = edges.length\n\n if (frame.node.final) {\n /* In Safari, at this point the prefix is sometimes corrupted, see:\n * https://github.com/olivernn/lunr.js/issues/279 Calling any\n * String.prototype method forces Safari to \"cast\" this string to what\n * it's supposed to be, fixing the bug. */\n frame.prefix.charAt(0)\n words.push(frame.prefix)\n }\n\n for (var i = 0; i < len; i++) {\n var edge = edges[i]\n\n stack.push({\n prefix: frame.prefix.concat(edge),\n node: frame.node.edges[edge]\n })\n }\n }\n\n return words\n}\n\n/**\n * Generates a string representation of a TokenSet.\n *\n * This is intended to allow TokenSets to be used as keys\n * in objects, largely to aid the construction and minimisation\n * of a TokenSet. As such it is not designed to be a human\n * friendly representation of the TokenSet.\n *\n * @returns {string}\n */\nlunr.TokenSet.prototype.toString = function () {\n // NOTE: Using Object.keys here as this.edges is very likely\n // to enter 'hash-mode' with many keys being added\n //\n // avoiding a for-in loop here as it leads to the function\n // being de-optimised (at least in V8). From some simple\n // benchmarks the performance is comparable, but allowing\n // V8 to optimize may mean easy performance wins in the future.\n\n if (this._str) {\n return this._str\n }\n\n var str = this.final ? '1' : '0',\n labels = Object.keys(this.edges).sort(),\n len = labels.length\n\n for (var i = 0; i < len; i++) {\n var label = labels[i],\n node = this.edges[label]\n\n str = str + label + node.id\n }\n\n return str\n}\n\n/**\n * Returns a new TokenSet that is the intersection of\n * this TokenSet and the passed TokenSet.\n *\n * This intersection will take into account any wildcards\n * contained within the TokenSet.\n *\n * @param {lunr.TokenSet} b - An other TokenSet to intersect with.\n * @returns {lunr.TokenSet}\n */\nlunr.TokenSet.prototype.intersect = function (b) {\n var output = new lunr.TokenSet,\n frame = undefined\n\n var stack = [{\n qNode: b,\n output: output,\n node: this\n }]\n\n while (stack.length) {\n frame = stack.pop()\n\n // NOTE: As with the #toString method, we are using\n // Object.keys and a for loop instead of a for-in loop\n // as both of these objects enter 'hash' mode, causing\n // the function to be de-optimised in V8\n var qEdges = Object.keys(frame.qNode.edges),\n qLen = qEdges.length,\n nEdges = Object.keys(frame.node.edges),\n nLen = nEdges.length\n\n for (var q = 0; q < qLen; q++) {\n var qEdge = qEdges[q]\n\n for (var n = 0; n < nLen; n++) {\n var nEdge = nEdges[n]\n\n if (nEdge == qEdge || qEdge == '*') {\n var node = frame.node.edges[nEdge],\n qNode = frame.qNode.edges[qEdge],\n final = node.final && qNode.final,\n next = undefined\n\n if (nEdge in frame.output.edges) {\n // an edge already exists for this character\n // no need to create a new node, just set the finality\n // bit unless this node is already final\n next = frame.output.edges[nEdge]\n next.final = next.final || final\n\n } else {\n // no edge exists yet, must create one\n // set the finality bit and insert it\n // into the output\n next = new lunr.TokenSet\n next.final = final\n frame.output.edges[nEdge] = next\n }\n\n stack.push({\n qNode: qNode,\n output: next,\n node: node\n })\n }\n }\n }\n }\n\n return output\n}\nlunr.TokenSet.Builder = function () {\n this.previousWord = \"\"\n this.root = new lunr.TokenSet\n this.uncheckedNodes = []\n this.minimizedNodes = {}\n}\n\nlunr.TokenSet.Builder.prototype.insert = function (word) {\n var node,\n commonPrefix = 0\n\n if (word < this.previousWord) {\n throw new Error (\"Out of order word insertion\")\n }\n\n for (var i = 0; i < word.length && i < this.previousWord.length; i++) {\n if (word[i] != this.previousWord[i]) break\n commonPrefix++\n }\n\n this.minimize(commonPrefix)\n\n if (this.uncheckedNodes.length == 0) {\n node = this.root\n } else {\n node = this.uncheckedNodes[this.uncheckedNodes.length - 1].child\n }\n\n for (var i = commonPrefix; i < word.length; i++) {\n var nextNode = new lunr.TokenSet,\n char = word[i]\n\n node.edges[char] = nextNode\n\n this.uncheckedNodes.push({\n parent: node,\n char: char,\n child: nextNode\n })\n\n node = nextNode\n }\n\n node.final = true\n this.previousWord = word\n}\n\nlunr.TokenSet.Builder.prototype.finish = function () {\n this.minimize(0)\n}\n\nlunr.TokenSet.Builder.prototype.minimize = function (downTo) {\n for (var i = this.uncheckedNodes.length - 1; i >= downTo; i--) {\n var node = this.uncheckedNodes[i],\n childKey = node.child.toString()\n\n if (childKey in this.minimizedNodes) {\n node.parent.edges[node.char] = this.minimizedNodes[childKey]\n } else {\n // Cache the key for this node since\n // we know it can't change anymore\n node.child._str = childKey\n\n this.minimizedNodes[childKey] = node.child\n }\n\n this.uncheckedNodes.pop()\n }\n}\n/*!\n * lunr.Index\n * Copyright (C) 2020 Oliver Nightingale\n */\n\n/**\n * An index contains the built index of all documents and provides a query interface\n * to the index.\n *\n * Usually instances of lunr.Index will not be created using this constructor, instead\n * lunr.Builder should be used to construct new indexes, or lunr.Index.load should be\n * used to load previously built and serialized indexes.\n *\n * @constructor\n * @param {Object} attrs - The attributes of the built search index.\n * @param {Object} attrs.invertedIndex - An index of term/field to document reference.\n * @param {Object} attrs.fieldVectors - Field vectors\n * @param {lunr.TokenSet} attrs.tokenSet - An set of all corpus tokens.\n * @param {string[]} attrs.fields - The names of indexed document fields.\n * @param {lunr.Pipeline} attrs.pipeline - The pipeline to use for search terms.\n */\nlunr.Index = function (attrs) {\n this.invertedIndex = attrs.invertedIndex\n this.fieldVectors = attrs.fieldVectors\n this.tokenSet = attrs.tokenSet\n this.fields = attrs.fields\n this.pipeline = attrs.pipeline\n}\n\n/**\n * A result contains details of a document matching a search query.\n * @typedef {Object} lunr.Index~Result\n * @property {string} ref - The reference of the document this result represents.\n * @property {number} score - A number between 0 and 1 representing how similar this document is to the query.\n * @property {lunr.MatchData} matchData - Contains metadata about this match including which term(s) caused the match.\n */\n\n/**\n * Although lunr provides the ability to create queries using lunr.Query, it also provides a simple\n * query language which itself is parsed into an instance of lunr.Query.\n *\n * For programmatically building queries it is advised to directly use lunr.Query, the query language\n * is best used for human entered text rather than program generated text.\n *\n * At its simplest queries can just be a single term, e.g. `hello`, multiple terms are also supported\n * and will be combined with OR, e.g `hello world` will match documents that contain either 'hello'\n * or 'world', though those that contain both will rank higher in the results.\n *\n * Wildcards can be included in terms to match one or more unspecified characters, these wildcards can\n * be inserted anywhere within the term, and more than one wildcard can exist in a single term. Adding\n * wildcards will increase the number of documents that will be found but can also have a negative\n * impact on query performance, especially with wildcards at the beginning of a term.\n *\n * Terms can be restricted to specific fields, e.g. `title:hello`, only documents with the term\n * hello in the title field will match this query. Using a field not present in the index will lead\n * to an error being thrown.\n *\n * Modifiers can also be added to terms, lunr supports edit distance and boost modifiers on terms. A term\n * boost will make documents matching that term score higher, e.g. `foo^5`. Edit distance is also supported\n * to provide fuzzy matching, e.g. 'hello~2' will match documents with hello with an edit distance of 2.\n * Avoid large values for edit distance to improve query performance.\n *\n * Each term also supports a presence modifier. By default a term's presence in document is optional, however\n * this can be changed to either required or prohibited. For a term's presence to be required in a document the\n * term should be prefixed with a '+', e.g. `+foo bar` is a search for documents that must contain 'foo' and\n * optionally contain 'bar'. Conversely a leading '-' sets the terms presence to prohibited, i.e. it must not\n * appear in a document, e.g. `-foo bar` is a search for documents that do not contain 'foo' but may contain 'bar'.\n *\n * To escape special characters the backslash character '\\' can be used, this allows searches to include\n * characters that would normally be considered modifiers, e.g. `foo\\~2` will search for a term \"foo~2\" instead\n * of attempting to apply a boost of 2 to the search term \"foo\".\n *\n * @typedef {string} lunr.Index~QueryString\n * @example Simple single term query\n * hello\n * @example Multiple term query\n * hello world\n * @example term scoped to a field\n * title:hello\n * @example term with a boost of 10\n * hello^10\n * @example term with an edit distance of 2\n * hello~2\n * @example terms with presence modifiers\n * -foo +bar baz\n */\n\n/**\n * Performs a search against the index using lunr query syntax.\n *\n * Results will be returned sorted by their score, the most relevant results\n * will be returned first. For details on how the score is calculated, please see\n * the {@link https://lunrjs.com/guides/searching.html#scoring|guide}.\n *\n * For more programmatic querying use lunr.Index#query.\n *\n * @param {lunr.Index~QueryString} queryString - A string containing a lunr query.\n * @throws {lunr.QueryParseError} If the passed query string cannot be parsed.\n * @returns {lunr.Index~Result[]}\n */\nlunr.Index.prototype.search = function (queryString) {\n return this.query(function (query) {\n var parser = new lunr.QueryParser(queryString, query)\n parser.parse()\n })\n}\n\n/**\n * A query builder callback provides a query object to be used to express\n * the query to perform on the index.\n *\n * @callback lunr.Index~queryBuilder\n * @param {lunr.Query} query - The query object to build up.\n * @this lunr.Query\n */\n\n/**\n * Performs a query against the index using the yielded lunr.Query object.\n *\n * If performing programmatic queries against the index, this method is preferred\n * over lunr.Index#search so as to avoid the additional query parsing overhead.\n *\n * A query object is yielded to the supplied function which should be used to\n * express the query to be run against the index.\n *\n * Note that although this function takes a callback parameter it is _not_ an\n * asynchronous operation, the callback is just yielded a query object to be\n * customized.\n *\n * @param {lunr.Index~queryBuilder} fn - A function that is used to build the query.\n * @returns {lunr.Index~Result[]}\n */\nlunr.Index.prototype.query = function (fn) {\n // for each query clause\n // * process terms\n // * expand terms from token set\n // * find matching documents and metadata\n // * get document vectors\n // * score documents\n\n var query = new lunr.Query(this.fields),\n matchingFields = Object.create(null),\n queryVectors = Object.create(null),\n termFieldCache = Object.create(null),\n requiredMatches = Object.create(null),\n prohibitedMatches = Object.create(null)\n\n /*\n * To support field level boosts a query vector is created per\n * field. An empty vector is eagerly created to support negated\n * queries.\n */\n for (var i = 0; i < this.fields.length; i++) {\n queryVectors[this.fields[i]] = new lunr.Vector\n }\n\n fn.call(query, query)\n\n for (var i = 0; i < query.clauses.length; i++) {\n /*\n * Unless the pipeline has been disabled for this term, which is\n * the case for terms with wildcards, we need to pass the clause\n * term through the search pipeline. A pipeline returns an array\n * of processed terms. Pipeline functions may expand the passed\n * term, which means we may end up performing multiple index lookups\n * for a single query term.\n */\n var clause = query.clauses[i],\n terms = null,\n clauseMatches = lunr.Set.empty\n\n if (clause.usePipeline) {\n terms = this.pipeline.runString(clause.term, {\n fields: clause.fields\n })\n } else {\n terms = [clause.term]\n }\n\n for (var m = 0; m < terms.length; m++) {\n var term = terms[m]\n\n /*\n * Each term returned from the pipeline needs to use the same query\n * clause object, e.g. the same boost and or edit distance. The\n * simplest way to do this is to re-use the clause object but mutate\n * its term property.\n */\n clause.term = term\n\n /*\n * From the term in the clause we create a token set which will then\n * be used to intersect the indexes token set to get a list of terms\n * to lookup in the inverted index\n */\n var termTokenSet = lunr.TokenSet.fromClause(clause),\n expandedTerms = this.tokenSet.intersect(termTokenSet).toArray()\n\n /*\n * If a term marked as required does not exist in the tokenSet it is\n * impossible for the search to return any matches. We set all the field\n * scoped required matches set to empty and stop examining any further\n * clauses.\n */\n if (expandedTerms.length === 0 && clause.presence === lunr.Query.presence.REQUIRED) {\n for (var k = 0; k < clause.fields.length; k++) {\n var field = clause.fields[k]\n requiredMatches[field] = lunr.Set.empty\n }\n\n break\n }\n\n for (var j = 0; j < expandedTerms.length; j++) {\n /*\n * For each term get the posting and termIndex, this is required for\n * building the query vector.\n */\n var expandedTerm = expandedTerms[j],\n posting = this.invertedIndex[expandedTerm],\n termIndex = posting._index\n\n for (var k = 0; k < clause.fields.length; k++) {\n /*\n * For each field that this query term is scoped by (by default\n * all fields are in scope) we need to get all the document refs\n * that have this term in that field.\n *\n * The posting is the entry in the invertedIndex for the matching\n * term from above.\n */\n var field = clause.fields[k],\n fieldPosting = posting[field],\n matchingDocumentRefs = Object.keys(fieldPosting),\n termField = expandedTerm + \"/\" + field,\n matchingDocumentsSet = new lunr.Set(matchingDocumentRefs)\n\n /*\n * if the presence of this term is required ensure that the matching\n * documents are added to the set of required matches for this clause.\n *\n */\n if (clause.presence == lunr.Query.presence.REQUIRED) {\n clauseMatches = clauseMatches.union(matchingDocumentsSet)\n\n if (requiredMatches[field] === undefined) {\n requiredMatches[field] = lunr.Set.complete\n }\n }\n\n /*\n * if the presence of this term is prohibited ensure that the matching\n * documents are added to the set of prohibited matches for this field,\n * creating that set if it does not yet exist.\n */\n if (clause.presence == lunr.Query.presence.PROHIBITED) {\n if (prohibitedMatches[field] === undefined) {\n prohibitedMatches[field] = lunr.Set.empty\n }\n\n prohibitedMatches[field] = prohibitedMatches[field].union(matchingDocumentsSet)\n\n /*\n * Prohibited matches should not be part of the query vector used for\n * similarity scoring and no metadata should be extracted so we continue\n * to the next field\n */\n continue\n }\n\n /*\n * The query field vector is populated using the termIndex found for\n * the term and a unit value with the appropriate boost applied.\n * Using upsert because there could already be an entry in the vector\n * for the term we are working with. In that case we just add the scores\n * together.\n */\n queryVectors[field].upsert(termIndex, clause.boost, function (a, b) { return a + b })\n\n /**\n * If we've already seen this term, field combo then we've already collected\n * the matching documents and metadata, no need to go through all that again\n */\n if (termFieldCache[termField]) {\n continue\n }\n\n for (var l = 0; l < matchingDocumentRefs.length; l++) {\n /*\n * All metadata for this term/field/document triple\n * are then extracted and collected into an instance\n * of lunr.MatchData ready to be returned in the query\n * results\n */\n var matchingDocumentRef = matchingDocumentRefs[l],\n matchingFieldRef = new lunr.FieldRef (matchingDocumentRef, field),\n metadata = fieldPosting[matchingDocumentRef],\n fieldMatch\n\n if ((fieldMatch = matchingFields[matchingFieldRef]) === undefined) {\n matchingFields[matchingFieldRef] = new lunr.MatchData (expandedTerm, field, metadata)\n } else {\n fieldMatch.add(expandedTerm, field, metadata)\n }\n\n }\n\n termFieldCache[termField] = true\n }\n }\n }\n\n /**\n * If the presence was required we need to update the requiredMatches field sets.\n * We do this after all fields for the term have collected their matches because\n * the clause terms presence is required in _any_ of the fields not _all_ of the\n * fields.\n */\n if (clause.presence === lunr.Query.presence.REQUIRED) {\n for (var k = 0; k < clause.fields.length; k++) {\n var field = clause.fields[k]\n requiredMatches[field] = requiredMatches[field].intersect(clauseMatches)\n }\n }\n }\n\n /**\n * Need to combine the field scoped required and prohibited\n * matching documents into a global set of required and prohibited\n * matches\n */\n var allRequiredMatches = lunr.Set.complete,\n allProhibitedMatches = lunr.Set.empty\n\n for (var i = 0; i < this.fields.length; i++) {\n var field = this.fields[i]\n\n if (requiredMatches[field]) {\n allRequiredMatches = allRequiredMatches.intersect(requiredMatches[field])\n }\n\n if (prohibitedMatches[field]) {\n allProhibitedMatches = allProhibitedMatches.union(prohibitedMatches[field])\n }\n }\n\n var matchingFieldRefs = Object.keys(matchingFields),\n results = [],\n matches = Object.create(null)\n\n /*\n * If the query is negated (contains only prohibited terms)\n * we need to get _all_ fieldRefs currently existing in the\n * index. This is only done when we know that the query is\n * entirely prohibited terms to avoid any cost of getting all\n * fieldRefs unnecessarily.\n *\n * Additionally, blank MatchData must be created to correctly\n * populate the results.\n */\n if (query.isNegated()) {\n matchingFieldRefs = Object.keys(this.fieldVectors)\n\n for (var i = 0; i < matchingFieldRefs.length; i++) {\n var matchingFieldRef = matchingFieldRefs[i]\n var fieldRef = lunr.FieldRef.fromString(matchingFieldRef)\n matchingFields[matchingFieldRef] = new lunr.MatchData\n }\n }\n\n for (var i = 0; i < matchingFieldRefs.length; i++) {\n /*\n * Currently we have document fields that match the query, but we\n * need to return documents. The matchData and scores are combined\n * from multiple fields belonging to the same document.\n *\n * Scores are calculated by field, using the query vectors created\n * above, and combined into a final document score using addition.\n */\n var fieldRef = lunr.FieldRef.fromString(matchingFieldRefs[i]),\n docRef = fieldRef.docRef\n\n if (!allRequiredMatches.contains(docRef)) {\n continue\n }\n\n if (allProhibitedMatches.contains(docRef)) {\n continue\n }\n\n var fieldVector = this.fieldVectors[fieldRef],\n score = queryVectors[fieldRef.fieldName].similarity(fieldVector),\n docMatch\n\n if ((docMatch = matches[docRef]) !== undefined) {\n docMatch.score += score\n docMatch.matchData.combine(matchingFields[fieldRef])\n } else {\n var match = {\n ref: docRef,\n score: score,\n matchData: matchingFields[fieldRef]\n }\n matches[docRef] = match\n results.push(match)\n }\n }\n\n /*\n * Sort the results objects by score, highest first.\n */\n return results.sort(function (a, b) {\n return b.score - a.score\n })\n}\n\n/**\n * Prepares the index for JSON serialization.\n *\n * The schema for this JSON blob will be described in a\n * separate JSON schema file.\n *\n * @returns {Object}\n */\nlunr.Index.prototype.toJSON = function () {\n var invertedIndex = Object.keys(this.invertedIndex)\n .sort()\n .map(function (term) {\n return [term, this.invertedIndex[term]]\n }, this)\n\n var fieldVectors = Object.keys(this.fieldVectors)\n .map(function (ref) {\n return [ref, this.fieldVectors[ref].toJSON()]\n }, this)\n\n return {\n version: lunr.version,\n fields: this.fields,\n fieldVectors: fieldVectors,\n invertedIndex: invertedIndex,\n pipeline: this.pipeline.toJSON()\n }\n}\n\n/**\n * Loads a previously serialized lunr.Index\n *\n * @param {Object} serializedIndex - A previously serialized lunr.Index\n * @returns {lunr.Index}\n */\nlunr.Index.load = function (serializedIndex) {\n var attrs = {},\n fieldVectors = {},\n serializedVectors = serializedIndex.fieldVectors,\n invertedIndex = Object.create(null),\n serializedInvertedIndex = serializedIndex.invertedIndex,\n tokenSetBuilder = new lunr.TokenSet.Builder,\n pipeline = lunr.Pipeline.load(serializedIndex.pipeline)\n\n if (serializedIndex.version != lunr.version) {\n lunr.utils.warn(\"Version mismatch when loading serialised index. Current version of lunr '\" + lunr.version + \"' does not match serialized index '\" + serializedIndex.version + \"'\")\n }\n\n for (var i = 0; i < serializedVectors.length; i++) {\n var tuple = serializedVectors[i],\n ref = tuple[0],\n elements = tuple[1]\n\n fieldVectors[ref] = new lunr.Vector(elements)\n }\n\n for (var i = 0; i < serializedInvertedIndex.length; i++) {\n var tuple = serializedInvertedIndex[i],\n term = tuple[0],\n posting = tuple[1]\n\n tokenSetBuilder.insert(term)\n invertedIndex[term] = posting\n }\n\n tokenSetBuilder.finish()\n\n attrs.fields = serializedIndex.fields\n\n attrs.fieldVectors = fieldVectors\n attrs.invertedIndex = invertedIndex\n attrs.tokenSet = tokenSetBuilder.root\n attrs.pipeline = pipeline\n\n return new lunr.Index(attrs)\n}\n/*!\n * lunr.Builder\n * Copyright (C) 2020 Oliver Nightingale\n */\n\n/**\n * lunr.Builder performs indexing on a set of documents and\n * returns instances of lunr.Index ready for querying.\n *\n * All configuration of the index is done via the builder, the\n * fields to index, the document reference, the text processing\n * pipeline and document scoring parameters are all set on the\n * builder before indexing.\n *\n * @constructor\n * @property {string} _ref - Internal reference to the document reference field.\n * @property {string[]} _fields - Internal reference to the document fields to index.\n * @property {object} invertedIndex - The inverted index maps terms to document fields.\n * @property {object} documentTermFrequencies - Keeps track of document term frequencies.\n * @property {object} documentLengths - Keeps track of the length of documents added to the index.\n * @property {lunr.tokenizer} tokenizer - Function for splitting strings into tokens for indexing.\n * @property {lunr.Pipeline} pipeline - The pipeline performs text processing on tokens before indexing.\n * @property {lunr.Pipeline} searchPipeline - A pipeline for processing search terms before querying the index.\n * @property {number} documentCount - Keeps track of the total number of documents indexed.\n * @property {number} _b - A parameter to control field length normalization, setting this to 0 disabled normalization, 1 fully normalizes field lengths, the default value is 0.75.\n * @property {number} _k1 - A parameter to control how quickly an increase in term frequency results in term frequency saturation, the default value is 1.2.\n * @property {number} termIndex - A counter incremented for each unique term, used to identify a terms position in the vector space.\n * @property {array} metadataWhitelist - A list of metadata keys that have been whitelisted for entry in the index.\n */\nlunr.Builder = function () {\n this._ref = \"id\"\n this._fields = Object.create(null)\n this._documents = Object.create(null)\n this.invertedIndex = Object.create(null)\n this.fieldTermFrequencies = {}\n this.fieldLengths = {}\n this.tokenizer = lunr.tokenizer\n this.pipeline = new lunr.Pipeline\n this.searchPipeline = new lunr.Pipeline\n this.documentCount = 0\n this._b = 0.75\n this._k1 = 1.2\n this.termIndex = 0\n this.metadataWhitelist = []\n}\n\n/**\n * Sets the document field used as the document reference. Every document must have this field.\n * The type of this field in the document should be a string, if it is not a string it will be\n * coerced into a string by calling toString.\n *\n * The default ref is 'id'.\n *\n * The ref should _not_ be changed during indexing, it should be set before any documents are\n * added to the index. Changing it during indexing can lead to inconsistent results.\n *\n * @param {string} ref - The name of the reference field in the document.\n */\nlunr.Builder.prototype.ref = function (ref) {\n this._ref = ref\n}\n\n/**\n * A function that is used to extract a field from a document.\n *\n * Lunr expects a field to be at the top level of a document, if however the field\n * is deeply nested within a document an extractor function can be used to extract\n * the right field for indexing.\n *\n * @callback fieldExtractor\n * @param {object} doc - The document being added to the index.\n * @returns {?(string|object|object[])} obj - The object that will be indexed for this field.\n * @example Extracting a nested field\n * function (doc) { return doc.nested.field }\n */\n\n/**\n * Adds a field to the list of document fields that will be indexed. Every document being\n * indexed should have this field. Null values for this field in indexed documents will\n * not cause errors but will limit the chance of that document being retrieved by searches.\n *\n * All fields should be added before adding documents to the index. Adding fields after\n * a document has been indexed will have no effect on already indexed documents.\n *\n * Fields can be boosted at build time. This allows terms within that field to have more\n * importance when ranking search results. Use a field boost to specify that matches within\n * one field are more important than other fields.\n *\n * @param {string} fieldName - The name of a field to index in all documents.\n * @param {object} attributes - Optional attributes associated with this field.\n * @param {number} [attributes.boost=1] - Boost applied to all terms within this field.\n * @param {fieldExtractor} [attributes.extractor] - Function to extract a field from a document.\n * @throws {RangeError} fieldName cannot contain unsupported characters '/'\n */\nlunr.Builder.prototype.field = function (fieldName, attributes) {\n if (/\\//.test(fieldName)) {\n throw new RangeError (\"Field '\" + fieldName + \"' contains illegal character '/'\")\n }\n\n this._fields[fieldName] = attributes || {}\n}\n\n/**\n * A parameter to tune the amount of field length normalisation that is applied when\n * calculating relevance scores. A value of 0 will completely disable any normalisation\n * and a value of 1 will fully normalise field lengths. The default is 0.75. Values of b\n * will be clamped to the range 0 - 1.\n *\n * @param {number} number - The value to set for this tuning parameter.\n */\nlunr.Builder.prototype.b = function (number) {\n if (number < 0) {\n this._b = 0\n } else if (number > 1) {\n this._b = 1\n } else {\n this._b = number\n }\n}\n\n/**\n * A parameter that controls the speed at which a rise in term frequency results in term\n * frequency saturation. The default value is 1.2. Setting this to a higher value will give\n * slower saturation levels, a lower value will result in quicker saturation.\n *\n * @param {number} number - The value to set for this tuning parameter.\n */\nlunr.Builder.prototype.k1 = function (number) {\n this._k1 = number\n}\n\n/**\n * Adds a document to the index.\n *\n * Before adding fields to the index the index should have been fully setup, with the document\n * ref and all fields to index already having been specified.\n *\n * The document must have a field name as specified by the ref (by default this is 'id') and\n * it should have all fields defined for indexing, though null or undefined values will not\n * cause errors.\n *\n * Entire documents can be boosted at build time. Applying a boost to a document indicates that\n * this document should rank higher in search results than other documents.\n *\n * @param {object} doc - The document to add to the index.\n * @param {object} attributes - Optional attributes associated with this document.\n * @param {number} [attributes.boost=1] - Boost applied to all terms within this document.\n */\nlunr.Builder.prototype.add = function (doc, attributes) {\n var docRef = doc[this._ref],\n fields = Object.keys(this._fields)\n\n this._documents[docRef] = attributes || {}\n this.documentCount += 1\n\n for (var i = 0; i < fields.length; i++) {\n var fieldName = fields[i],\n extractor = this._fields[fieldName].extractor,\n field = extractor ? extractor(doc) : doc[fieldName],\n tokens = this.tokenizer(field, {\n fields: [fieldName]\n }),\n terms = this.pipeline.run(tokens),\n fieldRef = new lunr.FieldRef (docRef, fieldName),\n fieldTerms = Object.create(null)\n\n this.fieldTermFrequencies[fieldRef] = fieldTerms\n this.fieldLengths[fieldRef] = 0\n\n // store the length of this field for this document\n this.fieldLengths[fieldRef] += terms.length\n\n // calculate term frequencies for this field\n for (var j = 0; j < terms.length; j++) {\n var term = terms[j]\n\n if (fieldTerms[term] == undefined) {\n fieldTerms[term] = 0\n }\n\n fieldTerms[term] += 1\n\n // add to inverted index\n // create an initial posting if one doesn't exist\n if (this.invertedIndex[term] == undefined) {\n var posting = Object.create(null)\n posting[\"_index\"] = this.termIndex\n this.termIndex += 1\n\n for (var k = 0; k < fields.length; k++) {\n posting[fields[k]] = Object.create(null)\n }\n\n this.invertedIndex[term] = posting\n }\n\n // add an entry for this term/fieldName/docRef to the invertedIndex\n if (this.invertedIndex[term][fieldName][docRef] == undefined) {\n this.invertedIndex[term][fieldName][docRef] = Object.create(null)\n }\n\n // store all whitelisted metadata about this token in the\n // inverted index\n for (var l = 0; l < this.metadataWhitelist.length; l++) {\n var metadataKey = this.metadataWhitelist[l],\n metadata = term.metadata[metadataKey]\n\n if (this.invertedIndex[term][fieldName][docRef][metadataKey] == undefined) {\n this.invertedIndex[term][fieldName][docRef][metadataKey] = []\n }\n\n this.invertedIndex[term][fieldName][docRef][metadataKey].push(metadata)\n }\n }\n\n }\n}\n\n/**\n * Calculates the average document length for this index\n *\n * @private\n */\nlunr.Builder.prototype.calculateAverageFieldLengths = function () {\n\n var fieldRefs = Object.keys(this.fieldLengths),\n numberOfFields = fieldRefs.length,\n accumulator = {},\n documentsWithField = {}\n\n for (var i = 0; i < numberOfFields; i++) {\n var fieldRef = lunr.FieldRef.fromString(fieldRefs[i]),\n field = fieldRef.fieldName\n\n documentsWithField[field] || (documentsWithField[field] = 0)\n documentsWithField[field] += 1\n\n accumulator[field] || (accumulator[field] = 0)\n accumulator[field] += this.fieldLengths[fieldRef]\n }\n\n var fields = Object.keys(this._fields)\n\n for (var i = 0; i < fields.length; i++) {\n var fieldName = fields[i]\n accumulator[fieldName] = accumulator[fieldName] / documentsWithField[fieldName]\n }\n\n this.averageFieldLength = accumulator\n}\n\n/**\n * Builds a vector space model of every document using lunr.Vector\n *\n * @private\n */\nlunr.Builder.prototype.createFieldVectors = function () {\n var fieldVectors = {},\n fieldRefs = Object.keys(this.fieldTermFrequencies),\n fieldRefsLength = fieldRefs.length,\n termIdfCache = Object.create(null)\n\n for (var i = 0; i < fieldRefsLength; i++) {\n var fieldRef = lunr.FieldRef.fromString(fieldRefs[i]),\n fieldName = fieldRef.fieldName,\n fieldLength = this.fieldLengths[fieldRef],\n fieldVector = new lunr.Vector,\n termFrequencies = this.fieldTermFrequencies[fieldRef],\n terms = Object.keys(termFrequencies),\n termsLength = terms.length\n\n\n var fieldBoost = this._fields[fieldName].boost || 1,\n docBoost = this._documents[fieldRef.docRef].boost || 1\n\n for (var j = 0; j < termsLength; j++) {\n var term = terms[j],\n tf = termFrequencies[term],\n termIndex = this.invertedIndex[term]._index,\n idf, score, scoreWithPrecision\n\n if (termIdfCache[term] === undefined) {\n idf = lunr.idf(this.invertedIndex[term], this.documentCount)\n termIdfCache[term] = idf\n } else {\n idf = termIdfCache[term]\n }\n\n score = idf * ((this._k1 + 1) * tf) / (this._k1 * (1 - this._b + this._b * (fieldLength / this.averageFieldLength[fieldName])) + tf)\n score *= fieldBoost\n score *= docBoost\n scoreWithPrecision = Math.round(score * 1000) / 1000\n // Converts 1.23456789 to 1.234.\n // Reducing the precision so that the vectors take up less\n // space when serialised. Doing it now so that they behave\n // the same before and after serialisation. Also, this is\n // the fastest approach to reducing a number's precision in\n // JavaScript.\n\n fieldVector.insert(termIndex, scoreWithPrecision)\n }\n\n fieldVectors[fieldRef] = fieldVector\n }\n\n this.fieldVectors = fieldVectors\n}\n\n/**\n * Creates a token set of all tokens in the index using lunr.TokenSet\n *\n * @private\n */\nlunr.Builder.prototype.createTokenSet = function () {\n this.tokenSet = lunr.TokenSet.fromArray(\n Object.keys(this.invertedIndex).sort()\n )\n}\n\n/**\n * Builds the index, creating an instance of lunr.Index.\n *\n * This completes the indexing process and should only be called\n * once all documents have been added to the index.\n *\n * @returns {lunr.Index}\n */\nlunr.Builder.prototype.build = function () {\n this.calculateAverageFieldLengths()\n this.createFieldVectors()\n this.createTokenSet()\n\n return new lunr.Index({\n invertedIndex: this.invertedIndex,\n fieldVectors: this.fieldVectors,\n tokenSet: this.tokenSet,\n fields: Object.keys(this._fields),\n pipeline: this.searchPipeline\n })\n}\n\n/**\n * Applies a plugin to the index builder.\n *\n * A plugin is a function that is called with the index builder as its context.\n * Plugins can be used to customise or extend the behaviour of the index\n * in some way. A plugin is just a function, that encapsulated the custom\n * behaviour that should be applied when building the index.\n *\n * The plugin function will be called with the index builder as its argument, additional\n * arguments can also be passed when calling use. The function will be called\n * with the index builder as its context.\n *\n * @param {Function} plugin The plugin to apply.\n */\nlunr.Builder.prototype.use = function (fn) {\n var args = Array.prototype.slice.call(arguments, 1)\n args.unshift(this)\n fn.apply(this, args)\n}\n/**\n * Contains and collects metadata about a matching document.\n * A single instance of lunr.MatchData is returned as part of every\n * lunr.Index~Result.\n *\n * @constructor\n * @param {string} term - The term this match data is associated with\n * @param {string} field - The field in which the term was found\n * @param {object} metadata - The metadata recorded about this term in this field\n * @property {object} metadata - A cloned collection of metadata associated with this document.\n * @see {@link lunr.Index~Result}\n */\nlunr.MatchData = function (term, field, metadata) {\n var clonedMetadata = Object.create(null),\n metadataKeys = Object.keys(metadata || {})\n\n // Cloning the metadata to prevent the original\n // being mutated during match data combination.\n // Metadata is kept in an array within the inverted\n // index so cloning the data can be done with\n // Array#slice\n for (var i = 0; i < metadataKeys.length; i++) {\n var key = metadataKeys[i]\n clonedMetadata[key] = metadata[key].slice()\n }\n\n this.metadata = Object.create(null)\n\n if (term !== undefined) {\n this.metadata[term] = Object.create(null)\n this.metadata[term][field] = clonedMetadata\n }\n}\n\n/**\n * An instance of lunr.MatchData will be created for every term that matches a\n * document. However only one instance is required in a lunr.Index~Result. This\n * method combines metadata from another instance of lunr.MatchData with this\n * objects metadata.\n *\n * @param {lunr.MatchData} otherMatchData - Another instance of match data to merge with this one.\n * @see {@link lunr.Index~Result}\n */\nlunr.MatchData.prototype.combine = function (otherMatchData) {\n var terms = Object.keys(otherMatchData.metadata)\n\n for (var i = 0; i < terms.length; i++) {\n var term = terms[i],\n fields = Object.keys(otherMatchData.metadata[term])\n\n if (this.metadata[term] == undefined) {\n this.metadata[term] = Object.create(null)\n }\n\n for (var j = 0; j < fields.length; j++) {\n var field = fields[j],\n keys = Object.keys(otherMatchData.metadata[term][field])\n\n if (this.metadata[term][field] == undefined) {\n this.metadata[term][field] = Object.create(null)\n }\n\n for (var k = 0; k < keys.length; k++) {\n var key = keys[k]\n\n if (this.metadata[term][field][key] == undefined) {\n this.metadata[term][field][key] = otherMatchData.metadata[term][field][key]\n } else {\n this.metadata[term][field][key] = this.metadata[term][field][key].concat(otherMatchData.metadata[term][field][key])\n }\n\n }\n }\n }\n}\n\n/**\n * Add metadata for a term/field pair to this instance of match data.\n *\n * @param {string} term - The term this match data is associated with\n * @param {string} field - The field in which the term was found\n * @param {object} metadata - The metadata recorded about this term in this field\n */\nlunr.MatchData.prototype.add = function (term, field, metadata) {\n if (!(term in this.metadata)) {\n this.metadata[term] = Object.create(null)\n this.metadata[term][field] = metadata\n return\n }\n\n if (!(field in this.metadata[term])) {\n this.metadata[term][field] = metadata\n return\n }\n\n var metadataKeys = Object.keys(metadata)\n\n for (var i = 0; i < metadataKeys.length; i++) {\n var key = metadataKeys[i]\n\n if (key in this.metadata[term][field]) {\n this.metadata[term][field][key] = this.metadata[term][field][key].concat(metadata[key])\n } else {\n this.metadata[term][field][key] = metadata[key]\n }\n }\n}\n/**\n * A lunr.Query provides a programmatic way of defining queries to be performed\n * against a {@link lunr.Index}.\n *\n * Prefer constructing a lunr.Query using the {@link lunr.Index#query} method\n * so the query object is pre-initialized with the right index fields.\n *\n * @constructor\n * @property {lunr.Query~Clause[]} clauses - An array of query clauses.\n * @property {string[]} allFields - An array of all available fields in a lunr.Index.\n */\nlunr.Query = function (allFields) {\n this.clauses = []\n this.allFields = allFields\n}\n\n/**\n * Constants for indicating what kind of automatic wildcard insertion will be used when constructing a query clause.\n *\n * This allows wildcards to be added to the beginning and end of a term without having to manually do any string\n * concatenation.\n *\n * The wildcard constants can be bitwise combined to select both leading and trailing wildcards.\n *\n * @constant\n * @default\n * @property {number} wildcard.NONE - The term will have no wildcards inserted, this is the default behaviour\n * @property {number} wildcard.LEADING - Prepend the term with a wildcard, unless a leading wildcard already exists\n * @property {number} wildcard.TRAILING - Append a wildcard to the term, unless a trailing wildcard already exists\n * @see lunr.Query~Clause\n * @see lunr.Query#clause\n * @see lunr.Query#term\n * @example query term with trailing wildcard\n * query.term('foo', { wildcard: lunr.Query.wildcard.TRAILING })\n * @example query term with leading and trailing wildcard\n * query.term('foo', {\n * wildcard: lunr.Query.wildcard.LEADING | lunr.Query.wildcard.TRAILING\n * })\n */\n\nlunr.Query.wildcard = new String (\"*\")\nlunr.Query.wildcard.NONE = 0\nlunr.Query.wildcard.LEADING = 1\nlunr.Query.wildcard.TRAILING = 2\n\n/**\n * Constants for indicating what kind of presence a term must have in matching documents.\n *\n * @constant\n * @enum {number}\n * @see lunr.Query~Clause\n * @see lunr.Query#clause\n * @see lunr.Query#term\n * @example query term with required presence\n * query.term('foo', { presence: lunr.Query.presence.REQUIRED })\n */\nlunr.Query.presence = {\n /**\n * Term's presence in a document is optional, this is the default value.\n */\n OPTIONAL: 1,\n\n /**\n * Term's presence in a document is required, documents that do not contain\n * this term will not be returned.\n */\n REQUIRED: 2,\n\n /**\n * Term's presence in a document is prohibited, documents that do contain\n * this term will not be returned.\n */\n PROHIBITED: 3\n}\n\n/**\n * A single clause in a {@link lunr.Query} contains a term and details on how to\n * match that term against a {@link lunr.Index}.\n *\n * @typedef {Object} lunr.Query~Clause\n * @property {string[]} fields - The fields in an index this clause should be matched against.\n * @property {number} [boost=1] - Any boost that should be applied when matching this clause.\n * @property {number} [editDistance] - Whether the term should have fuzzy matching applied, and how fuzzy the match should be.\n * @property {boolean} [usePipeline] - Whether the term should be passed through the search pipeline.\n * @property {number} [wildcard=lunr.Query.wildcard.NONE] - Whether the term should have wildcards appended or prepended.\n * @property {number} [presence=lunr.Query.presence.OPTIONAL] - The terms presence in any matching documents.\n */\n\n/**\n * Adds a {@link lunr.Query~Clause} to this query.\n *\n * Unless the clause contains the fields to be matched all fields will be matched. In addition\n * a default boost of 1 is applied to the clause.\n *\n * @param {lunr.Query~Clause} clause - The clause to add to this query.\n * @see lunr.Query~Clause\n * @returns {lunr.Query}\n */\nlunr.Query.prototype.clause = function (clause) {\n if (!('fields' in clause)) {\n clause.fields = this.allFields\n }\n\n if (!('boost' in clause)) {\n clause.boost = 1\n }\n\n if (!('usePipeline' in clause)) {\n clause.usePipeline = true\n }\n\n if (!('wildcard' in clause)) {\n clause.wildcard = lunr.Query.wildcard.NONE\n }\n\n if ((clause.wildcard & lunr.Query.wildcard.LEADING) && (clause.term.charAt(0) != lunr.Query.wildcard)) {\n clause.term = \"*\" + clause.term\n }\n\n if ((clause.wildcard & lunr.Query.wildcard.TRAILING) && (clause.term.slice(-1) != lunr.Query.wildcard)) {\n clause.term = \"\" + clause.term + \"*\"\n }\n\n if (!('presence' in clause)) {\n clause.presence = lunr.Query.presence.OPTIONAL\n }\n\n this.clauses.push(clause)\n\n return this\n}\n\n/**\n * A negated query is one in which every clause has a presence of\n * prohibited. These queries require some special processing to return\n * the expected results.\n *\n * @returns boolean\n */\nlunr.Query.prototype.isNegated = function () {\n for (var i = 0; i < this.clauses.length; i++) {\n if (this.clauses[i].presence != lunr.Query.presence.PROHIBITED) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * Adds a term to the current query, under the covers this will create a {@link lunr.Query~Clause}\n * to the list of clauses that make up this query.\n *\n * The term is used as is, i.e. no tokenization will be performed by this method. Instead conversion\n * to a token or token-like string should be done before calling this method.\n *\n * The term will be converted to a string by calling `toString`. Multiple terms can be passed as an\n * array, each term in the array will share the same options.\n *\n * @param {object|object[]} term - The term(s) to add to the query.\n * @param {object} [options] - Any additional properties to add to the query clause.\n * @returns {lunr.Query}\n * @see lunr.Query#clause\n * @see lunr.Query~Clause\n * @example adding a single term to a query\n * query.term(\"foo\")\n * @example adding a single term to a query and specifying search fields, term boost and automatic trailing wildcard\n * query.term(\"foo\", {\n * fields: [\"title\"],\n * boost: 10,\n * wildcard: lunr.Query.wildcard.TRAILING\n * })\n * @example using lunr.tokenizer to convert a string to tokens before using them as terms\n * query.term(lunr.tokenizer(\"foo bar\"))\n */\nlunr.Query.prototype.term = function (term, options) {\n if (Array.isArray(term)) {\n term.forEach(function (t) { this.term(t, lunr.utils.clone(options)) }, this)\n return this\n }\n\n var clause = options || {}\n clause.term = term.toString()\n\n this.clause(clause)\n\n return this\n}\nlunr.QueryParseError = function (message, start, end) {\n this.name = \"QueryParseError\"\n this.message = message\n this.start = start\n this.end = end\n}\n\nlunr.QueryParseError.prototype = new Error\nlunr.QueryLexer = function (str) {\n this.lexemes = []\n this.str = str\n this.length = str.length\n this.pos = 0\n this.start = 0\n this.escapeCharPositions = []\n}\n\nlunr.QueryLexer.prototype.run = function () {\n var state = lunr.QueryLexer.lexText\n\n while (state) {\n state = state(this)\n }\n}\n\nlunr.QueryLexer.prototype.sliceString = function () {\n var subSlices = [],\n sliceStart = this.start,\n sliceEnd = this.pos\n\n for (var i = 0; i < this.escapeCharPositions.length; i++) {\n sliceEnd = this.escapeCharPositions[i]\n subSlices.push(this.str.slice(sliceStart, sliceEnd))\n sliceStart = sliceEnd + 1\n }\n\n subSlices.push(this.str.slice(sliceStart, this.pos))\n this.escapeCharPositions.length = 0\n\n return subSlices.join('')\n}\n\nlunr.QueryLexer.prototype.emit = function (type) {\n this.lexemes.push({\n type: type,\n str: this.sliceString(),\n start: this.start,\n end: this.pos\n })\n\n this.start = this.pos\n}\n\nlunr.QueryLexer.prototype.escapeCharacter = function () {\n this.escapeCharPositions.push(this.pos - 1)\n this.pos += 1\n}\n\nlunr.QueryLexer.prototype.next = function () {\n if (this.pos >= this.length) {\n return lunr.QueryLexer.EOS\n }\n\n var char = this.str.charAt(this.pos)\n this.pos += 1\n return char\n}\n\nlunr.QueryLexer.prototype.width = function () {\n return this.pos - this.start\n}\n\nlunr.QueryLexer.prototype.ignore = function () {\n if (this.start == this.pos) {\n this.pos += 1\n }\n\n this.start = this.pos\n}\n\nlunr.QueryLexer.prototype.backup = function () {\n this.pos -= 1\n}\n\nlunr.QueryLexer.prototype.acceptDigitRun = function () {\n var char, charCode\n\n do {\n char = this.next()\n charCode = char.charCodeAt(0)\n } while (charCode > 47 && charCode < 58)\n\n if (char != lunr.QueryLexer.EOS) {\n this.backup()\n }\n}\n\nlunr.QueryLexer.prototype.more = function () {\n return this.pos < this.length\n}\n\nlunr.QueryLexer.EOS = 'EOS'\nlunr.QueryLexer.FIELD = 'FIELD'\nlunr.QueryLexer.TERM = 'TERM'\nlunr.QueryLexer.EDIT_DISTANCE = 'EDIT_DISTANCE'\nlunr.QueryLexer.BOOST = 'BOOST'\nlunr.QueryLexer.PRESENCE = 'PRESENCE'\n\nlunr.QueryLexer.lexField = function (lexer) {\n lexer.backup()\n lexer.emit(lunr.QueryLexer.FIELD)\n lexer.ignore()\n return lunr.QueryLexer.lexText\n}\n\nlunr.QueryLexer.lexTerm = function (lexer) {\n if (lexer.width() > 1) {\n lexer.backup()\n lexer.emit(lunr.QueryLexer.TERM)\n }\n\n lexer.ignore()\n\n if (lexer.more()) {\n return lunr.QueryLexer.lexText\n }\n}\n\nlunr.QueryLexer.lexEditDistance = function (lexer) {\n lexer.ignore()\n lexer.acceptDigitRun()\n lexer.emit(lunr.QueryLexer.EDIT_DISTANCE)\n return lunr.QueryLexer.lexText\n}\n\nlunr.QueryLexer.lexBoost = function (lexer) {\n lexer.ignore()\n lexer.acceptDigitRun()\n lexer.emit(lunr.QueryLexer.BOOST)\n return lunr.QueryLexer.lexText\n}\n\nlunr.QueryLexer.lexEOS = function (lexer) {\n if (lexer.width() > 0) {\n lexer.emit(lunr.QueryLexer.TERM)\n }\n}\n\n// This matches the separator used when tokenising fields\n// within a document. These should match otherwise it is\n// not possible to search for some tokens within a document.\n//\n// It is possible for the user to change the separator on the\n// tokenizer so it _might_ clash with any other of the special\n// characters already used within the search string, e.g. :.\n//\n// This means that it is possible to change the separator in\n// such a way that makes some words unsearchable using a search\n// string.\nlunr.QueryLexer.termSeparator = lunr.tokenizer.separator\n\nlunr.QueryLexer.lexText = function (lexer) {\n while (true) {\n var char = lexer.next()\n\n if (char == lunr.QueryLexer.EOS) {\n return lunr.QueryLexer.lexEOS\n }\n\n // Escape character is '\\'\n if (char.charCodeAt(0) == 92) {\n lexer.escapeCharacter()\n continue\n }\n\n if (char == \":\") {\n return lunr.QueryLexer.lexField\n }\n\n if (char == \"~\") {\n lexer.backup()\n if (lexer.width() > 0) {\n lexer.emit(lunr.QueryLexer.TERM)\n }\n return lunr.QueryLexer.lexEditDistance\n }\n\n if (char == \"^\") {\n lexer.backup()\n if (lexer.width() > 0) {\n lexer.emit(lunr.QueryLexer.TERM)\n }\n return lunr.QueryLexer.lexBoost\n }\n\n // \"+\" indicates term presence is required\n // checking for length to ensure that only\n // leading \"+\" are considered\n if (char == \"+\" && lexer.width() === 1) {\n lexer.emit(lunr.QueryLexer.PRESENCE)\n return lunr.QueryLexer.lexText\n }\n\n // \"-\" indicates term presence is prohibited\n // checking for length to ensure that only\n // leading \"-\" are considered\n if (char == \"-\" && lexer.width() === 1) {\n lexer.emit(lunr.QueryLexer.PRESENCE)\n return lunr.QueryLexer.lexText\n }\n\n if (char.match(lunr.QueryLexer.termSeparator)) {\n return lunr.QueryLexer.lexTerm\n }\n }\n}\n\nlunr.QueryParser = function (str, query) {\n this.lexer = new lunr.QueryLexer (str)\n this.query = query\n this.currentClause = {}\n this.lexemeIdx = 0\n}\n\nlunr.QueryParser.prototype.parse = function () {\n this.lexer.run()\n this.lexemes = this.lexer.lexemes\n\n var state = lunr.QueryParser.parseClause\n\n while (state) {\n state = state(this)\n }\n\n return this.query\n}\n\nlunr.QueryParser.prototype.peekLexeme = function () {\n return this.lexemes[this.lexemeIdx]\n}\n\nlunr.QueryParser.prototype.consumeLexeme = function () {\n var lexeme = this.peekLexeme()\n this.lexemeIdx += 1\n return lexeme\n}\n\nlunr.QueryParser.prototype.nextClause = function () {\n var completedClause = this.currentClause\n this.query.clause(completedClause)\n this.currentClause = {}\n}\n\nlunr.QueryParser.parseClause = function (parser) {\n var lexeme = parser.peekLexeme()\n\n if (lexeme == undefined) {\n return\n }\n\n switch (lexeme.type) {\n case lunr.QueryLexer.PRESENCE:\n return lunr.QueryParser.parsePresence\n case lunr.QueryLexer.FIELD:\n return lunr.QueryParser.parseField\n case lunr.QueryLexer.TERM:\n return lunr.QueryParser.parseTerm\n default:\n var errorMessage = \"expected either a field or a term, found \" + lexeme.type\n\n if (lexeme.str.length >= 1) {\n errorMessage += \" with value '\" + lexeme.str + \"'\"\n }\n\n throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end)\n }\n}\n\nlunr.QueryParser.parsePresence = function (parser) {\n var lexeme = parser.consumeLexeme()\n\n if (lexeme == undefined) {\n return\n }\n\n switch (lexeme.str) {\n case \"-\":\n parser.currentClause.presence = lunr.Query.presence.PROHIBITED\n break\n case \"+\":\n parser.currentClause.presence = lunr.Query.presence.REQUIRED\n break\n default:\n var errorMessage = \"unrecognised presence operator'\" + lexeme.str + \"'\"\n throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end)\n }\n\n var nextLexeme = parser.peekLexeme()\n\n if (nextLexeme == undefined) {\n var errorMessage = \"expecting term or field, found nothing\"\n throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end)\n }\n\n switch (nextLexeme.type) {\n case lunr.QueryLexer.FIELD:\n return lunr.QueryParser.parseField\n case lunr.QueryLexer.TERM:\n return lunr.QueryParser.parseTerm\n default:\n var errorMessage = \"expecting term or field, found '\" + nextLexeme.type + \"'\"\n throw new lunr.QueryParseError (errorMessage, nextLexeme.start, nextLexeme.end)\n }\n}\n\nlunr.QueryParser.parseField = function (parser) {\n var lexeme = parser.consumeLexeme()\n\n if (lexeme == undefined) {\n return\n }\n\n if (parser.query.allFields.indexOf(lexeme.str) == -1) {\n var possibleFields = parser.query.allFields.map(function (f) { return \"'\" + f + \"'\" }).join(', '),\n errorMessage = \"unrecognised field '\" + lexeme.str + \"', possible fields: \" + possibleFields\n\n throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end)\n }\n\n parser.currentClause.fields = [lexeme.str]\n\n var nextLexeme = parser.peekLexeme()\n\n if (nextLexeme == undefined) {\n var errorMessage = \"expecting term, found nothing\"\n throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end)\n }\n\n switch (nextLexeme.type) {\n case lunr.QueryLexer.TERM:\n return lunr.QueryParser.parseTerm\n default:\n var errorMessage = \"expecting term, found '\" + nextLexeme.type + \"'\"\n throw new lunr.QueryParseError (errorMessage, nextLexeme.start, nextLexeme.end)\n }\n}\n\nlunr.QueryParser.parseTerm = function (parser) {\n var lexeme = parser.consumeLexeme()\n\n if (lexeme == undefined) {\n return\n }\n\n parser.currentClause.term = lexeme.str.toLowerCase()\n\n if (lexeme.str.indexOf(\"*\") != -1) {\n parser.currentClause.usePipeline = false\n }\n\n var nextLexeme = parser.peekLexeme()\n\n if (nextLexeme == undefined) {\n parser.nextClause()\n return\n }\n\n switch (nextLexeme.type) {\n case lunr.QueryLexer.TERM:\n parser.nextClause()\n return lunr.QueryParser.parseTerm\n case lunr.QueryLexer.FIELD:\n parser.nextClause()\n return lunr.QueryParser.parseField\n case lunr.QueryLexer.EDIT_DISTANCE:\n return lunr.QueryParser.parseEditDistance\n case lunr.QueryLexer.BOOST:\n return lunr.QueryParser.parseBoost\n case lunr.QueryLexer.PRESENCE:\n parser.nextClause()\n return lunr.QueryParser.parsePresence\n default:\n var errorMessage = \"Unexpected lexeme type '\" + nextLexeme.type + \"'\"\n throw new lunr.QueryParseError (errorMessage, nextLexeme.start, nextLexeme.end)\n }\n}\n\nlunr.QueryParser.parseEditDistance = function (parser) {\n var lexeme = parser.consumeLexeme()\n\n if (lexeme == undefined) {\n return\n }\n\n var editDistance = parseInt(lexeme.str, 10)\n\n if (isNaN(editDistance)) {\n var errorMessage = \"edit distance must be numeric\"\n throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end)\n }\n\n parser.currentClause.editDistance = editDistance\n\n var nextLexeme = parser.peekLexeme()\n\n if (nextLexeme == undefined) {\n parser.nextClause()\n return\n }\n\n switch (nextLexeme.type) {\n case lunr.QueryLexer.TERM:\n parser.nextClause()\n return lunr.QueryParser.parseTerm\n case lunr.QueryLexer.FIELD:\n parser.nextClause()\n return lunr.QueryParser.parseField\n case lunr.QueryLexer.EDIT_DISTANCE:\n return lunr.QueryParser.parseEditDistance\n case lunr.QueryLexer.BOOST:\n return lunr.QueryParser.parseBoost\n case lunr.QueryLexer.PRESENCE:\n parser.nextClause()\n return lunr.QueryParser.parsePresence\n default:\n var errorMessage = \"Unexpected lexeme type '\" + nextLexeme.type + \"'\"\n throw new lunr.QueryParseError (errorMessage, nextLexeme.start, nextLexeme.end)\n }\n}\n\nlunr.QueryParser.parseBoost = function (parser) {\n var lexeme = parser.consumeLexeme()\n\n if (lexeme == undefined) {\n return\n }\n\n var boost = parseInt(lexeme.str, 10)\n\n if (isNaN(boost)) {\n var errorMessage = \"boost must be numeric\"\n throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end)\n }\n\n parser.currentClause.boost = boost\n\n var nextLexeme = parser.peekLexeme()\n\n if (nextLexeme == undefined) {\n parser.nextClause()\n return\n }\n\n switch (nextLexeme.type) {\n case lunr.QueryLexer.TERM:\n parser.nextClause()\n return lunr.QueryParser.parseTerm\n case lunr.QueryLexer.FIELD:\n parser.nextClause()\n return lunr.QueryParser.parseField\n case lunr.QueryLexer.EDIT_DISTANCE:\n return lunr.QueryParser.parseEditDistance\n case lunr.QueryLexer.BOOST:\n return lunr.QueryParser.parseBoost\n case lunr.QueryLexer.PRESENCE:\n parser.nextClause()\n return lunr.QueryParser.parsePresence\n default:\n var errorMessage = \"Unexpected lexeme type '\" + nextLexeme.type + \"'\"\n throw new lunr.QueryParseError (errorMessage, nextLexeme.start, nextLexeme.end)\n }\n}\n\n /**\n * export the module via AMD, CommonJS or as a browser global\n * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js\n */\n ;(function (root, factory) {\n if (typeof define === 'function' && define.amd) {\n // AMD. Register as an anonymous module.\n define(factory)\n } else if (typeof exports === 'object') {\n /**\n * Node. Does not work with strict CommonJS, but\n * only CommonJS-like enviroments that support module.exports,\n * like Node.\n */\n module.exports = factory()\n } else {\n // Browser globals (root is window)\n root.lunr = factory()\n }\n }(this, function () {\n /**\n * Just return a value to define the module export.\n * This example returns an object, but the module\n * can return a function as the exported value.\n */\n return lunr\n }))\n})();\n", "/*!\n * escape-html\n * Copyright(c) 2012-2013 TJ Holowaychuk\n * Copyright(c) 2015 Andreas Lubbe\n * Copyright(c) 2015 Tiancheng \"Timothy\" Gu\n * MIT Licensed\n */\n\n'use strict';\n\n/**\n * Module variables.\n * @private\n */\n\nvar matchHtmlRegExp = /[\"'&<>]/;\n\n/**\n * Module exports.\n * @public\n */\n\nmodule.exports = escapeHtml;\n\n/**\n * Escape special characters in the given string of html.\n *\n * @param {string} string The string to escape for inserting into HTML\n * @return {string}\n * @public\n */\n\nfunction escapeHtml(string) {\n var str = '' + string;\n var match = matchHtmlRegExp.exec(str);\n\n if (!match) {\n return str;\n }\n\n var escape;\n var html = '';\n var index = 0;\n var lastIndex = 0;\n\n for (index = match.index; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34: // \"\n escape = '"';\n break;\n case 38: // &\n escape = '&';\n break;\n case 39: // '\n escape = ''';\n break;\n case 60: // <\n escape = '<';\n break;\n case 62: // >\n escape = '>';\n break;\n default:\n continue;\n }\n\n if (lastIndex !== index) {\n html += str.substring(lastIndex, index);\n }\n\n lastIndex = index + 1;\n html += escape;\n }\n\n return lastIndex !== index\n ? html + str.substring(lastIndex, index)\n : html;\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A RTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport lunr from \"lunr\"\n\nimport { Search, SearchIndexConfig } from \"../../_\"\nimport {\n SearchMessage,\n SearchMessageType\n} from \"../message\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Add support for usage with `iframe-worker` polyfill\n *\n * While `importScripts` is synchronous when executed inside of a web worker,\n * it's not possible to provide a synchronous polyfilled implementation. The\n * cool thing is that awaiting a non-Promise is a noop, so extending the type\n * definition to return a `Promise` shouldn't break anything.\n *\n * @see https://bit.ly/2PjDnXi - GitHub comment\n */\ndeclare global {\n function importScripts(...urls: string[]): Promise | void\n}\n\n/* ----------------------------------------------------------------------------\n * Data\n * ------------------------------------------------------------------------- */\n\n/**\n * Search index\n */\nlet index: Search\n\n/* ----------------------------------------------------------------------------\n * Helper functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Fetch (= import) multi-language support through `lunr-languages`\n *\n * This function automatically imports the stemmers necessary to process the\n * languages, which are defined through the search index configuration.\n *\n * If the worker runs inside of an `iframe` (when using `iframe-worker` as\n * a shim), the base URL for the stemmers to be loaded must be determined by\n * searching for the first `script` element with a `src` attribute, which will\n * contain the contents of this script.\n *\n * @param config - Search index configuration\n *\n * @returns Promise resolving with no result\n */\nasync function setupSearchLanguages(\n config: SearchIndexConfig\n): Promise {\n let base = \"../lunr\"\n\n /* Detect `iframe-worker` and fix base URL */\n if (typeof parent !== \"undefined\" && \"IFrameWorker\" in parent) {\n const worker = document.querySelector(\"script[src]\")!\n const [path] = worker.src.split(\"/worker\")\n\n /* Prefix base with path */\n base = base.replace(\"..\", path)\n }\n\n /* Add scripts for languages */\n const scripts = []\n for (const lang of config.lang) {\n switch (lang) {\n\n /* Add segmenter for Japanese */\n case \"ja\":\n scripts.push(`${base}/tinyseg.js`)\n break\n\n /* Add segmenter for Hindi and Thai */\n case \"hi\":\n case \"th\":\n scripts.push(`${base}/wordcut.js`)\n break\n }\n\n /* Add language support */\n if (lang !== \"en\")\n scripts.push(`${base}/min/lunr.${lang}.min.js`)\n }\n\n /* Add multi-language support */\n if (config.lang.length > 1)\n scripts.push(`${base}/min/lunr.multi.min.js`)\n\n /* Load scripts synchronously */\n if (scripts.length)\n await importScripts(\n `${base}/min/lunr.stemmer.support.min.js`,\n ...scripts\n )\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Message handler\n *\n * @param message - Source message\n *\n * @returns Target message\n */\nexport async function handler(\n message: SearchMessage\n): Promise {\n switch (message.type) {\n\n /* Search setup message */\n case SearchMessageType.SETUP:\n await setupSearchLanguages(message.data.config)\n index = new Search(message.data)\n return {\n type: SearchMessageType.READY\n }\n\n /* Search query message */\n case SearchMessageType.QUERY:\n return {\n type: SearchMessageType.RESULT,\n data: index ? index.search(message.data) : { items: [] }\n }\n\n /* All other messages */\n default:\n throw new TypeError(\"Invalid message type\")\n }\n}\n\n/* ----------------------------------------------------------------------------\n * Worker\n * ------------------------------------------------------------------------- */\n\n/* @ts-ignore - expose Lunr.js in global scope, or stemmers will not work */\nself.lunr = lunr\n\n/* Handle messages */\naddEventListener(\"message\", async ev => {\n postMessage(await handler(ev.data))\n})\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport escapeHTML from \"escape-html\"\n\nimport { SearchIndexDocument } from \"../_\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Search document\n */\nexport interface SearchDocument extends SearchIndexDocument {\n parent?: SearchIndexDocument /* Parent article */\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Search document mapping\n */\nexport type SearchDocumentMap = Map\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Create a search document mapping\n *\n * @param docs - Search index documents\n *\n * @returns Search document map\n */\nexport function setupSearchDocumentMap(\n docs: SearchIndexDocument[]\n): SearchDocumentMap {\n const documents = new Map()\n const parents = new Set()\n for (const doc of docs) {\n const [path, hash] = doc.location.split(\"#\")\n\n /* Extract location and title */\n const location = doc.location\n const title = doc.title\n\n /* Escape and cleanup text */\n const text = escapeHTML(doc.text)\n .replace(/\\s+(?=[,.:;!?])/g, \"\")\n .replace(/\\s+/g, \" \")\n\n /* Handle section */\n if (hash) {\n const parent = documents.get(path)!\n\n /* Ignore first section, override article */\n if (!parents.has(parent)) {\n parent.title = doc.title\n parent.text = text\n\n /* Remember that we processed the article */\n parents.add(parent)\n\n /* Add subsequent section */\n } else {\n documents.set(location, {\n location,\n title,\n text,\n parent\n })\n }\n\n /* Add article */\n } else {\n documents.set(location, {\n location,\n title,\n text\n })\n }\n }\n return documents\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { SearchIndexConfig } from \"../_\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Search highlight function\n *\n * @param value - Value\n *\n * @returns Highlighted value\n */\nexport type SearchHighlightFn = (value: string) => string\n\n/**\n * Search highlight factory function\n *\n * @param query - Query value\n *\n * @returns Search highlight function\n */\nexport type SearchHighlightFactoryFn = (query: string) => SearchHighlightFn\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Create a search highlighter\n *\n * @param config - Search index configuration\n *\n * @returns Search highlight factory function\n */\nexport function setupSearchHighlighter(\n config: SearchIndexConfig\n): SearchHighlightFactoryFn {\n const separator = new RegExp(config.separator, \"img\")\n const highlight = (_: unknown, data: string, term: string) => {\n return `${data}${term}`\n }\n\n /* Return factory function */\n return (query: string) => {\n query = query\n .replace(/[\\s*+\\-:~^]+/g, \" \")\n .trim()\n\n /* Create search term match expression */\n const match = new RegExp(`(^|${config.separator})(${\n query\n .replace(/[|\\\\{}()[\\]^$+*?.-]/g, \"\\\\$&\")\n .replace(separator, \"|\")\n })`, \"img\")\n\n /* Highlight string value */\n return value => value\n .replace(match, highlight)\n .replace(/<\\/mark>(\\s+)]*>/img, \"$1\")\n }\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Search query clause\n */\nexport interface SearchQueryClause {\n presence: lunr.Query.presence /* Clause presence */\n term: string /* Clause term */\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Search query terms\n */\nexport type SearchQueryTerms = Record\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Parse a search query for analysis\n *\n * @param value - Query value\n *\n * @returns Search query clauses\n */\nexport function parseSearchQuery(\n value: string\n): SearchQueryClause[] {\n const query = new (lunr as any).Query([\"title\", \"text\"])\n const parser = new (lunr as any).QueryParser(value, query)\n\n /* Parse and return query clauses */\n parser.parse()\n return query.clauses\n}\n\n/**\n * Analyze the search query clauses in regard to the search terms found\n *\n * @param query - Search query clauses\n * @param terms - Search terms\n *\n * @returns Search query terms\n */\nexport function getSearchQueryTerms(\n query: SearchQueryClause[], terms: string[]\n): SearchQueryTerms {\n const clauses = new Set(query)\n\n /* Match query clauses against terms */\n const result: SearchQueryTerms = {}\n for (let t = 0; t < terms.length; t++)\n for (const clause of clauses)\n if (terms[t].startsWith(clause.term)) {\n result[clause.term] = true\n clauses.delete(clause)\n }\n\n /* Annotate unmatched query clauses */\n for (const clause of clauses)\n result[clause.term] = false\n\n /* Return query terms */\n return result\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport {\n SearchDocument,\n SearchDocumentMap,\n setupSearchDocumentMap\n} from \"../document\"\nimport {\n SearchHighlightFactoryFn,\n setupSearchHighlighter\n} from \"../highlighter\"\nimport { SearchOptions } from \"../options\"\nimport {\n SearchQueryTerms,\n getSearchQueryTerms,\n parseSearchQuery\n} from \"../query\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Search index configuration\n */\nexport interface SearchIndexConfig {\n lang: string[] /* Search languages */\n separator: string /* Search separator */\n}\n\n/**\n * Search index document\n */\nexport interface SearchIndexDocument {\n location: string /* Document location */\n title: string /* Document title */\n text: string /* Document text */\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Search index\n *\n * This interfaces describes the format of the `search_index.json` file which\n * is automatically built by the MkDocs search plugin.\n */\nexport interface SearchIndex {\n config: SearchIndexConfig /* Search index configuration */\n docs: SearchIndexDocument[] /* Search index documents */\n index?: object /* Prebuilt index */\n options: SearchOptions /* Search options */\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Search metadata\n */\nexport interface SearchMetadata {\n score: number /* Score (relevance) */\n terms: SearchQueryTerms /* Search query terms */\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Search result document\n */\nexport type SearchResultDocument = SearchDocument & SearchMetadata\n\n/**\n * Search result item\n */\nexport type SearchResultItem = SearchResultDocument[]\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * Search result\n */\nexport interface SearchResult {\n items: SearchResultItem[] /* Search result items */\n suggestions?: string[] /* Search suggestions */\n}\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Compute the difference of two lists of strings\n *\n * @param a - 1st list of strings\n * @param b - 2nd list of strings\n *\n * @returns Difference\n */\nfunction difference(a: string[], b: string[]): string[] {\n const [x, y] = [new Set(a), new Set(b)]\n return [\n ...new Set([...x].filter(value => !y.has(value)))\n ]\n}\n\n/* ----------------------------------------------------------------------------\n * Class\n * ------------------------------------------------------------------------- */\n\n/**\n * Search index\n */\nexport class Search {\n\n /**\n * Search document mapping\n *\n * A mapping of URLs (including hash fragments) to the actual articles and\n * sections of the documentation. The search document mapping must be created\n * regardless of whether the index was prebuilt or not, as Lunr.js itself\n * only stores the actual index.\n */\n protected documents: SearchDocumentMap\n\n /**\n * Search highlight factory function\n */\n protected highlight: SearchHighlightFactoryFn\n\n /**\n * The underlying Lunr.js search index\n */\n protected index: lunr.Index\n\n /**\n * Search options\n */\n protected options: SearchOptions\n\n /**\n * Create the search integration\n *\n * @param data - Search index\n */\n public constructor({ config, docs, index, options }: SearchIndex) {\n this.options = options\n\n /* Set up document map and highlighter factory */\n this.documents = setupSearchDocumentMap(docs)\n this.highlight = setupSearchHighlighter(config)\n\n /* Set separator for tokenizer */\n lunr.tokenizer.separator = new RegExp(config.separator)\n\n /* If no index was given, create it */\n if (typeof index === \"undefined\") {\n this.index = lunr(function () {\n\n /* Set up multi-language support */\n if (config.lang.length === 1 && config.lang[0] !== \"en\") {\n this.use((lunr as any)[config.lang[0]])\n } else if (config.lang.length > 1) {\n this.use((lunr as any).multiLanguage(...config.lang))\n }\n\n /* Compute functions to be removed from the pipeline */\n const fns = difference([\n \"trimmer\", \"stopWordFilter\", \"stemmer\"\n ], options.pipeline)\n\n /* Remove functions from the pipeline for registered languages */\n for (const lang of config.lang.map(language => (\n language === \"en\" ? lunr : (lunr as any)[language]\n ))) {\n for (const fn of fns) {\n this.pipeline.remove(lang[fn])\n this.searchPipeline.remove(lang[fn])\n }\n }\n\n /* Set up reference */\n this.ref(\"location\")\n\n /* Set up fields */\n this.field(\"title\", { boost: 1e3 })\n this.field(\"text\")\n\n /* Index documents */\n for (const doc of docs)\n this.add(doc)\n })\n\n /* Handle prebuilt index */\n } else {\n this.index = lunr.Index.load(index)\n }\n }\n\n /**\n * Search for matching documents\n *\n * The search index which MkDocs provides is divided up into articles, which\n * contain the whole content of the individual pages, and sections, which only\n * contain the contents of the subsections obtained by breaking the individual\n * pages up at `h1` ... `h6`. As there may be many sections on different pages\n * with identical titles (for example within this very project, e.g. \"Usage\"\n * or \"Installation\"), they need to be put into the context of the containing\n * page. For this reason, section results are grouped within their respective\n * articles which are the top-level results that are returned.\n *\n * @param query - Query value\n *\n * @returns Search results\n */\n public search(query: string): SearchResult {\n if (query) {\n try {\n const highlight = this.highlight(query)\n\n /* Parse query to extract clauses for analysis */\n const clauses = parseSearchQuery(query)\n .filter(clause => (\n clause.presence !== lunr.Query.presence.PROHIBITED\n ))\n\n /* Perform search and post-process results */\n const groups = this.index.search(`${query}*`)\n\n /* Apply post-query boosts based on title and search query terms */\n .reduce((item, { ref, score, matchData }) => {\n const document = this.documents.get(ref)\n if (typeof document !== \"undefined\") {\n const { location, title, text, parent } = document\n\n /* Compute and analyze search query terms */\n const terms = getSearchQueryTerms(\n clauses,\n Object.keys(matchData.metadata)\n )\n\n /* Highlight title and text and apply post-query boosts */\n const boost = +!parent + +Object.values(terms).every(t => t)\n item.push({\n location,\n title: highlight(title),\n text: highlight(text),\n score: score * (1 + boost),\n terms\n })\n }\n return item\n }, [])\n\n /* Sort search results again after applying boosts */\n .sort((a, b) => b.score - a.score)\n\n /* Group search results by page */\n .reduce((items, result) => {\n const document = this.documents.get(result.location)\n if (typeof document !== \"undefined\") {\n const ref = \"parent\" in document\n ? document.parent!.location\n : document.location\n items.set(ref, [...items.get(ref) || [], result])\n }\n return items\n }, new Map())\n\n /* Generate search suggestions, if desired */\n let suggestions: string[] | undefined\n if (this.options.suggestions) {\n const titles = this.index.query(builder => {\n for (const clause of clauses)\n builder.term(clause.term, {\n fields: [\"title\"],\n presence: lunr.Query.presence.REQUIRED,\n wildcard: lunr.Query.wildcard.TRAILING\n })\n })\n\n /* Retrieve suggestions for best match */\n suggestions = titles.length\n ? Object.keys(titles[0].matchData.metadata)\n : []\n }\n\n /* Return items and suggestions */\n return {\n items: [...groups.values()],\n ...typeof suggestions !== \"undefined\" && { suggestions }\n }\n\n /* Log errors to console (for now) */\n } catch {\n console.warn(`Invalid query: ${query} \u2013 see https://bit.ly/2s3ChXG`)\n }\n }\n\n /* Return nothing in case of error or empty query */\n return { items: [] }\n }\n}\n", "/*\n * Copyright (c) 2016-2021 Martin Donath \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A RTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\nimport { SearchIndex, SearchResult } from \"../../_\"\n\n/* ----------------------------------------------------------------------------\n * Types\n * ------------------------------------------------------------------------- */\n\n/**\n * Search message type\n */\nexport const enum SearchMessageType {\n SETUP, /* Search index setup */\n READY, /* Search index ready */\n QUERY, /* Search query */\n RESULT /* Search results */\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * A message containing the data necessary to setup the search index\n */\nexport interface SearchSetupMessage {\n type: SearchMessageType.SETUP /* Message type */\n data: SearchIndex /* Message data */\n}\n\n/**\n * A message indicating the search index is ready\n */\nexport interface SearchReadyMessage {\n type: SearchMessageType.READY /* Message type */\n}\n\n/**\n * A message containing a search query\n */\nexport interface SearchQueryMessage {\n type: SearchMessageType.QUERY /* Message type */\n data: string /* Message data */\n}\n\n/**\n * A message containing results for a search query\n */\nexport interface SearchResultMessage {\n type: SearchMessageType.RESULT /* Message type */\n data: SearchResult /* Message data */\n}\n\n/* ------------------------------------------------------------------------- */\n\n/**\n * A message exchanged with the search worker\n */\nexport type SearchMessage =\n | SearchSetupMessage\n | SearchReadyMessage\n | SearchQueryMessage\n | SearchResultMessage\n\n/* ----------------------------------------------------------------------------\n * Functions\n * ------------------------------------------------------------------------- */\n\n/**\n * Type guard for search setup messages\n *\n * @param message - Search worker message\n *\n * @returns Test result\n */\nexport function isSearchSetupMessage(\n message: SearchMessage\n): message is SearchSetupMessage {\n return message.type === SearchMessageType.SETUP\n}\n\n/**\n * Type guard for search ready messages\n *\n * @param message - Search worker message\n *\n * @returns Test result\n */\nexport function isSearchReadyMessage(\n message: SearchMessage\n): message is SearchReadyMessage {\n return message.type === SearchMessageType.READY\n}\n\n/**\n * Type guard for search query messages\n *\n * @param message - Search worker message\n *\n * @returns Test result\n */\nexport function isSearchQueryMessage(\n message: SearchMessage\n): message is SearchQueryMessage {\n return message.type === SearchMessageType.QUERY\n}\n\n/**\n * Type guard for search result messages\n *\n * @param message - Search worker message\n *\n * @returns Test result\n */\nexport function isSearchResultMessage(\n message: SearchMessage\n): message is SearchResultMessage {\n return message.type === SearchMessageType.RESULT\n}\n"], + "mappings": "kkCAAA;AAAA;AAAA;AAAA;AAAA,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,AAAI,IAAS,MACX,EAAQ,KAAK,GAAG,cAAiB,YAIrC,AAAI,EAAO,KAAK,OAAS,GACvB,EAAQ,KAAK,GAAG,2BAGd,EAAQ,QACV,MAAM,eACJ,GAAG,oCACH,GAAG,MAeT,YACE,EACwB,gCACxB,OAAQ,EAAQ,UAGT,GAAkB,MACrB,YAAM,IAAqB,EAAQ,KAAK,QACxC,EAAQ,GAAI,GAAO,EAAQ,MACpB,CACL,KAAM,EAAkB,WAIvB,GAAkB,MACrB,MAAO,CACL,KAAM,EAAkB,OACxB,KAAM,EAAQ,EAAM,OAAO,EAAQ,MAAQ,CAAE,MAAO,aAKtD,KAAM,IAAI,WAAU,2BAS1B,KAAK,KAAO,WAGZ,iBAAiB,UAAW,AAAM,GAAM,0BACtC,YAAY,KAAM,IAAQ,EAAG", + "names": [] +} diff --git a/en/2021.7/assets/plot-dataframe.png b/en/2021.7/assets/plot-dataframe.png new file mode 100644 index 000000000..6310b23b4 Binary files /dev/null and b/en/2021.7/assets/plot-dataframe.png differ diff --git a/en/2021.7/assets/plot-dataframe2.png b/en/2021.7/assets/plot-dataframe2.png new file mode 100644 index 000000000..d744b2035 Binary files /dev/null and b/en/2021.7/assets/plot-dataframe2.png differ diff --git a/en/2021.7/assets/plot-profit.png b/en/2021.7/assets/plot-profit.png new file mode 100644 index 000000000..88d69a2d4 Binary files /dev/null and b/en/2021.7/assets/plot-profit.png differ diff --git a/en/2021.7/assets/stylesheets/main.1118c9be.min.css b/en/2021.7/assets/stylesheets/main.1118c9be.min.css new file mode 100644 index 000000000..2a2226c7c --- /dev/null +++ b/en/2021.7/assets/stylesheets/main.1118c9be.min.css @@ -0,0 +1,2 @@ +@charset "UTF-8";html{-webkit-text-size-adjust:none;-ms-text-size-adjust:none;text-size-adjust:none;box-sizing:border-box}*,:after,:before{box-sizing:inherit}body{margin:0}a,button,input,label{-webkit-tap-highlight-color:transparent}a{color:inherit;text-decoration:none}hr{border:0;box-sizing:content-box;display:block;height:.05rem;overflow:visible;padding:0}small{font-size:80%}sub,sup{line-height:1em}img{border-style:none}table{border-collapse:separate;border-spacing:0}td,th{font-weight:400;vertical-align:top}button{background:transparent;border:0;font-family:inherit;font-size:inherit;margin:0;padding:0}input{border:0;outline:none}:root{--md-default-fg-color:rgba(0,0,0,0.87);--md-default-fg-color--light:rgba(0,0,0,0.54);--md-default-fg-color--lighter:rgba(0,0,0,0.32);--md-default-fg-color--lightest:rgba(0,0,0,0.07);--md-default-bg-color:#fff;--md-default-bg-color--light:hsla(0,0%,100%,0.7);--md-default-bg-color--lighter:hsla(0,0%,100%,0.3);--md-default-bg-color--lightest:hsla(0,0%,100%,0.12);--md-primary-fg-color:#4051b5;--md-primary-fg-color--light:#5d6cc0;--md-primary-fg-color--dark:#303fa1;--md-primary-bg-color:#fff;--md-primary-bg-color--light:hsla(0,0%,100%,0.7);--md-accent-fg-color:#526cfe;--md-accent-fg-color--transparent:rgba(82,108,254,0.1);--md-accent-bg-color:#fff;--md-accent-bg-color--light:hsla(0,0%,100%,0.7)}:root>*{--md-code-fg-color:#36464e;--md-code-bg-color:#f5f5f5;--md-code-hl-color:rgba(255,255,0,0.5);--md-code-hl-number-color:#d52a2a;--md-code-hl-special-color:#db1457;--md-code-hl-function-color:#a846b9;--md-code-hl-constant-color:#6e59d9;--md-code-hl-keyword-color:#3f6ec6;--md-code-hl-string-color:#1c7d4d;--md-code-hl-name-color:var(--md-code-fg-color);--md-code-hl-operator-color:var(--md-default-fg-color--light);--md-code-hl-punctuation-color:var(--md-default-fg-color--light);--md-code-hl-comment-color:var(--md-default-fg-color--light);--md-code-hl-generic-color:var(--md-default-fg-color--light);--md-code-hl-variable-color:var(--md-default-fg-color--light);--md-typeset-color:var(--md-default-fg-color);--md-typeset-a-color:var(--md-primary-fg-color);--md-typeset-mark-color:rgba(255,255,0,0.5);--md-typeset-del-color:hsla(6,90%,60%,0.15);--md-typeset-ins-color:rgba(11,213,112,0.15);--md-typeset-kbd-color:#fafafa;--md-typeset-kbd-accent-color:#fff;--md-typeset-kbd-border-color:#b8b8b8;--md-admonition-fg-color:var(--md-default-fg-color);--md-admonition-bg-color:var(--md-default-bg-color);--md-footer-fg-color:#fff;--md-footer-fg-color--light:hsla(0,0%,100%,0.7);--md-footer-fg-color--lighter:hsla(0,0%,100%,0.3);--md-footer-bg-color:rgba(0,0,0,0.87);--md-footer-bg-color--dark:rgba(0,0,0,0.32)}.md-icon svg{fill:currentColor;display:block;height:1.2rem;width:1.2rem}body{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}body,input{font-feature-settings:"kern","liga";font-family:var(--md-text-font-family,_),-apple-system,BlinkMacSystemFont,Helvetica,Arial,sans-serif}body,code,input,kbd,pre{color:var(--md-typeset-color)}code,kbd,pre{font-feature-settings:"kern";font-family:var(--md-code-font-family,_),SFMono-Regular,Consolas,Menlo,monospace}:root{--md-typeset-table--ascending:url('data:image/svg+xml;charset=utf-8,');--md-typeset-table--descending:url('data:image/svg+xml;charset=utf-8,')}.md-typeset{-webkit-print-color-adjust:exact;color-adjust:exact;font-size:.8rem;line-height:1.6}@media print{.md-typeset{font-size:.68rem}}.md-typeset blockquote,.md-typeset dl,.md-typeset figure,.md-typeset ol,.md-typeset pre,.md-typeset ul{margin:1em 0}.md-typeset h1{color:var(--md-default-fg-color--light);font-size:2em;line-height:1.3;margin:0 0 1.25em}.md-typeset h1,.md-typeset h2{font-weight:300;letter-spacing:-.01em}.md-typeset h2{font-size:1.5625em;line-height:1.4;margin:1.6em 0 .64em}.md-typeset h3{font-size:1.25em;font-weight:400;letter-spacing:-.01em;line-height:1.5;margin:1.6em 0 .8em}.md-typeset h2+h3{margin-top:.8em}.md-typeset h4{font-weight:700;letter-spacing:-.01em;margin:1em 0}.md-typeset h5,.md-typeset h6{color:var(--md-default-fg-color--light);font-size:.8em;font-weight:700;letter-spacing:-.01em;margin:1.25em 0}.md-typeset h5{text-transform:uppercase}.md-typeset hr{border-bottom:.05rem solid var(--md-default-fg-color--lightest);display:flow-root;margin:1.5em 0}.md-typeset a{color:var(--md-typeset-a-color);word-break:break-word}.md-typeset a,.md-typeset a:before{transition:color 125ms}.md-typeset a:focus,.md-typeset a:hover{color:var(--md-accent-fg-color)}.md-typeset a.focus-visible{outline-color:var(--md-accent-fg-color);outline-offset:.2rem}.md-typeset code,.md-typeset kbd,.md-typeset pre{color:var(--md-code-fg-color);direction:ltr}@media print{.md-typeset code,.md-typeset kbd,.md-typeset pre{white-space:pre-wrap}}.md-typeset code{background-color:var(--md-code-bg-color);border-radius:.1rem;-webkit-box-decoration-break:clone;box-decoration-break:clone;font-size:.85em;padding:0 .2941176471em;word-break:break-word}.md-typeset code:not(.focus-visible){-webkit-tap-highlight-color:transparent;outline:none}.md-typeset h1 code,.md-typeset h2 code,.md-typeset h3 code,.md-typeset h4 code,.md-typeset h5 code,.md-typeset h6 code{background-color:transparent;box-shadow:none;margin:initial;padding:initial}.md-typeset a code{color:currentColor}.md-typeset pre{display:flow-root;line-height:1.4;position:relative}.md-typeset pre>code{-webkit-box-decoration-break:slice;box-decoration-break:slice;box-shadow:none;display:block;margin:0;overflow:auto;padding:.7720588235em 1.1764705882em;scrollbar-color:var(--md-default-fg-color--lighter) transparent;scrollbar-width:thin;touch-action:auto;word-break:normal}.md-typeset pre>code:hover{scrollbar-color:var(--md-accent-fg-color) transparent}.md-typeset pre>code::-webkit-scrollbar{height:.2rem;width:.2rem}.md-typeset pre>code::-webkit-scrollbar-thumb{background-color:var(--md-default-fg-color--lighter)}.md-typeset pre>code::-webkit-scrollbar-thumb:hover{background-color:var(--md-accent-fg-color)}@media screen and (max-width:44.9375em){.md-typeset>pre{margin:1em -.8rem}.md-typeset>pre code{border-radius:0}}.md-typeset kbd{background-color:var(--md-typeset-kbd-color);border-radius:.1rem;box-shadow:0 .1rem 0 .05rem var(--md-typeset-kbd-border-color),0 .1rem 0 var(--md-typeset-kbd-border-color),0 -.1rem .2rem var(--md-typeset-kbd-accent-color) inset;color:var(--md-default-fg-color);display:inline-block;font-size:.75em;padding:0 .6666666667em;vertical-align:text-top;word-break:break-word}.md-typeset mark{background-color:var(--md-typeset-mark-color);-webkit-box-decoration-break:clone;box-decoration-break:clone;color:inherit;word-break:break-word}.md-typeset abbr{border-bottom:.05rem dotted var(--md-default-fg-color--light);cursor:help;text-decoration:none}@media (hover:none){.md-typeset abbr{position:relative}.md-typeset abbr[title]:focus:after,.md-typeset abbr[title]:hover:after{background-color:var(--md-default-fg-color);border-radius:.1rem;box-shadow:0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12),0 3px 1px -2px rgba(0,0,0,.2);color:var(--md-default-bg-color);content:attr(title);display:inline-block;font-size:.7rem;left:0;margin-top:2em;max-width:80%;min-width:-webkit-max-content;min-width:-moz-max-content;min-width:max-content;padding:.2rem .3rem;position:absolute;width:auto}}.md-typeset small{opacity:.75}.md-typeset sub,.md-typeset sup{margin-left:.078125em}[dir=rtl] .md-typeset sub,[dir=rtl] .md-typeset sup{margin-left:0;margin-right:.078125em}.md-typeset blockquote{border-left:.2rem solid var(--md-default-fg-color--lighter);color:var(--md-default-fg-color--light);display:flow-root;padding-left:.6rem}[dir=rtl] .md-typeset blockquote{border-left:initial;border-right:.2rem solid var(--md-default-fg-color--lighter);padding-left:0;padding-right:.6rem}.md-typeset ul{list-style-type:disc}.md-typeset ol,.md-typeset ul{display:flow-root;margin-left:.625em;padding:0}[dir=rtl] .md-typeset ol,[dir=rtl] .md-typeset ul{margin-left:0;margin-right:.625em}.md-typeset ol ol,.md-typeset ul ol{list-style-type:lower-alpha}.md-typeset ol ol ol,.md-typeset ul ol ol{list-style-type:lower-roman}.md-typeset ol li,.md-typeset ul li{margin-bottom:.5em;margin-left:1.25em}[dir=rtl] .md-typeset ol li,[dir=rtl] .md-typeset ul li{margin-left:0;margin-right:1.25em}.md-typeset ol li blockquote,.md-typeset ol li p,.md-typeset ul li blockquote,.md-typeset ul li p{margin:.5em 0}.md-typeset ol li:last-child,.md-typeset ul li:last-child{margin-bottom:0}.md-typeset ol li ol,.md-typeset ol li ul,.md-typeset ul li ol,.md-typeset ul li ul{margin:.5em 0 .5em .625em}[dir=rtl] .md-typeset ol li ol,[dir=rtl] .md-typeset ol li ul,[dir=rtl] .md-typeset ul li ol,[dir=rtl] .md-typeset ul li ul{margin-left:0;margin-right:.625em}.md-typeset dd{margin:1em 0 1.5em 1.875em}[dir=rtl] .md-typeset dd{margin-left:0;margin-right:1.875em}.md-typeset img,.md-typeset svg{height:auto;max-width:100%}.md-typeset img[align=left],.md-typeset svg[align=left]{margin:1em 1em 1em 0}.md-typeset img[align=right],.md-typeset svg[align=right]{margin:1em 0 1em 1em}.md-typeset img[align]:only-child,.md-typeset svg[align]:only-child{margin-top:0}.md-typeset figure{display:flow-root;margin:0 auto;max-width:100%;text-align:center;width:-webkit-fit-content;width:-moz-fit-content;width:fit-content}.md-typeset figure img{display:block}.md-typeset figcaption{font-style:italic;margin:1em auto 2em;max-width:24rem}.md-typeset iframe{max-width:100%}.md-typeset table:not([class]){background-color:var(--md-default-bg-color);border-radius:.1rem;box-shadow:0 .2rem .5rem rgba(0,0,0,.05),0 0 .05rem rgba(0,0,0,.1);display:inline-block;font-size:.64rem;max-width:100%;overflow:auto;touch-action:auto}@media print{.md-typeset table:not([class]){display:table}}.md-typeset table:not([class])+*{margin-top:1.5em}.md-typeset table:not([class]) td>:first-child,.md-typeset table:not([class]) th>:first-child{margin-top:0}.md-typeset table:not([class]) td>:last-child,.md-typeset table:not([class]) th>:last-child{margin-bottom:0}.md-typeset table:not([class]) td:not([align]),.md-typeset table:not([class]) th:not([align]){text-align:left}[dir=rtl] .md-typeset table:not([class]) td:not([align]),[dir=rtl] .md-typeset table:not([class]) th:not([align]){text-align:right}.md-typeset table:not([class]) th{background-color:var(--md-default-fg-color--light);color:var(--md-default-bg-color);min-width:5rem;padding:.9375em 1.25em;vertical-align:top}.md-typeset table:not([class]) th a{color:inherit}.md-typeset table:not([class]) td{border-top:.05rem solid var(--md-default-fg-color--lightest);padding:.9375em 1.25em;vertical-align:top}.md-typeset table:not([class]) tr{transition:background-color 125ms}.md-typeset table:not([class]) tr:hover{background-color:rgba(0,0,0,.035);box-shadow:0 .05rem 0 var(--md-default-bg-color) inset}.md-typeset table:not([class]) tr:first-child td{border-top:0}.md-typeset table:not([class]) a{word-break:normal}.md-typeset table th[role=columnheader]{cursor:pointer}.md-typeset table th[role=columnheader]:after{content:"";display:inline-block;height:1.2em;margin-left:.5em;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain;vertical-align:sub;width:1.2em}.md-typeset table th[role=columnheader][aria-sort=ascending]:after{background-color:currentColor;-webkit-mask-image:var(--md-typeset-table--ascending);mask-image:var(--md-typeset-table--ascending)}.md-typeset table th[role=columnheader][aria-sort=descending]:after{background-color:currentColor;-webkit-mask-image:var(--md-typeset-table--descending);mask-image:var(--md-typeset-table--descending)}.md-typeset__scrollwrap{margin:1em -.8rem;overflow-x:auto;touch-action:auto}.md-typeset__table{display:inline-block;margin-bottom:.5em;padding:0 .8rem}@media print{.md-typeset__table{display:block}}html .md-typeset__table table{display:table;margin:0;overflow:hidden;width:100%}html{font-size:125%;height:100%;overflow-x:hidden}@media screen and (min-width:100em){html{font-size:137.5%}}@media screen and (min-width:125em){html{font-size:150%}}body{background-color:var(--md-default-bg-color);display:flex;flex-direction:column;font-size:.5rem;min-height:100%;position:relative;width:100%}@media print{body{display:block}}@media screen and (max-width:59.9375em){body[data-md-state=lock]{position:fixed}}.md-grid{margin-left:auto;margin-right:auto;max-width:61rem}.md-container{display:flex;flex-direction:column;flex-grow:1}@media print{.md-container{display:block}}.md-main{flex-grow:1}.md-main__inner{display:flex;height:100%;margin-top:1.5rem}.md-ellipsis{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.md-toggle{display:none}.md-option{height:0;opacity:0;position:absolute;width:0}.md-option:checked+label:not([hidden]){display:block}.md-option.focus-visible+label{outline-color:var(--md-accent-fg-color);outline-style:auto}.md-skip{background-color:var(--md-default-fg-color);border-radius:.1rem;color:var(--md-default-bg-color);font-size:.64rem;margin:.5rem;opacity:0;outline-color:var(--md-accent-fg-color);padding:.3rem .5rem;position:fixed;transform:translateY(.4rem);z-index:-1}.md-skip:focus{opacity:1;transform:translateY(0);transition:transform .25s cubic-bezier(.4,0,.2,1),opacity 175ms 75ms;z-index:10}@page{margin:25mm}.md-announce{background-color:var(--md-footer-bg-color);overflow:auto}@media print{.md-announce{display:none}}.md-announce__inner{color:var(--md-footer-fg-color);font-size:.7rem;margin:.6rem auto;padding:0 .8rem}:root{--md-clipboard-icon:url('data:image/svg+xml;charset=utf-8,')}.md-clipboard{border-radius:.1rem;color:var(--md-default-fg-color--lightest);cursor:pointer;height:1.5em;outline-color:var(--md-accent-fg-color);outline-offset:.1rem;position:absolute;right:.5em;top:.5em;transition:color .25s;width:1.5em;z-index:1}@media print{.md-clipboard{display:none}}.md-clipboard:not(.focus-visible){-webkit-tap-highlight-color:transparent;outline:none}:hover>.md-clipboard{color:var(--md-default-fg-color--light)}.md-clipboard:focus,.md-clipboard:hover{color:var(--md-accent-fg-color)}.md-clipboard:after{background-color:currentColor;content:"";display:block;height:1.125em;margin:0 auto;-webkit-mask-image:var(--md-clipboard-icon);mask-image:var(--md-clipboard-icon);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain;width:1.125em}.md-clipboard--inline{cursor:pointer}.md-clipboard--inline code{transition:color .25s,background-color .25s}.md-clipboard--inline:focus code,.md-clipboard--inline:hover code{background-color:var(--md-accent-fg-color--transparent);color:var(--md-accent-fg-color)}.md-content{flex-grow:1;overflow:hidden;scroll-padding-top:51.2rem}.md-content__inner{margin:0 .8rem 1.2rem;padding-top:.6rem}@media screen and (min-width:76.25em){.md-sidebar--primary:not([hidden])~.md-content>.md-content__inner{margin-left:1.2rem}[dir=rtl] .md-sidebar--primary:not([hidden])~.md-content>.md-content__inner{margin-left:.8rem;margin-right:1.2rem}.md-sidebar--secondary:not([hidden])~.md-content>.md-content__inner{margin-right:1.2rem}[dir=rtl] .md-sidebar--secondary:not([hidden])~.md-content>.md-content__inner{margin-left:1.2rem;margin-right:.8rem}}.md-content__inner:before{content:"";display:block;height:.4rem}.md-content__inner>:last-child{margin-bottom:0}.md-content__button{float:right;margin:.4rem 0 .4rem .4rem;padding:0}@media print{.md-content__button{display:none}}[dir=rtl] .md-content__button{float:left;margin-left:0;margin-right:.4rem}[dir=rtl] .md-content__button svg{transform:scaleX(-1)}.md-typeset .md-content__button{color:var(--md-default-fg-color--lighter)}.md-content__button svg{display:inline;vertical-align:top}.md-dialog{background-color:var(--md-default-fg-color);border-radius:.1rem;bottom:.8rem;box-shadow:0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12),0 3px 1px -2px rgba(0,0,0,.2);left:auto;min-width:11.1rem;opacity:0;padding:.4rem .6rem;pointer-events:none;position:fixed;right:.8rem;transform:translateY(100%);transition:transform 0ms .4s,opacity .4s;z-index:3}@media print{.md-dialog{display:none}}[dir=rtl] .md-dialog{left:.8rem;right:auto}.md-dialog[data-md-state=open]{opacity:1;pointer-events:auto;transform:translateY(0);transition:transform .4s cubic-bezier(.075,.85,.175,1),opacity .4s}.md-dialog__inner{color:var(--md-default-bg-color);font-size:.7rem}.md-typeset .md-button{border:.1rem solid;border-radius:.1rem;color:var(--md-primary-fg-color);cursor:pointer;display:inline-block;font-weight:700;padding:.625em 2em;transition:color 125ms,background-color 125ms,border-color 125ms}.md-typeset .md-button--primary{background-color:var(--md-primary-fg-color);border-color:var(--md-primary-fg-color);color:var(--md-primary-bg-color)}.md-typeset .md-button:focus,.md-typeset .md-button:hover{background-color:var(--md-accent-fg-color);border-color:var(--md-accent-fg-color);color:var(--md-accent-bg-color)}.md-typeset .md-input{border-radius:.1rem;box-shadow:0 .2rem .5rem rgba(0,0,0,.1),0 .025rem .05rem rgba(0,0,0,.1);font-size:.8rem;height:1.8rem;padding:0 .6rem;transition:box-shadow .25s}.md-typeset .md-input:focus,.md-typeset .md-input:hover{box-shadow:0 .4rem 1rem rgba(0,0,0,.15),0 .025rem .05rem rgba(0,0,0,.15)}.md-typeset .md-input--stretch{width:100%}.md-header{background-color:var(--md-primary-fg-color);box-shadow:0 0 .2rem transparent,0 .2rem .4rem transparent;color:var(--md-primary-bg-color);left:0;position:-webkit-sticky;position:sticky;right:0;top:0;z-index:3}@media print{.md-header{display:none}}.md-header[data-md-state=shadow]{box-shadow:0 0 .2rem rgba(0,0,0,.1),0 .2rem .4rem rgba(0,0,0,.2);transition:transform .25s cubic-bezier(.1,.7,.1,1),box-shadow .25s}.md-header[data-md-state=hidden]{transform:translateY(-100%);transition:transform .25s cubic-bezier(.8,0,.6,1),box-shadow .25s}.md-header__inner{align-items:center;display:flex;padding:0 .2rem}.md-header__button{color:currentColor;cursor:pointer;margin:.2rem;outline-color:var(--md-accent-fg-color);padding:.4rem;position:relative;transition:opacity .25s;vertical-align:middle;z-index:1}.md-header__button:hover{opacity:.7}.md-header__button:not([hidden]){display:inline-block}.md-header__button:not(.focus-visible){-webkit-tap-highlight-color:transparent;outline:none}.md-header__button.md-logo{margin:.2rem;padding:.4rem}@media screen and (max-width:76.1875em){.md-header__button.md-logo{display:none}}.md-header__button.md-logo img,.md-header__button.md-logo svg{fill:currentColor;display:block;height:1.2rem;width:1.2rem}@media screen and (min-width:60em){.md-header__button[for=__search]{display:none}}.no-js .md-header__button[for=__search]{display:none}[dir=rtl] .md-header__button[for=__search] svg{transform:scaleX(-1)}@media screen and (min-width:76.25em){.md-header__button[for=__drawer]{display:none}}.md-header__topic{display:flex;max-width:100%;position:absolute;transition:transform .4s cubic-bezier(.1,.7,.1,1),opacity .15s}.md-header__topic+.md-header__topic{opacity:0;pointer-events:none;transform:translateX(1.25rem);transition:transform .4s cubic-bezier(1,.7,.1,.1),opacity .15s;z-index:-1}[dir=rtl] .md-header__topic+.md-header__topic{transform:translateX(-1.25rem)}.md-header__title{flex-grow:1;font-size:.9rem;height:2.4rem;line-height:2.4rem;margin-left:1rem;margin-right:.4rem}.md-header__title[data-md-state=active] .md-header__topic{opacity:0;pointer-events:none;transform:translateX(-1.25rem);transition:transform .4s cubic-bezier(1,.7,.1,.1),opacity .15s;z-index:-1}[dir=rtl] .md-header__title[data-md-state=active] .md-header__topic{transform:translateX(1.25rem)}.md-header__title[data-md-state=active] .md-header__topic+.md-header__topic{opacity:1;pointer-events:auto;transform:translateX(0);transition:transform .4s cubic-bezier(.1,.7,.1,1),opacity .15s;z-index:0}.md-header__title>.md-header__ellipsis{height:100%;position:relative;width:100%}.md-header__option{display:flex;flex-shrink:0;max-width:100%;transition:max-width 0ms .25s,opacity .25s .25s;white-space:nowrap}[data-md-toggle=search]:checked~.md-header .md-header__option{max-width:0;opacity:0;transition:max-width 0ms,opacity 0ms}.md-header__source{display:none}@media screen and (min-width:60em){.md-header__source{display:block;margin-left:1rem;max-width:11.7rem;width:11.7rem}[dir=rtl] .md-header__source{margin-left:0;margin-right:1rem}}@media screen and (min-width:76.25em){.md-header__source{margin-left:1.4rem}[dir=rtl] .md-header__source{margin-right:1.4rem}}.md-footer{background-color:var(--md-footer-bg-color);color:var(--md-footer-fg-color)}@media print{.md-footer{display:none}}.md-footer__inner{overflow:auto;padding:.2rem}.md-footer__link{display:flex;outline-color:var(--md-accent-fg-color);padding-bottom:.4rem;padding-top:1.4rem;transition:opacity .25s}@media screen and (min-width:45em){.md-footer__link{width:50%}}.md-footer__link:focus,.md-footer__link:hover{opacity:.7}.md-footer__link--prev{float:left}@media screen and (max-width:44.9375em){.md-footer__link--prev{width:25%}.md-footer__link--prev .md-footer__title{display:none}}[dir=rtl] .md-footer__link--prev{float:right}[dir=rtl] .md-footer__link--prev svg{transform:scaleX(-1)}.md-footer__link--next{float:right;text-align:right}@media screen and (max-width:44.9375em){.md-footer__link--next{width:75%}}[dir=rtl] .md-footer__link--next{float:left;text-align:left}[dir=rtl] .md-footer__link--next svg{transform:scaleX(-1)}.md-footer__title{flex-grow:1;font-size:.9rem;line-height:2.4rem;max-width:calc(100% - 2.4rem);padding:0 1rem;position:relative}.md-footer__button{margin:.2rem;padding:.4rem}.md-footer__direction{font-size:.64rem;left:0;margin-top:-1rem;opacity:.7;padding:0 1rem;position:absolute;right:0}.md-footer-meta{background-color:var(--md-footer-bg-color--dark)}.md-footer-meta__inner{display:flex;flex-wrap:wrap;justify-content:space-between;padding:.2rem}html .md-footer-meta.md-typeset a{color:var(--md-footer-fg-color--light)}html .md-footer-meta.md-typeset a:focus,html .md-footer-meta.md-typeset a:hover{color:var(--md-footer-fg-color)}.md-footer-copyright{color:var(--md-footer-fg-color--lighter);font-size:.64rem;margin:auto .6rem;padding:.4rem 0;width:100%}@media screen and (min-width:45em){.md-footer-copyright{width:auto}}.md-footer-copyright__highlight{color:var(--md-footer-fg-color--light)}.md-footer-social{margin:0 .4rem;padding:.2rem 0 .6rem}@media screen and (min-width:45em){.md-footer-social{padding:.6rem 0}}.md-footer-social__link{display:inline-block;height:1.6rem;text-align:center;width:1.6rem}.md-footer-social__link:before{line-height:1.9}.md-footer-social__link svg{fill:currentColor;max-height:.8rem;vertical-align:-25%}:root{--md-nav-icon--prev:url('data:image/svg+xml;charset=utf-8,');--md-nav-icon--next:url('data:image/svg+xml;charset=utf-8,');--md-toc-icon:url('data:image/svg+xml;charset=utf-8,')}.md-nav{font-size:.7rem;line-height:1.3}.md-nav__title{display:block;font-weight:700;overflow:hidden;padding:0 .6rem;text-overflow:ellipsis}.md-nav__title .md-nav__button{display:none}.md-nav__title .md-nav__button img{height:100%;width:auto}.md-nav__title .md-nav__button.md-logo img,.md-nav__title .md-nav__button.md-logo svg{fill:currentColor;display:block;height:2.4rem;width:2.4rem}.md-nav__list{list-style:none;margin:0;padding:0}.md-nav__item{padding:0 .6rem}.md-nav__item .md-nav__item{padding-right:0}[dir=rtl] .md-nav__item .md-nav__item{padding-left:0;padding-right:.6rem}.md-nav__link{cursor:pointer;display:block;margin-top:.625em;overflow:hidden;scroll-snap-align:start;text-overflow:ellipsis;transition:color 125ms}.md-nav__link[data-md-state=blur]{color:var(--md-default-fg-color--light)}.md-nav__item .md-nav__link--active{color:var(--md-typeset-a-color)}.md-nav__item--nested>.md-nav__link{color:inherit}.md-nav__link:focus,.md-nav__link:hover{color:var(--md-accent-fg-color)}.md-nav__link.focus-visible{outline-color:var(--md-accent-fg-color);outline-offset:.2rem}.md-nav--primary .md-nav__link[for=__toc]{display:none}.md-nav--primary .md-nav__link[for=__toc] .md-icon:after{background-color:currentColor;display:block;height:100%;-webkit-mask-image:var(--md-toc-icon);mask-image:var(--md-toc-icon);width:100%}.md-nav--primary .md-nav__link[for=__toc]~.md-nav{display:none}.md-nav__source{display:none}@media screen and (max-width:76.1875em){.md-nav--primary,.md-nav--primary .md-nav{background-color:var(--md-default-bg-color);display:flex;flex-direction:column;height:100%;left:0;position:absolute;right:0;top:0;z-index:1}.md-nav--primary .md-nav__item,.md-nav--primary .md-nav__title{font-size:.8rem;line-height:1.5}.md-nav--primary .md-nav__title{background-color:var(--md-default-fg-color--lightest);color:var(--md-default-fg-color--light);cursor:pointer;font-weight:400;height:5.6rem;line-height:2.4rem;padding:3rem .8rem .2rem;position:relative;white-space:nowrap}.md-nav--primary .md-nav__title .md-nav__icon{display:block;height:1.2rem;left:.4rem;margin:.2rem;position:absolute;top:.4rem;width:1.2rem}[dir=rtl] .md-nav--primary .md-nav__title .md-nav__icon{left:auto;right:.4rem}.md-nav--primary .md-nav__title .md-nav__icon:after{background-color:currentColor;content:"";display:block;height:100%;-webkit-mask-image:var(--md-nav-icon--prev);mask-image:var(--md-nav-icon--prev);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain;width:100%}.md-nav--primary .md-nav__title~.md-nav__list{background-color:var(--md-default-bg-color);box-shadow:0 .05rem 0 var(--md-default-fg-color--lightest) inset;overflow-y:auto;-ms-scroll-snap-type:y mandatory;scroll-snap-type:y mandatory;touch-action:pan-y}.md-nav--primary .md-nav__title~.md-nav__list>:first-child{border-top:0}.md-nav--primary .md-nav__title[for=__drawer]{background-color:var(--md-primary-fg-color);color:var(--md-primary-bg-color)}.md-nav--primary .md-nav__title .md-logo{display:block;left:.2rem;margin:.2rem;padding:.4rem;position:absolute;top:.2rem}[dir=rtl] .md-nav--primary .md-nav__title .md-logo{left:auto;right:.2rem}.md-nav--primary .md-nav__list{flex:1}.md-nav--primary .md-nav__item{border-top:.05rem solid var(--md-default-fg-color--lightest);padding:0}.md-nav--primary .md-nav__item--nested>.md-nav__link{padding-right:2.4rem}[dir=rtl] .md-nav--primary .md-nav__item--nested>.md-nav__link{padding-left:2.4rem;padding-right:.8rem}.md-nav--primary .md-nav__item--active>.md-nav__link{color:var(--md-typeset-a-color)}.md-nav--primary .md-nav__item--active>.md-nav__link:focus,.md-nav--primary .md-nav__item--active>.md-nav__link:hover{color:var(--md-accent-fg-color)}.md-nav--primary .md-nav__link{margin-top:0;padding:.6rem .8rem;position:relative}.md-nav--primary .md-nav__link .md-nav__icon{color:inherit;font-size:1.2rem;height:1.2rem;margin-top:-.6rem;position:absolute;right:.6rem;top:50%;width:1.2rem}[dir=rtl] .md-nav--primary .md-nav__link .md-nav__icon{left:.6rem;right:auto}.md-nav--primary .md-nav__link .md-nav__icon:after{background-color:currentColor;content:"";display:block;height:100%;-webkit-mask-image:var(--md-nav-icon--next);mask-image:var(--md-nav-icon--next);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain;width:100%}[dir=rtl] .md-nav--primary .md-nav__icon:after{transform:scale(-1)}.md-nav--primary .md-nav--secondary .md-nav__link{position:static}.md-nav--primary .md-nav--secondary .md-nav{background-color:transparent;position:static}.md-nav--primary .md-nav--secondary .md-nav .md-nav__link{padding-left:1.4rem}[dir=rtl] .md-nav--primary .md-nav--secondary .md-nav .md-nav__link{padding-left:0;padding-right:1.4rem}.md-nav--primary .md-nav--secondary .md-nav .md-nav .md-nav__link{padding-left:2rem}[dir=rtl] .md-nav--primary .md-nav--secondary .md-nav .md-nav .md-nav__link{padding-left:0;padding-right:2rem}.md-nav--primary .md-nav--secondary .md-nav .md-nav .md-nav .md-nav__link{padding-left:2.6rem}[dir=rtl] .md-nav--primary .md-nav--secondary .md-nav .md-nav .md-nav .md-nav__link{padding-left:0;padding-right:2.6rem}.md-nav--primary .md-nav--secondary .md-nav .md-nav .md-nav .md-nav .md-nav__link{padding-left:3.2rem}[dir=rtl] .md-nav--primary .md-nav--secondary .md-nav .md-nav .md-nav .md-nav .md-nav__link{padding-left:0;padding-right:3.2rem}.md-nav--secondary{background-color:transparent}.md-nav__toggle~.md-nav{display:flex;opacity:0;transform:translateX(100%);transition:transform .25s cubic-bezier(.8,0,.6,1),opacity 125ms 50ms}[dir=rtl] .md-nav__toggle~.md-nav{transform:translateX(-100%)}.md-nav__toggle:checked~.md-nav{opacity:1;transform:translateX(0);transition:transform .25s cubic-bezier(.4,0,.2,1),opacity 125ms 125ms}.md-nav__toggle:checked~.md-nav>.md-nav__list{-webkit-backface-visibility:hidden;backface-visibility:hidden}}@media screen and (max-width:59.9375em){.md-nav--primary .md-nav__link[for=__toc]{display:block;padding-right:2.4rem}[dir=rtl] .md-nav--primary .md-nav__link[for=__toc]{padding-left:2.4rem;padding-right:.8rem}.md-nav--primary .md-nav__link[for=__toc] .md-icon:after{content:""}.md-nav--primary .md-nav__link[for=__toc]+.md-nav__link{display:none}.md-nav--primary .md-nav__link[for=__toc]~.md-nav{display:flex}.md-nav__source{background-color:var(--md-primary-fg-color--dark);color:var(--md-primary-bg-color);display:block;padding:0 .2rem}}@media screen and (min-width:60em) and (max-width:76.1875em){.md-nav--integrated .md-nav__link[for=__toc]{display:block;padding-right:2.4rem;scroll-snap-align:none}[dir=rtl] .md-nav--integrated .md-nav__link[for=__toc]{padding-left:2.4rem;padding-right:.8rem}.md-nav--integrated .md-nav__link[for=__toc] .md-icon:after{content:""}.md-nav--integrated .md-nav__link[for=__toc]+.md-nav__link{display:none}.md-nav--integrated .md-nav__link[for=__toc]~.md-nav{display:flex}}@media screen and (min-width:60em){.md-nav--secondary .md-nav__title[for=__toc]{scroll-snap-align:start}.md-nav--secondary .md-nav__title .md-nav__icon{display:none}}@media screen and (min-width:76.25em){.md-nav{transition:max-height .25s cubic-bezier(.86,0,.07,1)}.md-nav--primary .md-nav__title[for=__drawer]{scroll-snap-align:start}.md-nav--primary .md-nav__title .md-nav__icon{display:none}.md-nav__toggle~.md-nav{display:none}.md-nav__toggle:checked~.md-nav,.md-nav__toggle:indeterminate~.md-nav{display:block}.md-nav__item--nested>.md-nav>.md-nav__title{display:none}.md-nav__item--section{display:block;margin:1.25em 0}.md-nav__item--section:last-child{margin-bottom:0}.md-nav__item--section>.md-nav__link{display:none}.md-nav__item--section>.md-nav{display:block}.md-nav__item--section>.md-nav>.md-nav__title{display:block;padding:0;pointer-events:none;scroll-snap-align:start}.md-nav__item--section>.md-nav>.md-nav__list>.md-nav__item{padding:0}.md-nav__icon{float:right;height:.9rem;transition:transform .25s;width:.9rem}[dir=rtl] .md-nav__icon{float:left;transform:rotate(180deg)}.md-nav__icon:after{background-color:currentColor;content:"";display:inline-block;height:100%;-webkit-mask-image:var(--md-nav-icon--next);mask-image:var(--md-nav-icon--next);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain;vertical-align:-.1rem;width:100%}.md-nav__item--nested .md-nav__toggle:checked~.md-nav__link .md-nav__icon,.md-nav__item--nested .md-nav__toggle:indeterminate~.md-nav__link .md-nav__icon{transform:rotate(90deg)}.md-nav--lifted>.md-nav__list>.md-nav__item--nested,.md-nav--lifted>.md-nav__title{display:none}.md-nav--lifted>.md-nav__list>.md-nav__item{display:none}.md-nav--lifted>.md-nav__list>.md-nav__item--active{display:block;padding:0}.md-nav--lifted>.md-nav__list>.md-nav__item--active>.md-nav__link{display:none}.md-nav--lifted>.md-nav__list>.md-nav__item--active>.md-nav>.md-nav__title{display:block;padding:0 .6rem;pointer-events:none;scroll-snap-align:start}.md-nav--lifted .md-nav[data-md-level="1"]{display:block}.md-nav--lifted .md-nav[data-md-level="1"]>.md-nav__list>.md-nav__item{padding-right:.6rem}.md-nav--integrated .md-nav__link[for=__toc]~.md-nav{border-left:.05rem solid var(--md-primary-fg-color);display:block;margin-bottom:1.25em}.md-nav--integrated .md-nav__link[for=__toc]~.md-nav>.md-nav__title{display:none}}:root{--md-search-result-icon:url('data:image/svg+xml;charset=utf-8,')}.md-search{position:relative}@media screen and (min-width:60em){.md-search{padding:.2rem 0}}.no-js .md-search{display:none}.md-search__overlay{opacity:0;z-index:1}@media screen and (max-width:59.9375em){.md-search__overlay{background-color:var(--md-default-bg-color);border-radius:1rem;height:2rem;left:-2.2rem;overflow:hidden;pointer-events:none;position:absolute;top:.2rem;transform-origin:center;transition:transform .3s .1s,opacity .2s .2s;width:2rem}[dir=rtl] .md-search__overlay{left:auto;right:-2.2rem}[data-md-toggle=search]:checked~.md-header .md-search__overlay{opacity:1;transition:transform .4s,opacity .1s}}@media screen and (min-width:60em){.md-search__overlay{background-color:rgba(0,0,0,.54);cursor:pointer;height:0;left:0;position:fixed;top:0;transition:width 0ms .25s,height 0ms .25s,opacity .25s;width:0}[dir=rtl] .md-search__overlay{left:auto;right:0}[data-md-toggle=search]:checked~.md-header .md-search__overlay{height:200vh;opacity:1;transition:width 0ms,height 0ms,opacity .25s;width:100%}}@media screen and (max-width:29.9375em){[data-md-toggle=search]:checked~.md-header .md-search__overlay{transform:scale(45)}}@media screen and (min-width:30em) and (max-width:44.9375em){[data-md-toggle=search]:checked~.md-header .md-search__overlay{transform:scale(60)}}@media screen and (min-width:45em) and (max-width:59.9375em){[data-md-toggle=search]:checked~.md-header .md-search__overlay{transform:scale(75)}}.md-search__inner{-webkit-backface-visibility:hidden;backface-visibility:hidden}@media screen and (max-width:59.9375em){.md-search__inner{height:100%;left:100%;opacity:0;position:fixed;top:0;transform:translateX(5%);transition:right 0ms .3s,left 0ms .3s,transform .15s cubic-bezier(.4,0,.2,1) .15s,opacity .15s .15s;width:100%;z-index:2}[data-md-toggle=search]:checked~.md-header .md-search__inner{left:0;opacity:1;transform:translateX(0);transition:right 0ms 0ms,left 0ms 0ms,transform .15s cubic-bezier(.1,.7,.1,1) .15s,opacity .15s .15s}[dir=rtl] [data-md-toggle=search]:checked~.md-header .md-search__inner{left:auto;right:0}html [dir=rtl] .md-search__inner{left:auto;right:100%;transform:translateX(-5%)}}@media screen and (min-width:60em){.md-search__inner{float:right;padding:.1rem 0;position:relative;transition:width .25s cubic-bezier(.1,.7,.1,1);width:11.7rem}[dir=rtl] .md-search__inner{float:left}}@media screen and (min-width:60em) and (max-width:76.1875em){[data-md-toggle=search]:checked~.md-header .md-search__inner{width:23.4rem}}@media screen and (min-width:76.25em){[data-md-toggle=search]:checked~.md-header .md-search__inner{width:34.4rem}}.md-search__form{background-color:var(--md-default-bg-color);box-shadow:0 0 .6rem transparent;height:2.4rem;position:relative;transition:color .25s,background-color .25s;z-index:2}@media screen and (min-width:60em){.md-search__form{background-color:rgba(0,0,0,.26);border-radius:.1rem;height:1.8rem}.md-search__form:hover{background-color:hsla(0,0%,100%,.12)}}[data-md-toggle=search]:checked~.md-header .md-search__form{background-color:var(--md-default-bg-color);border-radius:.1rem .1rem 0 0;box-shadow:0 0 .6rem rgba(0,0,0,.07);color:var(--md-default-fg-color)}.md-search__input{background:transparent;font-size:.9rem;height:100%;padding:0 2.2rem 0 3.6rem;position:relative;text-overflow:ellipsis;width:100%;z-index:2}[dir=rtl] .md-search__input{padding:0 3.6rem 0 2.2rem}.md-search__input::-webkit-input-placeholder{-webkit-transition:color .25s;transition:color .25s}.md-search__input::-moz-placeholder{-moz-transition:color .25s;transition:color .25s}.md-search__input::-ms-input-placeholder{-ms-transition:color .25s;transition:color .25s}.md-search__input::placeholder{transition:color .25s}.md-search__input::-webkit-input-placeholder{color:var(--md-default-fg-color--light)}.md-search__input::-moz-placeholder{color:var(--md-default-fg-color--light)}.md-search__input::-ms-input-placeholder{color:var(--md-default-fg-color--light)}.md-search__input::placeholder,.md-search__input~.md-search__icon{color:var(--md-default-fg-color--light)}.md-search__input::-ms-clear{display:none}@media screen and (max-width:59.9375em){.md-search__input{font-size:.9rem;height:2.4rem;width:100%}}@media screen and (min-width:60em){.md-search__input{color:inherit;font-size:.8rem;padding-left:2.2rem}[dir=rtl] .md-search__input{padding-right:2.2rem}.md-search__input::-webkit-input-placeholder{color:var(--md-primary-bg-color--light)}.md-search__input::-moz-placeholder{color:var(--md-primary-bg-color--light)}.md-search__input::-ms-input-placeholder{color:var(--md-primary-bg-color--light)}.md-search__input::placeholder{color:var(--md-primary-bg-color--light)}.md-search__input+.md-search__icon{color:var(--md-primary-bg-color)}[data-md-toggle=search]:checked~.md-header .md-search__input{text-overflow:clip}[data-md-toggle=search]:checked~.md-header .md-search__input::-webkit-input-placeholder{color:var(--md-default-fg-color--light)}[data-md-toggle=search]:checked~.md-header .md-search__input::-moz-placeholder{color:var(--md-default-fg-color--light)}[data-md-toggle=search]:checked~.md-header .md-search__input::-ms-input-placeholder{color:var(--md-default-fg-color--light)}[data-md-toggle=search]:checked~.md-header .md-search__input+.md-search__icon,[data-md-toggle=search]:checked~.md-header .md-search__input::placeholder{color:var(--md-default-fg-color--light)}}.md-search__icon{cursor:pointer;display:inline-block;height:1.2rem;transition:color .25s,opacity .25s;width:1.2rem}.md-search__icon:hover{opacity:.7}.md-search__icon[for=__search]{left:.5rem;position:absolute;top:.3rem;z-index:2}[dir=rtl] .md-search__icon[for=__search]{left:auto;right:.5rem}[dir=rtl] .md-search__icon[for=__search] svg{transform:scaleX(-1)}@media screen and (max-width:59.9375em){.md-search__icon[for=__search]{left:.8rem;top:.6rem}[dir=rtl] .md-search__icon[for=__search]{left:auto;right:.8rem}.md-search__icon[for=__search] svg:first-child{display:none}}@media screen and (min-width:60em){.md-search__icon[for=__search]{pointer-events:none}.md-search__icon[for=__search] svg:last-child{display:none}}.md-search__options{pointer-events:none;position:absolute;right:.5rem;top:.3rem;z-index:2}[dir=rtl] .md-search__options{left:.5rem;right:auto}@media screen and (max-width:59.9375em){.md-search__options{right:.8rem;top:.6rem}[dir=rtl] .md-search__options{left:.8rem;right:auto}}.md-search__options>*{color:var(--md-default-fg-color--light);margin-left:.2rem;opacity:0;transform:scale(.75);transition:transform .15s cubic-bezier(.1,.7,.1,1),opacity .15s}.md-search__options>:not(.focus-visible){-webkit-tap-highlight-color:transparent;outline:none}[data-md-toggle=search]:checked~.md-header .md-search__input:valid~.md-search__options>*{opacity:1;pointer-events:auto;transform:scale(1)}[data-md-toggle=search]:checked~.md-header .md-search__input:valid~.md-search__options>:hover{opacity:.7}.md-search__suggest{align-items:center;color:var(--md-default-fg-color--lighter);display:flex;font-size:.9rem;height:100%;opacity:0;padding:0 2.2rem 0 3.6rem;position:absolute;top:0;transition:opacity 50ms;white-space:nowrap;width:100%}[dir=rtl] .md-search__suggest{padding:0 3.6rem 0 2.2rem}@media screen and (min-width:60em){.md-search__suggest{font-size:.8rem;padding-left:2.2rem}[dir=rtl] .md-search__suggest{padding-right:2.2rem}}[data-md-toggle=search]:checked~.md-header .md-search__suggest{opacity:1;transition:opacity .3s .1s}.md-search__output{border-radius:0 0 .1rem .1rem;overflow:hidden;position:absolute;width:100%;z-index:1}@media screen and (max-width:59.9375em){.md-search__output{bottom:0;top:2.4rem}}@media screen and (min-width:60em){.md-search__output{opacity:0;top:1.9rem;transition:opacity .4s}[data-md-toggle=search]:checked~.md-header .md-search__output{box-shadow:0 6px 10px 0 rgba(0,0,0,.14),0 1px 18px 0 rgba(0,0,0,.12),0 3px 5px -1px rgba(0,0,0,.4);opacity:1}}.md-search__scrollwrap{-webkit-backface-visibility:hidden;backface-visibility:hidden;background-color:var(--md-default-bg-color);height:100%;overflow-y:auto;touch-action:pan-y}@media (-webkit-max-device-pixel-ratio:1),(max-resolution:1dppx){.md-search__scrollwrap{transform:translateZ(0)}}@media screen and (min-width:60em) and (max-width:76.1875em){.md-search__scrollwrap{width:23.4rem}}@media screen and (min-width:76.25em){.md-search__scrollwrap{width:34.4rem}}@media screen and (min-width:60em){.md-search__scrollwrap{max-height:0;scrollbar-color:var(--md-default-fg-color--lighter) transparent;scrollbar-width:thin}[data-md-toggle=search]:checked~.md-header .md-search__scrollwrap{max-height:75vh}.md-search__scrollwrap:hover{scrollbar-color:var(--md-accent-fg-color) transparent}.md-search__scrollwrap::-webkit-scrollbar{height:.2rem;width:.2rem}.md-search__scrollwrap::-webkit-scrollbar-thumb{background-color:var(--md-default-fg-color--lighter)}.md-search__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:var(--md-accent-fg-color)}}.md-search-result{color:var(--md-default-fg-color);word-break:break-word}.md-search-result__meta{background-color:var(--md-default-fg-color--lightest);color:var(--md-default-fg-color--light);font-size:.64rem;line-height:1.8rem;padding:0 .8rem;scroll-snap-align:start}@media screen and (min-width:60em){.md-search-result__meta{padding-left:2.2rem}[dir=rtl] .md-search-result__meta{padding-left:0;padding-right:2.2rem}}.md-search-result__list{list-style:none;margin:0;padding:0}.md-search-result__item{box-shadow:0 -.05rem 0 var(--md-default-fg-color--lightest)}.md-search-result__item:first-child{box-shadow:none}.md-search-result__link{display:block;outline:none;scroll-snap-align:start;transition:background-color .25s}.md-search-result__link:focus,.md-search-result__link:hover{background-color:var(--md-accent-fg-color--transparent)}.md-search-result__link:last-child p:last-child{margin-bottom:.6rem}.md-search-result__more summary{color:var(--md-typeset-a-color);cursor:pointer;display:block;font-size:.64rem;outline:none;padding:.75em .8rem;scroll-snap-align:start;transition:color .25s,background-color .25s}@media screen and (min-width:60em){.md-search-result__more summary{padding-left:2.2rem}[dir=rtl] .md-search-result__more summary{padding-left:.8rem;padding-right:2.2rem}}.md-search-result__more summary:focus,.md-search-result__more summary:hover{background-color:var(--md-accent-fg-color--transparent);color:var(--md-accent-fg-color)}.md-search-result__more summary::-webkit-details-marker,.md-search-result__more summary::marker{display:none}.md-search-result__more summary~*>*{opacity:.65}.md-search-result__article{overflow:hidden;padding:0 .8rem;position:relative}@media screen and (min-width:60em){.md-search-result__article{padding-left:2.2rem}[dir=rtl] .md-search-result__article{padding-left:.8rem;padding-right:2.2rem}}.md-search-result__article--document .md-search-result__title{font-size:.8rem;font-weight:400;line-height:1.4;margin:.55rem 0}.md-search-result__icon{color:var(--md-default-fg-color--light);height:1.2rem;left:0;margin:.5rem;position:absolute;width:1.2rem}@media screen and (max-width:59.9375em){.md-search-result__icon{display:none}}.md-search-result__icon:after{background-color:currentColor;content:"";display:inline-block;height:100%;-webkit-mask-image:var(--md-search-result-icon);mask-image:var(--md-search-result-icon);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain;width:100%}[dir=rtl] .md-search-result__icon{left:auto;right:0}[dir=rtl] .md-search-result__icon:after{transform:scaleX(-1)}.md-search-result__title{font-size:.64rem;font-weight:700;line-height:1.6;margin:.5em 0}.md-search-result__teaser{-webkit-box-orient:vertical;-webkit-line-clamp:2;color:var(--md-default-fg-color--light);display:-webkit-box;font-size:.64rem;line-height:1.6;margin:.5em 0;max-height:2rem;overflow:hidden;text-overflow:ellipsis}@media screen and (max-width:44.9375em){.md-search-result__teaser{-webkit-line-clamp:3;max-height:3rem}}@media screen and (min-width:60em) and (max-width:76.1875em){.md-search-result__teaser{-webkit-line-clamp:3;max-height:3rem}}.md-search-result__teaser mark{background-color:transparent;text-decoration:underline}.md-search-result__terms{font-size:.64rem;font-style:italic;margin:.5em 0}.md-search-result mark{background-color:transparent;color:var(--md-accent-fg-color)}.md-select{position:relative;z-index:1}.md-select__inner{background-color:var(--md-default-bg-color);border-radius:.1rem;box-shadow:0 .2rem .5rem rgba(0,0,0,.1),0 0 .05rem rgba(0,0,0,.25);color:var(--md-default-fg-color);left:50%;margin-top:.2rem;max-height:0;opacity:0;position:absolute;top:calc(100% - .2rem);transform:translate3d(-50%,.3rem,0);transition:transform .25s 375ms,opacity .25s .25s,max-height 0ms .5s}.md-select:focus-within .md-select__inner,.md-select:hover .md-select__inner{max-height:10rem;opacity:1;transform:translate3d(-50%,0,0);transition:transform .25s cubic-bezier(.1,.7,.1,1),opacity .25s,max-height 0ms}.md-select__inner:after{border-bottom:.2rem solid transparent;border-bottom-color:var(--md-default-bg-color);border-left:.2rem solid transparent;border-right:.2rem solid transparent;border-top:0;content:"";height:0;left:50%;margin-left:-.2rem;margin-top:-.2rem;position:absolute;top:0;width:0}.md-select__list{border-radius:.1rem;font-size:.8rem;list-style-type:none;margin:0;max-height:inherit;overflow:auto;padding:0}.md-select__item{line-height:1.8rem}.md-select__link{cursor:pointer;display:block;outline:none;padding-left:.6rem;padding-right:1.2rem;scroll-snap-align:start;transition:background-color .25s,color .25s;width:100%}[dir=rtl] .md-select__link{padding-left:1.2rem;padding-right:.6rem}.md-select__link:focus,.md-select__link:hover{color:var(--md-accent-fg-color)}.md-select__link:focus{background-color:var(--md-default-fg-color--lightest)}.md-sidebar{align-self:flex-start;flex-shrink:0;padding:1.2rem 0;position:-webkit-sticky;position:sticky;top:2.4rem;width:12.1rem}@media print{.md-sidebar{display:none}}@media screen and (max-width:76.1875em){.md-sidebar--primary{background-color:var(--md-default-bg-color);display:block;height:100%;left:-12.1rem;position:fixed;top:0;transform:translateX(0);transition:transform .25s cubic-bezier(.4,0,.2,1),box-shadow .25s;width:12.1rem;z-index:4}[dir=rtl] .md-sidebar--primary{left:auto;right:-12.1rem}[data-md-toggle=drawer]:checked~.md-container .md-sidebar--primary{box-shadow:0 8px 10px 1px rgba(0,0,0,.14),0 3px 14px 2px rgba(0,0,0,.12),0 5px 5px -3px rgba(0,0,0,.4);transform:translateX(12.1rem)}[dir=rtl] [data-md-toggle=drawer]:checked~.md-container .md-sidebar--primary{transform:translateX(-12.1rem)}.md-sidebar--primary .md-sidebar__scrollwrap{bottom:0;left:0;margin:0;overflow:hidden;position:absolute;right:0;-ms-scroll-snap-type:none;scroll-snap-type:none;top:0}}@media screen and (min-width:76.25em){.md-sidebar{height:0}.no-js .md-sidebar{height:auto}}.md-sidebar--secondary{display:none;order:2}@media screen and (min-width:60em){.md-sidebar--secondary{height:0}.no-js .md-sidebar--secondary{height:auto}.md-sidebar--secondary:not([hidden]){display:block}.md-sidebar--secondary .md-sidebar__scrollwrap{touch-action:pan-y}}.md-sidebar__scrollwrap{-webkit-backface-visibility:hidden;backface-visibility:hidden;margin:0 .2rem;overflow-y:auto;scrollbar-color:var(--md-default-fg-color--lighter) transparent;scrollbar-width:thin}.md-sidebar__scrollwrap:hover{scrollbar-color:var(--md-accent-fg-color) transparent}.md-sidebar__scrollwrap::-webkit-scrollbar{height:.2rem;width:.2rem}.md-sidebar__scrollwrap::-webkit-scrollbar-thumb{background-color:var(--md-default-fg-color--lighter)}.md-sidebar__scrollwrap::-webkit-scrollbar-thumb:hover{background-color:var(--md-accent-fg-color)}@media screen and (max-width:76.1875em){.md-overlay{background-color:rgba(0,0,0,.54);height:0;opacity:0;position:fixed;top:0;transition:width 0ms .25s,height 0ms .25s,opacity .25s;width:0;z-index:4}[data-md-toggle=drawer]:checked~.md-overlay{height:100%;opacity:1;transition:width 0ms,height 0ms,opacity .25s;width:100%}}@-webkit-keyframes facts{0%{height:0}to{height:.65rem}}@keyframes facts{0%{height:0}to{height:.65rem}}@-webkit-keyframes fact{0%{opacity:0;transform:translateY(100%)}50%{opacity:0}to{opacity:1;transform:translateY(0)}}@keyframes fact{0%{opacity:0;transform:translateY(100%)}50%{opacity:0}to{opacity:1;transform:translateY(0)}}:root{--md-source-forks-icon:url('data:image/svg+xml;charset=utf-8,');--md-source-repositories-icon:url('data:image/svg+xml;charset=utf-8,');--md-source-stars-icon:url('data:image/svg+xml;charset=utf-8,');--md-source-version-icon:url('data:image/svg+xml;charset=utf-8,')}.md-source{-webkit-backface-visibility:hidden;backface-visibility:hidden;display:block;font-size:.65rem;line-height:1.2;outline-color:var(--md-accent-fg-color);transition:opacity .25s;white-space:nowrap}.md-source:hover{opacity:.7}.md-source__icon{display:inline-block;height:2.4rem;vertical-align:middle;width:2rem}.md-source__icon svg{margin-left:.6rem;margin-top:.6rem}[dir=rtl] .md-source__icon svg{margin-left:0;margin-right:.6rem}.md-source__icon+.md-source__repository{margin-left:-2rem;padding-left:2rem}[dir=rtl] .md-source__icon+.md-source__repository{margin-left:0;margin-right:-2rem;padding-left:0;padding-right:2rem}.md-source__repository{display:inline-block;margin-left:.6rem;max-width:calc(100% - 1.2rem);overflow:hidden;text-overflow:ellipsis;vertical-align:middle}.md-source__facts{font-size:.55rem;list-style-type:none;margin:.1rem 0 0;opacity:.75;overflow:hidden;padding:0}[data-md-state=done] .md-source__facts{-webkit-animation:facts .25s ease-in;animation:facts .25s ease-in}.md-source__fact{display:inline-block}[data-md-state=done] .md-source__fact{-webkit-animation:fact .4s ease-out;animation:fact .4s ease-out}.md-source__fact:before{background-color:currentColor;content:"";display:inline-block;height:.6rem;margin-right:.1rem;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain;vertical-align:text-top;width:.6rem}.md-source__fact:nth-child(1n+2):before{margin-left:.4rem}[dir=rtl] .md-source__fact{margin-left:.1rem;margin-right:0}[dir=rtl] .md-source__fact:nth-child(1n+2):before{margin-left:0;margin-right:.4rem}.md-source__fact--version:before{-webkit-mask-image:var(--md-source-version-icon);mask-image:var(--md-source-version-icon)}.md-source__fact--stars:before{-webkit-mask-image:var(--md-source-stars-icon);mask-image:var(--md-source-stars-icon)}.md-source__fact--forks:before{-webkit-mask-image:var(--md-source-forks-icon);mask-image:var(--md-source-forks-icon)}.md-source__fact--repositories:before{-webkit-mask-image:var(--md-source-repositories-icon);mask-image:var(--md-source-repositories-icon)}.md-tabs{background-color:var(--md-primary-fg-color);color:var(--md-primary-bg-color);overflow:auto;width:100%}@media print{.md-tabs{display:none}}@media screen and (max-width:76.1875em){.md-tabs{display:none}}.md-tabs[data-md-state=hidden]{pointer-events:none}.md-tabs__list{contain:content;list-style:none;margin:0 0 0 .2rem;padding:0;white-space:nowrap}[dir=rtl] .md-tabs__list{margin-left:0;margin-right:.2rem}.md-tabs__item{display:inline-block;height:2.4rem;padding-left:.6rem;padding-right:.6rem}.md-tabs__link{-webkit-backface-visibility:hidden;backface-visibility:hidden;display:block;font-size:.7rem;margin-top:.8rem;opacity:.7;outline-color:var(--md-accent-fg-color);outline-offset:.2rem;transition:transform .4s cubic-bezier(.1,.7,.1,1),opacity .25s}.md-tabs__link--active,.md-tabs__link:focus,.md-tabs__link:hover{color:inherit;opacity:1}.md-tabs__item:nth-child(2) .md-tabs__link{transition-delay:20ms}.md-tabs__item:nth-child(3) .md-tabs__link{transition-delay:40ms}.md-tabs__item:nth-child(4) .md-tabs__link{transition-delay:60ms}.md-tabs__item:nth-child(5) .md-tabs__link{transition-delay:80ms}.md-tabs__item:nth-child(6) .md-tabs__link{transition-delay:.1s}.md-tabs__item:nth-child(7) .md-tabs__link{transition-delay:.12s}.md-tabs__item:nth-child(8) .md-tabs__link{transition-delay:.14s}.md-tabs__item:nth-child(9) .md-tabs__link{transition-delay:.16s}.md-tabs__item:nth-child(10) .md-tabs__link{transition-delay:.18s}.md-tabs__item:nth-child(11) .md-tabs__link{transition-delay:.2s}.md-tabs__item:nth-child(12) .md-tabs__link{transition-delay:.22s}.md-tabs__item:nth-child(13) .md-tabs__link{transition-delay:.24s}.md-tabs__item:nth-child(14) .md-tabs__link{transition-delay:.26s}.md-tabs__item:nth-child(15) .md-tabs__link{transition-delay:.28s}.md-tabs__item:nth-child(16) .md-tabs__link{transition-delay:.3s}.md-tabs[data-md-state=hidden] .md-tabs__link{opacity:0;transform:translateY(50%);transition:transform 0ms .1s,opacity .1s}.md-top{background-color:var(--md-default-bg-color);border-radius:1.6rem;box-shadow:0 .2rem .5rem rgba(0,0,0,.1),0 0 .05rem rgba(0,0,0,.25);color:var(--md-default-fg-color--light);font-size:.7rem;margin-left:50%;outline:none;padding:.4rem .8rem;position:fixed;top:3.2rem;transform:translate(-50%);transition:color 125ms,background-color 125ms,transform 125ms cubic-bezier(.4,0,.2,1),opacity 125ms;z-index:2}@media print{.md-top{display:none}}[dir=rtl] .md-top{float:left}.md-top[data-md-state=hidden]{opacity:0;pointer-events:none;transform:translate(-50%,.2rem);transition-duration:0ms}.md-top:focus,.md-top:hover{background-color:var(--md-accent-fg-color);color:var(--md-accent-bg-color)}.md-top svg{display:inline-block;vertical-align:-.5em}@-webkit-keyframes hoverfix{0%{pointer-events:none}}@keyframes hoverfix{0%{pointer-events:none}}:root{--md-version-icon:url('data:image/svg+xml;charset=utf-8,')}.md-version{flex-shrink:0;font-size:.8rem;height:2.4rem}.md-version__current{color:inherit;cursor:pointer;margin-left:1.4rem;margin-right:.4rem;outline:none;position:relative;top:.05rem}[dir=rtl] .md-version__current{margin-left:.4rem;margin-right:1.4rem}.md-version__current:after{background-color:currentColor;content:"";display:inline-block;height:.6rem;margin-left:.4rem;-webkit-mask-image:var(--md-version-icon);mask-image:var(--md-version-icon);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;width:.4rem}[dir=rtl] .md-version__current:after{margin-left:0;margin-right:.4rem}.md-version__list{background-color:var(--md-default-bg-color);border-radius:.1rem;box-shadow:0 .2rem .5rem rgba(0,0,0,.1),0 0 .05rem rgba(0,0,0,.25);color:var(--md-default-fg-color);list-style-type:none;margin:.2rem .8rem;max-height:0;opacity:0;overflow:auto;padding:0;position:absolute;-ms-scroll-snap-type:y mandatory;scroll-snap-type:y mandatory;top:.15rem;transition:max-height 0ms .5s,opacity .25s .25s;z-index:1}.md-version:focus-within .md-version__list,.md-version:hover .md-version__list{max-height:10rem;opacity:1;transition:max-height 0ms,opacity .25s}@media (pointer:coarse){.md-version:hover .md-version__list{-webkit-animation:hoverfix .25s forwards;animation:hoverfix .25s forwards}.md-version:focus-within .md-version__list{-webkit-animation:none;animation:none}}.md-version__item{line-height:1.8rem}.md-version__link{cursor:pointer;display:block;outline:none;padding-left:.6rem;padding-right:1.2rem;scroll-snap-align:start;transition:color .25s,background-color .25s;white-space:nowrap;width:100%}[dir=rtl] .md-version__link{padding-left:1.2rem;padding-right:.6rem}.md-version__link:focus,.md-version__link:hover{color:var(--md-accent-fg-color)}.md-version__link:focus{background-color:var(--md-default-fg-color--lightest)}:root{--md-admonition-icon--note:url('data:image/svg+xml;charset=utf-8,');--md-admonition-icon--abstract:url('data:image/svg+xml;charset=utf-8,');--md-admonition-icon--info:url('data:image/svg+xml;charset=utf-8,');--md-admonition-icon--tip:url('data:image/svg+xml;charset=utf-8,');--md-admonition-icon--success:url('data:image/svg+xml;charset=utf-8,');--md-admonition-icon--question:url('data:image/svg+xml;charset=utf-8,');--md-admonition-icon--warning:url('data:image/svg+xml;charset=utf-8,');--md-admonition-icon--failure:url('data:image/svg+xml;charset=utf-8,');--md-admonition-icon--danger:url('data:image/svg+xml;charset=utf-8,');--md-admonition-icon--bug:url('data:image/svg+xml;charset=utf-8,');--md-admonition-icon--example:url('data:image/svg+xml;charset=utf-8,');--md-admonition-icon--quote:url('data:image/svg+xml;charset=utf-8,')}.md-typeset .admonition,.md-typeset details{background-color:var(--md-admonition-bg-color);border-left:.2rem solid #448aff;border-radius:.1rem;box-shadow:0 .2rem .5rem rgba(0,0,0,.05),0 .025rem .05rem rgba(0,0,0,.05);color:var(--md-admonition-fg-color);font-size:.64rem;margin:1.5625em 0;overflow:hidden;padding:0 .6rem;page-break-inside:avoid}@media print{.md-typeset .admonition,.md-typeset details{box-shadow:none}}[dir=rtl] .md-typeset .admonition,[dir=rtl] .md-typeset details{border-left:none;border-right:.2rem solid #448aff}.md-typeset .admonition .admonition,.md-typeset .admonition details,.md-typeset details .admonition,.md-typeset details details{margin-bottom:1em;margin-top:1em}.md-typeset .admonition .md-typeset__scrollwrap,.md-typeset details .md-typeset__scrollwrap{margin:1em -.6rem}.md-typeset .admonition .md-typeset__table,.md-typeset details .md-typeset__table{padding:0 .6rem}.md-typeset .admonition>.tabbed-set:only-child,.md-typeset details>.tabbed-set:only-child{margin-top:0}html .md-typeset .admonition>:last-child,html .md-typeset details>:last-child{margin-bottom:.6rem}.md-typeset .admonition-title,.md-typeset summary{background-color:rgba(68,138,255,.1);border-left:.2rem solid #448aff;font-weight:700;margin:0 -.6rem 0 -.8rem;padding:.4rem .6rem .4rem 2rem;position:relative}[dir=rtl] .md-typeset .admonition-title,[dir=rtl] .md-typeset summary{border-left:none;border-right:.2rem solid #448aff;margin:0 -.8rem 0 -.6rem;padding:.4rem 2rem .4rem .6rem}html .md-typeset .admonition-title:last-child,html .md-typeset summary:last-child{margin-bottom:0}.md-typeset .admonition-title:before,.md-typeset summary:before{background-color:#448aff;content:"";height:1rem;left:.6rem;-webkit-mask-image:var(--md-admonition-icon--note);mask-image:var(--md-admonition-icon--note);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain;position:absolute;width:1rem}[dir=rtl] .md-typeset .admonition-title:before,[dir=rtl] .md-typeset summary:before{left:auto;right:.6rem}.md-typeset .admonition-title+.tabbed-set:last-child,.md-typeset summary+.tabbed-set:last-child{margin-top:0}.md-typeset .admonition.note,.md-typeset details.note{border-color:#448aff}.md-typeset .note>.admonition-title,.md-typeset .note>summary{background-color:rgba(68,138,255,.1);border-color:#448aff}.md-typeset .note>.admonition-title:before,.md-typeset .note>summary:before{background-color:#448aff;-webkit-mask-image:var(--md-admonition-icon--note);mask-image:var(--md-admonition-icon--note);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain}.md-typeset .admonition.abstract,.md-typeset .admonition.summary,.md-typeset .admonition.tldr,.md-typeset details.abstract,.md-typeset details.summary,.md-typeset details.tldr{border-color:#00b0ff}.md-typeset .abstract>.admonition-title,.md-typeset .abstract>summary,.md-typeset .summary>.admonition-title,.md-typeset .summary>summary,.md-typeset .tldr>.admonition-title,.md-typeset .tldr>summary{background-color:rgba(0,176,255,.1);border-color:#00b0ff}.md-typeset .abstract>.admonition-title:before,.md-typeset .abstract>summary:before,.md-typeset .summary>.admonition-title:before,.md-typeset .summary>summary:before,.md-typeset .tldr>.admonition-title:before,.md-typeset .tldr>summary:before{background-color:#00b0ff;-webkit-mask-image:var(--md-admonition-icon--abstract);mask-image:var(--md-admonition-icon--abstract);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain}.md-typeset .admonition.info,.md-typeset .admonition.todo,.md-typeset details.info,.md-typeset details.todo{border-color:#00b8d4}.md-typeset .info>.admonition-title,.md-typeset .info>summary,.md-typeset .todo>.admonition-title,.md-typeset .todo>summary{background-color:rgba(0,184,212,.1);border-color:#00b8d4}.md-typeset .info>.admonition-title:before,.md-typeset .info>summary:before,.md-typeset .todo>.admonition-title:before,.md-typeset .todo>summary:before{background-color:#00b8d4;-webkit-mask-image:var(--md-admonition-icon--info);mask-image:var(--md-admonition-icon--info);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain}.md-typeset .admonition.hint,.md-typeset .admonition.important,.md-typeset .admonition.tip,.md-typeset details.hint,.md-typeset details.important,.md-typeset details.tip{border-color:#00bfa5}.md-typeset .hint>.admonition-title,.md-typeset .hint>summary,.md-typeset .important>.admonition-title,.md-typeset .important>summary,.md-typeset .tip>.admonition-title,.md-typeset .tip>summary{background-color:rgba(0,191,165,.1);border-color:#00bfa5}.md-typeset .hint>.admonition-title:before,.md-typeset .hint>summary:before,.md-typeset .important>.admonition-title:before,.md-typeset .important>summary:before,.md-typeset .tip>.admonition-title:before,.md-typeset .tip>summary:before{background-color:#00bfa5;-webkit-mask-image:var(--md-admonition-icon--tip);mask-image:var(--md-admonition-icon--tip);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain}.md-typeset .admonition.check,.md-typeset .admonition.done,.md-typeset .admonition.success,.md-typeset details.check,.md-typeset details.done,.md-typeset details.success{border-color:#00c853}.md-typeset .check>.admonition-title,.md-typeset .check>summary,.md-typeset .done>.admonition-title,.md-typeset .done>summary,.md-typeset .success>.admonition-title,.md-typeset .success>summary{background-color:rgba(0,200,83,.1);border-color:#00c853}.md-typeset .check>.admonition-title:before,.md-typeset .check>summary:before,.md-typeset .done>.admonition-title:before,.md-typeset .done>summary:before,.md-typeset .success>.admonition-title:before,.md-typeset .success>summary:before{background-color:#00c853;-webkit-mask-image:var(--md-admonition-icon--success);mask-image:var(--md-admonition-icon--success);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain}.md-typeset .admonition.faq,.md-typeset .admonition.help,.md-typeset .admonition.question,.md-typeset details.faq,.md-typeset details.help,.md-typeset details.question{border-color:#64dd17}.md-typeset .faq>.admonition-title,.md-typeset .faq>summary,.md-typeset .help>.admonition-title,.md-typeset .help>summary,.md-typeset .question>.admonition-title,.md-typeset .question>summary{background-color:rgba(100,221,23,.1);border-color:#64dd17}.md-typeset .faq>.admonition-title:before,.md-typeset .faq>summary:before,.md-typeset .help>.admonition-title:before,.md-typeset .help>summary:before,.md-typeset .question>.admonition-title:before,.md-typeset .question>summary:before{background-color:#64dd17;-webkit-mask-image:var(--md-admonition-icon--question);mask-image:var(--md-admonition-icon--question);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain}.md-typeset .admonition.attention,.md-typeset .admonition.caution,.md-typeset .admonition.warning,.md-typeset details.attention,.md-typeset details.caution,.md-typeset details.warning{border-color:#ff9100}.md-typeset .attention>.admonition-title,.md-typeset .attention>summary,.md-typeset .caution>.admonition-title,.md-typeset .caution>summary,.md-typeset .warning>.admonition-title,.md-typeset .warning>summary{background-color:rgba(255,145,0,.1);border-color:#ff9100}.md-typeset .attention>.admonition-title:before,.md-typeset .attention>summary:before,.md-typeset .caution>.admonition-title:before,.md-typeset .caution>summary:before,.md-typeset .warning>.admonition-title:before,.md-typeset .warning>summary:before{background-color:#ff9100;-webkit-mask-image:var(--md-admonition-icon--warning);mask-image:var(--md-admonition-icon--warning);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain}.md-typeset .admonition.fail,.md-typeset .admonition.failure,.md-typeset .admonition.missing,.md-typeset details.fail,.md-typeset details.failure,.md-typeset details.missing{border-color:#ff5252}.md-typeset .fail>.admonition-title,.md-typeset .fail>summary,.md-typeset .failure>.admonition-title,.md-typeset .failure>summary,.md-typeset .missing>.admonition-title,.md-typeset .missing>summary{background-color:rgba(255,82,82,.1);border-color:#ff5252}.md-typeset .fail>.admonition-title:before,.md-typeset .fail>summary:before,.md-typeset .failure>.admonition-title:before,.md-typeset .failure>summary:before,.md-typeset .missing>.admonition-title:before,.md-typeset .missing>summary:before{background-color:#ff5252;-webkit-mask-image:var(--md-admonition-icon--failure);mask-image:var(--md-admonition-icon--failure);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain}.md-typeset .admonition.danger,.md-typeset .admonition.error,.md-typeset details.danger,.md-typeset details.error{border-color:#ff1744}.md-typeset .danger>.admonition-title,.md-typeset .danger>summary,.md-typeset .error>.admonition-title,.md-typeset .error>summary{background-color:rgba(255,23,68,.1);border-color:#ff1744}.md-typeset .danger>.admonition-title:before,.md-typeset .danger>summary:before,.md-typeset .error>.admonition-title:before,.md-typeset .error>summary:before{background-color:#ff1744;-webkit-mask-image:var(--md-admonition-icon--danger);mask-image:var(--md-admonition-icon--danger);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain}.md-typeset .admonition.bug,.md-typeset details.bug{border-color:#f50057}.md-typeset .bug>.admonition-title,.md-typeset .bug>summary{background-color:rgba(245,0,87,.1);border-color:#f50057}.md-typeset .bug>.admonition-title:before,.md-typeset .bug>summary:before{background-color:#f50057;-webkit-mask-image:var(--md-admonition-icon--bug);mask-image:var(--md-admonition-icon--bug);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain}.md-typeset .admonition.example,.md-typeset details.example{border-color:#7c4dff}.md-typeset .example>.admonition-title,.md-typeset .example>summary{background-color:rgba(124,77,255,.1);border-color:#7c4dff}.md-typeset .example>.admonition-title:before,.md-typeset .example>summary:before{background-color:#7c4dff;-webkit-mask-image:var(--md-admonition-icon--example);mask-image:var(--md-admonition-icon--example);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain}.md-typeset .admonition.cite,.md-typeset .admonition.quote,.md-typeset details.cite,.md-typeset details.quote{border-color:#9e9e9e}.md-typeset .cite>.admonition-title,.md-typeset .cite>summary,.md-typeset .quote>.admonition-title,.md-typeset .quote>summary{background-color:hsla(0,0%,62%,.1);border-color:#9e9e9e}.md-typeset .cite>.admonition-title:before,.md-typeset .cite>summary:before,.md-typeset .quote>.admonition-title:before,.md-typeset .quote>summary:before{background-color:#9e9e9e;-webkit-mask-image:var(--md-admonition-icon--quote);mask-image:var(--md-admonition-icon--quote);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain}:root{--md-footnotes-icon:url('data:image/svg+xml;charset=utf-8,')}.md-typeset .footnote{color:var(--md-default-fg-color--light);font-size:.64rem}.md-typeset .footnote>ol{margin-left:0}.md-typeset .footnote>ol>li{transition:color 125ms}.md-typeset .footnote>ol>li:target{color:var(--md-default-fg-color)}.md-typeset .footnote>ol>li:hover .footnote-backref,.md-typeset .footnote>ol>li:target .footnote-backref{opacity:1;transform:translateX(0)}.md-typeset .footnote>ol>li>:first-child{margin-top:0}.md-typeset .footnote-ref{font-size:.75em;font-weight:700}html .md-typeset .footnote-ref{outline-offset:.1rem}.md-typeset .footnote-backref{color:var(--md-typeset-a-color);display:inline-block;font-size:0;opacity:0;transform:translateX(.25rem);transition:color .25s,transform .25s .25s,opacity 125ms .25s;vertical-align:text-bottom}@media print{.md-typeset .footnote-backref{color:var(--md-typeset-a-color);opacity:1;transform:translateX(0)}}[dir=rtl] .md-typeset .footnote-backref{transform:translateX(-.25rem)}.md-typeset .footnote-backref:hover{color:var(--md-accent-fg-color)}.md-typeset .footnote-backref:before{background-color:currentColor;content:"";display:inline-block;height:.8rem;-webkit-mask-image:var(--md-footnotes-icon);mask-image:var(--md-footnotes-icon);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain;width:.8rem}[dir=rtl] .md-typeset .footnote-backref:before svg{transform:scaleX(-1)}.md-typeset [id^="fnref:"]:target{margin-top:-3.4rem;padding-top:3.4rem;scroll-margin-top:0}.md-typeset [id^="fnref:"]:target>.footnote-ref{outline:auto}.md-typeset [id^="fn:"]:target{margin-top:-3.45rem;padding-top:3.45rem;scroll-margin-top:0}.md-typeset .headerlink{color:var(--md-default-fg-color--lighter);display:inline-block;margin-left:.5rem;opacity:0;transition:color .25s,opacity 125ms}@media print{.md-typeset .headerlink{display:none}}[dir=rtl] .md-typeset .headerlink{margin-left:0;margin-right:.5rem}.md-typeset .headerlink:focus,.md-typeset :hover>.headerlink,.md-typeset :target>.headerlink{opacity:1;transition:color .25s,opacity 125ms}.md-typeset .headerlink:focus,.md-typeset .headerlink:hover,.md-typeset :target>.headerlink{color:var(--md-accent-fg-color)}.md-typeset :target{scroll-margin-top:3.6rem}.md-typeset h1:target,.md-typeset h2:target,.md-typeset h3:target{scroll-margin-top:0}.md-typeset h1:target:before,.md-typeset h2:target:before,.md-typeset h3:target:before{content:"";display:block;margin-top:-3.4rem;padding-top:3.4rem}.md-typeset h4:target{scroll-margin-top:0}.md-typeset h4:target:before{content:"";display:block;margin-top:-3.45rem;padding-top:3.45rem}.md-typeset h5:target,.md-typeset h6:target{scroll-margin-top:0}.md-typeset h5:target:before,.md-typeset h6:target:before{content:"";display:block;margin-top:-3.6rem;padding-top:3.6rem}.md-typeset div.arithmatex{overflow:auto}@media screen and (max-width:44.9375em){.md-typeset div.arithmatex{margin:0 -.8rem}}.md-typeset div.arithmatex>*{margin:1em auto!important;padding:0 .8rem;touch-action:auto;width:-webkit-min-content;width:-moz-min-content;width:min-content}.md-typeset .critic.comment,.md-typeset del.critic,.md-typeset ins.critic{-webkit-box-decoration-break:clone;box-decoration-break:clone}.md-typeset del.critic{background-color:var(--md-typeset-del-color)}.md-typeset ins.critic{background-color:var(--md-typeset-ins-color)}.md-typeset .critic.comment{color:var(--md-code-hl-comment-color)}.md-typeset .critic.comment:before{content:"/* "}.md-typeset .critic.comment:after{content:" */"}.md-typeset .critic.block{box-shadow:none;display:block;margin:1em 0;overflow:auto;padding-left:.8rem;padding-right:.8rem}.md-typeset .critic.block>:first-child{margin-top:.5em}.md-typeset .critic.block>:last-child{margin-bottom:.5em}:root{--md-details-icon:url('data:image/svg+xml;charset=utf-8,')}.md-typeset details{display:flow-root;overflow:visible;padding-top:0}.md-typeset details[open]>summary:after{transform:rotate(90deg)}.md-typeset details:not([open]){box-shadow:none;padding-bottom:0}.md-typeset details:not([open])>summary{border-radius:.1rem}.md-typeset details:after{content:"";display:table}.md-typeset summary{border-top-left-radius:.1rem;border-top-right-radius:.1rem;cursor:pointer;display:block;min-height:1rem;padding:.4rem 1.8rem .4rem 2rem}[dir=rtl] .md-typeset summary{padding:.4rem 2.2rem .4rem 1.8rem}.md-typeset summary:not(.focus-visible){-webkit-tap-highlight-color:transparent;outline:none}.md-typeset summary:after{background-color:currentColor;content:"";height:1rem;-webkit-mask-image:var(--md-details-icon);mask-image:var(--md-details-icon);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain;position:absolute;right:.4rem;top:.4rem;transform:rotate(0deg);transition:transform .25s;width:1rem}[dir=rtl] .md-typeset summary:after{left:.4rem;right:auto;transform:rotate(180deg)}.md-typeset summary::-webkit-details-marker,.md-typeset summary::marker{display:none}.md-typeset .emojione,.md-typeset .gemoji,.md-typeset .twemoji{display:inline-flex;height:1.125em;vertical-align:text-top}.md-typeset .emojione svg,.md-typeset .gemoji svg,.md-typeset .twemoji svg{fill:currentColor;max-height:100%;width:1.125em}.highlight .o,.highlight .ow{color:var(--md-code-hl-operator-color)}.highlight .p{color:var(--md-code-hl-punctuation-color)}.highlight .cpf,.highlight .l,.highlight .s,.highlight .s1,.highlight .s2,.highlight .sb,.highlight .sc,.highlight .si,.highlight .ss{color:var(--md-code-hl-string-color)}.highlight .cp,.highlight .se,.highlight .sh,.highlight .sr,.highlight .sx{color:var(--md-code-hl-special-color)}.highlight .il,.highlight .m,.highlight .mb,.highlight .mf,.highlight .mh,.highlight .mi,.highlight .mo{color:var(--md-code-hl-number-color)}.highlight .k,.highlight .kd,.highlight .kn,.highlight .kp,.highlight .kr,.highlight .kt{color:var(--md-code-hl-keyword-color)}.highlight .kc,.highlight .n{color:var(--md-code-hl-name-color)}.highlight .bp,.highlight .nb,.highlight .no{color:var(--md-code-hl-constant-color)}.highlight .nc,.highlight .ne,.highlight .nf,.highlight .nn{color:var(--md-code-hl-function-color)}.highlight .nd,.highlight .ni,.highlight .nl,.highlight .nt{color:var(--md-code-hl-keyword-color)}.highlight .c,.highlight .c1,.highlight .ch,.highlight .cm,.highlight .cs,.highlight .sd{color:var(--md-code-hl-comment-color)}.highlight .na,.highlight .nv,.highlight .vc,.highlight .vg,.highlight .vi{color:var(--md-code-hl-variable-color)}.highlight .ge,.highlight .gh,.highlight .go,.highlight .gp,.highlight .gr,.highlight .gs,.highlight .gt,.highlight .gu{color:var(--md-code-hl-generic-color)}.highlight .gd,.highlight .gi{border-radius:.1rem;margin:0 -.125em;padding:0 .125em}.highlight .gd{background-color:var(--md-typeset-del-color)}.highlight .gi{background-color:var(--md-typeset-ins-color)}.highlight .hll{background-color:var(--md-code-hl-color);display:block;margin:0 -1.1764705882em;padding:0 1.1764705882em}.highlight [data-linenos]:before{background-color:var(--md-code-bg-color);box-shadow:-.05rem 0 var(--md-default-fg-color--lightest) inset;color:var(--md-default-fg-color--light);content:attr(data-linenos);float:left;left:-1.1764705882em;margin-left:-1.1764705882em;margin-right:1.1764705882em;padding-left:1.1764705882em;position:-webkit-sticky;position:sticky;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.highlighttable{display:flow-root;overflow:hidden}.highlighttable tbody,.highlighttable td{display:block;padding:0}.highlighttable tr{display:flex}.highlighttable pre{margin:0}.highlighttable .linenos{background-color:var(--md-code-bg-color);font-size:.85em;padding:.7720588235em 0 .7720588235em 1.1764705882em;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.highlighttable .linenodiv{box-shadow:-.05rem 0 var(--md-default-fg-color--lightest) inset;padding-right:.5882352941em}.highlighttable .linenodiv pre{color:var(--md-default-fg-color--light);text-align:right}.highlighttable .code{flex:1;overflow:hidden}.md-typeset .highlighttable{border-radius:.1rem;direction:ltr;margin:1em 0}.md-typeset .highlighttable code{border-radius:0}@media screen and (max-width:44.9375em){.md-typeset>.highlight{margin:1em -.8rem}.md-typeset>.highlight .hll{margin:0 -.8rem;padding:0 .8rem}.md-typeset>.highlight code{border-radius:0}.md-typeset>.highlighttable{border-radius:0;margin:1em -.8rem}.md-typeset>.highlighttable .hll{margin:0 -.8rem;padding:0 .8rem}}.md-typeset .keys kbd:after,.md-typeset .keys kbd:before{-moz-osx-font-smoothing:initial;-webkit-font-smoothing:initial;color:inherit;margin:0;position:relative}.md-typeset .keys span{color:var(--md-default-fg-color--light);padding:0 .2em}.md-typeset .keys .key-alt:before{content:"⎇";padding-right:.4em}.md-typeset .keys .key-left-alt:before{content:"⎇";padding-right:.4em}.md-typeset .keys .key-right-alt:before{content:"⎇";padding-right:.4em}.md-typeset .keys .key-command:before{content:"⌘";padding-right:.4em}.md-typeset .keys .key-left-command:before{content:"⌘";padding-right:.4em}.md-typeset .keys .key-right-command:before{content:"⌘";padding-right:.4em}.md-typeset .keys .key-control:before{content:"⌃";padding-right:.4em}.md-typeset .keys .key-left-control:before{content:"⌃";padding-right:.4em}.md-typeset .keys .key-right-control:before{content:"⌃";padding-right:.4em}.md-typeset .keys .key-meta:before{content:"◆";padding-right:.4em}.md-typeset .keys .key-left-meta:before{content:"◆";padding-right:.4em}.md-typeset .keys .key-right-meta:before{content:"◆";padding-right:.4em}.md-typeset .keys .key-option:before{content:"⌥";padding-right:.4em}.md-typeset .keys .key-left-option:before{content:"⌥";padding-right:.4em}.md-typeset .keys .key-right-option:before{content:"⌥";padding-right:.4em}.md-typeset .keys .key-shift:before{content:"⇧";padding-right:.4em}.md-typeset .keys .key-left-shift:before{content:"⇧";padding-right:.4em}.md-typeset .keys .key-right-shift:before{content:"⇧";padding-right:.4em}.md-typeset .keys .key-super:before{content:"❖";padding-right:.4em}.md-typeset .keys .key-left-super:before{content:"❖";padding-right:.4em}.md-typeset .keys .key-right-super:before{content:"❖";padding-right:.4em}.md-typeset .keys .key-windows:before{content:"⊞";padding-right:.4em}.md-typeset .keys .key-left-windows:before{content:"⊞";padding-right:.4em}.md-typeset .keys .key-right-windows:before{content:"⊞";padding-right:.4em}.md-typeset .keys .key-arrow-down:before{content:"↓";padding-right:.4em}.md-typeset .keys .key-arrow-left:before{content:"←";padding-right:.4em}.md-typeset .keys .key-arrow-right:before{content:"→";padding-right:.4em}.md-typeset .keys .key-arrow-up:before{content:"↑";padding-right:.4em}.md-typeset .keys .key-backspace:before{content:"⌫";padding-right:.4em}.md-typeset .keys .key-backtab:before{content:"⇤";padding-right:.4em}.md-typeset .keys .key-caps-lock:before{content:"⇪";padding-right:.4em}.md-typeset .keys .key-clear:before{content:"⌧";padding-right:.4em}.md-typeset .keys .key-context-menu:before{content:"☰";padding-right:.4em}.md-typeset .keys .key-delete:before{content:"⌦";padding-right:.4em}.md-typeset .keys .key-eject:before{content:"⏏";padding-right:.4em}.md-typeset .keys .key-end:before{content:"⤓";padding-right:.4em}.md-typeset .keys .key-escape:before{content:"⎋";padding-right:.4em}.md-typeset .keys .key-home:before{content:"⤒";padding-right:.4em}.md-typeset .keys .key-insert:before{content:"⎀";padding-right:.4em}.md-typeset .keys .key-page-down:before{content:"⇟";padding-right:.4em}.md-typeset .keys .key-page-up:before{content:"⇞";padding-right:.4em}.md-typeset .keys .key-print-screen:before{content:"⎙";padding-right:.4em}.md-typeset .keys .key-tab:after{content:"⇥";padding-left:.4em}.md-typeset .keys .key-num-enter:after{content:"⌤";padding-left:.4em}.md-typeset .keys .key-enter:after{content:"⏎";padding-left:.4em}.md-typeset .tabbed-content{box-shadow:0 -.05rem var(--md-default-fg-color--lightest);display:none;order:99;width:100%}@media print{.md-typeset .tabbed-content{display:block;order:0}}.md-typeset .tabbed-content>.highlight:only-child pre,.md-typeset .tabbed-content>.highlighttable:only-child,.md-typeset .tabbed-content>pre:only-child{margin:0}.md-typeset .tabbed-content>.highlight:only-child pre>code,.md-typeset .tabbed-content>.highlighttable:only-child>code,.md-typeset .tabbed-content>pre:only-child>code{border-top-left-radius:0;border-top-right-radius:0}.md-typeset .tabbed-content>.tabbed-set{margin:0}.md-typeset .tabbed-set{border-radius:.1rem;display:flex;flex-wrap:wrap;margin:1em 0;position:relative}.md-typeset .tabbed-set>input{height:0;opacity:0;position:absolute;width:0}.md-typeset .tabbed-set>input:checked+label{border-color:var(--md-accent-fg-color);color:var(--md-accent-fg-color)}.md-typeset .tabbed-set>input:checked+label+.tabbed-content{display:block}.md-typeset .tabbed-set>input:focus+label{outline-color:var(--md-accent-fg-color);outline-style:auto}.md-typeset .tabbed-set>input:not(.focus-visible)+label{-webkit-tap-highlight-color:transparent;outline:none}.md-typeset .tabbed-set>label{border-bottom:.1rem solid transparent;color:var(--md-default-fg-color--light);cursor:pointer;font-size:.64rem;font-weight:700;padding:.9375em 1.25em .78125em;transition:color .25s;width:auto;z-index:1}.md-typeset .tabbed-set>label:hover{color:var(--md-accent-fg-color)}:root{--md-tasklist-icon:url('data:image/svg+xml;charset=utf-8,');--md-tasklist-icon--checked:url('data:image/svg+xml;charset=utf-8,')}.md-typeset .task-list-item{list-style-type:none;position:relative}.md-typeset .task-list-item [type=checkbox]{left:-2em;position:absolute;top:.45em}[dir=rtl] .md-typeset .task-list-item [type=checkbox]{left:auto;right:-2em}.md-typeset .task-list-control [type=checkbox]{opacity:0;z-index:-1}.md-typeset .task-list-indicator:before{background-color:var(--md-default-fg-color--lightest);content:"";height:1.25em;left:-1.5em;-webkit-mask-image:var(--md-tasklist-icon);mask-image:var(--md-tasklist-icon);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-size:contain;mask-size:contain;position:absolute;top:.15em;width:1.25em}[dir=rtl] .md-typeset .task-list-indicator:before{left:auto;right:-1.5em}.md-typeset [type=checkbox]:checked+.task-list-indicator:before{background-color:#00e676;-webkit-mask-image:var(--md-tasklist-icon--checked);mask-image:var(--md-tasklist-icon--checked)}@media screen and (min-width:45em){.md-typeset .inline{float:left;margin-bottom:.8rem;margin-right:.8rem;margin-top:0;width:11.7rem}[dir=rtl] .md-typeset .inline{float:right;margin-left:.8rem;margin-right:0}.md-typeset .inline.end{float:right;margin-left:.8rem;margin-right:0}[dir=rtl] .md-typeset .inline.end{float:left;margin-left:0;margin-right:.8rem}} +/*# sourceMappingURL=main.1118c9be.min.css.map */ \ No newline at end of file diff --git a/en/2021.7/assets/stylesheets/main.1118c9be.min.css.map b/en/2021.7/assets/stylesheets/main.1118c9be.min.css.map new file mode 100644 index 000000000..812628986 --- /dev/null +++ b/en/2021.7/assets/stylesheets/main.1118c9be.min.css.map @@ -0,0 +1 @@ +{"version":3,"sources":["src/assets/stylesheets/main/extensions/pymdownx/_keys.scss","src/assets/stylesheets/main.scss","src/assets/stylesheets/main/_reset.scss","src/assets/stylesheets/main/_colors.scss","src/assets/stylesheets/main/_icons.scss","src/assets/stylesheets/main/_typeset.scss","src/assets/stylesheets/utilities/_break.scss","node_modules/material-shadows/material-shadows.scss","src/assets/stylesheets/main/layout/_base.scss","src/assets/stylesheets/main/layout/_announce.scss","src/assets/stylesheets/main/layout/_clipboard.scss","src/assets/stylesheets/main/layout/_content.scss","src/assets/stylesheets/main/layout/_dialog.scss","src/assets/stylesheets/main/layout/_form.scss","src/assets/stylesheets/main/layout/_header.scss","src/assets/stylesheets/main/layout/_footer.scss","src/assets/stylesheets/main/layout/_nav.scss","src/assets/stylesheets/main/layout/_search.scss","src/assets/stylesheets/main/layout/_select.scss","src/assets/stylesheets/main/layout/_sidebar.scss","src/assets/stylesheets/main/layout/_source.scss","src/assets/stylesheets/main/layout/_tabs.scss","src/assets/stylesheets/main/layout/_top.scss","src/assets/stylesheets/main/layout/_version.scss","src/assets/stylesheets/main/extensions/markdown/_admonition.scss","node_modules/material-design-color/material-color.scss","src/assets/stylesheets/main/extensions/markdown/_footnotes.scss","src/assets/stylesheets/main/extensions/markdown/_toc.scss","src/assets/stylesheets/main/extensions/pymdownx/_arithmatex.scss","src/assets/stylesheets/main/extensions/pymdownx/_critic.scss","src/assets/stylesheets/main/extensions/pymdownx/_details.scss","src/assets/stylesheets/main/extensions/pymdownx/_emoji.scss","src/assets/stylesheets/main/extensions/pymdownx/_highlight.scss","src/assets/stylesheets/main/extensions/pymdownx/_tabbed.scss","src/assets/stylesheets/main/extensions/pymdownx/_tasklist.scss","src/assets/stylesheets/main/_modifiers.scss"],"names":[],"mappings":"AAkGQ,gBCgzGR,CCt3GA,KAEE,6BAAA,CAAA,yBAAA,CAAA,qBAAA,CADA,qBDzBF,CC8BA,iBAGE,kBD3BF,CC+BA,KACE,QD5BF,CCgCA,qBAIE,uCD7BF,CCiCA,EACE,aAAA,CACA,oBD9BF,CCkCA,GAME,QAAA,CAJA,sBAAA,CADA,aAAA,CAEA,aAAA,CAEA,gBAAA,CADA,SD7BF,CCmCA,MACE,aDhCF,CCoCA,QAEE,eDjCF,CCqCA,IACE,iBDlCF,CCsCA,MACE,wBAAA,CACA,gBDnCF,CCuCA,MAEE,eAAA,CACA,kBDpCF,CCwCA,OAKE,sBAAA,CACA,QAAA,CAFA,mBAAA,CADA,iBAAA,CAFA,QAAA,CACA,SDjCF,CCyCA,MACE,QAAA,CACA,YDtCF,CE9CA,MAGE,sCAAA,CACA,6CAAA,CACA,+CAAA,CACA,gDAAA,CACA,0BAAA,CACA,gDAAA,CACA,kDAAA,CACA,oDAAA,CAGA,6BAAA,CACA,oCAAA,CACA,mCAAA,CACA,0BAAA,C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ShC0hHN,CgC/gHM,oCACE,+BhCihHR,CiC5mHA,MACE,mVAAA,CAEA,4VjCgnHF,CiCtmHE,4BAEE,oBAAA,CADA,iBjC0mHJ,CiCrmHI,4CAGE,SAAA,CAFA,iBAAA,CACA,SjCwmHN,CiCpmHM,sDAEE,SAAA,CADA,UjCumHR,CiChmHE,+CAEE,SAAA,CADA,UjCmmHJ,CiC9lHE,wCAME,qDAAA,CAIA,UAAA,CALA,aAAA,CAFA,WAAA,CAIA,0CAAA,CAAA,kCAAA,CACA,6BAAA,CAAA,qBAAA,CACA,yBAAA,CAAA,iBAAA,CARA,iBAAA,CACA,SAAA,CAEA,YjCsmHJ,CiC7lHI,kDAEE,SAAA,CADA,YjCgmHN,CiC1lHE,gEACE,wBT8Va,CS7Vb,mDAAA,CAAA,2CjC4lHJ,CKv/GI,mC6B5JA,oBACE,UAAA,CAIA,mBAAA,CADA,kBAAA,CADA,YAAA,CADA,alC0pHJ,CkCppHI,8BACE,WAAA,CAEA,iBAAA,CADA,clCupHN,CkClpHI,wBACE,WAAA,CAEA,iBAAA,CADA,clCqpHN,CkCjpHM,kCACE,UAAA,CAEA,aAAA,CADA,kBlCopHR,CACF","file":"src/assets/stylesheets/main.scss","sourcesContent":["////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Scoped in typesetted content to match specificity of regular content\n.md-typeset {\n\n // Keyboard key\n .keys {\n\n // Keyboard key icon\n kbd::before,\n kbd::after {\n position: relative;\n margin: 0;\n color: inherit;\n -moz-osx-font-smoothing: initial;\n -webkit-font-smoothing: initial;\n }\n\n // Surrounding text\n span {\n padding: 0 px2em(3.2px);\n color: var(--md-default-fg-color--light);\n }\n\n // Define keyboard keys with left icon\n @each $name, $code in (\n\n // Modifiers\n \"alt\": \"\\2387\",\n \"left-alt\": \"\\2387\",\n \"right-alt\": \"\\2387\",\n \"command\": \"\\2318\",\n \"left-command\": \"\\2318\",\n \"right-command\": \"\\2318\",\n \"control\": \"\\2303\",\n \"left-control\": \"\\2303\",\n \"right-control\": \"\\2303\",\n \"meta\": \"\\25C6\",\n \"left-meta\": \"\\25C6\",\n \"right-meta\": \"\\25C6\",\n \"option\": \"\\2325\",\n \"left-option\": \"\\2325\",\n \"right-option\": \"\\2325\",\n \"shift\": \"\\21E7\",\n \"left-shift\": \"\\21E7\",\n \"right-shift\": \"\\21E7\",\n \"super\": \"\\2756\",\n \"left-super\": \"\\2756\",\n \"right-super\": \"\\2756\",\n \"windows\": \"\\229E\",\n \"left-windows\": \"\\229E\",\n \"right-windows\": \"\\229E\",\n\n // Other keys\n \"arrow-down\": \"\\2193\",\n \"arrow-left\": \"\\2190\",\n \"arrow-right\": \"\\2192\",\n \"arrow-up\": \"\\2191\",\n \"backspace\": \"\\232B\",\n \"backtab\": \"\\21E4\",\n \"caps-lock\": \"\\21EA\",\n \"clear\": \"\\2327\",\n \"context-menu\": \"\\2630\",\n \"delete\": \"\\2326\",\n \"eject\": \"\\23CF\",\n \"end\": \"\\2913\",\n \"escape\": \"\\238B\",\n \"home\": \"\\2912\",\n \"insert\": \"\\2380\",\n \"page-down\": \"\\21DF\",\n \"page-up\": \"\\21DE\",\n \"print-screen\": \"\\2399\"\n ) {\n .key-#{$name} {\n &::before {\n padding-right: px2em(6.4px);\n content: $code;\n }\n }\n }\n\n // Define keyboard keys with right icon\n @each $name, $code in (\n \"tab\": \"\\21E5\",\n \"num-enter\": \"\\2324\",\n \"enter\": \"\\23CE\"\n ) {\n .key-#{$name} {\n &::after {\n padding-left: px2em(6.4px);\n content: $code;\n }\n }\n }\n }\n}\n","@charset \"UTF-8\";\nhtml {\n box-sizing: border-box;\n text-size-adjust: none;\n}\n\n*,\n*::before,\n*::after {\n box-sizing: inherit;\n}\n\nbody {\n margin: 0;\n}\n\na,\nbutton,\nlabel,\ninput {\n -webkit-tap-highlight-color: transparent;\n}\n\na {\n color: inherit;\n text-decoration: none;\n}\n\nhr {\n display: block;\n box-sizing: content-box;\n height: 0.05rem;\n padding: 0;\n overflow: visible;\n border: 0;\n}\n\nsmall {\n font-size: 80%;\n}\n\nsub,\nsup {\n line-height: 1em;\n}\n\nimg {\n border-style: none;\n}\n\ntable {\n border-collapse: separate;\n border-spacing: 0;\n}\n\ntd,\nth {\n font-weight: 400;\n vertical-align: top;\n}\n\nbutton {\n margin: 0;\n padding: 0;\n font-size: inherit;\n font-family: inherit;\n background: transparent;\n border: 0;\n}\n\ninput {\n border: 0;\n outline: none;\n}\n\n:root {\n --md-default-fg-color: hsla(0, 0%, 0%, 0.87);\n --md-default-fg-color--light: hsla(0, 0%, 0%, 0.54);\n --md-default-fg-color--lighter: hsla(0, 0%, 0%, 0.32);\n --md-default-fg-color--lightest: hsla(0, 0%, 0%, 0.07);\n --md-default-bg-color: hsla(0, 0%, 100%, 1);\n --md-default-bg-color--light: hsla(0, 0%, 100%, 0.7);\n --md-default-bg-color--lighter: hsla(0, 0%, 100%, 0.3);\n --md-default-bg-color--lightest: hsla(0, 0%, 100%, 0.12);\n --md-primary-fg-color: hsla(231, 48%, 48%, 1);\n --md-primary-fg-color--light: hsla(231, 44%, 56%, 1);\n --md-primary-fg-color--dark: hsla(232, 54%, 41%, 1);\n --md-primary-bg-color: hsla(0, 0%, 100%, 1);\n --md-primary-bg-color--light: hsla(0, 0%, 100%, 0.7);\n --md-accent-fg-color: hsla(231, 99%, 66%, 1);\n --md-accent-fg-color--transparent: hsla(231, 99%, 66%, 0.1);\n --md-accent-bg-color: hsla(0, 0%, 100%, 1);\n --md-accent-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n:root > * {\n --md-code-fg-color: hsla(200, 18%, 26%, 1);\n --md-code-bg-color: hsla(0, 0%, 96%, 1);\n --md-code-hl-color: hsla(60, 100%, 50%, 0.5);\n --md-code-hl-number-color: hsla(0, 67%, 50%, 1);\n --md-code-hl-special-color: hsla(340, 83%, 47%, 1);\n --md-code-hl-function-color: hsla(291, 45%, 50%, 1);\n --md-code-hl-constant-color: hsla(250, 63%, 60%, 1);\n --md-code-hl-keyword-color: hsla(219, 54%, 51%, 1);\n --md-code-hl-string-color: hsla(150, 63%, 30%, 1);\n --md-code-hl-name-color: var(--md-code-fg-color);\n --md-code-hl-operator-color: var(--md-default-fg-color--light);\n --md-code-hl-punctuation-color: var(--md-default-fg-color--light);\n --md-code-hl-comment-color: var(--md-default-fg-color--light);\n --md-code-hl-generic-color: var(--md-default-fg-color--light);\n --md-code-hl-variable-color: var(--md-default-fg-color--light);\n --md-typeset-color: var(--md-default-fg-color);\n --md-typeset-a-color: var(--md-primary-fg-color);\n --md-typeset-mark-color: hsla(60, 100%, 50%, 0.5);\n --md-typeset-del-color: hsla(6, 90%, 60%, 0.15);\n --md-typeset-ins-color: hsla(150, 90%, 44%, 0.15);\n --md-typeset-kbd-color: hsla(0, 0%, 98%, 1);\n --md-typeset-kbd-accent-color: hsla(0, 100%, 100%, 1);\n --md-typeset-kbd-border-color: hsla(0, 0%, 72%, 1);\n --md-admonition-fg-color: var(--md-default-fg-color);\n --md-admonition-bg-color: var(--md-default-bg-color);\n --md-footer-fg-color: hsla(0, 0%, 100%, 1);\n --md-footer-fg-color--light: hsla(0, 0%, 100%, 0.7);\n --md-footer-fg-color--lighter: hsla(0, 0%, 100%, 0.3);\n --md-footer-bg-color: hsla(0, 0%, 0%, 0.87);\n --md-footer-bg-color--dark: hsla(0, 0%, 0%, 0.32);\n}\n\n.md-icon svg {\n display: block;\n width: 1.2rem;\n height: 1.2rem;\n fill: currentColor;\n}\n\nbody {\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\nbody,\ninput {\n color: var(--md-typeset-color);\n font-feature-settings: \"kern\", \"liga\";\n font-family: var(--md-text-font-family, _), -apple-system, BlinkMacSystemFont, Helvetica, Arial, sans-serif;\n}\n\ncode,\npre,\nkbd {\n color: var(--md-typeset-color);\n font-feature-settings: \"kern\";\n font-family: var(--md-code-font-family, _), SFMono-Regular, Consolas, Menlo, monospace;\n}\n\n:root {\n --md-typeset-table--ascending: svg-load(\"material/arrow-down.svg\");\n --md-typeset-table--descending: svg-load(\"material/arrow-up.svg\");\n}\n\n.md-typeset {\n font-size: 0.8rem;\n line-height: 1.6;\n color-adjust: exact;\n}\n@media print {\n .md-typeset {\n font-size: 0.68rem;\n }\n}\n.md-typeset ul,\n.md-typeset ol,\n.md-typeset dl,\n.md-typeset figure,\n.md-typeset blockquote,\n.md-typeset pre {\n margin: 1em 0;\n}\n.md-typeset h1 {\n margin: 0 0 1.25em;\n color: var(--md-default-fg-color--light);\n font-weight: 300;\n font-size: 2em;\n line-height: 1.3;\n letter-spacing: -0.01em;\n}\n.md-typeset h2 {\n margin: 1.6em 0 0.64em;\n font-weight: 300;\n font-size: 1.5625em;\n line-height: 1.4;\n letter-spacing: -0.01em;\n}\n.md-typeset h3 {\n margin: 1.6em 0 0.8em;\n font-weight: 400;\n font-size: 1.25em;\n line-height: 1.5;\n letter-spacing: -0.01em;\n}\n.md-typeset h2 + h3 {\n margin-top: 0.8em;\n}\n.md-typeset h4 {\n margin: 1em 0;\n font-weight: 700;\n letter-spacing: -0.01em;\n}\n.md-typeset h5,\n.md-typeset h6 {\n margin: 1.25em 0;\n color: var(--md-default-fg-color--light);\n font-weight: 700;\n font-size: 0.8em;\n letter-spacing: -0.01em;\n}\n.md-typeset h5 {\n text-transform: uppercase;\n}\n.md-typeset hr {\n display: flow-root;\n margin: 1.5em 0;\n border-bottom: 0.05rem solid var(--md-default-fg-color--lightest);\n}\n.md-typeset a {\n color: var(--md-typeset-a-color);\n word-break: break-word;\n}\n.md-typeset a, .md-typeset a::before {\n transition: color 125ms;\n}\n.md-typeset a:focus, .md-typeset a:hover {\n color: var(--md-accent-fg-color);\n}\n.md-typeset a.focus-visible {\n outline-color: var(--md-accent-fg-color);\n outline-offset: 0.2rem;\n}\n.md-typeset code,\n.md-typeset pre,\n.md-typeset kbd {\n color: var(--md-code-fg-color);\n direction: ltr;\n}\n@media print {\n .md-typeset code,\n.md-typeset pre,\n.md-typeset kbd {\n white-space: pre-wrap;\n }\n}\n.md-typeset code {\n padding: 0 0.2941176471em;\n font-size: 0.85em;\n word-break: break-word;\n background-color: var(--md-code-bg-color);\n border-radius: 0.1rem;\n box-decoration-break: clone;\n}\n.md-typeset code:not(.focus-visible) {\n outline: none;\n -webkit-tap-highlight-color: transparent;\n}\n.md-typeset h1 code,\n.md-typeset h2 code,\n.md-typeset h3 code,\n.md-typeset h4 code,\n.md-typeset h5 code,\n.md-typeset h6 code {\n margin: initial;\n padding: initial;\n background-color: transparent;\n box-shadow: none;\n}\n.md-typeset a code {\n color: currentColor;\n}\n.md-typeset pre {\n position: relative;\n display: flow-root;\n line-height: 1.4;\n}\n.md-typeset pre > code {\n display: block;\n margin: 0;\n padding: 0.7720588235em 1.1764705882em;\n overflow: auto;\n word-break: normal;\n box-shadow: none;\n box-decoration-break: slice;\n touch-action: auto;\n scrollbar-width: thin;\n scrollbar-color: var(--md-default-fg-color--lighter) transparent;\n}\n.md-typeset pre > code:hover {\n scrollbar-color: var(--md-accent-fg-color) transparent;\n}\n.md-typeset pre > code::-webkit-scrollbar {\n width: 0.2rem;\n height: 0.2rem;\n}\n.md-typeset pre > code::-webkit-scrollbar-thumb {\n background-color: var(--md-default-fg-color--lighter);\n}\n.md-typeset pre > code::-webkit-scrollbar-thumb:hover {\n background-color: var(--md-accent-fg-color);\n}\n@media screen and (max-width: 44.9375em) {\n .md-typeset > pre {\n margin: 1em -0.8rem;\n }\n .md-typeset > pre code {\n border-radius: 0;\n }\n}\n.md-typeset kbd {\n display: inline-block;\n padding: 0 0.6666666667em;\n color: var(--md-default-fg-color);\n font-size: 0.75em;\n vertical-align: text-top;\n word-break: break-word;\n background-color: var(--md-typeset-kbd-color);\n border-radius: 0.1rem;\n box-shadow: 0 0.1rem 0 0.05rem var(--md-typeset-kbd-border-color), 0 0.1rem 0 var(--md-typeset-kbd-border-color), 0 -0.1rem 0.2rem var(--md-typeset-kbd-accent-color) inset;\n}\n.md-typeset mark {\n color: inherit;\n word-break: break-word;\n background-color: var(--md-typeset-mark-color);\n box-decoration-break: clone;\n}\n.md-typeset abbr {\n text-decoration: none;\n border-bottom: 0.05rem dotted var(--md-default-fg-color--light);\n cursor: help;\n}\n@media (hover: none) {\n .md-typeset abbr {\n position: relative;\n }\n .md-typeset abbr[title]:focus::after, .md-typeset abbr[title]:hover::after {\n box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12), 0 3px 1px -2px rgba(0, 0, 0, 0.2);\n position: absolute;\n left: 0;\n display: inline-block;\n width: auto;\n min-width: max-content;\n max-width: 80%;\n margin-top: 2em;\n padding: 0.2rem 0.3rem;\n color: var(--md-default-bg-color);\n font-size: 0.7rem;\n background-color: var(--md-default-fg-color);\n border-radius: 0.1rem;\n content: attr(title);\n }\n}\n.md-typeset small {\n opacity: 0.75;\n}\n.md-typeset sup,\n.md-typeset sub {\n margin-left: 0.078125em;\n}\n[dir=rtl] .md-typeset sup,\n[dir=rtl] .md-typeset sub {\n margin-right: 0.078125em;\n margin-left: initial;\n}\n.md-typeset blockquote {\n display: flow-root;\n padding-left: 0.6rem;\n color: var(--md-default-fg-color--light);\n border-left: 0.2rem solid var(--md-default-fg-color--lighter);\n}\n[dir=rtl] .md-typeset blockquote {\n padding-right: 0.6rem;\n padding-left: initial;\n border-right: 0.2rem solid var(--md-default-fg-color--lighter);\n border-left: initial;\n}\n.md-typeset ul {\n list-style-type: disc;\n}\n.md-typeset ul,\n.md-typeset ol {\n display: flow-root;\n margin-left: 0.625em;\n padding: 0;\n}\n[dir=rtl] .md-typeset ul,\n[dir=rtl] .md-typeset ol {\n margin-right: 0.625em;\n margin-left: initial;\n}\n.md-typeset ul ol,\n.md-typeset ol ol {\n list-style-type: lower-alpha;\n}\n.md-typeset ul ol ol,\n.md-typeset ol ol ol {\n list-style-type: lower-roman;\n}\n.md-typeset ul li,\n.md-typeset ol li {\n margin-bottom: 0.5em;\n margin-left: 1.25em;\n}\n[dir=rtl] .md-typeset ul li,\n[dir=rtl] .md-typeset ol li {\n margin-right: 1.25em;\n margin-left: initial;\n}\n.md-typeset ul li p,\n.md-typeset ul li blockquote,\n.md-typeset ol li p,\n.md-typeset ol li blockquote {\n margin: 0.5em 0;\n}\n.md-typeset ul li:last-child,\n.md-typeset ol li:last-child {\n margin-bottom: 0;\n}\n.md-typeset ul li ul,\n.md-typeset ul li ol,\n.md-typeset ol li ul,\n.md-typeset ol li ol {\n margin: 0.5em 0 0.5em 0.625em;\n}\n[dir=rtl] .md-typeset ul li ul,\n[dir=rtl] .md-typeset ul li ol,\n[dir=rtl] .md-typeset ol li ul,\n[dir=rtl] .md-typeset ol li ol {\n margin-right: 0.625em;\n margin-left: initial;\n}\n.md-typeset dd {\n margin: 1em 0 1.5em 1.875em;\n}\n[dir=rtl] .md-typeset dd {\n margin-right: 1.875em;\n margin-left: initial;\n}\n.md-typeset img,\n.md-typeset svg {\n max-width: 100%;\n height: auto;\n}\n.md-typeset img[align=left],\n.md-typeset svg[align=left] {\n margin: 1em;\n margin-left: 0;\n}\n.md-typeset img[align=right],\n.md-typeset svg[align=right] {\n margin: 1em;\n margin-right: 0;\n}\n.md-typeset img[align]:only-child,\n.md-typeset svg[align]:only-child {\n margin-top: 0;\n}\n.md-typeset figure {\n display: flow-root;\n width: fit-content;\n max-width: 100%;\n margin: 0 auto;\n text-align: center;\n}\n.md-typeset figure img {\n display: block;\n}\n.md-typeset figcaption {\n max-width: 24rem;\n margin: 1em auto 2em;\n font-style: italic;\n}\n.md-typeset iframe {\n max-width: 100%;\n}\n.md-typeset table:not([class]) {\n display: inline-block;\n max-width: 100%;\n overflow: auto;\n font-size: 0.64rem;\n background-color: var(--md-default-bg-color);\n border-radius: 0.1rem;\n box-shadow: 0 0.2rem 0.5rem rgba(0, 0, 0, 0.05), 0 0 0.05rem rgba(0, 0, 0, 0.1);\n touch-action: auto;\n}\n@media print {\n .md-typeset table:not([class]) {\n display: table;\n }\n}\n.md-typeset table:not([class]) + * {\n margin-top: 1.5em;\n}\n.md-typeset table:not([class]) th > *:first-child,\n.md-typeset table:not([class]) td > *:first-child {\n margin-top: 0;\n}\n.md-typeset table:not([class]) th > *:last-child,\n.md-typeset table:not([class]) td > *:last-child {\n margin-bottom: 0;\n}\n.md-typeset table:not([class]) th:not([align]),\n.md-typeset table:not([class]) td:not([align]) {\n text-align: left;\n}\n[dir=rtl] .md-typeset table:not([class]) th:not([align]),\n[dir=rtl] .md-typeset table:not([class]) td:not([align]) {\n text-align: right;\n}\n.md-typeset table:not([class]) th {\n min-width: 5rem;\n padding: 0.9375em 1.25em;\n color: var(--md-default-bg-color);\n vertical-align: top;\n background-color: var(--md-default-fg-color--light);\n}\n.md-typeset table:not([class]) th a {\n color: inherit;\n}\n.md-typeset table:not([class]) td {\n padding: 0.9375em 1.25em;\n vertical-align: top;\n border-top: 0.05rem solid var(--md-default-fg-color--lightest);\n}\n.md-typeset table:not([class]) tr {\n transition: background-color 125ms;\n}\n.md-typeset table:not([class]) tr:hover {\n background-color: rgba(0, 0, 0, 0.035);\n box-shadow: 0 0.05rem 0 var(--md-default-bg-color) inset;\n}\n.md-typeset table:not([class]) tr:first-child td {\n border-top: 0;\n}\n.md-typeset table:not([class]) a {\n word-break: normal;\n}\n.md-typeset table th[role=columnheader] {\n cursor: pointer;\n}\n.md-typeset table th[role=columnheader]::after {\n display: inline-block;\n width: 1.2em;\n height: 1.2em;\n margin-left: 0.5em;\n vertical-align: sub;\n mask-repeat: no-repeat;\n mask-size: contain;\n content: \"\";\n}\n.md-typeset table th[role=columnheader][aria-sort=ascending]::after {\n background-color: currentColor;\n mask-image: var(--md-typeset-table--ascending);\n}\n.md-typeset table th[role=columnheader][aria-sort=descending]::after {\n background-color: currentColor;\n mask-image: var(--md-typeset-table--descending);\n}\n.md-typeset__scrollwrap {\n margin: 1em -0.8rem;\n overflow-x: auto;\n touch-action: auto;\n}\n.md-typeset__table {\n display: inline-block;\n margin-bottom: 0.5em;\n padding: 0 0.8rem;\n}\n@media print {\n .md-typeset__table {\n display: block;\n }\n}\nhtml .md-typeset__table table {\n display: table;\n width: 100%;\n margin: 0;\n overflow: hidden;\n}\n\nhtml {\n height: 100%;\n overflow-x: hidden;\n font-size: 125%;\n}\n@media screen and (min-width: 100em) {\n html {\n font-size: 137.5%;\n }\n}\n@media screen and (min-width: 125em) {\n html {\n font-size: 150%;\n }\n}\n\nbody {\n position: relative;\n display: flex;\n flex-direction: column;\n width: 100%;\n min-height: 100%;\n font-size: 0.5rem;\n background-color: var(--md-default-bg-color);\n}\n@media print {\n body {\n display: block;\n }\n}\n@media screen and (max-width: 59.9375em) {\n body[data-md-state=lock] {\n position: fixed;\n }\n}\n\n.md-grid {\n max-width: 61rem;\n margin-right: auto;\n margin-left: auto;\n}\n\n.md-container {\n display: flex;\n flex-direction: column;\n flex-grow: 1;\n}\n@media print {\n .md-container {\n display: block;\n }\n}\n\n.md-main {\n flex-grow: 1;\n}\n.md-main__inner {\n display: flex;\n height: 100%;\n margin-top: 1.5rem;\n}\n\n.md-ellipsis {\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n\n.md-toggle {\n display: none;\n}\n\n.md-option {\n position: absolute;\n width: 0;\n height: 0;\n opacity: 0;\n}\n.md-option:checked + label:not([hidden]) {\n display: block;\n}\n.md-option.focus-visible + label {\n outline-style: auto;\n outline-color: var(--md-accent-fg-color);\n}\n\n.md-skip {\n position: fixed;\n z-index: -1;\n margin: 0.5rem;\n padding: 0.3rem 0.5rem;\n color: var(--md-default-bg-color);\n font-size: 0.64rem;\n background-color: var(--md-default-fg-color);\n border-radius: 0.1rem;\n outline-color: var(--md-accent-fg-color);\n transform: translateY(0.4rem);\n opacity: 0;\n}\n.md-skip:focus {\n z-index: 10;\n transform: translateY(0);\n opacity: 1;\n transition: transform 250ms cubic-bezier(0.4, 0, 0.2, 1), opacity 175ms 75ms;\n}\n\n@page {\n margin: 25mm;\n}\n.md-announce {\n overflow: auto;\n background-color: var(--md-footer-bg-color);\n}\n@media print {\n .md-announce {\n display: none;\n }\n}\n.md-announce__inner {\n margin: 0.6rem auto;\n padding: 0 0.8rem;\n color: var(--md-footer-fg-color);\n font-size: 0.7rem;\n}\n\n:root {\n --md-clipboard-icon: svg-load(\"material/content-copy.svg\");\n}\n\n.md-clipboard {\n position: absolute;\n top: 0.5em;\n right: 0.5em;\n z-index: 1;\n width: 1.5em;\n height: 1.5em;\n color: var(--md-default-fg-color--lightest);\n border-radius: 0.1rem;\n outline-color: var(--md-accent-fg-color);\n outline-offset: 0.1rem;\n cursor: pointer;\n transition: color 250ms;\n}\n@media print {\n .md-clipboard {\n display: none;\n }\n}\n.md-clipboard:not(.focus-visible) {\n outline: none;\n -webkit-tap-highlight-color: transparent;\n}\n:hover > .md-clipboard {\n color: var(--md-default-fg-color--light);\n}\n.md-clipboard:focus, .md-clipboard:hover {\n color: var(--md-accent-fg-color);\n}\n.md-clipboard::after {\n display: block;\n width: 1.125em;\n height: 1.125em;\n margin: 0 auto;\n background-color: currentColor;\n mask-image: var(--md-clipboard-icon);\n mask-repeat: no-repeat;\n mask-size: contain;\n content: \"\";\n}\n.md-clipboard--inline {\n cursor: pointer;\n}\n.md-clipboard--inline code {\n transition: color 250ms, background-color 250ms;\n}\n.md-clipboard--inline:focus code, .md-clipboard--inline:hover code {\n color: var(--md-accent-fg-color);\n background-color: var(--md-accent-fg-color--transparent);\n}\n\n.md-content {\n flex-grow: 1;\n overflow: hidden;\n scroll-padding-top: 51.2rem;\n}\n.md-content__inner {\n margin: 0 0.8rem 1.2rem;\n padding-top: 0.6rem;\n}\n@media screen and (min-width: 76.25em) {\n .md-sidebar--primary:not([hidden]) ~ .md-content > .md-content__inner {\n margin-left: 1.2rem;\n }\n [dir=rtl] .md-sidebar--primary:not([hidden]) ~ .md-content > .md-content__inner {\n margin-right: 1.2rem;\n margin-left: 0.8rem;\n }\n .md-sidebar--secondary:not([hidden]) ~ .md-content > .md-content__inner {\n margin-right: 1.2rem;\n }\n [dir=rtl] .md-sidebar--secondary:not([hidden]) ~ .md-content > .md-content__inner {\n margin-right: 0.8rem;\n margin-left: 1.2rem;\n }\n}\n.md-content__inner::before {\n display: block;\n height: 0.4rem;\n content: \"\";\n}\n.md-content__inner > :last-child {\n margin-bottom: 0;\n}\n.md-content__button {\n float: right;\n margin: 0.4rem 0;\n margin-left: 0.4rem;\n padding: 0;\n}\n@media print {\n .md-content__button {\n display: none;\n }\n}\n[dir=rtl] .md-content__button {\n float: left;\n margin-right: 0.4rem;\n margin-left: initial;\n}\n[dir=rtl] .md-content__button svg {\n transform: scaleX(-1);\n}\n.md-typeset .md-content__button {\n color: var(--md-default-fg-color--lighter);\n}\n.md-content__button svg {\n display: inline;\n vertical-align: top;\n}\n\n.md-dialog {\n box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12), 0 3px 1px -2px rgba(0, 0, 0, 0.2);\n position: fixed;\n right: 0.8rem;\n bottom: 0.8rem;\n left: initial;\n z-index: 3;\n min-width: 11.1rem;\n padding: 0.4rem 0.6rem;\n background-color: var(--md-default-fg-color);\n border-radius: 0.1rem;\n transform: translateY(100%);\n opacity: 0;\n transition: transform 0ms 400ms, opacity 400ms;\n pointer-events: none;\n}\n@media print {\n .md-dialog {\n display: none;\n }\n}\n[dir=rtl] .md-dialog {\n right: initial;\n left: 0.8rem;\n}\n.md-dialog[data-md-state=open] {\n transform: translateY(0);\n opacity: 1;\n transition: transform 400ms cubic-bezier(0.075, 0.85, 0.175, 1), opacity 400ms;\n pointer-events: initial;\n}\n.md-dialog__inner {\n color: var(--md-default-bg-color);\n font-size: 0.7rem;\n}\n\n.md-typeset .md-button {\n display: inline-block;\n padding: 0.625em 2em;\n color: var(--md-primary-fg-color);\n font-weight: 700;\n border: 0.1rem solid currentColor;\n border-radius: 0.1rem;\n cursor: pointer;\n transition: color 125ms, background-color 125ms, border-color 125ms;\n}\n.md-typeset .md-button--primary {\n color: var(--md-primary-bg-color);\n background-color: var(--md-primary-fg-color);\n border-color: var(--md-primary-fg-color);\n}\n.md-typeset .md-button:focus, .md-typeset .md-button:hover {\n color: var(--md-accent-bg-color);\n background-color: var(--md-accent-fg-color);\n border-color: var(--md-accent-fg-color);\n}\n.md-typeset .md-input {\n height: 1.8rem;\n padding: 0 0.6rem;\n font-size: 0.8rem;\n border-radius: 0.1rem;\n box-shadow: 0 0.2rem 0.5rem rgba(0, 0, 0, 0.1), 0 0.025rem 0.05rem rgba(0, 0, 0, 0.1);\n transition: box-shadow 250ms;\n}\n.md-typeset .md-input:focus, .md-typeset .md-input:hover {\n box-shadow: 0 0.4rem 1rem rgba(0, 0, 0, 0.15), 0 0.025rem 0.05rem rgba(0, 0, 0, 0.15);\n}\n.md-typeset .md-input--stretch {\n width: 100%;\n}\n\n.md-header {\n position: sticky;\n top: 0;\n right: 0;\n left: 0;\n z-index: 3;\n color: var(--md-primary-bg-color);\n background-color: var(--md-primary-fg-color);\n box-shadow: 0 0 0.2rem rgba(0, 0, 0, 0), 0 0.2rem 0.4rem rgba(0, 0, 0, 0);\n}\n@media print {\n .md-header {\n display: none;\n }\n}\n.md-header[data-md-state=shadow] {\n box-shadow: 0 0 0.2rem rgba(0, 0, 0, 0.1), 0 0.2rem 0.4rem rgba(0, 0, 0, 0.2);\n transition: transform 250ms cubic-bezier(0.1, 0.7, 0.1, 1), box-shadow 250ms;\n}\n.md-header[data-md-state=hidden] {\n transform: translateY(-100%);\n transition: transform 250ms cubic-bezier(0.8, 0, 0.6, 1), box-shadow 250ms;\n}\n.md-header__inner {\n display: flex;\n align-items: center;\n padding: 0 0.2rem;\n}\n.md-header__button {\n position: relative;\n z-index: 1;\n margin: 0.2rem;\n padding: 0.4rem;\n color: currentColor;\n vertical-align: middle;\n outline-color: var(--md-accent-fg-color);\n cursor: pointer;\n transition: opacity 250ms;\n}\n.md-header__button:hover {\n opacity: 0.7;\n}\n.md-header__button:not([hidden]) {\n display: inline-block;\n}\n.md-header__button:not(.focus-visible) {\n outline: none;\n -webkit-tap-highlight-color: transparent;\n}\n.md-header__button.md-logo {\n margin: 0.2rem;\n padding: 0.4rem;\n}\n@media screen and (max-width: 76.1875em) {\n .md-header__button.md-logo {\n display: none;\n }\n}\n.md-header__button.md-logo img,\n.md-header__button.md-logo svg {\n display: block;\n width: 1.2rem;\n height: 1.2rem;\n fill: currentColor;\n}\n@media screen and (min-width: 60em) {\n .md-header__button[for=__search] {\n display: none;\n }\n}\n.no-js .md-header__button[for=__search] {\n display: none;\n}\n[dir=rtl] .md-header__button[for=__search] svg {\n transform: scaleX(-1);\n}\n@media screen and (min-width: 76.25em) {\n .md-header__button[for=__drawer] {\n display: none;\n }\n}\n.md-header__topic {\n position: absolute;\n display: flex;\n max-width: 100%;\n transition: transform 400ms cubic-bezier(0.1, 0.7, 0.1, 1), opacity 150ms;\n}\n.md-header__topic + .md-header__topic {\n z-index: -1;\n transform: translateX(1.25rem);\n opacity: 0;\n transition: transform 400ms cubic-bezier(1, 0.7, 0.1, 0.1), opacity 150ms;\n pointer-events: none;\n}\n[dir=rtl] .md-header__topic + .md-header__topic {\n transform: translateX(-1.25rem);\n}\n.md-header__title {\n flex-grow: 1;\n height: 2.4rem;\n margin-right: 0.4rem;\n margin-left: 1rem;\n font-size: 0.9rem;\n line-height: 2.4rem;\n}\n.md-header__title[data-md-state=active] .md-header__topic {\n z-index: -1;\n transform: translateX(-1.25rem);\n opacity: 0;\n transition: transform 400ms cubic-bezier(1, 0.7, 0.1, 0.1), opacity 150ms;\n pointer-events: none;\n}\n[dir=rtl] .md-header__title[data-md-state=active] .md-header__topic {\n transform: translateX(1.25rem);\n}\n.md-header__title[data-md-state=active] .md-header__topic + .md-header__topic {\n z-index: 0;\n transform: translateX(0);\n opacity: 1;\n transition: transform 400ms cubic-bezier(0.1, 0.7, 0.1, 1), opacity 150ms;\n pointer-events: initial;\n}\n.md-header__title > .md-header__ellipsis {\n position: relative;\n width: 100%;\n height: 100%;\n}\n.md-header__option {\n display: flex;\n flex-shrink: 0;\n max-width: 100%;\n white-space: nowrap;\n transition: max-width 0ms 250ms, opacity 250ms 250ms;\n}\n[data-md-toggle=search]:checked ~ .md-header .md-header__option {\n max-width: 0;\n opacity: 0;\n transition: max-width 0ms, opacity 0ms;\n}\n.md-header__source {\n display: none;\n}\n@media screen and (min-width: 60em) {\n .md-header__source {\n display: block;\n width: 11.7rem;\n max-width: 11.7rem;\n margin-left: 1rem;\n }\n [dir=rtl] .md-header__source {\n margin-right: 1rem;\n margin-left: initial;\n }\n}\n@media screen and (min-width: 76.25em) {\n .md-header__source {\n margin-left: 1.4rem;\n }\n [dir=rtl] .md-header__source {\n margin-right: 1.4rem;\n }\n}\n\n.md-footer {\n color: var(--md-footer-fg-color);\n background-color: var(--md-footer-bg-color);\n}\n@media print {\n .md-footer {\n display: none;\n }\n}\n.md-footer__inner {\n padding: 0.2rem;\n overflow: auto;\n}\n.md-footer__link {\n display: flex;\n padding-top: 1.4rem;\n padding-bottom: 0.4rem;\n outline-color: var(--md-accent-fg-color);\n transition: opacity 250ms;\n}\n@media screen and (min-width: 45em) {\n .md-footer__link {\n width: 50%;\n }\n}\n.md-footer__link:focus, .md-footer__link:hover {\n opacity: 0.7;\n}\n.md-footer__link--prev {\n float: left;\n}\n@media screen and (max-width: 44.9375em) {\n .md-footer__link--prev {\n width: 25%;\n }\n .md-footer__link--prev .md-footer__title {\n display: none;\n }\n}\n[dir=rtl] .md-footer__link--prev {\n float: right;\n}\n[dir=rtl] .md-footer__link--prev svg {\n transform: scaleX(-1);\n}\n.md-footer__link--next {\n float: right;\n text-align: right;\n}\n@media screen and (max-width: 44.9375em) {\n .md-footer__link--next {\n width: 75%;\n }\n}\n[dir=rtl] .md-footer__link--next {\n float: left;\n text-align: left;\n}\n[dir=rtl] .md-footer__link--next svg {\n transform: scaleX(-1);\n}\n.md-footer__title {\n position: relative;\n flex-grow: 1;\n max-width: calc(100% - 2.4rem);\n padding: 0 1rem;\n font-size: 0.9rem;\n line-height: 2.4rem;\n}\n.md-footer__button {\n margin: 0.2rem;\n padding: 0.4rem;\n}\n.md-footer__direction {\n position: absolute;\n right: 0;\n left: 0;\n margin-top: -1rem;\n padding: 0 1rem;\n font-size: 0.64rem;\n opacity: 0.7;\n}\n\n.md-footer-meta {\n background-color: var(--md-footer-bg-color--dark);\n}\n.md-footer-meta__inner {\n display: flex;\n flex-wrap: wrap;\n justify-content: space-between;\n padding: 0.2rem;\n}\nhtml .md-footer-meta.md-typeset a {\n color: var(--md-footer-fg-color--light);\n}\nhtml .md-footer-meta.md-typeset a:focus, html .md-footer-meta.md-typeset a:hover {\n color: var(--md-footer-fg-color);\n}\n\n.md-footer-copyright {\n width: 100%;\n margin: auto 0.6rem;\n padding: 0.4rem 0;\n color: var(--md-footer-fg-color--lighter);\n font-size: 0.64rem;\n}\n@media screen and (min-width: 45em) {\n .md-footer-copyright {\n width: auto;\n }\n}\n.md-footer-copyright__highlight {\n color: var(--md-footer-fg-color--light);\n}\n\n.md-footer-social {\n margin: 0 0.4rem;\n padding: 0.2rem 0 0.6rem;\n}\n@media screen and (min-width: 45em) {\n .md-footer-social {\n padding: 0.6rem 0;\n }\n}\n.md-footer-social__link {\n display: inline-block;\n width: 1.6rem;\n height: 1.6rem;\n text-align: center;\n}\n.md-footer-social__link::before {\n line-height: 1.9;\n}\n.md-footer-social__link svg {\n max-height: 0.8rem;\n vertical-align: -25%;\n fill: currentColor;\n}\n\n:root {\n --md-nav-icon--prev: svg-load(\"material/arrow-left.svg\");\n --md-nav-icon--next: svg-load(\"material/chevron-right.svg\");\n --md-toc-icon: svg-load(\"material/table-of-contents.svg\");\n}\n\n.md-nav {\n font-size: 0.7rem;\n line-height: 1.3;\n}\n.md-nav__title {\n display: block;\n padding: 0 0.6rem;\n overflow: hidden;\n font-weight: 700;\n text-overflow: ellipsis;\n}\n.md-nav__title .md-nav__button {\n display: none;\n}\n.md-nav__title .md-nav__button img {\n width: auto;\n height: 100%;\n}\n.md-nav__title .md-nav__button.md-logo img,\n.md-nav__title .md-nav__button.md-logo svg {\n display: block;\n width: 2.4rem;\n height: 2.4rem;\n fill: currentColor;\n}\n.md-nav__list {\n margin: 0;\n padding: 0;\n list-style: none;\n}\n.md-nav__item {\n padding: 0 0.6rem;\n}\n.md-nav__item .md-nav__item {\n padding-right: 0;\n}\n[dir=rtl] .md-nav__item .md-nav__item {\n padding-right: 0.6rem;\n padding-left: 0;\n}\n.md-nav__link {\n display: block;\n margin-top: 0.625em;\n overflow: hidden;\n text-overflow: ellipsis;\n cursor: pointer;\n transition: color 125ms;\n scroll-snap-align: start;\n}\n.md-nav__link[data-md-state=blur] {\n color: var(--md-default-fg-color--light);\n}\n.md-nav__item .md-nav__link--active {\n color: var(--md-typeset-a-color);\n}\n.md-nav__item--nested > .md-nav__link {\n color: inherit;\n}\n.md-nav__link:focus, .md-nav__link:hover {\n color: var(--md-accent-fg-color);\n}\n.md-nav__link.focus-visible {\n outline-color: var(--md-accent-fg-color);\n outline-offset: 0.2rem;\n}\n.md-nav--primary .md-nav__link[for=__toc] {\n display: none;\n}\n.md-nav--primary .md-nav__link[for=__toc] .md-icon::after {\n display: block;\n width: 100%;\n height: 100%;\n mask-image: var(--md-toc-icon);\n background-color: currentColor;\n}\n.md-nav--primary .md-nav__link[for=__toc] ~ .md-nav {\n display: none;\n}\n.md-nav__source {\n display: none;\n}\n@media screen and (max-width: 76.1875em) {\n .md-nav--primary, .md-nav--primary .md-nav {\n position: absolute;\n top: 0;\n right: 0;\n left: 0;\n z-index: 1;\n display: flex;\n flex-direction: column;\n height: 100%;\n background-color: var(--md-default-bg-color);\n }\n .md-nav--primary .md-nav__title,\n.md-nav--primary .md-nav__item {\n font-size: 0.8rem;\n line-height: 1.5;\n }\n .md-nav--primary .md-nav__title {\n position: relative;\n height: 5.6rem;\n padding: 3rem 0.8rem 0.2rem;\n color: var(--md-default-fg-color--light);\n font-weight: 400;\n line-height: 2.4rem;\n white-space: nowrap;\n background-color: var(--md-default-fg-color--lightest);\n cursor: pointer;\n }\n .md-nav--primary .md-nav__title .md-nav__icon {\n position: absolute;\n top: 0.4rem;\n left: 0.4rem;\n display: block;\n width: 1.2rem;\n height: 1.2rem;\n margin: 0.2rem;\n }\n [dir=rtl] .md-nav--primary .md-nav__title .md-nav__icon {\n right: 0.4rem;\n left: initial;\n }\n .md-nav--primary .md-nav__title .md-nav__icon::after {\n display: block;\n width: 100%;\n height: 100%;\n background-color: currentColor;\n mask-image: var(--md-nav-icon--prev);\n mask-repeat: no-repeat;\n mask-size: contain;\n content: \"\";\n }\n .md-nav--primary .md-nav__title ~ .md-nav__list {\n overflow-y: auto;\n background-color: var(--md-default-bg-color);\n box-shadow: 0 0.05rem 0 var(--md-default-fg-color--lightest) inset;\n scroll-snap-type: y mandatory;\n touch-action: pan-y;\n }\n .md-nav--primary .md-nav__title ~ .md-nav__list > :first-child {\n border-top: 0;\n }\n .md-nav--primary .md-nav__title[for=__drawer] {\n color: var(--md-primary-bg-color);\n background-color: var(--md-primary-fg-color);\n }\n .md-nav--primary .md-nav__title .md-logo {\n position: absolute;\n top: 0.2rem;\n left: 0.2rem;\n display: block;\n margin: 0.2rem;\n padding: 0.4rem;\n }\n [dir=rtl] .md-nav--primary .md-nav__title .md-logo {\n right: 0.2rem;\n left: initial;\n }\n .md-nav--primary .md-nav__list {\n flex: 1;\n }\n .md-nav--primary .md-nav__item {\n padding: 0;\n border-top: 0.05rem solid var(--md-default-fg-color--lightest);\n }\n .md-nav--primary .md-nav__item--nested > .md-nav__link {\n padding-right: 2.4rem;\n }\n [dir=rtl] .md-nav--primary .md-nav__item--nested > .md-nav__link {\n padding-right: 0.8rem;\n padding-left: 2.4rem;\n }\n .md-nav--primary .md-nav__item--active > .md-nav__link {\n color: var(--md-typeset-a-color);\n }\n .md-nav--primary .md-nav__item--active > .md-nav__link:focus, .md-nav--primary .md-nav__item--active > .md-nav__link:hover {\n color: var(--md-accent-fg-color);\n }\n .md-nav--primary .md-nav__link {\n position: relative;\n margin-top: 0;\n padding: 0.6rem 0.8rem;\n }\n .md-nav--primary .md-nav__link .md-nav__icon {\n position: absolute;\n top: 50%;\n right: 0.6rem;\n width: 1.2rem;\n height: 1.2rem;\n margin-top: -0.6rem;\n color: inherit;\n font-size: 1.2rem;\n }\n [dir=rtl] .md-nav--primary .md-nav__link .md-nav__icon {\n right: initial;\n left: 0.6rem;\n }\n .md-nav--primary .md-nav__link .md-nav__icon::after {\n display: block;\n width: 100%;\n height: 100%;\n background-color: currentColor;\n mask-image: var(--md-nav-icon--next);\n mask-repeat: no-repeat;\n mask-size: contain;\n content: \"\";\n }\n [dir=rtl] .md-nav--primary .md-nav__icon::after {\n transform: scale(-1);\n }\n .md-nav--primary .md-nav--secondary .md-nav__link {\n position: static;\n }\n .md-nav--primary .md-nav--secondary .md-nav {\n position: static;\n background-color: transparent;\n }\n .md-nav--primary .md-nav--secondary .md-nav .md-nav__link {\n padding-left: 1.4rem;\n }\n [dir=rtl] .md-nav--primary .md-nav--secondary .md-nav .md-nav__link {\n padding-right: 1.4rem;\n padding-left: initial;\n }\n .md-nav--primary .md-nav--secondary .md-nav .md-nav .md-nav__link {\n padding-left: 2rem;\n }\n [dir=rtl] .md-nav--primary .md-nav--secondary .md-nav .md-nav .md-nav__link {\n padding-right: 2rem;\n padding-left: initial;\n }\n .md-nav--primary .md-nav--secondary .md-nav .md-nav .md-nav .md-nav__link {\n padding-left: 2.6rem;\n }\n [dir=rtl] .md-nav--primary .md-nav--secondary .md-nav .md-nav .md-nav .md-nav__link {\n padding-right: 2.6rem;\n padding-left: initial;\n }\n .md-nav--primary .md-nav--secondary .md-nav .md-nav .md-nav .md-nav .md-nav__link {\n padding-left: 3.2rem;\n }\n [dir=rtl] .md-nav--primary .md-nav--secondary .md-nav .md-nav .md-nav .md-nav .md-nav__link {\n padding-right: 3.2rem;\n padding-left: initial;\n }\n .md-nav--secondary {\n background-color: transparent;\n }\n .md-nav__toggle ~ .md-nav {\n display: flex;\n transform: translateX(100%);\n opacity: 0;\n transition: transform 250ms cubic-bezier(0.8, 0, 0.6, 1), opacity 125ms 50ms;\n }\n [dir=rtl] .md-nav__toggle ~ .md-nav {\n transform: translateX(-100%);\n }\n .md-nav__toggle:checked ~ .md-nav {\n transform: translateX(0);\n opacity: 1;\n transition: transform 250ms cubic-bezier(0.4, 0, 0.2, 1), opacity 125ms 125ms;\n }\n .md-nav__toggle:checked ~ .md-nav > .md-nav__list {\n backface-visibility: hidden;\n }\n}\n@media screen and (max-width: 59.9375em) {\n .md-nav--primary .md-nav__link[for=__toc] {\n display: block;\n padding-right: 2.4rem;\n }\n [dir=rtl] .md-nav--primary .md-nav__link[for=__toc] {\n padding-right: 0.8rem;\n padding-left: 2.4rem;\n }\n .md-nav--primary .md-nav__link[for=__toc] .md-icon::after {\n content: \"\";\n }\n .md-nav--primary .md-nav__link[for=__toc] + .md-nav__link {\n display: none;\n }\n .md-nav--primary .md-nav__link[for=__toc] ~ .md-nav {\n display: flex;\n }\n .md-nav__source {\n display: block;\n padding: 0 0.2rem;\n color: var(--md-primary-bg-color);\n background-color: var(--md-primary-fg-color--dark);\n }\n}\n@media screen and (min-width: 60em) and (max-width: 76.1875em) {\n .md-nav--integrated .md-nav__link[for=__toc] {\n display: block;\n padding-right: 2.4rem;\n scroll-snap-align: initial;\n }\n [dir=rtl] .md-nav--integrated .md-nav__link[for=__toc] {\n padding-right: 0.8rem;\n padding-left: 2.4rem;\n }\n .md-nav--integrated .md-nav__link[for=__toc] .md-icon::after {\n content: \"\";\n }\n .md-nav--integrated .md-nav__link[for=__toc] + .md-nav__link {\n display: none;\n }\n .md-nav--integrated .md-nav__link[for=__toc] ~ .md-nav {\n display: flex;\n }\n}\n@media screen and (min-width: 60em) {\n .md-nav--secondary .md-nav__title[for=__toc] {\n scroll-snap-align: start;\n }\n .md-nav--secondary .md-nav__title .md-nav__icon {\n display: none;\n }\n}\n@media screen and (min-width: 76.25em) {\n .md-nav {\n transition: max-height 250ms cubic-bezier(0.86, 0, 0.07, 1);\n }\n .md-nav--primary .md-nav__title[for=__drawer] {\n scroll-snap-align: start;\n }\n .md-nav--primary .md-nav__title .md-nav__icon {\n display: none;\n }\n .md-nav__toggle ~ .md-nav {\n display: none;\n }\n .md-nav__toggle:checked ~ .md-nav, .md-nav__toggle:indeterminate ~ .md-nav {\n display: block;\n }\n .md-nav__item--nested > .md-nav > .md-nav__title {\n display: none;\n }\n .md-nav__item--section {\n display: block;\n margin: 1.25em 0;\n }\n .md-nav__item--section:last-child {\n margin-bottom: 0;\n }\n .md-nav__item--section > .md-nav__link {\n display: none;\n }\n .md-nav__item--section > .md-nav {\n display: block;\n }\n .md-nav__item--section > .md-nav > .md-nav__title {\n display: block;\n padding: 0;\n pointer-events: none;\n scroll-snap-align: start;\n }\n .md-nav__item--section > .md-nav > .md-nav__list > .md-nav__item {\n padding: 0;\n }\n .md-nav__icon {\n float: right;\n width: 0.9rem;\n height: 0.9rem;\n transition: transform 250ms;\n }\n [dir=rtl] .md-nav__icon {\n float: left;\n transform: rotate(180deg);\n }\n .md-nav__icon::after {\n display: inline-block;\n width: 100%;\n height: 100%;\n vertical-align: -0.1rem;\n background-color: currentColor;\n mask-image: var(--md-nav-icon--next);\n mask-repeat: no-repeat;\n mask-size: contain;\n content: \"\";\n }\n .md-nav__item--nested .md-nav__toggle:checked ~ .md-nav__link .md-nav__icon, .md-nav__item--nested .md-nav__toggle:indeterminate ~ .md-nav__link .md-nav__icon {\n transform: rotate(90deg);\n }\n .md-nav--lifted > .md-nav__list > .md-nav__item--nested,\n.md-nav--lifted > .md-nav__title {\n display: none;\n }\n .md-nav--lifted > .md-nav__list > .md-nav__item {\n display: none;\n }\n .md-nav--lifted > .md-nav__list > .md-nav__item--active {\n display: block;\n padding: 0;\n }\n .md-nav--lifted > .md-nav__list > .md-nav__item--active > .md-nav__link {\n display: none;\n }\n .md-nav--lifted > .md-nav__list > .md-nav__item--active > .md-nav > .md-nav__title {\n display: block;\n padding: 0 0.6rem;\n pointer-events: none;\n scroll-snap-align: start;\n }\n .md-nav--lifted .md-nav[data-md-level=\"1\"] {\n display: block;\n }\n .md-nav--lifted .md-nav[data-md-level=\"1\"] > .md-nav__list > .md-nav__item {\n padding-right: 0.6rem;\n }\n .md-nav--integrated .md-nav__link[for=__toc] ~ .md-nav {\n display: block;\n margin-bottom: 1.25em;\n border-left: 0.05rem solid var(--md-primary-fg-color);\n }\n .md-nav--integrated .md-nav__link[for=__toc] ~ .md-nav > .md-nav__title {\n display: none;\n }\n}\n\n:root {\n --md-search-result-icon: svg-load(\"material/file-search-outline.svg\");\n}\n\n.md-search {\n position: relative;\n}\n@media screen and (min-width: 60em) {\n .md-search {\n padding: 0.2rem 0;\n }\n}\n.no-js .md-search {\n display: none;\n}\n.md-search__overlay {\n z-index: 1;\n opacity: 0;\n}\n@media screen and (max-width: 59.9375em) {\n .md-search__overlay {\n position: absolute;\n top: 0.2rem;\n left: -2.2rem;\n width: 2rem;\n height: 2rem;\n overflow: hidden;\n background-color: var(--md-default-bg-color);\n border-radius: 1rem;\n transform-origin: center;\n transition: transform 300ms 100ms, opacity 200ms 200ms;\n pointer-events: none;\n }\n [dir=rtl] .md-search__overlay {\n right: -2.2rem;\n left: initial;\n }\n [data-md-toggle=search]:checked ~ .md-header .md-search__overlay {\n opacity: 1;\n transition: transform 400ms, opacity 100ms;\n }\n}\n@media screen and (min-width: 60em) {\n .md-search__overlay {\n position: fixed;\n top: 0;\n left: 0;\n width: 0;\n height: 0;\n background-color: rgba(0, 0, 0, 0.54);\n cursor: pointer;\n transition: width 0ms 250ms, height 0ms 250ms, opacity 250ms;\n }\n [dir=rtl] .md-search__overlay {\n right: 0;\n left: initial;\n }\n [data-md-toggle=search]:checked ~ .md-header .md-search__overlay {\n width: 100%;\n height: 200vh;\n opacity: 1;\n transition: width 0ms, height 0ms, opacity 250ms;\n }\n}\n@media screen and (max-width: 29.9375em) {\n [data-md-toggle=search]:checked ~ .md-header .md-search__overlay {\n transform: scale(45);\n }\n}\n@media screen and (min-width: 30em) and (max-width: 44.9375em) {\n [data-md-toggle=search]:checked ~ .md-header .md-search__overlay {\n transform: scale(60);\n }\n}\n@media screen and (min-width: 45em) and (max-width: 59.9375em) {\n [data-md-toggle=search]:checked ~ .md-header .md-search__overlay {\n transform: scale(75);\n }\n}\n.md-search__inner {\n backface-visibility: hidden;\n}\n@media screen and (max-width: 59.9375em) {\n .md-search__inner {\n position: fixed;\n top: 0;\n left: 100%;\n z-index: 2;\n width: 100%;\n height: 100%;\n transform: translateX(5%);\n opacity: 0;\n transition: right 0ms 300ms, left 0ms 300ms, transform 150ms 150ms cubic-bezier(0.4, 0, 0.2, 1), opacity 150ms 150ms;\n }\n [data-md-toggle=search]:checked ~ .md-header .md-search__inner {\n left: 0;\n transform: translateX(0);\n opacity: 1;\n transition: right 0ms 0ms, left 0ms 0ms, transform 150ms 150ms cubic-bezier(0.1, 0.7, 0.1, 1), opacity 150ms 150ms;\n }\n [dir=rtl] [data-md-toggle=search]:checked ~ .md-header .md-search__inner {\n right: 0;\n left: initial;\n }\n html [dir=rtl] .md-search__inner {\n right: 100%;\n left: initial;\n transform: translateX(-5%);\n }\n}\n@media screen and (min-width: 60em) {\n .md-search__inner {\n position: relative;\n float: right;\n width: 11.7rem;\n padding: 0.1rem 0;\n transition: width 250ms cubic-bezier(0.1, 0.7, 0.1, 1);\n }\n [dir=rtl] .md-search__inner {\n float: left;\n }\n}\n@media screen and (min-width: 60em) and (max-width: 76.1875em) {\n [data-md-toggle=search]:checked ~ .md-header .md-search__inner {\n width: 23.4rem;\n }\n}\n@media screen and (min-width: 76.25em) {\n [data-md-toggle=search]:checked ~ .md-header .md-search__inner {\n width: 34.4rem;\n }\n}\n.md-search__form {\n position: relative;\n z-index: 2;\n height: 2.4rem;\n background-color: var(--md-default-bg-color);\n box-shadow: 0 0 0.6rem transparent;\n transition: color 250ms, background-color 250ms;\n}\n@media screen and (min-width: 60em) {\n .md-search__form {\n height: 1.8rem;\n background-color: rgba(0, 0, 0, 0.26);\n border-radius: 0.1rem;\n }\n .md-search__form:hover {\n background-color: rgba(255, 255, 255, 0.12);\n }\n}\n[data-md-toggle=search]:checked ~ .md-header .md-search__form {\n color: var(--md-default-fg-color);\n background-color: var(--md-default-bg-color);\n border-radius: 0.1rem 0.1rem 0 0;\n box-shadow: 0 0 0.6rem rgba(0, 0, 0, 0.07);\n}\n.md-search__input {\n position: relative;\n z-index: 2;\n width: 100%;\n height: 100%;\n padding: 0 2.2rem 0 3.6rem;\n font-size: 0.9rem;\n text-overflow: ellipsis;\n background: transparent;\n}\n[dir=rtl] .md-search__input {\n padding: 0 3.6rem 0 2.2rem;\n}\n.md-search__input::placeholder {\n transition: color 250ms;\n}\n.md-search__input ~ .md-search__icon, .md-search__input::placeholder {\n color: var(--md-default-fg-color--light);\n}\n.md-search__input::-ms-clear {\n display: none;\n}\n@media screen and (max-width: 59.9375em) {\n .md-search__input {\n width: 100%;\n height: 2.4rem;\n font-size: 0.9rem;\n }\n}\n@media screen and (min-width: 60em) {\n .md-search__input {\n padding-left: 2.2rem;\n color: inherit;\n font-size: 0.8rem;\n }\n [dir=rtl] .md-search__input {\n padding-right: 2.2rem;\n }\n .md-search__input::placeholder {\n color: var(--md-primary-bg-color--light);\n }\n .md-search__input + .md-search__icon {\n color: var(--md-primary-bg-color);\n }\n [data-md-toggle=search]:checked ~ .md-header .md-search__input {\n text-overflow: clip;\n }\n [data-md-toggle=search]:checked ~ .md-header .md-search__input + .md-search__icon, [data-md-toggle=search]:checked ~ .md-header .md-search__input::placeholder {\n color: var(--md-default-fg-color--light);\n }\n}\n.md-search__icon {\n display: inline-block;\n width: 1.2rem;\n height: 1.2rem;\n cursor: pointer;\n transition: color 250ms, opacity 250ms;\n}\n.md-search__icon:hover {\n opacity: 0.7;\n}\n.md-search__icon[for=__search] {\n position: absolute;\n top: 0.3rem;\n left: 0.5rem;\n z-index: 2;\n}\n[dir=rtl] .md-search__icon[for=__search] {\n right: 0.5rem;\n left: initial;\n}\n[dir=rtl] .md-search__icon[for=__search] svg {\n transform: scaleX(-1);\n}\n@media screen and (max-width: 59.9375em) {\n .md-search__icon[for=__search] {\n top: 0.6rem;\n left: 0.8rem;\n }\n [dir=rtl] .md-search__icon[for=__search] {\n right: 0.8rem;\n left: initial;\n }\n .md-search__icon[for=__search] svg:first-child {\n display: none;\n }\n}\n@media screen and (min-width: 60em) {\n .md-search__icon[for=__search] {\n pointer-events: none;\n }\n .md-search__icon[for=__search] svg:last-child {\n display: none;\n }\n}\n.md-search__options {\n position: absolute;\n top: 0.3rem;\n right: 0.5rem;\n z-index: 2;\n pointer-events: none;\n}\n[dir=rtl] .md-search__options {\n right: initial;\n left: 0.5rem;\n}\n@media screen and (max-width: 59.9375em) {\n .md-search__options {\n top: 0.6rem;\n right: 0.8rem;\n }\n [dir=rtl] .md-search__options {\n right: initial;\n left: 0.8rem;\n }\n}\n.md-search__options > * {\n margin-left: 0.2rem;\n color: var(--md-default-fg-color--light);\n transform: scale(0.75);\n opacity: 0;\n transition: transform 150ms cubic-bezier(0.1, 0.7, 0.1, 1), opacity 150ms;\n}\n.md-search__options > *:not(.focus-visible) {\n outline: none;\n -webkit-tap-highlight-color: transparent;\n}\n[data-md-toggle=search]:checked ~ .md-header .md-search__input:valid ~ .md-search__options > * {\n transform: scale(1);\n opacity: 1;\n pointer-events: initial;\n}\n[data-md-toggle=search]:checked ~ .md-header .md-search__input:valid ~ .md-search__options > *:hover {\n opacity: 0.7;\n}\n.md-search__suggest {\n position: absolute;\n top: 0;\n display: flex;\n align-items: center;\n width: 100%;\n height: 100%;\n padding: 0 2.2rem 0 3.6rem;\n color: var(--md-default-fg-color--lighter);\n font-size: 0.9rem;\n white-space: nowrap;\n opacity: 0;\n transition: opacity 50ms;\n}\n[dir=rtl] .md-search__suggest {\n padding: 0 3.6rem 0 2.2rem;\n}\n@media screen and (min-width: 60em) {\n .md-search__suggest {\n padding-left: 2.2rem;\n font-size: 0.8rem;\n }\n [dir=rtl] .md-search__suggest {\n padding-right: 2.2rem;\n }\n}\n[data-md-toggle=search]:checked ~ .md-header .md-search__suggest {\n opacity: 1;\n transition: opacity 300ms 100ms;\n}\n.md-search__output {\n position: absolute;\n z-index: 1;\n width: 100%;\n overflow: hidden;\n border-radius: 0 0 0.1rem 0.1rem;\n}\n@media screen and (max-width: 59.9375em) {\n .md-search__output {\n top: 2.4rem;\n bottom: 0;\n }\n}\n@media screen and (min-width: 60em) {\n .md-search__output {\n top: 1.9rem;\n opacity: 0;\n transition: opacity 400ms;\n }\n [data-md-toggle=search]:checked ~ .md-header .md-search__output {\n box-shadow: 0 6px 10px 0 rgba(0, 0, 0, 0.14), 0 1px 18px 0 rgba(0, 0, 0, 0.12), 0 3px 5px -1px rgba(0, 0, 0, 0.4);\n opacity: 1;\n }\n}\n.md-search__scrollwrap {\n height: 100%;\n overflow-y: auto;\n background-color: var(--md-default-bg-color);\n backface-visibility: hidden;\n touch-action: pan-y;\n}\n@media (max-resolution: 1dppx) {\n .md-search__scrollwrap {\n transform: translateZ(0);\n }\n}\n@media screen and (min-width: 60em) and (max-width: 76.1875em) {\n .md-search__scrollwrap {\n width: 23.4rem;\n }\n}\n@media screen and (min-width: 76.25em) {\n .md-search__scrollwrap {\n width: 34.4rem;\n }\n}\n@media screen and (min-width: 60em) {\n .md-search__scrollwrap {\n max-height: 0;\n scrollbar-width: thin;\n scrollbar-color: var(--md-default-fg-color--lighter) transparent;\n }\n [data-md-toggle=search]:checked ~ .md-header .md-search__scrollwrap {\n max-height: 75vh;\n }\n .md-search__scrollwrap:hover {\n scrollbar-color: var(--md-accent-fg-color) transparent;\n }\n .md-search__scrollwrap::-webkit-scrollbar {\n width: 0.2rem;\n height: 0.2rem;\n }\n .md-search__scrollwrap::-webkit-scrollbar-thumb {\n background-color: var(--md-default-fg-color--lighter);\n }\n .md-search__scrollwrap::-webkit-scrollbar-thumb:hover {\n background-color: var(--md-accent-fg-color);\n }\n}\n\n.md-search-result {\n color: var(--md-default-fg-color);\n word-break: break-word;\n}\n.md-search-result__meta {\n padding: 0 0.8rem;\n color: var(--md-default-fg-color--light);\n font-size: 0.64rem;\n line-height: 1.8rem;\n background-color: var(--md-default-fg-color--lightest);\n scroll-snap-align: start;\n}\n@media screen and (min-width: 60em) {\n .md-search-result__meta {\n padding-left: 2.2rem;\n }\n [dir=rtl] .md-search-result__meta {\n padding-right: 2.2rem;\n padding-left: initial;\n }\n}\n.md-search-result__list {\n margin: 0;\n padding: 0;\n list-style: none;\n}\n.md-search-result__item {\n box-shadow: 0 -0.05rem 0 var(--md-default-fg-color--lightest);\n}\n.md-search-result__item:first-child {\n box-shadow: none;\n}\n.md-search-result__link {\n display: block;\n outline: none;\n transition: background-color 250ms;\n scroll-snap-align: start;\n}\n.md-search-result__link:focus, .md-search-result__link:hover {\n background-color: var(--md-accent-fg-color--transparent);\n}\n.md-search-result__link:last-child p:last-child {\n margin-bottom: 0.6rem;\n}\n.md-search-result__more summary {\n display: block;\n padding: 0.75em 0.8rem;\n color: var(--md-typeset-a-color);\n font-size: 0.64rem;\n outline: none;\n cursor: pointer;\n transition: color 250ms, background-color 250ms;\n scroll-snap-align: start;\n}\n@media screen and (min-width: 60em) {\n .md-search-result__more summary {\n padding-left: 2.2rem;\n }\n [dir=rtl] .md-search-result__more summary {\n padding-right: 2.2rem;\n padding-left: 0.8rem;\n }\n}\n.md-search-result__more summary:focus, .md-search-result__more summary:hover {\n color: var(--md-accent-fg-color);\n background-color: var(--md-accent-fg-color--transparent);\n}\n.md-search-result__more summary::marker, .md-search-result__more summary::-webkit-details-marker {\n display: none;\n}\n.md-search-result__more summary ~ * > * {\n opacity: 0.65;\n}\n.md-search-result__article {\n position: relative;\n padding: 0 0.8rem;\n overflow: hidden;\n}\n@media screen and (min-width: 60em) {\n .md-search-result__article {\n padding-left: 2.2rem;\n }\n [dir=rtl] .md-search-result__article {\n padding-right: 2.2rem;\n padding-left: 0.8rem;\n }\n}\n.md-search-result__article--document .md-search-result__title {\n margin: 0.55rem 0;\n font-weight: 400;\n font-size: 0.8rem;\n line-height: 1.4;\n}\n.md-search-result__icon {\n position: absolute;\n left: 0;\n width: 1.2rem;\n height: 1.2rem;\n margin: 0.5rem;\n color: var(--md-default-fg-color--light);\n}\n@media screen and (max-width: 59.9375em) {\n .md-search-result__icon {\n display: none;\n }\n}\n.md-search-result__icon::after {\n display: inline-block;\n width: 100%;\n height: 100%;\n background-color: currentColor;\n mask-image: var(--md-search-result-icon);\n mask-repeat: no-repeat;\n mask-size: contain;\n content: \"\";\n}\n[dir=rtl] .md-search-result__icon {\n right: 0;\n left: initial;\n}\n[dir=rtl] .md-search-result__icon::after {\n transform: scaleX(-1);\n}\n.md-search-result__title {\n margin: 0.5em 0;\n font-weight: 700;\n font-size: 0.64rem;\n line-height: 1.6;\n}\n.md-search-result__teaser {\n display: -webkit-box;\n max-height: 2rem;\n margin: 0.5em 0;\n overflow: hidden;\n color: var(--md-default-fg-color--light);\n font-size: 0.64rem;\n line-height: 1.6;\n text-overflow: ellipsis;\n -webkit-box-orient: vertical;\n -webkit-line-clamp: 2;\n}\n@media screen and (max-width: 44.9375em) {\n .md-search-result__teaser {\n max-height: 3rem;\n -webkit-line-clamp: 3;\n }\n}\n@media screen and (min-width: 60em) and (max-width: 76.1875em) {\n .md-search-result__teaser {\n max-height: 3rem;\n -webkit-line-clamp: 3;\n }\n}\n.md-search-result__teaser mark {\n text-decoration: underline;\n background-color: transparent;\n}\n.md-search-result__terms {\n margin: 0.5em 0;\n font-size: 0.64rem;\n font-style: italic;\n}\n.md-search-result mark {\n color: var(--md-accent-fg-color);\n background-color: transparent;\n}\n\n.md-select {\n position: relative;\n z-index: 1;\n}\n.md-select__inner {\n position: absolute;\n top: calc(100% - 0.2rem);\n left: 50%;\n max-height: 0;\n margin-top: 0.2rem;\n color: var(--md-default-fg-color);\n background-color: var(--md-default-bg-color);\n border-radius: 0.1rem;\n box-shadow: 0 0.2rem 0.5rem rgba(0, 0, 0, 0.1), 0 0 0.05rem rgba(0, 0, 0, 0.25);\n transform: translate3d(-50%, 0.3rem, 0);\n opacity: 0;\n transition: transform 250ms 375ms, opacity 250ms 250ms, max-height 0ms 500ms;\n}\n.md-select:focus-within .md-select__inner, .md-select:hover .md-select__inner {\n max-height: 10rem;\n transform: translate3d(-50%, 0, 0);\n opacity: 1;\n transition: transform 250ms cubic-bezier(0.1, 0.7, 0.1, 1), opacity 250ms, max-height 0ms;\n}\n.md-select__inner::after {\n position: absolute;\n top: 0;\n left: 50%;\n width: 0;\n height: 0;\n margin-top: -0.2rem;\n margin-left: -0.2rem;\n border: 0.2rem solid transparent;\n border-top: 0;\n border-bottom-color: var(--md-default-bg-color);\n content: \"\";\n}\n.md-select__list {\n max-height: inherit;\n margin: 0;\n padding: 0;\n overflow: auto;\n font-size: 0.8rem;\n list-style-type: none;\n border-radius: 0.1rem;\n}\n.md-select__item {\n line-height: 1.8rem;\n}\n.md-select__link {\n display: block;\n width: 100%;\n padding-right: 1.2rem;\n padding-left: 0.6rem;\n outline: none;\n cursor: pointer;\n transition: background-color 250ms, color 250ms;\n scroll-snap-align: start;\n}\n[dir=rtl] .md-select__link {\n padding-right: 0.6rem;\n padding-left: 1.2rem;\n}\n.md-select__link:focus, .md-select__link:hover {\n color: var(--md-accent-fg-color);\n}\n.md-select__link:focus {\n background-color: var(--md-default-fg-color--lightest);\n}\n\n.md-sidebar {\n position: sticky;\n top: 2.4rem;\n flex-shrink: 0;\n align-self: flex-start;\n width: 12.1rem;\n padding: 1.2rem 0;\n}\n@media print {\n .md-sidebar {\n display: none;\n }\n}\n@media screen and (max-width: 76.1875em) {\n .md-sidebar--primary {\n position: fixed;\n top: 0;\n left: -12.1rem;\n z-index: 4;\n display: block;\n width: 12.1rem;\n height: 100%;\n background-color: var(--md-default-bg-color);\n transform: translateX(0);\n transition: transform 250ms cubic-bezier(0.4, 0, 0.2, 1), box-shadow 250ms;\n }\n [dir=rtl] .md-sidebar--primary {\n right: -12.1rem;\n left: initial;\n }\n [data-md-toggle=drawer]:checked ~ .md-container .md-sidebar--primary {\n box-shadow: 0 8px 10px 1px rgba(0, 0, 0, 0.14), 0 3px 14px 2px rgba(0, 0, 0, 0.12), 0 5px 5px -3px rgba(0, 0, 0, 0.4);\n transform: translateX(12.1rem);\n }\n [dir=rtl] [data-md-toggle=drawer]:checked ~ .md-container .md-sidebar--primary {\n transform: translateX(-12.1rem);\n }\n .md-sidebar--primary .md-sidebar__scrollwrap {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n margin: 0;\n scroll-snap-type: none;\n overflow: hidden;\n }\n}\n@media screen and (min-width: 76.25em) {\n .md-sidebar {\n height: 0;\n }\n .no-js .md-sidebar {\n height: auto;\n }\n}\n.md-sidebar--secondary {\n display: none;\n order: 2;\n}\n@media screen and (min-width: 60em) {\n .md-sidebar--secondary {\n height: 0;\n }\n .no-js .md-sidebar--secondary {\n height: auto;\n }\n .md-sidebar--secondary:not([hidden]) {\n display: block;\n }\n .md-sidebar--secondary .md-sidebar__scrollwrap {\n touch-action: pan-y;\n }\n}\n.md-sidebar__scrollwrap {\n margin: 0 0.2rem;\n overflow-y: auto;\n backface-visibility: hidden;\n scrollbar-width: thin;\n scrollbar-color: var(--md-default-fg-color--lighter) transparent;\n}\n.md-sidebar__scrollwrap:hover {\n scrollbar-color: var(--md-accent-fg-color) transparent;\n}\n.md-sidebar__scrollwrap::-webkit-scrollbar {\n width: 0.2rem;\n height: 0.2rem;\n}\n.md-sidebar__scrollwrap::-webkit-scrollbar-thumb {\n background-color: var(--md-default-fg-color--lighter);\n}\n.md-sidebar__scrollwrap::-webkit-scrollbar-thumb:hover {\n background-color: var(--md-accent-fg-color);\n}\n\n@media screen and (max-width: 76.1875em) {\n .md-overlay {\n position: fixed;\n top: 0;\n z-index: 4;\n width: 0;\n height: 0;\n background-color: rgba(0, 0, 0, 0.54);\n opacity: 0;\n transition: width 0ms 250ms, height 0ms 250ms, opacity 250ms;\n }\n [data-md-toggle=drawer]:checked ~ .md-overlay {\n width: 100%;\n height: 100%;\n opacity: 1;\n transition: width 0ms, height 0ms, opacity 250ms;\n }\n}\n@keyframes facts {\n 0% {\n height: 0;\n }\n 100% {\n height: 0.65rem;\n }\n}\n@keyframes fact {\n 0% {\n transform: translateY(100%);\n opacity: 0;\n }\n 50% {\n opacity: 0;\n }\n 100% {\n transform: translateY(0%);\n opacity: 1;\n }\n}\n:root {\n --md-source-forks-icon: svg-load(\"octicons/repo-forked-16.svg\");\n --md-source-repositories-icon: svg-load(\"octicons/repo-16.svg\");\n --md-source-stars-icon: svg-load(\"octicons/star-16.svg\");\n --md-source-version-icon: svg-load(\"octicons/tag-16.svg\");\n}\n\n.md-source {\n display: block;\n font-size: 0.65rem;\n line-height: 1.2;\n white-space: nowrap;\n outline-color: var(--md-accent-fg-color);\n backface-visibility: hidden;\n transition: opacity 250ms;\n}\n.md-source:hover {\n opacity: 0.7;\n}\n.md-source__icon {\n display: inline-block;\n width: 2rem;\n height: 2.4rem;\n vertical-align: middle;\n}\n.md-source__icon svg {\n margin-top: 0.6rem;\n margin-left: 0.6rem;\n}\n[dir=rtl] .md-source__icon svg {\n margin-right: 0.6rem;\n margin-left: initial;\n}\n.md-source__icon + .md-source__repository {\n margin-left: -2rem;\n padding-left: 2rem;\n}\n[dir=rtl] .md-source__icon + .md-source__repository {\n margin-right: -2rem;\n margin-left: initial;\n padding-right: 2rem;\n padding-left: initial;\n}\n.md-source__repository {\n display: inline-block;\n max-width: calc(100% - 1.2rem);\n margin-left: 0.6rem;\n overflow: hidden;\n text-overflow: ellipsis;\n vertical-align: middle;\n}\n.md-source__facts {\n margin: 0.1rem 0 0;\n padding: 0;\n overflow: hidden;\n font-size: 0.55rem;\n list-style-type: none;\n opacity: 0.75;\n}\n[data-md-state=done] .md-source__facts {\n animation: facts 250ms ease-in;\n}\n.md-source__fact {\n display: inline-block;\n}\n[data-md-state=done] .md-source__fact {\n animation: fact 400ms ease-out;\n}\n.md-source__fact::before {\n display: inline-block;\n width: 0.6rem;\n height: 0.6rem;\n margin-right: 0.1rem;\n vertical-align: text-top;\n background-color: currentColor;\n mask-repeat: no-repeat;\n mask-size: contain;\n content: \"\";\n}\n.md-source__fact:nth-child(1n+2)::before {\n margin-left: 0.4rem;\n}\n[dir=rtl] .md-source__fact {\n margin-right: initial;\n margin-left: 0.1rem;\n}\n[dir=rtl] .md-source__fact:nth-child(1n+2)::before {\n margin-right: 0.4rem;\n margin-left: initial;\n}\n.md-source__fact--version::before {\n mask-image: var(--md-source-version-icon);\n}\n.md-source__fact--stars::before {\n mask-image: var(--md-source-stars-icon);\n}\n.md-source__fact--forks::before {\n mask-image: var(--md-source-forks-icon);\n}\n.md-source__fact--repositories::before {\n mask-image: var(--md-source-repositories-icon);\n}\n\n.md-tabs {\n width: 100%;\n overflow: auto;\n color: var(--md-primary-bg-color);\n background-color: var(--md-primary-fg-color);\n}\n@media print {\n .md-tabs {\n display: none;\n }\n}\n@media screen and (max-width: 76.1875em) {\n .md-tabs {\n display: none;\n }\n}\n.md-tabs[data-md-state=hidden] {\n pointer-events: none;\n}\n.md-tabs__list {\n margin: 0;\n margin-left: 0.2rem;\n padding: 0;\n white-space: nowrap;\n list-style: none;\n contain: content;\n}\n[dir=rtl] .md-tabs__list {\n margin-right: 0.2rem;\n margin-left: initial;\n}\n.md-tabs__item {\n display: inline-block;\n height: 2.4rem;\n padding-right: 0.6rem;\n padding-left: 0.6rem;\n}\n.md-tabs__link {\n display: block;\n margin-top: 0.8rem;\n font-size: 0.7rem;\n outline-color: var(--md-accent-fg-color);\n outline-offset: 0.2rem;\n backface-visibility: hidden;\n opacity: 0.7;\n transition: transform 400ms cubic-bezier(0.1, 0.7, 0.1, 1), opacity 250ms;\n}\n.md-tabs__link--active, .md-tabs__link:focus, .md-tabs__link:hover {\n color: inherit;\n opacity: 1;\n}\n.md-tabs__item:nth-child(2) .md-tabs__link {\n transition-delay: 20ms;\n}\n.md-tabs__item:nth-child(3) .md-tabs__link {\n transition-delay: 40ms;\n}\n.md-tabs__item:nth-child(4) .md-tabs__link {\n transition-delay: 60ms;\n}\n.md-tabs__item:nth-child(5) .md-tabs__link {\n transition-delay: 80ms;\n}\n.md-tabs__item:nth-child(6) .md-tabs__link {\n transition-delay: 100ms;\n}\n.md-tabs__item:nth-child(7) .md-tabs__link {\n transition-delay: 120ms;\n}\n.md-tabs__item:nth-child(8) .md-tabs__link {\n transition-delay: 140ms;\n}\n.md-tabs__item:nth-child(9) .md-tabs__link {\n transition-delay: 160ms;\n}\n.md-tabs__item:nth-child(10) .md-tabs__link {\n transition-delay: 180ms;\n}\n.md-tabs__item:nth-child(11) .md-tabs__link {\n transition-delay: 200ms;\n}\n.md-tabs__item:nth-child(12) .md-tabs__link {\n transition-delay: 220ms;\n}\n.md-tabs__item:nth-child(13) .md-tabs__link {\n transition-delay: 240ms;\n}\n.md-tabs__item:nth-child(14) .md-tabs__link {\n transition-delay: 260ms;\n}\n.md-tabs__item:nth-child(15) .md-tabs__link {\n transition-delay: 280ms;\n}\n.md-tabs__item:nth-child(16) .md-tabs__link {\n transition-delay: 300ms;\n}\n.md-tabs[data-md-state=hidden] .md-tabs__link {\n transform: translateY(50%);\n opacity: 0;\n transition: transform 0ms 100ms, opacity 100ms;\n}\n\n.md-top {\n position: fixed;\n top: 3.2rem;\n z-index: 2;\n margin-left: 50%;\n padding: 0.4rem 0.8rem;\n color: var(--md-default-fg-color--light);\n font-size: 0.7rem;\n background-color: var(--md-default-bg-color);\n border-radius: 1.6rem;\n outline: none;\n box-shadow: 0 0.2rem 0.5rem rgba(0, 0, 0, 0.1), 0 0 0.05rem rgba(0, 0, 0, 0.25);\n transform: translate(-50%, 0);\n transition: color 125ms, background-color 125ms, transform 125ms cubic-bezier(0.4, 0, 0.2, 1), opacity 125ms;\n}\n@media print {\n .md-top {\n display: none;\n }\n}\n[dir=rtl] .md-top {\n float: left;\n}\n.md-top[data-md-state=hidden] {\n transform: translate(-50%, 0.2rem);\n opacity: 0;\n transition-duration: 0ms;\n pointer-events: none;\n}\n.md-top:focus, .md-top:hover {\n color: var(--md-accent-bg-color);\n background-color: var(--md-accent-fg-color);\n}\n.md-top svg {\n display: inline-block;\n vertical-align: -0.5em;\n}\n\n@keyframes hoverfix {\n 0% {\n pointer-events: none;\n }\n}\n:root {\n --md-version-icon: svg-load(\"fontawesome/solid/caret-down.svg\");\n}\n\n.md-version {\n flex-shrink: 0;\n height: 2.4rem;\n font-size: 0.8rem;\n}\n.md-version__current {\n position: relative;\n top: 0.05rem;\n margin-right: 0.4rem;\n margin-left: 1.4rem;\n color: inherit;\n outline: none;\n cursor: pointer;\n}\n[dir=rtl] .md-version__current {\n margin-right: 1.4rem;\n margin-left: 0.4rem;\n}\n.md-version__current::after {\n display: inline-block;\n width: 0.4rem;\n height: 0.6rem;\n margin-left: 0.4rem;\n background-color: currentColor;\n mask-image: var(--md-version-icon);\n mask-repeat: no-repeat;\n content: \"\";\n}\n[dir=rtl] .md-version__current::after {\n margin-right: 0.4rem;\n margin-left: initial;\n}\n.md-version__list {\n position: absolute;\n top: 0.15rem;\n z-index: 1;\n max-height: 0;\n margin: 0.2rem 0.8rem;\n padding: 0;\n overflow: auto;\n color: var(--md-default-fg-color);\n list-style-type: none;\n background-color: var(--md-default-bg-color);\n border-radius: 0.1rem;\n box-shadow: 0 0.2rem 0.5rem rgba(0, 0, 0, 0.1), 0 0 0.05rem rgba(0, 0, 0, 0.25);\n opacity: 0;\n transition: max-height 0ms 500ms, opacity 250ms 250ms;\n scroll-snap-type: y mandatory;\n}\n.md-version:focus-within .md-version__list, .md-version:hover .md-version__list {\n max-height: 10rem;\n opacity: 1;\n transition: max-height 0ms, opacity 250ms;\n}\n@media (pointer: coarse) {\n .md-version:hover .md-version__list {\n animation: hoverfix 250ms forwards;\n }\n .md-version:focus-within .md-version__list {\n animation: none;\n }\n}\n.md-version__item {\n line-height: 1.8rem;\n}\n.md-version__link {\n display: block;\n width: 100%;\n padding-right: 1.2rem;\n padding-left: 0.6rem;\n white-space: nowrap;\n outline: none;\n cursor: pointer;\n transition: color 250ms, background-color 250ms;\n scroll-snap-align: start;\n}\n[dir=rtl] .md-version__link {\n padding-right: 0.6rem;\n padding-left: 1.2rem;\n}\n.md-version__link:focus, .md-version__link:hover {\n color: var(--md-accent-fg-color);\n}\n.md-version__link:focus {\n background-color: var(--md-default-fg-color--lightest);\n}\n\n:root {\n --md-admonition-icon--note:\n svg-load(\"material/pencil.svg\");\n --md-admonition-icon--abstract:\n svg-load(\"material/text-subject.svg\");\n --md-admonition-icon--info:\n svg-load(\"material/information.svg\");\n --md-admonition-icon--tip:\n svg-load(\"material/fire.svg\");\n --md-admonition-icon--success:\n svg-load(\"material/check-circle.svg\");\n --md-admonition-icon--question:\n svg-load(\"material/help-circle.svg\");\n --md-admonition-icon--warning:\n svg-load(\"material/alert.svg\");\n --md-admonition-icon--failure:\n svg-load(\"material/close-circle.svg\");\n --md-admonition-icon--danger:\n svg-load(\"material/flash-circle.svg\");\n --md-admonition-icon--bug:\n svg-load(\"material/bug.svg\");\n --md-admonition-icon--example:\n svg-load(\"material/format-list-numbered.svg\");\n --md-admonition-icon--quote:\n svg-load(\"material/format-quote-close.svg\");\n}\n\n.md-typeset .admonition, .md-typeset details {\n margin: 1.5625em 0;\n padding: 0 0.6rem;\n overflow: hidden;\n color: var(--md-admonition-fg-color);\n font-size: 0.64rem;\n page-break-inside: avoid;\n background-color: var(--md-admonition-bg-color);\n border-left: 0.2rem solid #448aff;\n border-radius: 0.1rem;\n box-shadow: 0 0.2rem 0.5rem rgba(0, 0, 0, 0.05), 0 0.025rem 0.05rem rgba(0, 0, 0, 0.05);\n}\n@media print {\n .md-typeset .admonition, .md-typeset details {\n box-shadow: none;\n }\n}\n[dir=rtl] .md-typeset .admonition, [dir=rtl] .md-typeset details {\n border-right: 0.2rem solid #448aff;\n border-left: none;\n}\n.md-typeset .admonition .admonition, .md-typeset details .admonition, .md-typeset .admonition details, .md-typeset details details {\n margin-top: 1em;\n margin-bottom: 1em;\n}\n.md-typeset .admonition .md-typeset__scrollwrap, .md-typeset details .md-typeset__scrollwrap {\n margin: 1em -0.6rem;\n}\n.md-typeset .admonition .md-typeset__table, .md-typeset details .md-typeset__table {\n padding: 0 0.6rem;\n}\n.md-typeset .admonition > .tabbed-set:only-child, .md-typeset details > .tabbed-set:only-child {\n margin-top: 0;\n}\nhtml .md-typeset .admonition > :last-child, html .md-typeset details > :last-child {\n margin-bottom: 0.6rem;\n}\n.md-typeset .admonition-title, .md-typeset summary {\n position: relative;\n margin: 0 -0.6rem 0 -0.8rem;\n padding: 0.4rem 0.6rem 0.4rem 2rem;\n font-weight: 700;\n background-color: rgba(68, 138, 255, 0.1);\n border-left: 0.2rem solid #448aff;\n}\n[dir=rtl] .md-typeset .admonition-title, [dir=rtl] .md-typeset summary {\n margin: 0 -0.8rem 0 -0.6rem;\n padding: 0.4rem 2rem 0.4rem 0.6rem;\n border-right: 0.2rem solid #448aff;\n border-left: none;\n}\nhtml .md-typeset .admonition-title:last-child, html .md-typeset summary:last-child {\n margin-bottom: 0;\n}\n.md-typeset .admonition-title::before, .md-typeset summary::before {\n position: absolute;\n left: 0.6rem;\n width: 1rem;\n height: 1rem;\n background-color: #448aff;\n mask-image: var(--md-admonition-icon--note);\n mask-repeat: no-repeat;\n mask-size: contain;\n content: \"\";\n}\n[dir=rtl] .md-typeset .admonition-title::before, [dir=rtl] .md-typeset summary::before {\n right: 0.6rem;\n left: initial;\n}\n.md-typeset .admonition-title + .tabbed-set:last-child, .md-typeset summary + .tabbed-set:last-child {\n margin-top: 0;\n}\n\n.md-typeset .admonition.note, .md-typeset details.note {\n border-color: #448aff;\n}\n\n.md-typeset .note > .admonition-title, .md-typeset .note > summary {\n background-color: rgba(68, 138, 255, 0.1);\n border-color: #448aff;\n}\n.md-typeset .note > .admonition-title::before, .md-typeset .note > summary::before {\n background-color: #448aff;\n mask-image: var(--md-admonition-icon--note);\n mask-repeat: no-repeat;\n mask-size: contain;\n}\n\n.md-typeset .admonition.abstract, .md-typeset details.abstract, .md-typeset .admonition.tldr, .md-typeset details.tldr, .md-typeset .admonition.summary, .md-typeset details.summary {\n border-color: #00b0ff;\n}\n\n.md-typeset .abstract > .admonition-title, .md-typeset .abstract > summary, .md-typeset .tldr > .admonition-title, .md-typeset .tldr > summary, .md-typeset .summary > .admonition-title, .md-typeset .summary > summary {\n background-color: rgba(0, 176, 255, 0.1);\n border-color: #00b0ff;\n}\n.md-typeset .abstract > .admonition-title::before, .md-typeset .abstract > summary::before, .md-typeset .tldr > .admonition-title::before, .md-typeset .tldr > summary::before, .md-typeset .summary > .admonition-title::before, .md-typeset .summary > summary::before {\n background-color: #00b0ff;\n mask-image: var(--md-admonition-icon--abstract);\n mask-repeat: no-repeat;\n mask-size: contain;\n}\n\n.md-typeset .admonition.info, .md-typeset details.info, .md-typeset .admonition.todo, .md-typeset details.todo {\n border-color: #00b8d4;\n}\n\n.md-typeset .info > .admonition-title, .md-typeset .info > summary, .md-typeset .todo > .admonition-title, .md-typeset .todo > summary {\n background-color: rgba(0, 184, 212, 0.1);\n border-color: #00b8d4;\n}\n.md-typeset .info > .admonition-title::before, .md-typeset .info > summary::before, .md-typeset .todo > .admonition-title::before, .md-typeset .todo > summary::before {\n background-color: #00b8d4;\n mask-image: var(--md-admonition-icon--info);\n mask-repeat: no-repeat;\n mask-size: contain;\n}\n\n.md-typeset .admonition.tip, .md-typeset details.tip, .md-typeset .admonition.important, .md-typeset details.important, .md-typeset .admonition.hint, .md-typeset details.hint {\n border-color: #00bfa5;\n}\n\n.md-typeset .tip > .admonition-title, .md-typeset .tip > summary, .md-typeset .important > .admonition-title, .md-typeset .important > summary, .md-typeset .hint > .admonition-title, .md-typeset .hint > summary {\n background-color: rgba(0, 191, 165, 0.1);\n border-color: #00bfa5;\n}\n.md-typeset .tip > .admonition-title::before, .md-typeset .tip > summary::before, .md-typeset .important > .admonition-title::before, .md-typeset .important > summary::before, .md-typeset .hint > .admonition-title::before, .md-typeset .hint > summary::before {\n background-color: #00bfa5;\n mask-image: var(--md-admonition-icon--tip);\n mask-repeat: no-repeat;\n mask-size: contain;\n}\n\n.md-typeset .admonition.success, .md-typeset details.success, .md-typeset .admonition.done, .md-typeset details.done, .md-typeset .admonition.check, .md-typeset details.check {\n border-color: #00c853;\n}\n\n.md-typeset .success > .admonition-title, .md-typeset .success > summary, .md-typeset .done > .admonition-title, .md-typeset .done > summary, .md-typeset .check > .admonition-title, .md-typeset .check > summary {\n background-color: rgba(0, 200, 83, 0.1);\n border-color: #00c853;\n}\n.md-typeset .success > .admonition-title::before, .md-typeset .success > summary::before, .md-typeset .done > .admonition-title::before, .md-typeset .done > summary::before, .md-typeset .check > .admonition-title::before, .md-typeset .check > summary::before {\n background-color: #00c853;\n mask-image: var(--md-admonition-icon--success);\n mask-repeat: no-repeat;\n mask-size: contain;\n}\n\n.md-typeset .admonition.question, .md-typeset details.question, .md-typeset .admonition.faq, .md-typeset details.faq, .md-typeset .admonition.help, .md-typeset details.help {\n border-color: #64dd17;\n}\n\n.md-typeset .question > .admonition-title, .md-typeset .question > summary, .md-typeset .faq > .admonition-title, .md-typeset .faq > summary, .md-typeset .help > .admonition-title, .md-typeset .help > summary {\n background-color: rgba(100, 221, 23, 0.1);\n border-color: #64dd17;\n}\n.md-typeset .question > .admonition-title::before, .md-typeset .question > summary::before, .md-typeset .faq > .admonition-title::before, .md-typeset .faq > summary::before, .md-typeset .help > .admonition-title::before, .md-typeset .help > summary::before {\n background-color: #64dd17;\n mask-image: var(--md-admonition-icon--question);\n mask-repeat: no-repeat;\n mask-size: contain;\n}\n\n.md-typeset .admonition.warning, .md-typeset details.warning, .md-typeset .admonition.attention, .md-typeset details.attention, .md-typeset .admonition.caution, .md-typeset details.caution {\n border-color: #ff9100;\n}\n\n.md-typeset .warning > .admonition-title, .md-typeset .warning > summary, .md-typeset .attention > .admonition-title, .md-typeset .attention > summary, .md-typeset .caution > .admonition-title, .md-typeset .caution > summary {\n background-color: rgba(255, 145, 0, 0.1);\n border-color: #ff9100;\n}\n.md-typeset .warning > .admonition-title::before, .md-typeset .warning > summary::before, .md-typeset .attention > .admonition-title::before, .md-typeset .attention > summary::before, .md-typeset .caution > .admonition-title::before, .md-typeset .caution > summary::before {\n background-color: #ff9100;\n mask-image: var(--md-admonition-icon--warning);\n mask-repeat: no-repeat;\n mask-size: contain;\n}\n\n.md-typeset .admonition.failure, .md-typeset details.failure, .md-typeset .admonition.missing, .md-typeset details.missing, .md-typeset .admonition.fail, .md-typeset details.fail {\n border-color: #ff5252;\n}\n\n.md-typeset .failure > .admonition-title, .md-typeset .failure > summary, .md-typeset .missing > .admonition-title, .md-typeset .missing > summary, .md-typeset .fail > .admonition-title, .md-typeset .fail > summary {\n background-color: rgba(255, 82, 82, 0.1);\n border-color: #ff5252;\n}\n.md-typeset .failure > .admonition-title::before, .md-typeset .failure > summary::before, .md-typeset .missing > .admonition-title::before, .md-typeset .missing > summary::before, .md-typeset .fail > .admonition-title::before, .md-typeset .fail > summary::before {\n background-color: #ff5252;\n mask-image: var(--md-admonition-icon--failure);\n mask-repeat: no-repeat;\n mask-size: contain;\n}\n\n.md-typeset .admonition.danger, .md-typeset details.danger, .md-typeset .admonition.error, .md-typeset details.error {\n border-color: #ff1744;\n}\n\n.md-typeset .danger > .admonition-title, .md-typeset .danger > summary, .md-typeset .error > .admonition-title, .md-typeset .error > summary {\n background-color: rgba(255, 23, 68, 0.1);\n border-color: #ff1744;\n}\n.md-typeset .danger > .admonition-title::before, .md-typeset .danger > summary::before, .md-typeset .error > .admonition-title::before, .md-typeset .error > summary::before {\n background-color: #ff1744;\n mask-image: var(--md-admonition-icon--danger);\n mask-repeat: no-repeat;\n mask-size: contain;\n}\n\n.md-typeset .admonition.bug, .md-typeset details.bug {\n border-color: #f50057;\n}\n\n.md-typeset .bug > .admonition-title, .md-typeset .bug > summary {\n background-color: rgba(245, 0, 87, 0.1);\n border-color: #f50057;\n}\n.md-typeset .bug > .admonition-title::before, .md-typeset .bug > summary::before {\n background-color: #f50057;\n mask-image: var(--md-admonition-icon--bug);\n mask-repeat: no-repeat;\n mask-size: contain;\n}\n\n.md-typeset .admonition.example, .md-typeset details.example {\n border-color: #7c4dff;\n}\n\n.md-typeset .example > .admonition-title, .md-typeset .example > summary {\n background-color: rgba(124, 77, 255, 0.1);\n border-color: #7c4dff;\n}\n.md-typeset .example > .admonition-title::before, .md-typeset .example > summary::before {\n background-color: #7c4dff;\n mask-image: var(--md-admonition-icon--example);\n mask-repeat: no-repeat;\n mask-size: contain;\n}\n\n.md-typeset .admonition.quote, .md-typeset details.quote, .md-typeset .admonition.cite, .md-typeset details.cite {\n border-color: #9e9e9e;\n}\n\n.md-typeset .quote > .admonition-title, .md-typeset .quote > summary, .md-typeset .cite > .admonition-title, .md-typeset .cite > summary {\n background-color: rgba(158, 158, 158, 0.1);\n border-color: #9e9e9e;\n}\n.md-typeset .quote > .admonition-title::before, .md-typeset .quote > summary::before, .md-typeset .cite > .admonition-title::before, .md-typeset .cite > summary::before {\n background-color: #9e9e9e;\n mask-image: var(--md-admonition-icon--quote);\n mask-repeat: no-repeat;\n mask-size: contain;\n}\n\n:root {\n --md-footnotes-icon: svg-load(\"material/keyboard-return.svg\");\n}\n\n.md-typeset .footnote {\n color: var(--md-default-fg-color--light);\n font-size: 0.64rem;\n}\n.md-typeset .footnote > ol {\n margin-left: 0;\n}\n.md-typeset .footnote > ol > li {\n transition: color 125ms;\n}\n.md-typeset .footnote > ol > li:target {\n color: var(--md-default-fg-color);\n}\n.md-typeset .footnote > ol > li:hover .footnote-backref, .md-typeset .footnote > ol > li:target .footnote-backref {\n transform: translateX(0);\n opacity: 1;\n}\n.md-typeset .footnote > ol > li > :first-child {\n margin-top: 0;\n}\n.md-typeset .footnote-ref {\n font-weight: 700;\n font-size: 0.75em;\n}\nhtml .md-typeset .footnote-ref {\n outline-offset: 0.1rem;\n}\n.md-typeset .footnote-backref {\n display: inline-block;\n color: var(--md-typeset-a-color);\n font-size: 0;\n vertical-align: text-bottom;\n transform: translateX(0.25rem);\n opacity: 0;\n transition: color 250ms, transform 250ms 250ms, opacity 125ms 250ms;\n}\n@media print {\n .md-typeset .footnote-backref {\n color: var(--md-typeset-a-color);\n transform: translateX(0);\n opacity: 1;\n }\n}\n[dir=rtl] .md-typeset .footnote-backref {\n transform: translateX(-0.25rem);\n}\n.md-typeset .footnote-backref:hover {\n color: var(--md-accent-fg-color);\n}\n.md-typeset .footnote-backref::before {\n display: inline-block;\n width: 0.8rem;\n height: 0.8rem;\n background-color: currentColor;\n mask-image: var(--md-footnotes-icon);\n mask-repeat: no-repeat;\n mask-size: contain;\n content: \"\";\n}\n[dir=rtl] .md-typeset .footnote-backref::before svg {\n transform: scaleX(-1);\n}\n.md-typeset [id^=\"fnref:\"]:target {\n scroll-margin-top: initial;\n margin-top: -3.4rem;\n padding-top: 3.4rem;\n}\n.md-typeset [id^=\"fnref:\"]:target > .footnote-ref {\n outline: auto;\n}\n.md-typeset [id^=\"fn:\"]:target {\n scroll-margin-top: initial;\n margin-top: -3.45rem;\n padding-top: 3.45rem;\n}\n\n.md-typeset .headerlink {\n display: inline-block;\n margin-left: 0.5rem;\n color: var(--md-default-fg-color--lighter);\n opacity: 0;\n transition: color 250ms, opacity 125ms;\n}\n@media print {\n .md-typeset .headerlink {\n display: none;\n }\n}\n[dir=rtl] .md-typeset .headerlink {\n margin-right: 0.5rem;\n margin-left: initial;\n}\n.md-typeset :hover > .headerlink,\n.md-typeset :target > .headerlink,\n.md-typeset .headerlink:focus {\n opacity: 1;\n transition: color 250ms, opacity 125ms;\n}\n.md-typeset :target > .headerlink,\n.md-typeset .headerlink:focus,\n.md-typeset .headerlink:hover {\n color: var(--md-accent-fg-color);\n}\n.md-typeset :target {\n scroll-margin-top: 3.6rem;\n}\n.md-typeset h1:target,\n.md-typeset h2:target,\n.md-typeset h3:target {\n scroll-margin-top: initial;\n}\n.md-typeset h1:target::before,\n.md-typeset h2:target::before,\n.md-typeset h3:target::before {\n display: block;\n margin-top: -3.4rem;\n padding-top: 3.4rem;\n content: \"\";\n}\n.md-typeset h4:target {\n scroll-margin-top: initial;\n}\n.md-typeset h4:target::before {\n display: block;\n margin-top: -3.45rem;\n padding-top: 3.45rem;\n content: \"\";\n}\n.md-typeset h5:target,\n.md-typeset h6:target {\n scroll-margin-top: initial;\n}\n.md-typeset h5:target::before,\n.md-typeset h6:target::before {\n display: block;\n margin-top: -3.6rem;\n padding-top: 3.6rem;\n content: \"\";\n}\n\n.md-typeset div.arithmatex {\n overflow: auto;\n}\n@media screen and (max-width: 44.9375em) {\n .md-typeset div.arithmatex {\n margin: 0 -0.8rem;\n }\n}\n.md-typeset div.arithmatex > * {\n width: min-content;\n margin: 1em auto !important;\n padding: 0 0.8rem;\n touch-action: auto;\n}\n\n.md-typeset del.critic,\n.md-typeset ins.critic,\n.md-typeset .critic.comment {\n box-decoration-break: clone;\n}\n.md-typeset del.critic {\n background-color: var(--md-typeset-del-color);\n}\n.md-typeset ins.critic {\n background-color: var(--md-typeset-ins-color);\n}\n.md-typeset .critic.comment {\n color: var(--md-code-hl-comment-color);\n}\n.md-typeset .critic.comment::before {\n content: \"/* \";\n}\n.md-typeset .critic.comment::after {\n content: \" */\";\n}\n.md-typeset .critic.block {\n display: block;\n margin: 1em 0;\n padding-right: 0.8rem;\n padding-left: 0.8rem;\n overflow: auto;\n box-shadow: none;\n}\n.md-typeset .critic.block > :first-child {\n margin-top: 0.5em;\n}\n.md-typeset .critic.block > :last-child {\n margin-bottom: 0.5em;\n}\n\n:root {\n --md-details-icon: svg-load(\"material/chevron-right.svg\");\n}\n\n.md-typeset details {\n display: flow-root;\n padding-top: 0;\n overflow: visible;\n}\n.md-typeset details[open] > summary::after {\n transform: rotate(90deg);\n}\n.md-typeset details:not([open]) {\n padding-bottom: 0;\n box-shadow: none;\n}\n.md-typeset details:not([open]) > summary {\n border-radius: 0.1rem;\n}\n.md-typeset details::after {\n display: table;\n content: \"\";\n}\n.md-typeset summary {\n display: block;\n min-height: 1rem;\n padding: 0.4rem 1.8rem 0.4rem 2rem;\n border-top-left-radius: 0.1rem;\n border-top-right-radius: 0.1rem;\n cursor: pointer;\n}\n[dir=rtl] .md-typeset summary {\n padding: 0.4rem 2.2rem 0.4rem 1.8rem;\n}\n.md-typeset summary:not(.focus-visible) {\n outline: none;\n -webkit-tap-highlight-color: transparent;\n}\n.md-typeset summary::after {\n position: absolute;\n top: 0.4rem;\n right: 0.4rem;\n width: 1rem;\n height: 1rem;\n background-color: currentColor;\n mask-image: var(--md-details-icon);\n mask-repeat: no-repeat;\n mask-size: contain;\n transform: rotate(0deg);\n transition: transform 250ms;\n content: \"\";\n}\n[dir=rtl] .md-typeset summary::after {\n right: initial;\n left: 0.4rem;\n transform: rotate(180deg);\n}\n.md-typeset summary::marker, .md-typeset summary::-webkit-details-marker {\n display: none;\n}\n\n.md-typeset .emojione,\n.md-typeset .twemoji,\n.md-typeset .gemoji {\n display: inline-flex;\n height: 1.125em;\n vertical-align: text-top;\n}\n.md-typeset .emojione svg,\n.md-typeset .twemoji svg,\n.md-typeset .gemoji svg {\n width: 1.125em;\n max-height: 100%;\n fill: currentColor;\n}\n\n.highlight .o,\n.highlight .ow {\n color: var(--md-code-hl-operator-color);\n}\n.highlight .p {\n color: var(--md-code-hl-punctuation-color);\n}\n.highlight .cpf,\n.highlight .l,\n.highlight .s,\n.highlight .sb,\n.highlight .sc,\n.highlight .s2,\n.highlight .si,\n.highlight .s1,\n.highlight .ss {\n color: var(--md-code-hl-string-color);\n}\n.highlight .cp,\n.highlight .se,\n.highlight .sh,\n.highlight .sr,\n.highlight .sx {\n color: var(--md-code-hl-special-color);\n}\n.highlight .m,\n.highlight .mb,\n.highlight .mf,\n.highlight .mh,\n.highlight .mi,\n.highlight .il,\n.highlight .mo {\n color: var(--md-code-hl-number-color);\n}\n.highlight .k,\n.highlight .kd,\n.highlight .kn,\n.highlight .kp,\n.highlight .kr,\n.highlight .kt {\n color: var(--md-code-hl-keyword-color);\n}\n.highlight .kc,\n.highlight .n {\n color: var(--md-code-hl-name-color);\n}\n.highlight .no,\n.highlight .nb,\n.highlight .bp {\n color: var(--md-code-hl-constant-color);\n}\n.highlight .nc,\n.highlight .ne,\n.highlight .nf,\n.highlight .nn {\n color: var(--md-code-hl-function-color);\n}\n.highlight .nd,\n.highlight .ni,\n.highlight .nl,\n.highlight .nt {\n color: var(--md-code-hl-keyword-color);\n}\n.highlight .c,\n.highlight .cm,\n.highlight .c1,\n.highlight .ch,\n.highlight .cs,\n.highlight .sd {\n color: var(--md-code-hl-comment-color);\n}\n.highlight .na,\n.highlight .nv,\n.highlight .vc,\n.highlight .vg,\n.highlight .vi {\n color: var(--md-code-hl-variable-color);\n}\n.highlight .ge,\n.highlight .gr,\n.highlight .gh,\n.highlight .go,\n.highlight .gp,\n.highlight .gs,\n.highlight .gu,\n.highlight .gt {\n color: var(--md-code-hl-generic-color);\n}\n.highlight .gd,\n.highlight .gi {\n margin: 0 -0.125em;\n padding: 0 0.125em;\n border-radius: 0.1rem;\n}\n.highlight .gd {\n background-color: var(--md-typeset-del-color);\n}\n.highlight .gi {\n background-color: var(--md-typeset-ins-color);\n}\n.highlight .hll {\n display: block;\n margin: 0 -1.1764705882em;\n padding: 0 1.1764705882em;\n background-color: var(--md-code-hl-color);\n}\n.highlight [data-linenos]::before {\n position: sticky;\n left: -1.1764705882em;\n float: left;\n margin-right: 1.1764705882em;\n margin-left: -1.1764705882em;\n padding-left: 1.1764705882em;\n color: var(--md-default-fg-color--light);\n background-color: var(--md-code-bg-color);\n box-shadow: -0.05rem 0 var(--md-default-fg-color--lightest) inset;\n content: attr(data-linenos);\n user-select: none;\n}\n\n.highlighttable {\n display: flow-root;\n overflow: hidden;\n}\n.highlighttable tbody,\n.highlighttable td {\n display: block;\n padding: 0;\n}\n.highlighttable tr {\n display: flex;\n}\n.highlighttable pre {\n margin: 0;\n}\n.highlighttable .linenos {\n padding: 0.7720588235em 1.1764705882em;\n padding-right: 0;\n font-size: 0.85em;\n background-color: var(--md-code-bg-color);\n user-select: none;\n}\n.highlighttable .linenodiv {\n padding-right: 0.5882352941em;\n box-shadow: -0.05rem 0 var(--md-default-fg-color--lightest) inset;\n}\n.highlighttable .linenodiv pre {\n color: var(--md-default-fg-color--light);\n text-align: right;\n}\n.highlighttable .code {\n flex: 1;\n overflow: hidden;\n}\n\n.md-typeset .highlighttable {\n margin: 1em 0;\n direction: ltr;\n border-radius: 0.1rem;\n}\n.md-typeset .highlighttable code {\n border-radius: 0;\n}\n@media screen and (max-width: 44.9375em) {\n .md-typeset > .highlight {\n margin: 1em -0.8rem;\n }\n .md-typeset > .highlight .hll {\n margin: 0 -0.8rem;\n padding: 0 0.8rem;\n }\n .md-typeset > .highlight code {\n border-radius: 0;\n }\n .md-typeset > .highlighttable {\n margin: 1em -0.8rem;\n border-radius: 0;\n }\n .md-typeset > .highlighttable .hll {\n margin: 0 -0.8rem;\n padding: 0 0.8rem;\n }\n}\n\n.md-typeset .keys kbd::before,\n.md-typeset .keys kbd::after {\n position: relative;\n margin: 0;\n color: inherit;\n -moz-osx-font-smoothing: initial;\n -webkit-font-smoothing: initial;\n}\n.md-typeset .keys span {\n padding: 0 0.2em;\n color: var(--md-default-fg-color--light);\n}\n.md-typeset .keys .key-alt::before {\n padding-right: 0.4em;\n content: \"⎇\";\n}\n.md-typeset .keys .key-left-alt::before {\n padding-right: 0.4em;\n content: \"⎇\";\n}\n.md-typeset .keys .key-right-alt::before {\n padding-right: 0.4em;\n content: \"⎇\";\n}\n.md-typeset .keys .key-command::before {\n padding-right: 0.4em;\n content: \"⌘\";\n}\n.md-typeset .keys .key-left-command::before {\n padding-right: 0.4em;\n content: \"⌘\";\n}\n.md-typeset .keys .key-right-command::before {\n padding-right: 0.4em;\n content: \"⌘\";\n}\n.md-typeset .keys .key-control::before {\n padding-right: 0.4em;\n content: \"⌃\";\n}\n.md-typeset .keys .key-left-control::before {\n padding-right: 0.4em;\n content: \"⌃\";\n}\n.md-typeset .keys .key-right-control::before {\n padding-right: 0.4em;\n content: \"⌃\";\n}\n.md-typeset .keys .key-meta::before {\n padding-right: 0.4em;\n content: \"◆\";\n}\n.md-typeset .keys .key-left-meta::before {\n padding-right: 0.4em;\n content: \"◆\";\n}\n.md-typeset .keys .key-right-meta::before {\n padding-right: 0.4em;\n content: \"◆\";\n}\n.md-typeset .keys .key-option::before {\n padding-right: 0.4em;\n content: \"⌥\";\n}\n.md-typeset .keys .key-left-option::before {\n padding-right: 0.4em;\n content: \"⌥\";\n}\n.md-typeset .keys .key-right-option::before {\n padding-right: 0.4em;\n content: \"⌥\";\n}\n.md-typeset .keys .key-shift::before {\n padding-right: 0.4em;\n content: \"⇧\";\n}\n.md-typeset .keys .key-left-shift::before {\n padding-right: 0.4em;\n content: \"⇧\";\n}\n.md-typeset .keys .key-right-shift::before {\n padding-right: 0.4em;\n content: \"⇧\";\n}\n.md-typeset .keys .key-super::before {\n padding-right: 0.4em;\n content: \"❖\";\n}\n.md-typeset .keys .key-left-super::before {\n padding-right: 0.4em;\n content: \"❖\";\n}\n.md-typeset .keys .key-right-super::before {\n padding-right: 0.4em;\n content: \"❖\";\n}\n.md-typeset .keys .key-windows::before {\n padding-right: 0.4em;\n content: \"⊞\";\n}\n.md-typeset .keys .key-left-windows::before {\n padding-right: 0.4em;\n content: \"⊞\";\n}\n.md-typeset .keys .key-right-windows::before {\n padding-right: 0.4em;\n content: \"⊞\";\n}\n.md-typeset .keys .key-arrow-down::before {\n padding-right: 0.4em;\n content: \"↓\";\n}\n.md-typeset .keys .key-arrow-left::before {\n padding-right: 0.4em;\n content: \"←\";\n}\n.md-typeset .keys .key-arrow-right::before {\n padding-right: 0.4em;\n content: \"→\";\n}\n.md-typeset .keys .key-arrow-up::before {\n padding-right: 0.4em;\n content: \"↑\";\n}\n.md-typeset .keys .key-backspace::before {\n padding-right: 0.4em;\n content: \"⌫\";\n}\n.md-typeset .keys .key-backtab::before {\n padding-right: 0.4em;\n content: \"⇤\";\n}\n.md-typeset .keys .key-caps-lock::before {\n padding-right: 0.4em;\n content: \"⇪\";\n}\n.md-typeset .keys .key-clear::before {\n padding-right: 0.4em;\n content: \"⌧\";\n}\n.md-typeset .keys .key-context-menu::before {\n padding-right: 0.4em;\n content: \"☰\";\n}\n.md-typeset .keys .key-delete::before {\n padding-right: 0.4em;\n content: \"⌦\";\n}\n.md-typeset .keys .key-eject::before {\n padding-right: 0.4em;\n content: \"⏏\";\n}\n.md-typeset .keys .key-end::before {\n padding-right: 0.4em;\n content: \"⤓\";\n}\n.md-typeset .keys .key-escape::before {\n padding-right: 0.4em;\n content: \"⎋\";\n}\n.md-typeset .keys .key-home::before {\n padding-right: 0.4em;\n content: \"⤒\";\n}\n.md-typeset .keys .key-insert::before {\n padding-right: 0.4em;\n content: \"⎀\";\n}\n.md-typeset .keys .key-page-down::before {\n padding-right: 0.4em;\n content: \"⇟\";\n}\n.md-typeset .keys .key-page-up::before {\n padding-right: 0.4em;\n content: \"⇞\";\n}\n.md-typeset .keys .key-print-screen::before {\n padding-right: 0.4em;\n content: \"⎙\";\n}\n.md-typeset .keys .key-tab::after {\n padding-left: 0.4em;\n content: \"⇥\";\n}\n.md-typeset .keys .key-num-enter::after {\n padding-left: 0.4em;\n content: \"⌤\";\n}\n.md-typeset .keys .key-enter::after {\n padding-left: 0.4em;\n content: \"⏎\";\n}\n\n.md-typeset .tabbed-content {\n display: none;\n order: 99;\n width: 100%;\n box-shadow: 0 -0.05rem var(--md-default-fg-color--lightest);\n}\n@media print {\n .md-typeset .tabbed-content {\n display: block;\n order: initial;\n }\n}\n.md-typeset .tabbed-content > pre:only-child,\n.md-typeset .tabbed-content > .highlight:only-child pre,\n.md-typeset .tabbed-content > .highlighttable:only-child {\n margin: 0;\n}\n.md-typeset .tabbed-content > pre:only-child > code,\n.md-typeset .tabbed-content > .highlight:only-child pre > code,\n.md-typeset .tabbed-content > .highlighttable:only-child > code {\n border-top-left-radius: 0;\n border-top-right-radius: 0;\n}\n.md-typeset .tabbed-content > .tabbed-set {\n margin: 0;\n}\n.md-typeset .tabbed-set {\n position: relative;\n display: flex;\n flex-wrap: wrap;\n margin: 1em 0;\n border-radius: 0.1rem;\n}\n.md-typeset .tabbed-set > input {\n position: absolute;\n width: 0;\n height: 0;\n opacity: 0;\n}\n.md-typeset .tabbed-set > input:checked + label {\n color: var(--md-accent-fg-color);\n border-color: var(--md-accent-fg-color);\n}\n.md-typeset .tabbed-set > input:checked + label + .tabbed-content {\n display: block;\n}\n.md-typeset .tabbed-set > input:focus + label {\n outline-style: auto;\n outline-color: var(--md-accent-fg-color);\n}\n.md-typeset .tabbed-set > input:not(.focus-visible) + label {\n outline: none;\n -webkit-tap-highlight-color: transparent;\n}\n.md-typeset .tabbed-set > label {\n z-index: 1;\n width: auto;\n padding: 0.9375em 1.25em 0.78125em;\n color: var(--md-default-fg-color--light);\n font-weight: 700;\n font-size: 0.64rem;\n border-bottom: 0.1rem solid transparent;\n cursor: pointer;\n transition: color 250ms;\n}\n.md-typeset .tabbed-set > label:hover {\n color: var(--md-accent-fg-color);\n}\n\n:root {\n --md-tasklist-icon:\n svg-load(\"octicons/check-circle-fill-24.svg\");\n --md-tasklist-icon--checked:\n svg-load(\"octicons/check-circle-fill-24.svg\");\n}\n\n.md-typeset .task-list-item {\n position: relative;\n list-style-type: none;\n}\n.md-typeset .task-list-item [type=checkbox] {\n position: absolute;\n top: 0.45em;\n left: -2em;\n}\n[dir=rtl] .md-typeset .task-list-item [type=checkbox] {\n right: -2em;\n left: initial;\n}\n.md-typeset .task-list-control [type=checkbox] {\n z-index: -1;\n opacity: 0;\n}\n.md-typeset .task-list-indicator::before {\n position: absolute;\n top: 0.15em;\n left: -1.5em;\n width: 1.25em;\n height: 1.25em;\n background-color: var(--md-default-fg-color--lightest);\n mask-image: var(--md-tasklist-icon);\n mask-repeat: no-repeat;\n mask-size: contain;\n content: \"\";\n}\n[dir=rtl] .md-typeset .task-list-indicator::before {\n right: -1.5em;\n left: initial;\n}\n.md-typeset [type=checkbox]:checked + .task-list-indicator::before {\n background-color: #00e676;\n mask-image: var(--md-tasklist-icon--checked);\n}\n\n@media screen and (min-width: 45em) {\n .md-typeset .inline {\n float: left;\n width: 11.7rem;\n margin-top: 0;\n margin-right: 0.8rem;\n margin-bottom: 0.8rem;\n }\n [dir=rtl] .md-typeset .inline {\n float: right;\n margin-right: 0;\n margin-left: 0.8rem;\n }\n .md-typeset .inline.end {\n float: right;\n margin-right: 0;\n margin-left: 0.8rem;\n }\n [dir=rtl] .md-typeset .inline.end {\n float: left;\n margin-right: 0.8rem;\n margin-left: 0;\n }\n}\n\n/*# sourceMappingURL=main.css.map */","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Enforce correct box model and prevent adjustments of font size after\n// orientation changes in IE and iOS\nhtml {\n box-sizing: border-box;\n text-size-adjust: none;\n}\n\n// All elements shall inherit the document default\n*,\n*::before,\n*::after {\n box-sizing: inherit;\n}\n\n// Remove margin in all browsers\nbody {\n margin: 0;\n}\n\n// Reset tap outlines on iOS and Android\na,\nbutton,\nlabel,\ninput {\n -webkit-tap-highlight-color: transparent;\n}\n\n// Reset link styles\na {\n color: inherit;\n text-decoration: none;\n}\n\n// Normalize horizontal separator styles\nhr {\n display: block;\n box-sizing: content-box;\n height: px2rem(1px);\n padding: 0;\n overflow: visible;\n border: 0;\n}\n\n// Normalize font-size in all browsers\nsmall {\n font-size: 80%;\n}\n\n// Prevent subscript and superscript from affecting line-height\nsub,\nsup {\n line-height: 1em;\n}\n\n// Remove border on image\nimg {\n border-style: none;\n}\n\n// Reset table styles\ntable {\n border-collapse: separate;\n border-spacing: 0;\n}\n\n// Reset table cell styles\ntd,\nth {\n font-weight: 400;\n vertical-align: top;\n}\n\n// Reset button styles\nbutton {\n margin: 0;\n padding: 0;\n font-size: inherit;\n font-family: inherit;\n background: transparent;\n border: 0;\n}\n\n// Reset input styles\ninput {\n border: 0;\n outline: none;\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Color definitions\n:root {\n\n // Default color shades\n --md-default-fg-color: hsla(0, 0%, 0%, 0.87);\n --md-default-fg-color--light: hsla(0, 0%, 0%, 0.54);\n --md-default-fg-color--lighter: hsla(0, 0%, 0%, 0.32);\n --md-default-fg-color--lightest: hsla(0, 0%, 0%, 0.07);\n --md-default-bg-color: hsla(0, 0%, 100%, 1);\n --md-default-bg-color--light: hsla(0, 0%, 100%, 0.7);\n --md-default-bg-color--lighter: hsla(0, 0%, 100%, 0.3);\n --md-default-bg-color--lightest: hsla(0, 0%, 100%, 0.12);\n\n // Primary color shades\n --md-primary-fg-color: hsla(#{hex2hsl($clr-indigo-500)}, 1);\n --md-primary-fg-color--light: hsla(#{hex2hsl($clr-indigo-400)}, 1);\n --md-primary-fg-color--dark: hsla(#{hex2hsl($clr-indigo-700)}, 1);\n --md-primary-bg-color: hsla(0, 0%, 100%, 1);\n --md-primary-bg-color--light: hsla(0, 0%, 100%, 0.7);\n\n // Accent color shades\n --md-accent-fg-color: hsla(#{hex2hsl($clr-indigo-a200)}, 1);\n --md-accent-fg-color--transparent: hsla(#{hex2hsl($clr-indigo-a200)}, 0.1);\n --md-accent-bg-color: hsla(0, 0%, 100%, 1);\n --md-accent-bg-color--light: hsla(0, 0%, 100%, 0.7);\n\n // Light theme (default)\n > * {\n\n // Code color shades\n --md-code-fg-color: hsla(200, 18%, 26%, 1);\n --md-code-bg-color: hsla(0, 0%, 96%, 1);\n\n // Code highlighting color shades\n --md-code-hl-color: hsla(#{hex2hsl($clr-yellow-a200)}, 0.5);\n --md-code-hl-number-color: hsla(0, 67%, 50%, 1);\n --md-code-hl-special-color: hsla(340, 83%, 47%, 1);\n --md-code-hl-function-color: hsla(291, 45%, 50%, 1);\n --md-code-hl-constant-color: hsla(250, 63%, 60%, 1);\n --md-code-hl-keyword-color: hsla(219, 54%, 51%, 1);\n --md-code-hl-string-color: hsla(150, 63%, 30%, 1);\n --md-code-hl-name-color: var(--md-code-fg-color);\n --md-code-hl-operator-color: var(--md-default-fg-color--light);\n --md-code-hl-punctuation-color: var(--md-default-fg-color--light);\n --md-code-hl-comment-color: var(--md-default-fg-color--light);\n --md-code-hl-generic-color: var(--md-default-fg-color--light);\n --md-code-hl-variable-color: var(--md-default-fg-color--light);\n\n // Typeset color shades\n --md-typeset-color: var(--md-default-fg-color);\n\n // Typeset `a` color shades\n --md-typeset-a-color: var(--md-primary-fg-color);\n\n // Typeset `mark` color shades\n --md-typeset-mark-color: hsla(#{hex2hsl($clr-yellow-a200)}, 0.5);\n\n // Typeset `del` and `ins` color shades\n --md-typeset-del-color: hsla(6, 90%, 60%, 0.15);\n --md-typeset-ins-color: hsla(150, 90%, 44%, 0.15);\n\n // Typeset `kbd` color shades\n --md-typeset-kbd-color: hsla(0, 0%, 98%, 1);\n --md-typeset-kbd-accent-color: hsla(0, 100%, 100%, 1);\n --md-typeset-kbd-border-color: hsla(0, 0%, 72%, 1);\n\n // Admonition color shades\n --md-admonition-fg-color: var(--md-default-fg-color);\n --md-admonition-bg-color: var(--md-default-bg-color);\n\n // Footer color shades\n --md-footer-fg-color: hsla(0, 0%, 100%, 1);\n --md-footer-fg-color--light: hsla(0, 0%, 100%, 0.7);\n --md-footer-fg-color--lighter: hsla(0, 0%, 100%, 0.3);\n --md-footer-bg-color: hsla(0, 0%, 0%, 0.87);\n --md-footer-bg-color--dark: hsla(0, 0%, 0%, 0.32);\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Icon\n.md-icon {\n\n // SVG defaults\n svg {\n display: block;\n width: px2rem(24px);\n height: px2rem(24px);\n fill: currentColor;\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules: font definitions\n// ----------------------------------------------------------------------------\n\n// Enable font-smoothing in Webkit and FF\nbody {\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\n// Define default fonts\nbody,\ninput {\n color: var(--md-typeset-color);\n font-feature-settings: \"kern\", \"liga\";\n font-family:\n var(--md-text-font-family, _),\n -apple-system, BlinkMacSystemFont, Helvetica, Arial, sans-serif;\n}\n\n// Define monospaced fonts\ncode,\npre,\nkbd {\n color: var(--md-typeset-color);\n font-feature-settings: \"kern\";\n font-family:\n var(--md-code-font-family, _),\n SFMono-Regular, Consolas, Menlo, monospace;\n}\n\n// ----------------------------------------------------------------------------\n// Rules: typesetted content\n// ----------------------------------------------------------------------------\n\n// Icon definitions\n:root {\n --md-typeset-table--ascending: svg-load(\"material/arrow-down.svg\");\n --md-typeset-table--descending: svg-load(\"material/arrow-up.svg\");\n}\n\n// ----------------------------------------------------------------------------\n\n// Content that is typeset - if possible, all margins, paddings and font sizes\n// should be set in ems, so nested blocks (e.g. admonitions) render correctly.\n.md-typeset {\n font-size: px2rem(16px);\n line-height: 1.6;\n color-adjust: exact;\n\n // [print]: We'll use a smaller `font-size` for printing, so code examples\n // don't break too early, and `16px` looks too big anyway.\n @media print {\n font-size: px2rem(13.6px);\n }\n\n // Default spacing\n ul,\n ol,\n dl,\n figure,\n blockquote,\n pre {\n margin: 1em 0;\n }\n\n // Headline on level 1\n h1 {\n margin: 0 0 px2em(40px, 32px);\n color: var(--md-default-fg-color--light);\n font-weight: 300;\n font-size: px2em(32px);\n line-height: 1.3;\n letter-spacing: -0.01em;\n }\n\n // Headline on level 2\n h2 {\n margin: px2em(40px, 25px) 0 px2em(16px, 25px);\n font-weight: 300;\n font-size: px2em(25px);\n line-height: 1.4;\n letter-spacing: -0.01em;\n }\n\n // Headline on level 3\n h3 {\n margin: px2em(32px, 20px) 0 px2em(16px, 20px);\n font-weight: 400;\n font-size: px2em(20px);\n line-height: 1.5;\n letter-spacing: -0.01em;\n }\n\n // Headline on level 3 following level 2\n h2 + h3 {\n margin-top: px2em(16px, 20px);\n }\n\n // Headline on level 4\n h4 {\n margin: px2em(16px) 0;\n font-weight: 700;\n letter-spacing: -0.01em;\n }\n\n // Headline on level 5-6\n h5,\n h6 {\n margin: px2em(16px, 12.8px) 0;\n color: var(--md-default-fg-color--light);\n font-weight: 700;\n font-size: px2em(12.8px);\n letter-spacing: -0.01em;\n }\n\n // Headline on level 5\n h5 {\n text-transform: uppercase;\n }\n\n // Horizontal separator\n hr {\n display: flow-root;\n margin: 1.5em 0;\n border-bottom: px2rem(1px) solid var(--md-default-fg-color--lightest);\n }\n\n // Text link\n a {\n color: var(--md-typeset-a-color);\n word-break: break-word;\n\n // Also enable color transition on pseudo elements\n &,\n &::before {\n transition: color 125ms;\n }\n\n // Text link on focus/hover\n &:focus,\n &:hover {\n color: var(--md-accent-fg-color);\n }\n\n // Text link on keyboard focus\n &.focus-visible {\n outline-color: var(--md-accent-fg-color);\n outline-offset: px2rem(4px);\n }\n }\n\n // Code block\n code,\n pre,\n kbd {\n color: var(--md-code-fg-color);\n direction: ltr;\n\n // [print]: Wrap text and hide scollbars\n @media print {\n white-space: pre-wrap;\n }\n }\n\n // Inline code block\n code {\n padding: 0 px2em(4px, 13.6px);\n font-size: px2em(13.6px);\n word-break: break-word;\n background-color: var(--md-code-bg-color);\n border-radius: px2rem(2px);\n box-decoration-break: clone;\n\n // Hide outline for pointer devices\n &:not(.focus-visible) {\n outline: none;\n -webkit-tap-highlight-color: transparent;\n }\n }\n\n // Code block in headline\n h1 code,\n h2 code,\n h3 code,\n h4 code,\n h5 code,\n h6 code {\n margin: initial;\n padding: initial;\n background-color: transparent;\n box-shadow: none;\n }\n\n // Ensure link color in code blocks\n a code {\n color: currentColor;\n }\n\n // Unformatted content\n pre {\n position: relative;\n display: flow-root;\n line-height: 1.4;\n\n // Code block\n > code {\n display: block;\n margin: 0;\n padding: px2em(10.5px, 13.6px) px2em(16px, 13.6px);\n overflow: auto;\n word-break: normal;\n box-shadow: none;\n box-decoration-break: slice;\n touch-action: auto;\n scrollbar-width: thin;\n scrollbar-color: var(--md-default-fg-color--lighter) transparent;\n\n // Code block on hover\n &:hover {\n scrollbar-color: var(--md-accent-fg-color) transparent;\n }\n\n // Webkit scrollbar\n &::-webkit-scrollbar {\n width: px2rem(4px);\n height: px2rem(4px);\n }\n\n // Webkit scrollbar thumb\n &::-webkit-scrollbar-thumb {\n background-color: var(--md-default-fg-color--lighter);\n\n // Webkit scrollbar thumb on hover\n &:hover {\n background-color: var(--md-accent-fg-color);\n }\n }\n }\n }\n\n // [mobile -]: Align with body copy\n @include break-to-device(mobile) {\n\n // Unformatted text\n > pre {\n margin: 1em px2rem(-16px);\n\n // Code block\n code {\n border-radius: 0;\n }\n }\n }\n\n // Keyboard key\n kbd {\n display: inline-block;\n padding: 0 px2em(8px, 12px);\n color: var(--md-default-fg-color);\n font-size: px2em(12px);\n vertical-align: text-top;\n word-break: break-word;\n background-color: var(--md-typeset-kbd-color);\n border-radius: px2rem(2px);\n box-shadow:\n 0 px2rem(2px) 0 px2rem(1px) var(--md-typeset-kbd-border-color),\n 0 px2rem(2px) 0 var(--md-typeset-kbd-border-color),\n 0 px2rem(-2px) px2rem(4px) var(--md-typeset-kbd-accent-color) inset;\n }\n\n // Text highlighting marker\n mark {\n color: inherit;\n word-break: break-word;\n background-color: var(--md-typeset-mark-color);\n box-decoration-break: clone;\n }\n\n // Abbreviation\n abbr {\n text-decoration: none;\n border-bottom: px2rem(1px) dotted var(--md-default-fg-color--light);\n cursor: help;\n\n // Show tooltip for touch devices\n @media (hover: none) {\n position: relative;\n\n // Tooltip\n &[title]:focus::after,\n &[title]:hover::after {\n @include z-depth(2);\n\n position: absolute;\n left: 0;\n display: inline-block;\n width: auto;\n min-width: max-content;\n max-width: 80%;\n margin-top: 2em;\n padding: px2rem(4px) px2rem(6px);\n color: var(--md-default-bg-color);\n font-size: px2rem(14px);\n background-color: var(--md-default-fg-color);\n border-radius: px2rem(2px);\n content: attr(title);\n }\n }\n }\n\n // Small text\n small {\n opacity: 0.75;\n }\n\n // Superscript and subscript\n sup,\n sub {\n margin-left: px2em(1px, 12.8px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n margin-right: px2em(1px, 12.8px);\n margin-left: initial;\n }\n }\n\n // Blockquotes, possibly nested\n blockquote {\n display: flow-root;\n padding-left: px2rem(12px);\n color: var(--md-default-fg-color--light);\n border-left: px2rem(4px) solid var(--md-default-fg-color--lighter);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n padding-right: px2rem(12px);\n padding-left: initial;\n border-right: px2rem(4px) solid var(--md-default-fg-color--lighter);\n border-left: initial;\n }\n }\n\n // Unordered list\n ul {\n list-style-type: disc;\n }\n\n // Unordered and ordered list\n ul,\n ol {\n display: flow-root;\n margin-left: px2em(10px);\n padding: 0;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n margin-right: px2em(10px);\n margin-left: initial;\n }\n\n // Nested ordered list\n ol {\n list-style-type: lower-alpha;\n\n // Triply nested ordered list\n ol {\n list-style-type: lower-roman;\n }\n }\n\n // List element\n li {\n margin-bottom: 0.5em;\n margin-left: px2em(20px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n margin-right: px2em(20px);\n margin-left: initial;\n }\n\n // Adjust spacing\n p,\n blockquote {\n margin: 0.5em 0;\n }\n\n // Adjust spacing on last child\n &:last-child {\n margin-bottom: 0;\n }\n\n // Nested list\n ul,\n ol {\n margin: 0.5em 0 0.5em px2em(10px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n margin-right: px2em(10px);\n margin-left: initial;\n }\n }\n }\n }\n\n // Definition list\n dd {\n margin: 1em 0 1.5em px2em(30px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n margin-right: px2em(30px);\n margin-left: initial;\n }\n }\n\n // Image or icon\n img,\n svg {\n max-width: 100%;\n height: auto;\n\n // Adjust spacing when left-aligned\n &[align=\"left\"] {\n margin: 1em;\n margin-left: 0;\n }\n\n // Adjust spacing when right-aligned\n &[align=\"right\"] {\n margin: 1em;\n margin-right: 0;\n }\n\n // Adjust spacing when sole children\n &[align]:only-child {\n margin-top: 0;\n }\n }\n\n // Figure\n figure {\n display: flow-root;\n width: fit-content;\n max-width: 100%;\n margin: 0 auto;\n text-align: center;\n\n // Figure images\n img {\n display: block;\n }\n }\n\n // Figure caption\n figcaption {\n max-width: px2rem(480px);\n margin: 1em auto 2em;\n font-style: italic;\n }\n\n // Limit width to container\n iframe {\n max-width: 100%;\n }\n\n // Data table\n table:not([class]) {\n display: inline-block;\n max-width: 100%;\n overflow: auto;\n font-size: px2rem(12.8px);\n background-color: var(--md-default-bg-color);\n border-radius: px2rem(2px);\n box-shadow:\n 0 px2rem(4px) px2rem(10px) hsla(0, 0%, 0%, 0.05),\n 0 0 px2rem(1px) hsla(0, 0%, 0%, 0.1);\n touch-action: auto;\n\n // [print]: Reset display mode so table header wraps when printing\n @media print {\n display: table;\n }\n\n // Due to margin collapse because of the necessary inline-block hack, we\n // cannot increase the bottom margin on the table, so we just increase the\n // top margin on the following element\n + * {\n margin-top: 1.5em;\n }\n\n // Elements in table heading and cell\n th > *,\n td > * {\n\n // Adjust spacing on first child\n &:first-child {\n margin-top: 0;\n }\n\n // Adjust spacing on last child\n &:last-child {\n margin-bottom: 0;\n }\n }\n\n // Table heading and cell\n th:not([align]),\n td:not([align]) {\n text-align: left;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n text-align: right;\n }\n }\n\n // Table heading\n th {\n min-width: px2rem(100px);\n padding: px2em(12px, 12.8px) px2em(16px, 12.8px);\n color: var(--md-default-bg-color);\n vertical-align: top;\n background-color: var(--md-default-fg-color--light);\n\n // Links in table headings\n a {\n color: inherit;\n }\n }\n\n // Table cell\n td {\n padding: px2em(12px, 12.8px) px2em(16px, 12.8px);\n vertical-align: top;\n border-top: px2rem(1px) solid var(--md-default-fg-color--lightest);\n }\n\n // Table row\n tr {\n transition: background-color 125ms;\n\n // Table row on hover\n &:hover {\n background-color: rgba(0, 0, 0, 0.035);\n box-shadow: 0 px2rem(1px) 0 var(--md-default-bg-color) inset;\n }\n\n // Hide border on first table row\n &:first-child td {\n border-top: 0;\n }\n }\n\n // Text link in table\n a {\n word-break: normal;\n }\n }\n\n // Sortable table\n table th[role=\"columnheader\"] {\n cursor: pointer;\n\n // Sort icon\n &::after {\n display: inline-block;\n width: 1.2em;\n height: 1.2em;\n margin-left: 0.5em;\n vertical-align: sub;\n mask-repeat: no-repeat;\n mask-size: contain;\n content: \"\";\n }\n\n // Sort ascending\n &[aria-sort=\"ascending\"]::after {\n background-color: currentColor;\n mask-image: var(--md-typeset-table--ascending);\n }\n\n // Sort descending\n &[aria-sort=\"descending\"]::after {\n background-color: currentColor;\n mask-image: var(--md-typeset-table--descending);\n }\n }\n\n // Data table scroll wrapper\n &__scrollwrap {\n margin: 1em px2rem(-16px);\n overflow-x: auto;\n touch-action: auto;\n }\n\n // Data table wrapper\n &__table {\n display: inline-block;\n margin-bottom: 0.5em;\n padding: 0 px2rem(16px);\n\n // [print]: Reset display mode so table header wraps when printing\n @media print {\n display: block;\n }\n\n // Data table\n html & table {\n display: table;\n width: 100%;\n margin: 0;\n overflow: hidden;\n }\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Variables\n// ----------------------------------------------------------------------------\n\n///\n/// Device-specific breakpoints\n///\n/// @example\n/// $break-devices: (\n/// mobile: (\n/// portrait: 220px 479px,\n/// landscape: 480px 719px\n/// ),\n/// tablet: (\n/// portrait: 720px 959px,\n/// landscape: 960px 1219px\n/// ),\n/// screen: (\n/// small: 1220px 1599px,\n/// medium: 1600px 1999px,\n/// large: 2000px\n/// )\n/// );\n///\n$break-devices: () !default;\n\n// ----------------------------------------------------------------------------\n// Helpers\n// ----------------------------------------------------------------------------\n\n///\n/// Choose minimum and maximum device widths\n///\n@function break-select-min-max($devices) {\n $min: 1000000;\n $max: 0;\n @each $key, $value in $devices {\n @while type-of($value) == map {\n $value: break-select-min-max($value);\n }\n @if type-of($value) == list {\n @each $number in $value {\n @if type-of($number) == number {\n $min: min($number, $min);\n @if $max {\n $max: max($number, $max);\n }\n } @else {\n @error \"Invalid number: #{$number}\";\n }\n }\n } @else if type-of($value) == number {\n $min: min($value, $min);\n $max: null;\n } @else {\n @error \"Invalid value: #{$value}\";\n }\n }\n @return $min, $max;\n}\n\n///\n/// Select minimum and maximum widths for a device breakpoint\n///\n@function break-select-device($device) {\n $current: $break-devices;\n @for $n from 1 through length($device) {\n @if type-of($current) == map {\n $current: map-get($current, nth($device, $n));\n } @else {\n @error \"Invalid device map: #{$devices}\";\n }\n }\n @if type-of($current) == list or type-of($current) == number {\n $current: (default: $current);\n }\n @return break-select-min-max($current);\n}\n\n// ----------------------------------------------------------------------------\n// Mixins\n// ----------------------------------------------------------------------------\n\n///\n/// A minimum-maximum media query breakpoint\n///\n@mixin break-at($breakpoint) {\n @if type-of($breakpoint) == number {\n @media screen and (min-width: $breakpoint) {\n @content;\n }\n } @else if type-of($breakpoint) == list {\n $min: nth($breakpoint, 1);\n $max: nth($breakpoint, 2);\n @if type-of($min) == number and type-of($max) == number {\n @media screen and (min-width: $min) and (max-width: $max) {\n @content;\n }\n } @else {\n @error \"Invalid breakpoint: #{$breakpoint}\";\n }\n } @else {\n @error \"Invalid breakpoint: #{$breakpoint}\";\n }\n}\n\n///\n/// An orientation media query breakpoint\n///\n@mixin break-at-orientation($breakpoint) {\n @if type-of($breakpoint) == string {\n @media screen and (orientation: $breakpoint) {\n @content;\n }\n } @else {\n @error \"Invalid breakpoint: #{$breakpoint}\";\n }\n}\n\n///\n/// A maximum-aspect-ratio media query breakpoint\n///\n@mixin break-at-ratio($breakpoint) {\n @if type-of($breakpoint) == number {\n @media screen and (max-aspect-ratio: $breakpoint) {\n @content;\n }\n } @else {\n @error \"Invalid breakpoint: #{$breakpoint}\";\n }\n}\n\n///\n/// A minimum-maximum media query device breakpoint\n///\n@mixin break-at-device($device) {\n @if type-of($device) == string {\n $device: $device,;\n }\n @if type-of($device) == list {\n $breakpoint: break-select-device($device);\n @if nth($breakpoint, 2) {\n $min: nth($breakpoint, 1);\n $max: nth($breakpoint, 2);\n\n @media screen and (min-width: $min) and (max-width: $max) {\n @content;\n }\n } @else {\n @error \"Invalid device: #{$device}\";\n }\n } @else {\n @error \"Invalid device: #{$device}\";\n }\n}\n\n///\n/// A minimum media query device breakpoint\n///\n@mixin break-from-device($device) {\n @if type-of($device) == string {\n $device: $device,;\n }\n @if type-of($device) == list {\n $breakpoint: break-select-device($device);\n $min: nth($breakpoint, 1);\n\n @media screen and (min-width: $min) {\n @content;\n }\n } @else {\n @error \"Invalid device: #{$device}\";\n }\n}\n\n///\n/// A maximum media query device breakpoint\n///\n@mixin break-to-device($device) {\n @if type-of($device) == string {\n $device: $device,;\n }\n @if type-of($device) == list {\n $breakpoint: break-select-device($device);\n $max: nth($breakpoint, 2);\n\n @media screen and (max-width: $max) {\n @content;\n }\n } @else {\n @error \"Invalid device: #{$device}\";\n }\n}\n","//\n// Name: Material Shadows\n// Description: Mixins for Material Design Shadows.\n// Version: 3.0.1\n//\n// Author: Denis Malinochkin\n// Git: https://github.com/mrmlnc/material-shadows\n//\n// twitter: @mrmlnc\n//\n// ------------------------------------\n\n\n// Mixins\n// ------------------------------------\n\n@mixin z-depth-transition() {\n transition: box-shadow .28s cubic-bezier(.4, 0, .2, 1);\n}\n\n@mixin z-depth-focus() {\n box-shadow: 0 0 8px rgba(0, 0, 0, .18), 0 8px 16px rgba(0, 0, 0, .36);\n}\n\n@mixin z-depth-2dp() {\n box-shadow: 0 2px 2px 0 rgba(0, 0, 0, .14),\n 0 1px 5px 0 rgba(0, 0, 0, .12),\n 0 3px 1px -2px rgba(0, 0, 0, .2);\n}\n\n@mixin z-depth-3dp() {\n box-shadow: 0 3px 4px 0 rgba(0, 0, 0, .14),\n 0 1px 8px 0 rgba(0, 0, 0, .12),\n 0 3px 3px -2px rgba(0, 0, 0, .4);\n}\n\n@mixin z-depth-4dp() {\n box-shadow: 0 4px 5px 0 rgba(0, 0, 0, .14),\n 0 1px 10px 0 rgba(0, 0, 0, .12),\n 0 2px 4px -1px rgba(0, 0, 0, .4);\n}\n\n@mixin z-depth-6dp() {\n box-shadow: 0 6px 10px 0 rgba(0, 0, 0, .14),\n 0 1px 18px 0 rgba(0, 0, 0, .12),\n 0 3px 5px -1px rgba(0, 0, 0, .4);\n}\n\n@mixin z-depth-8dp() {\n box-shadow: 0 8px 10px 1px rgba(0, 0, 0, .14),\n 0 3px 14px 2px rgba(0, 0, 0, .12),\n 0 5px 5px -3px rgba(0, 0, 0, .4);\n}\n\n@mixin z-depth-16dp() {\n box-shadow: 0 16px 24px 2px rgba(0, 0, 0, .14),\n 0 6px 30px 5px rgba(0, 0, 0, .12),\n 0 8px 10px -5px rgba(0, 0, 0, .4);\n}\n\n@mixin z-depth-24dp() {\n box-shadow: 0 9px 46px 8px rgba(0, 0, 0, .14),\n 0 24px 38px 3px rgba(0, 0, 0, .12),\n 0 11px 15px -7px rgba(0, 0, 0, .4);\n}\n\n@mixin z-depth($dp: 2) {\n @if $dp == 2 {\n @include z-depth-2dp();\n } @else if $dp == 3 {\n @include z-depth-3dp();\n } @else if $dp == 4 {\n @include z-depth-4dp();\n } @else if $dp == 6 {\n @include z-depth-6dp();\n } @else if $dp == 8 {\n @include z-depth-8dp();\n } @else if $dp == 16 {\n @include z-depth-16dp();\n } @else if $dp == 24 {\n @include z-depth-24dp();\n }\n}\n\n\n// Class generator\n// ------------------------------------\n\n@mixin z-depth-classes($transition: false, $focus: false) {\n @if $transition == true {\n &-transition {\n @include z-depth-transition();\n }\n }\n\n @if $focus == true {\n &-focus {\n @include z-depth-focus();\n }\n }\n\n // The available values for the shadow depth\n @each $depth in 2, 3, 4, 6, 8, 16, 24 {\n &-#{$depth}dp {\n @include z-depth($depth);\n }\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules: base grid and containers\n// ----------------------------------------------------------------------------\n\n// Stretch container to viewport and set base `font-size`\nhtml {\n height: 100%;\n overflow-x: hidden;\n // Hack: normally, we would set the base `font-size` to `62.5%`, so we can\n // base all calculations on `10px`, but Chromium and Chrome define a minimal\n // `font-size` of `12px` if the system language is set to Chinese. For this\n // reason we just double the `font-size` and set it to `20px`.\n //\n // See https://github.com/squidfunk/mkdocs-material/issues/911\n font-size: 125%;\n\n // [screen medium +]: Set base `font-size` to `11px`\n @include break-from-device(screen medium) {\n font-size: 137.5%;\n }\n\n // [screen large +]: Set base `font-size` to `12px`\n @include break-from-device(screen large) {\n font-size: 150%;\n }\n}\n\n// Stretch body to container - flexbox is used, so the footer will always be\n// aligned to the bottom of the viewport\nbody {\n position: relative;\n display: flex;\n flex-direction: column;\n width: 100%;\n min-height: 100%;\n // Hack: reset `font-size` to `10px`, so the spacing for all inline elements\n // is correct again. Otherwise the spacing would be based on `20px`.\n font-size: px2rem(10px);\n background-color: var(--md-default-bg-color);\n\n // [print]: Omit flexbox layout due to a Firefox bug (https://mzl.la/39DgR3m)\n @media print {\n display: block;\n }\n\n // Body in locked state\n &[data-md-state=\"lock\"] {\n\n // [tablet portrait -]: Omit scroll bubbling\n @include break-to-device(tablet portrait) {\n position: fixed;\n }\n }\n}\n\n// ----------------------------------------------------------------------------\n\n// Grid container - this class is applied to wrapper elements within the\n// header, content area and footer, and makes sure that their width is limited\n// to `1220px`, and they are rendered centered if the screen is larger.\n.md-grid {\n max-width: px2rem(1220px);\n margin-right: auto;\n margin-left: auto;\n}\n\n// Main container\n.md-container {\n display: flex;\n flex-direction: column;\n flex-grow: 1;\n\n // [print]: Omit flexbox layout due to a Firefox bug (https://mzl.la/39DgR3m)\n @media print {\n display: block;\n }\n}\n\n// Main area - stretch to remaining space of container\n.md-main {\n flex-grow: 1;\n\n // Main area wrapper\n &__inner {\n display: flex;\n height: 100%;\n margin-top: px2rem(24px + 6px);\n }\n}\n\n// Add ellipsis in case of overflowing text\n.md-ellipsis {\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n\n// ----------------------------------------------------------------------------\n// Rules: navigational elements\n// ----------------------------------------------------------------------------\n\n// Toggle - this class is applied to checkbox elements, which are used to\n// implement the CSS-only drawer and navigation, as well as the search\n.md-toggle {\n display: none;\n}\n\n// Option - this class is applied to radio elements, which are used to\n// implement the color palette toggle\n.md-option {\n position: absolute;\n width: 0;\n height: 0;\n opacity: 0;\n\n // Option label for checked radio button\n &:checked + label:not([hidden]) {\n display: block;\n }\n\n // Show outline for pointer devices\n &.focus-visible + label {\n outline-style: auto;\n outline-color: var(--md-accent-fg-color);\n }\n}\n\n// Skip link\n.md-skip {\n position: fixed;\n // Hack: if we don't set the negative `z-index`, the skip link will force the\n // creation of new layers when code blocks are near the header on scrolling\n z-index: -1;\n margin: px2rem(10px);\n padding: px2rem(6px) px2rem(10px);\n color: var(--md-default-bg-color);\n font-size: px2rem(12.8px);\n background-color: var(--md-default-fg-color);\n border-radius: px2rem(2px);\n outline-color: var(--md-accent-fg-color);\n transform: translateY(px2rem(8px));\n opacity: 0;\n\n // Show skip link on focus\n &:focus {\n z-index: 10;\n transform: translateY(0);\n opacity: 1;\n transition:\n transform 250ms cubic-bezier(0.4, 0, 0.2, 1),\n opacity 175ms 75ms;\n }\n}\n\n// ----------------------------------------------------------------------------\n// Rules: print styles\n// ----------------------------------------------------------------------------\n\n// Add margins to page\n@page {\n margin: 25mm;\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Announcement bar\n.md-announce {\n overflow: auto;\n background-color: var(--md-footer-bg-color);\n\n // [print]: Hide announcement bar\n @media print {\n display: none;\n }\n\n // Announcement wrapper\n &__inner {\n margin: px2rem(12px) auto;\n padding: 0 px2rem(16px);\n color: var(--md-footer-fg-color);\n font-size: px2rem(14px);\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Icon definitions\n:root {\n --md-clipboard-icon: svg-load(\"material/content-copy.svg\");\n}\n\n// ----------------------------------------------------------------------------\n\n// Button to copy to clipboard\n.md-clipboard {\n position: absolute;\n top: px2em(8px);\n right: px2em(8px);\n z-index: 1;\n width: px2em(24px);\n height: px2em(24px);\n color: var(--md-default-fg-color--lightest);\n border-radius: px2rem(2px);\n outline-color: var(--md-accent-fg-color);\n outline-offset: px2rem(2px);\n cursor: pointer;\n transition: color 250ms;\n\n // [print]: Hide button\n @media print {\n display: none;\n }\n\n // Hide outline for pointer devices\n &:not(.focus-visible) {\n outline: none;\n -webkit-tap-highlight-color: transparent;\n }\n\n // Darken color on code block hover\n :hover > & {\n color: var(--md-default-fg-color--light);\n }\n\n // Button on focus/hover\n &:focus,\n &:hover {\n color: var(--md-accent-fg-color);\n }\n\n // Button icon - the width and height are defined in `em`, so the size is\n // automatically adjusted for nested code blocks (e.g. in admonitions)\n &::after {\n display: block;\n width: px2em(18px);\n height: px2em(18px);\n margin: 0 auto;\n background-color: currentColor;\n mask-image: var(--md-clipboard-icon);\n mask-repeat: no-repeat;\n mask-size: contain;\n content: \"\";\n }\n\n // Inline button\n &--inline {\n cursor: pointer;\n\n // Code block\n code {\n transition:\n color 250ms,\n background-color 250ms;\n }\n\n // Code block on focus/hover\n &:focus code,\n &:hover code {\n color: var(--md-accent-fg-color);\n background-color: var(--md-accent-fg-color--transparent);\n }\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Content area\n.md-content {\n flex-grow: 1;\n // Hack: we must use `overflow: hidden`, so the content area is capped by\n // the dimensions of its parent. Otherwise, long code blocks might lead to\n // a wider content area which will break everything. This, however, induces\n // margin collapse, which will break scroll margins. Adding a large enough\n // scroll padding seems to do the trick, at least in Chrome and Firefox.\n overflow: hidden;\n scroll-padding-top: px2rem(1024px);\n\n // Content wrapper\n &__inner {\n margin: 0 px2rem(16px) px2rem(24px);\n padding-top: px2rem(12px);\n\n // [screen +]: Adjust spacing between content area and sidebars\n @include break-from-device(screen) {\n\n // Sidebar with navigation is visible\n .md-sidebar--primary:not([hidden]) ~ .md-content > & {\n margin-left: px2rem(24px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n margin-right: px2rem(24px);\n margin-left: px2rem(16px);\n }\n }\n\n // Sidebar with table of contents is visible\n .md-sidebar--secondary:not([hidden]) ~ .md-content > & {\n margin-right: px2rem(24px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n margin-right: px2rem(16px);\n margin-left: px2rem(24px);\n }\n }\n }\n\n // Hack: add pseudo element for spacing, as the overflow of the content\n // container may not be hidden due to an imminent offset error on targets\n &::before {\n display: block;\n height: px2rem(8px);\n content: \"\";\n }\n\n // Adjust spacing on last child\n > :last-child {\n margin-bottom: 0;\n }\n }\n\n // Button inside of the content area - these buttons are meant for actions on\n // a document-level, i.e. linking to related source code files, printing etc.\n &__button {\n float: right;\n margin: px2rem(8px) 0;\n margin-left: px2rem(8px);\n padding: 0;\n\n // [print]: Hide buttons\n @media print {\n display: none;\n }\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n float: left;\n margin-right: px2rem(8px);\n margin-left: initial;\n\n // Flip icon vertically\n svg {\n transform: scaleX(-1);\n }\n }\n\n // Adjust default link color for icons\n .md-typeset & {\n color: var(--md-default-fg-color--lighter);\n }\n\n // Align with body copy located next to icon\n svg {\n display: inline;\n vertical-align: top;\n }\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Dialog\n.md-dialog {\n @include z-depth(2);\n\n position: fixed;\n right: px2rem(16px);\n bottom: px2rem(16px);\n left: initial;\n z-index: 3;\n min-width: px2rem(222px);\n padding: px2rem(8px) px2rem(12px);\n background-color: var(--md-default-fg-color);\n border-radius: px2rem(2px);\n transform: translateY(100%);\n opacity: 0;\n transition:\n transform 0ms 400ms,\n opacity 400ms;\n pointer-events: none;\n\n // [print]: Hide dialog\n @media print {\n display: none;\n }\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n right: initial;\n left: px2rem(16px);\n }\n\n // Dialog in open state\n &[data-md-state=\"open\"] {\n transform: translateY(0);\n opacity: 1;\n transition:\n transform 400ms cubic-bezier(0.075, 0.85, 0.175, 1),\n opacity 400ms;\n pointer-events: initial;\n }\n\n // Dialog wrapper\n &__inner {\n color: var(--md-default-bg-color);\n font-size: px2rem(14px);\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Scoped in typesetted content to match specificity of regular content\n.md-typeset {\n\n // Form button\n .md-button {\n display: inline-block;\n padding: px2em(10px) px2em(32px);\n color: var(--md-primary-fg-color);\n font-weight: 700;\n border: px2rem(2px) solid currentColor;\n border-radius: px2rem(2px);\n cursor: pointer;\n transition:\n color 125ms,\n background-color 125ms,\n border-color 125ms;\n\n // Primary button\n &--primary {\n color: var(--md-primary-bg-color);\n background-color: var(--md-primary-fg-color);\n border-color: var(--md-primary-fg-color);\n }\n\n // Button on focus/hover\n &:focus,\n &:hover {\n color: var(--md-accent-bg-color);\n background-color: var(--md-accent-fg-color);\n border-color: var(--md-accent-fg-color);\n }\n }\n\n // Form input\n .md-input {\n height: px2rem(36px);\n padding: 0 px2rem(12px);\n font-size: px2rem(16px);\n border-radius: px2rem(2px);\n box-shadow:\n 0 px2rem(4px) px2rem(10px) hsla(0, 0%, 0%, 0.1),\n 0 px2rem(0.5px) px2rem(1px) hsla(0, 0%, 0%, 0.1);\n transition: box-shadow 250ms;\n\n // Input on focus/hover\n &:focus,\n &:hover {\n box-shadow:\n 0 px2rem(8px) px2rem(20px) hsla(0, 0%, 0%, 0.15),\n 0 px2rem(0.5px) px2rem(1px) hsla(0, 0%, 0%, 0.15);\n }\n\n // Stretch to full width\n &--stretch {\n width: 100%;\n }\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Header - by default, the header will be sticky and stay always on top of the\n// viewport. If this behavior is not desired, just set `position: static`.\n.md-header {\n position: sticky;\n top: 0;\n right: 0;\n left: 0;\n z-index: 3;\n color: var(--md-primary-bg-color);\n background-color: var(--md-primary-fg-color);\n // Hack: reduce jitter by adding a transparent box shadow of the same size\n // so the size of the layer doesn't change during animation\n box-shadow:\n 0 0 px2rem(4px) rgba(0, 0, 0, 0),\n 0 px2rem(4px) px2rem(8px) rgba(0, 0, 0, 0);\n\n // [print]: Hide header\n @media print {\n display: none;\n }\n\n // Header in shadow state, i.e. shadow is visible\n &[data-md-state=\"shadow\"] {\n box-shadow:\n 0 0 px2rem(4px) rgba(0, 0, 0, 0.1),\n 0 px2rem(4px) px2rem(8px) rgba(0, 0, 0, 0.2);\n transition:\n transform 250ms cubic-bezier(0.1, 0.7, 0.1, 1),\n box-shadow 250ms;\n }\n\n // Header in hidden state, i.e. moved out of sight\n &[data-md-state=\"hidden\"] {\n transform: translateY(-100%);\n transition:\n transform 250ms cubic-bezier(0.8, 0, 0.6, 1),\n box-shadow 250ms;\n }\n\n // Header wrapper\n &__inner {\n display: flex;\n align-items: center;\n padding: 0 px2rem(4px);\n }\n\n // Header button\n &__button {\n position: relative;\n z-index: 1;\n margin: px2rem(4px);\n padding: px2rem(8px);\n color: currentColor;\n vertical-align: middle;\n outline-color: var(--md-accent-fg-color);\n cursor: pointer;\n transition: opacity 250ms;\n\n // Button on hover\n &:hover {\n opacity: 0.7;\n }\n\n // Header button is visible\n &:not([hidden]) {\n display: inline-block;\n }\n\n // Hide outline for pointer devices\n &:not(.focus-visible) {\n outline: none;\n -webkit-tap-highlight-color: transparent;\n }\n\n // Button with logo, pointing to `config.site_url`\n &.md-logo {\n margin: px2rem(4px);\n padding: px2rem(8px);\n\n // [tablet -]: Hide button\n @include break-to-device(tablet) {\n display: none;\n }\n\n // Image or icon\n img,\n svg {\n display: block;\n width: px2rem(24px);\n height: px2rem(24px);\n fill: currentColor;\n }\n }\n\n // Button for search\n &[for=\"__search\"] {\n\n // [tablet landscape +]: Hide button\n @include break-from-device(tablet landscape) {\n display: none;\n }\n\n // [no-js]: Hide button\n .no-js & {\n display: none;\n }\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n\n // Flip icon vertically\n svg {\n transform: scaleX(-1);\n }\n }\n }\n\n // Button for drawer\n &[for=\"__drawer\"] {\n\n // [screen +]: Hide button\n @include break-from-device(screen) {\n display: none;\n }\n }\n }\n\n // Header topic\n &__topic {\n position: absolute;\n display: flex;\n max-width: 100%;\n transition:\n transform 400ms cubic-bezier(0.1, 0.7, 0.1, 1),\n opacity 150ms;\n\n // Second header topic - title of the current page\n & + & {\n z-index: -1;\n transform: translateX(px2rem(25px));\n opacity: 0;\n transition:\n transform 400ms cubic-bezier(1, 0.7, 0.1, 0.1),\n opacity 150ms;\n pointer-events: none;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n transform: translateX(px2rem(-25px));\n }\n }\n }\n\n // Header title\n &__title {\n flex-grow: 1;\n height: px2rem(48px);\n margin-right: px2rem(8px);\n margin-left: px2rem(20px);\n font-size: px2rem(18px);\n line-height: px2rem(48px);\n\n // Header title in active state, i.e. page title is visible\n &[data-md-state=\"active\"] .md-header__topic {\n z-index: -1;\n transform: translateX(px2rem(-25px));\n opacity: 0;\n transition:\n transform 400ms cubic-bezier(1, 0.7, 0.1, 0.1),\n opacity 150ms;\n pointer-events: none;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n transform: translateX(px2rem(25px));\n }\n\n // Second header topic - title of the current page\n + .md-header__topic {\n z-index: 0;\n transform: translateX(0);\n opacity: 1;\n transition:\n transform 400ms cubic-bezier(0.1, 0.7, 0.1, 1),\n opacity 150ms;\n pointer-events: initial;\n }\n }\n\n // Add ellipsis in case of overflowing text\n > .md-header__ellipsis {\n position: relative;\n width: 100%;\n height: 100%;\n }\n }\n\n // Header option\n &__option {\n display: flex;\n flex-shrink: 0;\n max-width: 100%;\n white-space: nowrap;\n transition:\n max-width 0ms 250ms,\n opacity 250ms 250ms;\n\n // Hide toggle when search is active\n [data-md-toggle=\"search\"]:checked ~ .md-header & {\n max-width: 0;\n opacity: 0;\n transition:\n max-width 0ms,\n opacity 0ms;\n }\n }\n\n // Repository information container\n &__source {\n display: none;\n\n // [tablet landscape +]: Show repository information\n @include break-from-device(tablet landscape) {\n display: block;\n width: px2rem(234px);\n max-width: px2rem(234px);\n margin-left: px2rem(20px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n margin-right: px2rem(20px);\n margin-left: initial;\n }\n }\n\n // [screen +]: Adjust spacing of search bar\n @include break-from-device(screen) {\n margin-left: px2rem(28px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n margin-right: px2rem(28px);\n }\n }\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Footer\n.md-footer {\n color: var(--md-footer-fg-color);\n background-color: var(--md-footer-bg-color);\n\n // [print]: Hide footer\n @media print {\n display: none;\n }\n\n // Footer wrapper\n &__inner {\n padding: px2rem(4px);\n overflow: auto;\n }\n\n // Footer link to previous and next page\n &__link {\n display: flex;\n padding-top: px2rem(28px);\n padding-bottom: px2rem(8px);\n outline-color: var(--md-accent-fg-color);\n transition: opacity 250ms;\n\n // [tablet +]: Adjust width to 50/50\n @include break-from-device(tablet) {\n width: 50%;\n }\n\n // Footer link on focus/hover\n &:focus,\n &:hover {\n opacity: 0.7;\n }\n\n // Footer link to previous page\n &--prev {\n float: left;\n\n // [mobile -]: Adjust width to 25/75 and hide title\n @include break-to-device(mobile) {\n width: 25%;\n\n // Hide footer title\n .md-footer__title {\n display: none;\n }\n }\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n float: right;\n\n // Flip icon vertically\n svg {\n transform: scaleX(-1);\n }\n }\n }\n\n // Footer link to next page\n &--next {\n float: right;\n text-align: right;\n\n // [mobile -]: Adjust width to 25/75\n @include break-to-device(mobile) {\n width: 75%;\n }\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n float: left;\n text-align: left;\n\n // Flip icon vertically\n svg {\n transform: scaleX(-1);\n }\n }\n }\n }\n\n // Footer title\n &__title {\n position: relative;\n flex-grow: 1;\n max-width: calc(100% - #{px2rem(48px)});\n padding: 0 px2rem(20px);\n font-size: px2rem(18px);\n line-height: px2rem(48px);\n }\n\n // Footer link button\n &__button {\n margin: px2rem(4px);\n padding: px2rem(8px);\n }\n\n // Footer link direction (i.e. prev and next)\n &__direction {\n position: absolute;\n right: 0;\n left: 0;\n margin-top: px2rem(-20px);\n padding: 0 px2rem(20px);\n font-size: px2rem(12.8px);\n opacity: 0.7;\n }\n}\n\n// Footer metadata\n.md-footer-meta {\n background-color: var(--md-footer-bg-color--dark);\n\n // Footer metadata wrapper\n &__inner {\n display: flex;\n flex-wrap: wrap;\n justify-content: space-between;\n padding: px2rem(4px);\n }\n\n // Lighten color for non-hovered text links\n html &.md-typeset a {\n color: var(--md-footer-fg-color--light);\n\n // Text link on focus/hover\n &:focus,\n &:hover {\n color: var(--md-footer-fg-color);\n }\n }\n}\n\n// Footer copyright and theme information\n.md-footer-copyright {\n width: 100%;\n margin: auto px2rem(12px);\n padding: px2rem(8px) 0;\n color: var(--md-footer-fg-color--lighter);\n font-size: px2rem(12.8px);\n\n // [tablet portrait +]: Show copyright and social links in one line\n @include break-from-device(tablet portrait) {\n width: auto;\n }\n\n // Footer copyright highlight - this is the upper part of the copyright and\n // theme information, which will include a darker color than the theme link\n &__highlight {\n color: var(--md-footer-fg-color--light);\n }\n}\n\n// Footer social links\n.md-footer-social {\n margin: 0 px2rem(8px);\n padding: px2rem(4px) 0 px2rem(12px);\n\n // [tablet portrait +]: Show copyright and social links in one line\n @include break-from-device(tablet portrait) {\n padding: px2rem(12px) 0;\n }\n\n // Footer social link\n &__link {\n display: inline-block;\n width: px2rem(32px);\n height: px2rem(32px);\n text-align: center;\n\n // Adjust line-height to match height for correct alignment\n &::before {\n line-height: 1.9;\n }\n\n // Fill icon with current color\n svg {\n max-height: px2rem(16px);\n vertical-align: -25%;\n fill: currentColor;\n }\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Icon definitions\n:root {\n --md-nav-icon--prev: svg-load(\"material/arrow-left.svg\");\n --md-nav-icon--next: svg-load(\"material/chevron-right.svg\");\n --md-toc-icon: svg-load(\"material/table-of-contents.svg\");\n}\n\n// ----------------------------------------------------------------------------\n\n// Navigation\n.md-nav {\n font-size: px2rem(14px);\n line-height: 1.3;\n\n // Navigation title\n &__title {\n display: block;\n padding: 0 px2rem(12px);\n overflow: hidden;\n font-weight: 700;\n text-overflow: ellipsis;\n\n // Navigaton button\n .md-nav__button {\n display: none;\n\n // Stretch images based on height, as it's the smaller dimension\n img {\n width: auto;\n height: 100%;\n }\n\n // Button with logo, pointing to `config.site_url`\n &.md-logo {\n\n // Image or icon\n img,\n svg {\n display: block;\n width: px2rem(48px);\n height: px2rem(48px);\n fill: currentColor;\n }\n }\n }\n }\n\n // Navigation list\n &__list {\n margin: 0;\n padding: 0;\n list-style: none;\n }\n\n // Navigation item\n &__item {\n padding: 0 px2rem(12px);\n\n // Navigation item on level 2\n & & {\n padding-right: 0;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n padding-right: px2rem(12px);\n padding-left: 0;\n }\n }\n }\n\n // Navigation link\n &__link {\n display: block;\n margin-top: 0.625em;\n overflow: hidden;\n text-overflow: ellipsis;\n cursor: pointer;\n transition: color 125ms;\n scroll-snap-align: start;\n\n // Link in blurred state\n &[data-md-state=\"blur\"] {\n color: var(--md-default-fg-color--light);\n }\n\n // Active link\n .md-nav__item &--active {\n color: var(--md-typeset-a-color);\n }\n\n // Navigation link in nested list\n .md-nav__item--nested > & {\n color: inherit;\n }\n\n // Navigation link on focus/hover\n &:focus,\n &:hover {\n color: var(--md-accent-fg-color);\n }\n\n // Navigation link on keyboard focus\n &.focus-visible {\n outline-color: var(--md-accent-fg-color);\n outline-offset: px2rem(4px);\n }\n\n // Navigation link to table of contents\n .md-nav--primary &[for=\"__toc\"] {\n display: none;\n\n // Table of contents icon\n .md-icon::after {\n display: block;\n width: 100%;\n height: 100%;\n mask-image: var(--md-toc-icon);\n background-color: currentColor;\n }\n\n // Hide table of contents\n ~ .md-nav {\n display: none;\n }\n }\n }\n\n // Repository information container\n &__source {\n display: none;\n }\n\n // [tablet -]: Layered navigation\n @include break-to-device(tablet) {\n\n // Primary and nested navigation\n &--primary,\n &--primary & {\n position: absolute;\n top: 0;\n right: 0;\n left: 0;\n z-index: 1;\n display: flex;\n flex-direction: column;\n height: 100%;\n background-color: var(--md-default-bg-color);\n }\n\n // Primary navigation\n &--primary {\n\n // Navigation title and item\n .md-nav__title,\n .md-nav__item {\n font-size: px2rem(16px);\n line-height: 1.5;\n }\n\n // Navigation title\n .md-nav__title {\n position: relative;\n height: px2rem(112px);\n padding: px2rem(60px) px2rem(16px) px2rem(4px);\n color: var(--md-default-fg-color--light);\n font-weight: 400;\n line-height: px2rem(48px);\n white-space: nowrap;\n background-color: var(--md-default-fg-color--lightest);\n cursor: pointer;\n\n // Navigation icon\n .md-nav__icon {\n position: absolute;\n top: px2rem(8px);\n left: px2rem(8px);\n display: block;\n width: px2rem(24px);\n height: px2rem(24px);\n margin: px2rem(4px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n right: px2rem(8px);\n left: initial;\n }\n\n // Navigation icon in link to previous level\n &::after {\n display: block;\n width: 100%;\n height: 100%;\n background-color: currentColor;\n mask-image: var(--md-nav-icon--prev);\n mask-repeat: no-repeat;\n mask-size: contain;\n content: \"\";\n }\n }\n\n // Navigation list\n ~ .md-nav__list {\n overflow-y: auto;\n background-color: var(--md-default-bg-color);\n box-shadow:\n 0 px2rem(1px) 0 var(--md-default-fg-color--lightest) inset;\n scroll-snap-type: y mandatory;\n touch-action: pan-y;\n\n // Omit border on first child\n > :first-child {\n border-top: 0;\n }\n }\n\n // Top-level navigation title\n &[for=\"__drawer\"] {\n color: var(--md-primary-bg-color);\n background-color: var(--md-primary-fg-color);\n }\n\n // Button with logo, pointing to `config.site_url`\n .md-logo {\n position: absolute;\n top: px2rem(4px);\n left: px2rem(4px);\n display: block;\n margin: px2rem(4px);\n padding: px2rem(8px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n right: px2rem(4px);\n left: initial;\n }\n }\n }\n\n // Navigation list\n .md-nav__list {\n flex: 1;\n }\n\n // Navigation item\n .md-nav__item {\n padding: 0;\n border-top: px2rem(1px) solid var(--md-default-fg-color--lightest);\n\n // Navigation link in nested navigation\n &--nested > .md-nav__link {\n padding-right: px2rem(48px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n padding-right: px2rem(16px);\n padding-left: px2rem(48px);\n }\n }\n\n // Navigation link in active navigation\n &--active > .md-nav__link {\n color: var(--md-typeset-a-color);\n\n // Navigation link on focus/hover\n &:focus,\n &:hover {\n color: var(--md-accent-fg-color);\n }\n }\n }\n\n // Navigation link\n .md-nav__link {\n position: relative;\n margin-top: 0;\n padding: px2rem(12px) px2rem(16px);\n\n // Navigation icon\n .md-nav__icon {\n position: absolute;\n top: 50%;\n right: px2rem(12px);\n width: px2rem(24px);\n height: px2rem(24px);\n margin-top: px2rem(-12px);\n color: inherit;\n font-size: px2rem(24px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n right: initial;\n left: px2rem(12px);\n }\n\n // Navigation icon in link to next level\n &::after {\n display: block;\n width: 100%;\n height: 100%;\n background-color: currentColor;\n mask-image: var(--md-nav-icon--next);\n mask-repeat: no-repeat;\n mask-size: contain;\n content: \"\";\n }\n }\n }\n\n // Flip icon vertically\n .md-nav__icon {\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] &::after {\n transform: scale(-1);\n }\n }\n\n // Table of contents contained in primary navigation\n .md-nav--secondary {\n\n // Navigation link - omit unnecessary layering\n .md-nav__link {\n position: static;\n }\n\n // Navigation on level 2-6\n .md-nav {\n position: static;\n background-color: transparent;\n\n // Navigation link on level 3\n .md-nav__link {\n padding-left: px2rem(28px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n padding-right: px2rem(28px);\n padding-left: initial;\n }\n }\n\n // Navigation link on level 4\n .md-nav .md-nav__link {\n padding-left: px2rem(40px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n padding-right: px2rem(40px);\n padding-left: initial;\n }\n }\n\n // Navigation link on level 5\n .md-nav .md-nav .md-nav__link {\n padding-left: px2rem(52px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n padding-right: px2rem(52px);\n padding-left: initial;\n }\n }\n\n // Navigation link on level 6\n .md-nav .md-nav .md-nav .md-nav__link {\n padding-left: px2rem(64px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n padding-right: px2rem(64px);\n padding-left: initial;\n }\n }\n }\n }\n }\n\n // Table of contents\n &--secondary {\n background-color: transparent;\n }\n\n // Toggle for nested navigation\n &__toggle ~ & {\n display: flex;\n transform: translateX(100%);\n opacity: 0;\n transition:\n transform 250ms cubic-bezier(0.8, 0, 0.6, 1),\n opacity 125ms 50ms;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n transform: translateX(-100%);\n }\n }\n\n // Show nested navigation when toggle is active\n &__toggle:checked ~ & {\n transform: translateX(0);\n opacity: 1;\n transition:\n transform 250ms cubic-bezier(0.4, 0, 0.2, 1),\n opacity 125ms 125ms;\n\n // Navigation list\n > .md-nav__list {\n // Hack: promote to own layer to reduce jitter\n backface-visibility: hidden;\n }\n }\n }\n\n // [tablet portrait -]: Layered navigation with table of contents\n @include break-to-device(tablet portrait) {\n\n // Show link to table of contents\n &--primary &__link[for=\"__toc\"] {\n display: block;\n padding-right: px2rem(48px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n padding-right: px2rem(16px);\n padding-left: px2rem(48px);\n }\n\n // Show table of contents icon\n .md-icon::after {\n content: \"\";\n }\n\n // Hide navigation link to current page\n + .md-nav__link {\n display: none;\n }\n\n // Show table of contents\n ~ .md-nav {\n display: flex;\n }\n }\n\n // Repository information container\n &__source {\n display: block;\n padding: 0 px2rem(4px);\n color: var(--md-primary-bg-color);\n background-color: var(--md-primary-fg-color--dark);\n }\n }\n\n // [tablet landscape]: Layered navigation with table of contents\n @include break-at-device(tablet landscape) {\n\n // Show link to integrated table of contents\n &--integrated &__link[for=\"__toc\"] {\n display: block;\n padding-right: px2rem(48px);\n scroll-snap-align: initial;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n padding-right: px2rem(16px);\n padding-left: px2rem(48px);\n }\n\n // Show table of contents icon\n .md-icon::after {\n content: \"\";\n }\n\n // Hide navigation link to current page\n + .md-nav__link {\n display: none;\n }\n\n // Show table of contents\n ~ .md-nav {\n display: flex;\n }\n }\n }\n\n // [tablet landscape +]: Tree-like table of contents\n @include break-from-device(tablet landscape) {\n\n // Navigation title\n &--secondary &__title {\n\n // Adjust snapping behavior\n &[for=\"__toc\"] {\n scroll-snap-align: start;\n }\n\n // Hide navigation icon\n .md-nav__icon {\n display: none;\n }\n }\n }\n\n // [screen +]: Tree-like navigation\n @include break-from-device(screen) {\n transition: max-height 250ms cubic-bezier(0.86, 0, 0.07, 1);\n\n // Navigation title\n &--primary &__title {\n\n // Adjust snapping behavior\n &[for=\"__drawer\"] {\n scroll-snap-align: start;\n }\n\n // Hide navigation icon\n .md-nav__icon {\n display: none;\n }\n }\n\n // Hide toggle for nested navigation\n &__toggle ~ & {\n display: none;\n }\n\n // Show nested navigation when toggle is active or indeterminate\n &__toggle:checked ~ &,\n &__toggle:indeterminate ~ & {\n display: block;\n }\n\n // Hide navigation title in nested navigation\n &__item--nested > & > &__title {\n display: none;\n }\n\n // Navigation section\n &__item--section {\n display: block;\n margin: 1.25em 0;\n\n // Adjust spacing on last child\n &:last-child {\n margin-bottom: 0;\n }\n\n // Hide navigation link, as sections are always expanded\n > .md-nav__link {\n display: none;\n }\n\n // Navigation\n > .md-nav {\n display: block;\n\n // Navigation title\n > .md-nav__title {\n display: block;\n padding: 0;\n pointer-events: none;\n scroll-snap-align: start;\n }\n\n // Adjust spacing on next level item\n > .md-nav__list > .md-nav__item {\n padding: 0;\n }\n }\n }\n\n // Navigation icon\n &__icon {\n float: right;\n width: px2rem(18px);\n height: px2rem(18px);\n transition: transform 250ms;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n float: left;\n transform: rotate(180deg);\n }\n\n // Navigation icon content\n &::after {\n display: inline-block;\n width: 100%;\n height: 100%;\n vertical-align: px2rem(-2px);\n background-color: currentColor;\n mask-image: var(--md-nav-icon--next);\n mask-repeat: no-repeat;\n mask-size: contain;\n content: \"\";\n }\n\n // Navigation icon - rotate icon when toggle is active or indeterminate\n .md-nav__item--nested .md-nav__toggle:checked ~ .md-nav__link &,\n .md-nav__item--nested .md-nav__toggle:indeterminate ~ .md-nav__link & {\n transform: rotate(90deg);\n }\n }\n\n // Modifier for when navigation tabs are rendered\n &--lifted {\n\n // Hide nested level 0 items and site title\n > .md-nav__list > .md-nav__item--nested,\n > .md-nav__title {\n display: none;\n }\n\n // Hide level 0 items\n > .md-nav__list > .md-nav__item {\n display: none;\n\n // Active parent navigation item\n &--active {\n display: block;\n padding: 0;\n\n // Hide nested links\n > .md-nav__link {\n display: none;\n }\n\n // Show title and adjust spacing\n > .md-nav > .md-nav__title {\n display: block;\n padding: 0 px2rem(12px);\n pointer-events: none;\n scroll-snap-align: start;\n }\n }\n }\n\n // Hack: Always show active navigation tab on breakpoint screen, despite\n // of checkbox being checked or not. Fixes #1655.\n .md-nav[data-md-level=\"1\"] {\n display: block;\n\n // Adjust spacing for level 1 items\n > .md-nav__list > .md-nav__item {\n padding-right: px2rem(12px);\n }\n }\n }\n\n // Modifier for when table of contents is rendered in primary navigation\n &--integrated &__link[for=\"__toc\"] ~ .md-nav {\n display: block;\n margin-bottom: 1.25em;\n border-left: px2rem(1px) solid var(--md-primary-fg-color);\n\n // Hide navigation title\n > .md-nav__title {\n display: none;\n }\n }\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Icon definitions\n:root {\n --md-search-result-icon: svg-load(\"material/file-search-outline.svg\");\n}\n\n// ----------------------------------------------------------------------------\n\n// Search\n.md-search {\n position: relative;\n\n // [tablet landscape +]: Header-embedded search\n @include break-from-device(tablet landscape) {\n padding: px2rem(4px) 0;\n }\n\n // [no-js]: Hide search\n .no-js & {\n display: none;\n }\n\n // Search overlay\n &__overlay {\n z-index: 1;\n opacity: 0;\n\n // [tablet portrait -]: Search modal\n @include break-to-device(tablet portrait) {\n position: absolute;\n top: px2rem(4px);\n left: px2rem(-44px);\n width: px2rem(40px);\n height: px2rem(40px);\n overflow: hidden;\n background-color: var(--md-default-bg-color);\n border-radius: px2rem(20px);\n transform-origin: center;\n transition:\n transform 300ms 100ms,\n opacity 200ms 200ms;\n pointer-events: none;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n right: px2rem(-44px);\n left: initial;\n }\n\n // Show overlay when search is active\n [data-md-toggle=\"search\"]:checked ~ .md-header & {\n opacity: 1;\n transition:\n transform 400ms,\n opacity 100ms;\n }\n }\n\n // [tablet landscape +]: Header-embedded search\n @include break-from-device(tablet landscape) {\n position: fixed;\n top: 0;\n left: 0;\n width: 0;\n height: 0;\n background-color: hsla(0, 0%, 0%, 0.54);\n cursor: pointer;\n transition:\n width 0ms 250ms,\n height 0ms 250ms,\n opacity 250ms;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n right: 0;\n left: initial;\n }\n\n // Show overlay when search is active\n [data-md-toggle=\"search\"]:checked ~ .md-header & {\n width: 100%;\n // Hack: when the header is translated upon scrolling, a new layer is\n // induced, which means that the height will now refer to the height of\n // the header, albeit positioning is fixed. This should be mitigated\n // in all cases when setting the height to 2x the viewport.\n height: 200vh;\n opacity: 1;\n transition:\n width 0ms,\n height 0ms,\n opacity 250ms;\n }\n }\n\n // Adjust appearance when search is active\n [data-md-toggle=\"search\"]:checked ~ .md-header & {\n\n // [mobile portrait -]: Scale up 45 times\n @include break-to-device(mobile portrait) {\n transform: scale(45);\n }\n\n // [mobile landscape]: Scale up 60 times\n @include break-at-device(mobile landscape) {\n transform: scale(60);\n }\n\n // [tablet portrait]: Scale up 75 times\n @include break-at-device(tablet portrait) {\n transform: scale(75);\n }\n }\n }\n\n // Search wrapper\n &__inner {\n // Hack: promote to own layer to reduce jitter\n backface-visibility: hidden;\n\n // [tablet portrait -]: Search modal\n @include break-to-device(tablet portrait) {\n position: fixed;\n top: 0;\n left: 100%;\n z-index: 2;\n width: 100%;\n height: 100%;\n transform: translateX(5%);\n opacity: 0;\n transition:\n right 0ms 300ms,\n left 0ms 300ms,\n transform 150ms 150ms cubic-bezier(0.4, 0, 0.2, 1),\n opacity 150ms 150ms;\n\n // Adjust appearance when search is active\n [data-md-toggle=\"search\"]:checked ~ .md-header & {\n left: 0;\n transform: translateX(0);\n opacity: 1;\n transition:\n right 0ms 0ms,\n left 0ms 0ms,\n transform 150ms 150ms cubic-bezier(0.1, 0.7, 0.1, 1),\n opacity 150ms 150ms;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n right: 0;\n left: initial;\n }\n }\n\n // Adjust for right-to-left languages\n html [dir=\"rtl\"] & {\n right: 100%;\n left: initial;\n transform: translateX(-5%);\n }\n }\n\n // [tablet landscape +]: Header-embedded search\n @include break-from-device(tablet landscape) {\n position: relative;\n float: right;\n width: px2rem(234px);\n padding: px2rem(2px) 0;\n transition: width 250ms cubic-bezier(0.1, 0.7, 0.1, 1);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n float: left;\n }\n }\n\n // Adjust appearance when search is active\n [data-md-toggle=\"search\"]:checked ~ .md-header & {\n\n // [tablet landscape]: Omit overlaying header title\n @include break-at-device(tablet landscape) {\n width: px2rem(468px);\n }\n\n // [screen +]: Match width of content area\n @include break-from-device(screen) {\n width: px2rem(688px);\n }\n }\n }\n\n // Search form\n &__form {\n position: relative;\n z-index: 2;\n height: px2rem(48px);\n background-color: var(--md-default-bg-color);\n box-shadow: 0 0 px2rem(12px) transparent;\n transition:\n color 250ms,\n background-color 250ms;\n\n // [tablet landscape +]: Header-embedded search\n @include break-from-device(tablet landscape) {\n height: px2rem(36px);\n background-color: hsla(0, 0%, 0%, 0.26);\n border-radius: px2rem(2px);\n\n // Search form on hover\n &:hover {\n background-color: hsla(0, 0%, 100%, 0.12);\n }\n }\n\n // Adjust appearance when search is active\n [data-md-toggle=\"search\"]:checked ~ .md-header & {\n color: var(--md-default-fg-color);\n background-color: var(--md-default-bg-color);\n border-radius: px2rem(2px) px2rem(2px) 0 0;\n box-shadow: 0 0 px2rem(12px) hsla(0, 0%, 0%, 0.07);\n }\n }\n\n // Search input\n &__input {\n position: relative;\n z-index: 2;\n width: 100%;\n height: 100%;\n padding: 0 px2rem(44px) 0 px2rem(72px);\n font-size: px2rem(18px);\n text-overflow: ellipsis;\n background: transparent;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n padding: 0 px2rem(72px) 0 px2rem(44px);\n }\n\n // Search placeholder\n &::placeholder {\n transition: color 250ms;\n }\n\n // Search icon and placeholder\n ~ .md-search__icon,\n &::placeholder {\n color: var(--md-default-fg-color--light);\n }\n\n // Remove the \"x\" rendered by Internet Explorer\n &::-ms-clear {\n display: none;\n }\n\n // [tablet portrait -]: Search modal\n @include break-to-device(tablet portrait) {\n width: 100%;\n height: px2rem(48px);\n font-size: px2rem(18px);\n }\n\n // [tablet landscape +]: Header-embedded search\n @include break-from-device(tablet landscape) {\n padding-left: px2rem(44px);\n color: inherit;\n font-size: px2rem(16px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n padding-right: px2rem(44px);\n }\n\n // Search placeholder\n &::placeholder {\n color: var(--md-primary-bg-color--light);\n }\n\n // Search icon\n + .md-search__icon {\n color: var(--md-primary-bg-color);\n }\n\n // Adjust appearance when search is active\n [data-md-toggle=\"search\"]:checked ~ .md-header & {\n text-overflow: clip;\n\n // Search icon and placeholder\n + .md-search__icon,\n &::placeholder {\n color: var(--md-default-fg-color--light);\n }\n }\n }\n }\n\n // Search icon\n &__icon {\n display: inline-block;\n width: px2rem(24px);\n height: px2rem(24px);\n cursor: pointer;\n transition:\n color 250ms,\n opacity 250ms;\n\n // Search icon on hover\n &:hover {\n opacity: 0.7;\n }\n\n // Search focus button\n &[for=\"__search\"] {\n position: absolute;\n top: px2rem(6px);\n left: px2rem(10px);\n z-index: 2;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n right: px2rem(10px);\n left: initial;\n\n // Flip icon vertically\n svg {\n transform: scaleX(-1);\n }\n }\n\n // [tablet portrait -]: Search modal\n @include break-to-device(tablet portrait) {\n top: px2rem(12px);\n left: px2rem(16px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n right: px2rem(16px);\n left: initial;\n }\n\n // Hide the magnifying glass\n svg:first-child {\n display: none;\n }\n }\n\n // [tablet landscape +]: Header-embedded search\n @include break-from-device(tablet landscape) {\n pointer-events: none;\n\n // Hide the back arrow\n svg:last-child {\n display: none;\n }\n }\n }\n }\n\n // Search options\n &__options {\n position: absolute;\n top: px2rem(6px);\n right: px2rem(10px);\n z-index: 2;\n pointer-events: none;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n right: initial;\n left: px2rem(10px);\n }\n\n // [tablet portrait -]: Search modal\n @include break-to-device(tablet portrait) {\n top: px2rem(12px);\n right: px2rem(16px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n right: initial;\n left: px2rem(16px);\n }\n }\n\n // Search option buttons\n > * {\n margin-left: px2rem(4px);\n color: var(--md-default-fg-color--light);\n transform: scale(0.75);\n opacity: 0;\n transition:\n transform 150ms cubic-bezier(0.1, 0.7, 0.1, 1),\n opacity 150ms;\n\n // Hide outline for pointer devices\n &:not(.focus-visible) {\n outline: none;\n -webkit-tap-highlight-color: transparent;\n }\n\n // Show reset button when search is active and input non-empty\n [data-md-toggle=\"search\"]:checked ~ .md-header\n .md-search__input:valid ~ & {\n transform: scale(1);\n opacity: 1;\n pointer-events: initial;\n\n // Search focus icon\n &:hover {\n opacity: 0.7;\n }\n }\n }\n }\n\n // Search suggestions\n &__suggest {\n position: absolute;\n top: 0;\n display: flex;\n align-items: center;\n width: 100%;\n height: 100%;\n padding: 0 px2rem(44px) 0 px2rem(72px);\n color: var(--md-default-fg-color--lighter);\n font-size: px2rem(18px);\n white-space: nowrap;\n opacity: 0;\n transition: opacity 50ms;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n padding: 0 px2rem(72px) 0 px2rem(44px);\n }\n\n // [tablet landscape +]: Header-embedded search\n @include break-from-device(tablet landscape) {\n padding-left: px2rem(44px);\n font-size: px2rem(16px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n padding-right: px2rem(44px);\n }\n }\n\n // Show suggestions when search is active\n [data-md-toggle=\"search\"]:checked ~ .md-header & {\n opacity: 1;\n transition: opacity 300ms 100ms;\n }\n }\n\n // Search output\n &__output {\n position: absolute;\n z-index: 1;\n width: 100%;\n overflow: hidden;\n border-radius: 0 0 px2rem(2px) px2rem(2px);\n\n // [tablet portrait -]: Search modal\n @include break-to-device(tablet portrait) {\n top: px2rem(48px);\n bottom: 0;\n }\n\n // [tablet landscape +]: Header-embedded search\n @include break-from-device(tablet landscape) {\n top: px2rem(38px);\n opacity: 0;\n transition: opacity 400ms;\n\n // Show output when search is active\n [data-md-toggle=\"search\"]:checked ~ .md-header & {\n @include z-depth(6);\n\n opacity: 1;\n }\n }\n }\n\n // Search scroll wrapper\n &__scrollwrap {\n height: 100%;\n overflow-y: auto;\n background-color: var(--md-default-bg-color);\n // Hack: promote to own layer to reduce jitter\n backface-visibility: hidden;\n // Hack: Chrome 88+ has weird overscroll behavior. Overall, scroll snapping\n // seems to be something that is not ready for prime time on some browsers.\n // scroll-snap-type: y mandatory;\n touch-action: pan-y;\n\n // Mitigiate excessive repaints on non-retina devices\n @media (max-resolution: 1dppx) {\n transform: translateZ(0);\n }\n\n // [tablet landscape]: Set fixed width to omit unnecessary reflow\n @include break-at-device(tablet landscape) {\n width: px2rem(468px);\n }\n\n // [screen +]: Set fixed width to omit unnecessary reflow\n @include break-from-device(screen) {\n width: px2rem(688px);\n }\n\n // [tablet landscape +]: Limit height to viewport\n @include break-from-device(tablet landscape) {\n max-height: 0;\n scrollbar-width: thin;\n scrollbar-color: var(--md-default-fg-color--lighter) transparent;\n\n // Show scroll wrapper when search is active\n [data-md-toggle=\"search\"]:checked ~ .md-header & {\n max-height: 75vh;\n }\n\n // Search scroll wrapper on hover\n &:hover {\n scrollbar-color: var(--md-accent-fg-color) transparent;\n }\n\n // Webkit scrollbar\n &::-webkit-scrollbar {\n width: px2rem(4px);\n height: px2rem(4px);\n }\n\n // Webkit scrollbar thumb\n &::-webkit-scrollbar-thumb {\n background-color: var(--md-default-fg-color--lighter);\n\n // Webkit scrollbar thumb on hover\n &:hover {\n background-color: var(--md-accent-fg-color);\n }\n }\n }\n }\n}\n\n// Search result\n.md-search-result {\n color: var(--md-default-fg-color);\n word-break: break-word;\n\n // Search result metadata\n &__meta {\n padding: 0 px2rem(16px);\n color: var(--md-default-fg-color--light);\n font-size: px2rem(12.8px);\n line-height: px2rem(36px);\n background-color: var(--md-default-fg-color--lightest);\n scroll-snap-align: start;\n\n // [tablet landscape +]: Adjust spacing\n @include break-from-device(tablet landscape) {\n padding-left: px2rem(44px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n padding-right: px2rem(44px);\n padding-left: initial;\n }\n }\n }\n\n // Search result list\n &__list {\n margin: 0;\n padding: 0;\n list-style: none;\n }\n\n // Search result item\n &__item {\n box-shadow: 0 px2rem(-1px) 0 var(--md-default-fg-color--lightest);\n\n // Omit border on first child\n &:first-child {\n box-shadow: none;\n }\n }\n\n // Search result link\n &__link {\n display: block;\n outline: none;\n transition: background-color 250ms;\n scroll-snap-align: start;\n\n // Search result link on focus/hover\n &:focus,\n &:hover {\n background-color: var(--md-accent-fg-color--transparent);\n }\n\n // Adjust spacing on last child of last link\n &:last-child p:last-child {\n margin-bottom: px2rem(12px);\n }\n }\n\n // Search result more link\n &__more summary {\n display: block;\n padding: px2em(12px) px2rem(16px);\n color: var(--md-typeset-a-color);\n font-size: px2rem(12.8px);\n outline: none;\n cursor: pointer;\n transition:\n color 250ms,\n background-color 250ms;\n scroll-snap-align: start;\n\n // [tablet landscape +]: Adjust spacing\n @include break-from-device(tablet landscape) {\n padding-left: px2rem(44px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n padding-right: px2rem(44px);\n padding-left: px2rem(16px);\n }\n }\n\n // Search result more link on focus/hover\n &:focus,\n &:hover {\n color: var(--md-accent-fg-color);\n background-color: var(--md-accent-fg-color--transparent);\n }\n\n // Hide native details marker\n &::marker,\n &::-webkit-details-marker {\n display: none;\n }\n\n // Adjust transparency of less relevant results\n ~ * > * {\n opacity: 0.65;\n }\n }\n\n // Search result article\n &__article {\n position: relative;\n padding: 0 px2rem(16px);\n overflow: hidden;\n\n // [tablet landscape +]: Adjust spacing\n @include break-from-device(tablet landscape) {\n padding-left: px2rem(44px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n padding-right: px2rem(44px);\n padding-left: px2rem(16px);\n }\n }\n\n // Search result article document\n &--document {\n\n // Search result title\n .md-search-result__title {\n margin: px2rem(11px) 0;\n font-weight: 400;\n font-size: px2rem(16px);\n line-height: 1.4;\n }\n }\n }\n\n // Search result icon\n &__icon {\n position: absolute;\n left: 0;\n width: px2rem(24px);\n height: px2rem(24px);\n margin: px2rem(10px);\n color: var(--md-default-fg-color--light);\n\n // [tablet portrait -]: Hide icon\n @include break-to-device(tablet portrait) {\n display: none;\n }\n\n // Search result icon content\n &::after {\n display: inline-block;\n width: 100%;\n height: 100%;\n background-color: currentColor;\n mask-image: var(--md-search-result-icon);\n mask-repeat: no-repeat;\n mask-size: contain;\n content: \"\";\n }\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n right: 0;\n left: initial;\n\n // Flip icon vertically\n &::after {\n transform: scaleX(-1);\n }\n }\n }\n\n // Search result title\n &__title {\n margin: 0.5em 0;\n font-weight: 700;\n font-size: px2rem(12.8px);\n line-height: 1.6;\n }\n\n // Search result teaser\n &__teaser {\n display: -webkit-box;\n max-height: px2rem(40px);\n margin: 0.5em 0;\n overflow: hidden;\n color: var(--md-default-fg-color--light);\n font-size: px2rem(12.8px);\n line-height: 1.6;\n text-overflow: ellipsis;\n -webkit-box-orient: vertical;\n -webkit-line-clamp: 2;\n\n // [mobile -]: Adjust number of lines\n @include break-to-device(mobile) {\n max-height: px2rem(60px);\n -webkit-line-clamp: 3;\n }\n\n // [tablet landscape]: Adjust number of lines\n @include break-at-device(tablet landscape) {\n max-height: px2rem(60px);\n -webkit-line-clamp: 3;\n }\n\n // Search term highlighting\n mark {\n text-decoration: underline;\n background-color: transparent;\n }\n }\n\n // Search result terms\n &__terms {\n margin: 0.5em 0;\n font-size: px2rem(12.8px);\n font-style: italic;\n }\n\n // Search term highlighting\n mark {\n color: var(--md-accent-fg-color);\n background-color: transparent;\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Selection\n.md-select {\n position: relative;\n z-index: 1;\n\n // Selection bubble\n &__inner {\n position: absolute;\n top: calc(100% - #{px2rem(4px)});\n left: 50%;\n max-height: 0;\n margin-top: px2rem(4px);\n color: var(--md-default-fg-color);\n background-color: var(--md-default-bg-color);\n border-radius: px2rem(2px);\n box-shadow:\n 0 px2rem(4px) px2rem(10px) hsla(0, 0%, 0%, 0.1),\n 0 0 px2rem(1px) hsla(0, 0%, 0%, 0.25);\n transform: translate3d(-50%, px2rem(6px), 0);\n opacity: 0;\n transition:\n transform 250ms 375ms,\n opacity 250ms 250ms,\n max-height 0ms 500ms;\n\n // Selection bubble on parent focus/hover\n .md-select:focus-within &,\n .md-select:hover & {\n max-height: px2rem(200px);\n transform: translate3d(-50%, 0, 0);\n opacity: 1;\n transition:\n transform 250ms cubic-bezier(0.1, 0.7, 0.1, 1),\n opacity 250ms,\n max-height 0ms;\n }\n\n // Selection bubble handle\n &::after {\n position: absolute;\n top: 0;\n left: 50%;\n width: 0;\n height: 0;\n margin-top: px2rem(-4px);\n margin-left: px2rem(-4px);\n border: px2rem(4px) solid transparent;\n border-top: 0;\n border-bottom-color: var(--md-default-bg-color);\n content: \"\";\n }\n }\n\n // Selection list\n &__list {\n max-height: inherit;\n margin: 0;\n padding: 0;\n overflow: auto;\n font-size: px2rem(16px);\n list-style-type: none;\n border-radius: px2rem(2px);\n }\n\n // Selection item\n &__item {\n line-height: px2rem(36px);\n }\n\n // Selection link\n &__link {\n display: block;\n width: 100%;\n padding-right: px2rem(24px);\n padding-left: px2rem(12px);\n outline: none;\n cursor: pointer;\n transition:\n background-color 250ms,\n color 250ms;\n scroll-snap-align: start;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n padding-right: px2rem(12px);\n padding-left: px2rem(24px);\n }\n\n // Link on focus/hover\n &:focus,\n &:hover {\n color: var(--md-accent-fg-color);\n }\n\n // Link on focus\n &:focus {\n background-color: var(--md-default-fg-color--lightest);\n }\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Sidebar\n.md-sidebar {\n position: sticky;\n top: px2rem(48px);\n flex-shrink: 0;\n align-self: flex-start;\n width: px2rem(242px);\n padding: px2rem(24px) 0;\n\n // [print]: Hide sidebar\n @media print {\n display: none;\n }\n\n // [tablet -]: Show navigation as drawer\n @include break-to-device(tablet) {\n\n // Primary sidebar with navigation\n &--primary {\n position: fixed;\n top: 0;\n left: px2rem(-242px);\n z-index: 4;\n display: block;\n width: px2rem(242px);\n height: 100%;\n background-color: var(--md-default-bg-color);\n transform: translateX(0);\n transition:\n transform 250ms cubic-bezier(0.4, 0, 0.2, 1),\n box-shadow 250ms;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n right: px2rem(-242px);\n left: initial;\n }\n\n // Show sidebar when drawer is active\n [data-md-toggle=\"drawer\"]:checked ~ .md-container & {\n @include z-depth(8);\n\n transform: translateX(px2rem(242px));\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n transform: translateX(px2rem(-242px));\n }\n }\n\n // Stretch scroll wrapper for primary sidebar\n .md-sidebar__scrollwrap {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n margin: 0;\n scroll-snap-type: none;\n overflow: hidden;\n }\n }\n }\n\n // [screen +]: Show navigation as sidebar\n @include break-from-device(screen) {\n height: 0;\n\n // [no-js]: Switch to native sticky behavior\n .no-js & {\n height: auto;\n }\n }\n\n // Secondary sidebar with table of contents\n &--secondary {\n display: none;\n order: 2;\n\n // [tablet landscape +]: Show table of contents as sidebar\n @include break-from-device(tablet landscape) {\n height: 0;\n\n // [no-js]: Switch to native sticky behavior\n .no-js & {\n height: auto;\n }\n\n // Sidebar is visible\n &:not([hidden]) {\n display: block;\n }\n\n // Ensure smooth scrolling on iOS\n .md-sidebar__scrollwrap {\n touch-action: pan-y;\n }\n }\n }\n\n // Sidebar scroll wrapper\n &__scrollwrap {\n margin: 0 px2rem(4px);\n overflow-y: auto;\n // Hack: promote to own layer to reduce jitter\n backface-visibility: hidden;\n // Hack: Chrome 81+ exhibits a strange bug, where it scrolls the container\n // to the bottom if `scroll-snap-type` is set on the initial render. For\n // this reason, we disable scroll snapping until this is resolved (#1667).\n // scroll-snap-type: y mandatory;\n scrollbar-width: thin;\n scrollbar-color: var(--md-default-fg-color--lighter) transparent;\n\n // Sidebar scroll wrapper on hover\n &:hover {\n scrollbar-color: var(--md-accent-fg-color) transparent;\n }\n\n // Webkit scrollbar\n &::-webkit-scrollbar {\n width: px2rem(4px);\n height: px2rem(4px);\n }\n\n // Webkit scrollbar thumb\n &::-webkit-scrollbar-thumb {\n background-color: var(--md-default-fg-color--lighter);\n\n // Webkit scrollbar thumb on hover\n &:hover {\n background-color: var(--md-accent-fg-color);\n }\n }\n }\n}\n\n// [tablet -]: Show overlay on active drawer\n@include break-to-device(tablet) {\n\n // Sidebar overlay\n .md-overlay {\n position: fixed;\n top: 0;\n z-index: 4;\n width: 0;\n height: 0;\n background-color: hsla(0, 0%, 0%, 0.54);\n opacity: 0;\n transition:\n width 0ms 250ms,\n height 0ms 250ms,\n opacity 250ms;\n\n // Show overlay when drawer is active\n [data-md-toggle=\"drawer\"]:checked ~ & {\n width: 100%;\n height: 100%;\n opacity: 1;\n transition:\n width 0ms,\n height 0ms,\n opacity 250ms;\n }\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Keyframes\n// ----------------------------------------------------------------------------\n\n// Show repository facts\n@keyframes facts {\n 0% {\n height: 0;\n }\n\n 100% {\n height: px2rem(13px);\n }\n}\n\n// Show repository fact\n@keyframes fact {\n 0% {\n transform: translateY(100%);\n opacity: 0;\n }\n\n 50% {\n opacity: 0;\n }\n\n 100% {\n transform: translateY(0%);\n opacity: 1;\n }\n}\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Icon definitions\n:root {\n --md-source-forks-icon: svg-load(\"octicons/repo-forked-16.svg\");\n --md-source-repositories-icon: svg-load(\"octicons/repo-16.svg\");\n --md-source-stars-icon: svg-load(\"octicons/star-16.svg\");\n --md-source-version-icon: svg-load(\"octicons/tag-16.svg\");\n}\n\n// ----------------------------------------------------------------------------\n\n// Repository information\n.md-source {\n display: block;\n font-size: px2rem(13px);\n line-height: 1.2;\n white-space: nowrap;\n outline-color: var(--md-accent-fg-color);\n // Hack: promote to own layer to reduce jitter\n backface-visibility: hidden;\n transition: opacity 250ms;\n\n // Repository information on hover\n &:hover {\n opacity: 0.7;\n }\n\n // Repository icon\n &__icon {\n display: inline-block;\n width: px2rem(40px);\n height: px2rem(48px);\n vertical-align: middle;\n\n // Align with margin only (as opposed to normal button alignment)\n svg {\n margin-top: px2rem(12px);\n margin-left: px2rem(12px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n margin-right: px2rem(12px);\n margin-left: initial;\n }\n }\n\n // Adjust spacing if icon is present\n + .md-source__repository {\n margin-left: px2rem(-40px);\n padding-left: px2rem(40px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n margin-right: px2rem(-40px);\n margin-left: initial;\n padding-right: px2rem(40px);\n padding-left: initial;\n }\n }\n }\n\n // Repository name\n &__repository {\n display: inline-block;\n max-width: calc(100% - #{px2rem(24px)});\n margin-left: px2rem(12px);\n overflow: hidden;\n text-overflow: ellipsis;\n vertical-align: middle;\n }\n\n // Repository facts\n &__facts {\n margin: px2rem(2px) 0 0;\n padding: 0;\n overflow: hidden;\n font-size: px2rem(11px);\n list-style-type: none;\n opacity: 0.75;\n\n // Show after the data was loaded\n [data-md-state=\"done\"] & {\n animation: facts 250ms ease-in;\n }\n }\n\n // Repository fact\n &__fact {\n display: inline-block;\n\n // Show after the data was loaded\n [data-md-state=\"done\"] & {\n animation: fact 400ms ease-out;\n }\n\n // Repository fact icon\n &::before {\n display: inline-block;\n width: px2rem(12px);\n height: px2rem(12px);\n margin-right: px2rem(2px);\n vertical-align: text-top;\n background-color: currentColor;\n mask-repeat: no-repeat;\n mask-size: contain;\n content: \"\";\n }\n\n // Adjust spacing for repository fact icon\n &:nth-child(1n+2)::before {\n margin-left: px2rem(8px);\n }\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n margin-right: initial;\n margin-left: px2rem(2px);\n\n // Adjust spacing for repository fact icon\n &:nth-child(1n+2)::before {\n margin-right: px2rem(8px);\n margin-left: initial;\n }\n }\n\n // Repository fact: version\n &--version::before {\n mask-image: var(--md-source-version-icon);\n }\n\n // Repository fact: stars\n &--stars::before {\n mask-image: var(--md-source-stars-icon);\n }\n\n // Repository fact: forks\n &--forks::before {\n mask-image: var(--md-source-forks-icon);\n }\n\n // Repository fact: repositories\n &--repositories::before {\n mask-image: var(--md-source-repositories-icon);\n }\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Navigation tabs\n.md-tabs {\n width: 100%;\n overflow: auto;\n color: var(--md-primary-bg-color);\n background-color: var(--md-primary-fg-color);\n\n // [print]: Hide tabs\n @media print {\n display: none;\n }\n\n // [tablet -]: Hide tabs\n @include break-to-device(tablet) {\n display: none;\n }\n\n // Tabs in hidden state, i.e. when scrolling down\n &[data-md-state=\"hidden\"] {\n pointer-events: none;\n }\n\n // Navigation tabs list\n &__list {\n margin: 0;\n margin-left: px2rem(4px);\n padding: 0;\n white-space: nowrap;\n list-style: none;\n contain: content;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n margin-right: px2rem(4px);\n margin-left: initial;\n }\n }\n\n // Navigation tabs item\n &__item {\n display: inline-block;\n height: px2rem(48px);\n padding-right: px2rem(12px);\n padding-left: px2rem(12px);\n }\n\n // Navigation tabs link - could be defined as block elements and aligned via\n // line height, but this would imply more repaints when scrolling\n &__link {\n display: block;\n margin-top: px2rem(16px);\n font-size: px2rem(14px);\n outline-color: var(--md-accent-fg-color);\n outline-offset: px2rem(4px);\n // Hack: save a repaint when tabs are appearing on scrolling up\n backface-visibility: hidden;\n opacity: 0.7;\n transition:\n transform 400ms cubic-bezier(0.1, 0.7, 0.1, 1),\n opacity 250ms;\n\n // Active link and link on focus/hover\n &--active,\n &:focus,\n &:hover {\n color: inherit;\n opacity: 1;\n }\n\n // Delay transitions by a small amount\n @for $i from 2 through 16 {\n .md-tabs__item:nth-child(#{$i}) & {\n transition-delay: 20ms * ($i - 1);\n }\n }\n\n // Hide tabs upon scrolling - disable transition to minimizes repaints\n // while scrolling down, while scrolling up seems to be okay\n .md-tabs[data-md-state=\"hidden\"] & {\n transform: translateY(50%);\n opacity: 0;\n transition:\n transform 0ms 100ms,\n opacity 100ms;\n }\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Back-to-top button\n.md-top {\n position: fixed;\n top: px2rem(48px + 16px);\n z-index: 2;\n margin-left: 50%;\n padding: px2rem(8px) px2rem(16px);\n color: var(--md-default-fg-color--light);\n font-size: px2rem(14px);\n background-color: var(--md-default-bg-color);\n border-radius: px2rem(32px);\n outline: none;\n box-shadow:\n 0 px2rem(4px) px2rem(10px) hsla(0, 0%, 0%, 0.1),\n 0 0 px2rem(1px) hsla(0, 0%, 0%, 0.25);\n transform: translate(-50%, 0);\n transition:\n color 125ms,\n background-color 125ms,\n transform 125ms cubic-bezier(0.4, 0, 0.2, 1),\n opacity 125ms;\n\n // [print]: Hide back-to-top button\n @media print {\n display: none;\n }\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n float: left;\n }\n\n // Back-to-top button in hidden state\n &[data-md-state=\"hidden\"] {\n transform: translate(-50%, px2rem(4px));\n opacity: 0;\n transition-duration: 0ms;\n pointer-events: none;\n }\n\n // Back-to-top button on focus/hover\n &:focus,\n &:hover {\n color: var(--md-accent-bg-color);\n background-color: var(--md-accent-fg-color);\n }\n\n // Inline icon\n svg {\n display: inline-block;\n vertical-align: -0.5em;\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Keyframes\n// ----------------------------------------------------------------------------\n\n// See https://github.com/squidfunk/mkdocs-material/issues/2429\n@keyframes hoverfix {\n 0% {\n pointer-events: none;\n }\n}\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Icon definitions\n:root {\n --md-version-icon: svg-load(\"fontawesome/solid/caret-down.svg\");\n}\n\n// ----------------------------------------------------------------------------\n\n// Version selection\n.md-version {\n flex-shrink: 0;\n height: px2rem(48px);\n font-size: px2rem(16px);\n\n // Current selection\n &__current {\n position: relative;\n // Hack: in general, we would use `vertical-align` to align the version at\n // the bottom with the title, but since the list uses absolute positioning,\n // this won't work consistently. Furthermore, we would need to use inline\n // positioning to align the links, which looks jagged.\n top: px2rem(1px);\n margin-right: px2rem(8px);\n margin-left: px2rem(28px);\n color: inherit;\n outline: none;\n cursor: pointer;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n margin-right: px2rem(28px);\n margin-left: px2rem(8px);\n }\n\n // Version selection icon\n &::after {\n display: inline-block;\n width: px2rem(8px);\n height: px2rem(12px);\n margin-left: px2rem(8px);\n background-color: currentColor;\n mask-image: var(--md-version-icon);\n mask-repeat: no-repeat;\n content: \"\";\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n margin-right: px2rem(8px);\n margin-left: initial;\n }\n }\n }\n\n // Version selection list\n &__list {\n position: absolute;\n top: px2rem(3px);\n z-index: 1;\n max-height: 0;\n margin: px2rem(4px) px2rem(16px);\n padding: 0;\n overflow: auto;\n color: var(--md-default-fg-color);\n list-style-type: none;\n background-color: var(--md-default-bg-color);\n border-radius: px2rem(2px);\n box-shadow:\n 0 px2rem(4px) px2rem(10px) hsla(0, 0%, 0%, 0.1),\n 0 0 px2rem(1px) hsla(0, 0%, 0%, 0.25);\n opacity: 0;\n transition:\n max-height 0ms 500ms,\n opacity 250ms 250ms;\n scroll-snap-type: y mandatory;\n\n // Version selection list on parent focus/hover\n .md-version:focus-within &,\n .md-version:hover & {\n max-height: px2rem(200px);\n opacity: 1;\n transition:\n max-height 0ms,\n opacity 250ms;\n }\n\n // Fix hover on touch devices\n @media (pointer: coarse) {\n\n // Switch off on hover\n .md-version:hover & {\n animation: hoverfix 250ms forwards;\n }\n\n // Enable on focus\n .md-version:focus-within & {\n animation: none;\n }\n }\n }\n\n // Version selection item\n &__item {\n line-height: px2rem(36px);\n }\n\n // Version selection link\n &__link {\n display: block;\n width: 100%;\n padding-right: px2rem(24px);\n padding-left: px2rem(12px);\n white-space: nowrap;\n outline: none;\n cursor: pointer;\n transition:\n color 250ms,\n background-color 250ms;\n scroll-snap-align: start;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n padding-right: px2rem(12px);\n padding-left: px2rem(24px);\n }\n\n // Link on focus/hover\n &:focus,\n &:hover {\n color: var(--md-accent-fg-color);\n }\n\n // Link on focus\n &:focus {\n background-color: var(--md-default-fg-color--lightest);\n }\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Variables\n// ----------------------------------------------------------------------------\n\n/// Admonition flavours\n$admonitions: (\n note: pencil $clr-blue-a200,\n abstract summary tldr: text-subject $clr-light-blue-a400,\n info todo: information $clr-cyan-a700,\n tip hint important: fire $clr-teal-a700,\n success check done: check-circle $clr-green-a700,\n question help faq: help-circle $clr-light-green-a700,\n warning caution attention: alert $clr-orange-a400,\n failure fail missing: close-circle $clr-red-a200,\n danger error: flash-circle $clr-red-a400,\n bug: bug $clr-pink-a400,\n example: format-list-numbered $clr-deep-purple-a200,\n quote cite: format-quote-close $clr-grey\n) !default;\n\n// ----------------------------------------------------------------------------\n// Rules: layout\n// ----------------------------------------------------------------------------\n\n// Icon definitions\n:root {\n @each $names, $props in $admonitions {\n --md-admonition-icon--#{nth($names, 1)}:\n svg-load(\"material/#{nth($props, 1)}.svg\");\n }\n}\n\n// ----------------------------------------------------------------------------\n\n// Scoped in typesetted content to match specificity of regular content\n.md-typeset {\n\n // Admonition\n .admonition {\n margin: px2em(20px, 12.8px) 0;\n padding: 0 px2rem(12px);\n overflow: hidden;\n color: var(--md-admonition-fg-color);\n font-size: px2rem(12.8px);\n page-break-inside: avoid;\n background-color: var(--md-admonition-bg-color);\n border-left: px2rem(4px) solid $clr-blue-a200;\n border-radius: px2rem(2px);\n box-shadow:\n 0 px2rem(4px) px2rem(10px) hsla(0, 0%, 0%, 0.05),\n 0 px2rem(0.5px) px2rem(1px) hsla(0, 0%, 0%, 0.05);\n\n // [print]: Omit shadow as it may lead to rendering errors\n @media print {\n box-shadow: none;\n }\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n border-right: px2rem(4px) solid $clr-blue-a200;\n border-left: none;\n }\n\n // Adjust vertical spacing for nested admonitions\n .admonition {\n margin-top: 1em;\n margin-bottom: 1em;\n }\n\n // Adjust spacing for contained table wrappers\n .md-typeset__scrollwrap {\n margin: 1em px2rem(-12px);\n }\n\n // Adjust spacing for contained tables\n .md-typeset__table {\n padding: 0 px2rem(12px);\n }\n\n // Adjust spacing for single-child tabbed block container\n > .tabbed-set:only-child {\n margin-top: 0;\n }\n\n // Adjust spacing on last child\n html & > :last-child {\n margin-bottom: px2rem(12px);\n }\n }\n\n // Admonition title\n .admonition-title {\n position: relative;\n margin: 0 px2rem(-12px) 0 px2rem(-16px);\n padding: px2rem(8px) px2rem(12px) px2rem(8px) px2rem(40px);\n font-weight: 700;\n background-color: transparentize($clr-blue-a200, 0.9);\n border-left: px2rem(4px) solid $clr-blue-a200;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n margin: 0 px2rem(-16px) 0 px2rem(-12px);\n padding: px2rem(8px) px2rem(40px) px2rem(8px) px2rem(12px);\n border-right: px2rem(4px) solid $clr-blue-a200;\n border-left: none;\n }\n\n // Adjust spacing for title-only admonitions\n html &:last-child {\n margin-bottom: 0;\n }\n\n // Admonition icon\n &::before {\n position: absolute;\n left: px2rem(12px);\n width: px2rem(20px);\n height: px2rem(20px);\n background-color: $clr-blue-a200;\n mask-image: var(--md-admonition-icon--note);\n mask-repeat: no-repeat;\n mask-size: contain;\n content: \"\";\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n right: px2rem(12px);\n left: initial;\n }\n }\n\n // Adjust spacing on last tabbed block container child - if the tabbed\n // block container is the sole child, it looks better to omit the margin\n + .tabbed-set:last-child {\n margin-top: 0;\n }\n }\n}\n\n// ----------------------------------------------------------------------------\n// Rules: flavours\n// ----------------------------------------------------------------------------\n\n@each $names, $props in $admonitions {\n $name: nth($names, 1);\n $tint: nth($props, 2);\n\n // Admonition flavour\n .md-typeset .admonition.#{$name} {\n border-color: $tint;\n }\n\n // Admonition flavour title\n .md-typeset .#{$name} > .admonition-title {\n background-color: transparentize($tint, 0.9);\n border-color: $tint;\n\n // Admonition icon\n &::before {\n background-color: $tint;\n mask-image: var(--md-admonition-icon--#{$name});\n mask-repeat: no-repeat;\n mask-size: contain;\n }\n }\n\n // Define synonyms for flavours\n @if length($names) > 1 {\n @for $n from 2 through length($names) {\n .#{nth($names, $n)} {\n @extend .#{$name};\n }\n }\n }\n}\n","// ==========================================================================\n//\n// Name: UI Color Palette\n// Description: The color palette of material design.\n// Version: 2.3.1\n//\n// Author: Denis Malinochkin\n// Git: https://github.com/mrmlnc/material-color\n//\n// twitter: @mrmlnc\n//\n// ==========================================================================\n\n\n//\n// List of base colors\n//\n\n// $clr-red\n// $clr-pink\n// $clr-purple\n// $clr-deep-purple\n// $clr-indigo\n// $clr-blue\n// $clr-light-blue\n// $clr-cyan\n// $clr-teal\n// $clr-green\n// $clr-light-green\n// $clr-lime\n// $clr-yellow\n// $clr-amber\n// $clr-orange\n// $clr-deep-orange\n// $clr-brown\n// $clr-grey\n// $clr-blue-grey\n// $clr-black\n// $clr-white\n\n\n//\n// Red\n//\n\n$clr-red-list: (\n \"base\": #f44336,\n \"50\": #ffebee,\n \"100\": #ffcdd2,\n \"200\": #ef9a9a,\n \"300\": #e57373,\n \"400\": #ef5350,\n \"500\": #f44336,\n \"600\": #e53935,\n \"700\": #d32f2f,\n \"800\": #c62828,\n \"900\": #b71c1c,\n \"a100\": #ff8a80,\n \"a200\": #ff5252,\n \"a400\": #ff1744,\n \"a700\": #d50000\n);\n\n$clr-red: map-get($clr-red-list, \"base\");\n\n$clr-red-50: map-get($clr-red-list, \"50\");\n$clr-red-100: map-get($clr-red-list, \"100\");\n$clr-red-200: map-get($clr-red-list, \"200\");\n$clr-red-300: map-get($clr-red-list, \"300\");\n$clr-red-400: map-get($clr-red-list, \"400\");\n$clr-red-500: map-get($clr-red-list, \"500\");\n$clr-red-600: map-get($clr-red-list, \"600\");\n$clr-red-700: map-get($clr-red-list, \"700\");\n$clr-red-800: map-get($clr-red-list, \"800\");\n$clr-red-900: map-get($clr-red-list, \"900\");\n$clr-red-a100: map-get($clr-red-list, \"a100\");\n$clr-red-a200: map-get($clr-red-list, \"a200\");\n$clr-red-a400: map-get($clr-red-list, \"a400\");\n$clr-red-a700: map-get($clr-red-list, \"a700\");\n\n\n//\n// Pink\n//\n\n$clr-pink-list: (\n \"base\": #e91e63,\n \"50\": #fce4ec,\n \"100\": #f8bbd0,\n \"200\": #f48fb1,\n \"300\": #f06292,\n \"400\": #ec407a,\n \"500\": #e91e63,\n \"600\": #d81b60,\n \"700\": #c2185b,\n \"800\": #ad1457,\n \"900\": #880e4f,\n \"a100\": #ff80ab,\n \"a200\": #ff4081,\n \"a400\": #f50057,\n \"a700\": #c51162\n);\n\n$clr-pink: map-get($clr-pink-list, \"base\");\n\n$clr-pink-50: map-get($clr-pink-list, \"50\");\n$clr-pink-100: map-get($clr-pink-list, \"100\");\n$clr-pink-200: map-get($clr-pink-list, \"200\");\n$clr-pink-300: map-get($clr-pink-list, \"300\");\n$clr-pink-400: map-get($clr-pink-list, \"400\");\n$clr-pink-500: map-get($clr-pink-list, \"500\");\n$clr-pink-600: map-get($clr-pink-list, \"600\");\n$clr-pink-700: map-get($clr-pink-list, \"700\");\n$clr-pink-800: map-get($clr-pink-list, \"800\");\n$clr-pink-900: map-get($clr-pink-list, \"900\");\n$clr-pink-a100: map-get($clr-pink-list, \"a100\");\n$clr-pink-a200: map-get($clr-pink-list, \"a200\");\n$clr-pink-a400: map-get($clr-pink-list, \"a400\");\n$clr-pink-a700: map-get($clr-pink-list, \"a700\");\n\n\n//\n// Purple\n//\n\n$clr-purple-list: (\n \"base\": #9c27b0,\n \"50\": #f3e5f5,\n \"100\": #e1bee7,\n \"200\": #ce93d8,\n \"300\": #ba68c8,\n \"400\": #ab47bc,\n \"500\": #9c27b0,\n \"600\": #8e24aa,\n \"700\": #7b1fa2,\n \"800\": #6a1b9a,\n \"900\": #4a148c,\n \"a100\": #ea80fc,\n \"a200\": #e040fb,\n \"a400\": #d500f9,\n \"a700\": #aa00ff\n);\n\n$clr-purple: map-get($clr-purple-list, \"base\");\n\n$clr-purple-50: map-get($clr-purple-list, \"50\");\n$clr-purple-100: map-get($clr-purple-list, \"100\");\n$clr-purple-200: map-get($clr-purple-list, \"200\");\n$clr-purple-300: map-get($clr-purple-list, \"300\");\n$clr-purple-400: map-get($clr-purple-list, \"400\");\n$clr-purple-500: map-get($clr-purple-list, \"500\");\n$clr-purple-600: map-get($clr-purple-list, \"600\");\n$clr-purple-700: map-get($clr-purple-list, \"700\");\n$clr-purple-800: map-get($clr-purple-list, \"800\");\n$clr-purple-900: map-get($clr-purple-list, \"900\");\n$clr-purple-a100: map-get($clr-purple-list, \"a100\");\n$clr-purple-a200: map-get($clr-purple-list, \"a200\");\n$clr-purple-a400: map-get($clr-purple-list, \"a400\");\n$clr-purple-a700: map-get($clr-purple-list, \"a700\");\n\n\n//\n// Deep purple\n//\n\n$clr-deep-purple-list: (\n \"base\": #673ab7,\n \"50\": #ede7f6,\n \"100\": #d1c4e9,\n \"200\": #b39ddb,\n \"300\": #9575cd,\n \"400\": #7e57c2,\n \"500\": #673ab7,\n \"600\": #5e35b1,\n \"700\": #512da8,\n \"800\": #4527a0,\n \"900\": #311b92,\n \"a100\": #b388ff,\n \"a200\": #7c4dff,\n \"a400\": #651fff,\n \"a700\": #6200ea\n);\n\n$clr-deep-purple: map-get($clr-deep-purple-list, \"base\");\n\n$clr-deep-purple-50: map-get($clr-deep-purple-list, \"50\");\n$clr-deep-purple-100: map-get($clr-deep-purple-list, \"100\");\n$clr-deep-purple-200: map-get($clr-deep-purple-list, \"200\");\n$clr-deep-purple-300: map-get($clr-deep-purple-list, \"300\");\n$clr-deep-purple-400: map-get($clr-deep-purple-list, \"400\");\n$clr-deep-purple-500: map-get($clr-deep-purple-list, \"500\");\n$clr-deep-purple-600: map-get($clr-deep-purple-list, \"600\");\n$clr-deep-purple-700: map-get($clr-deep-purple-list, \"700\");\n$clr-deep-purple-800: map-get($clr-deep-purple-list, \"800\");\n$clr-deep-purple-900: map-get($clr-deep-purple-list, \"900\");\n$clr-deep-purple-a100: map-get($clr-deep-purple-list, \"a100\");\n$clr-deep-purple-a200: map-get($clr-deep-purple-list, \"a200\");\n$clr-deep-purple-a400: map-get($clr-deep-purple-list, \"a400\");\n$clr-deep-purple-a700: map-get($clr-deep-purple-list, \"a700\");\n\n\n//\n// Indigo\n//\n\n$clr-indigo-list: (\n \"base\": #3f51b5,\n \"50\": #e8eaf6,\n \"100\": #c5cae9,\n \"200\": #9fa8da,\n \"300\": #7986cb,\n \"400\": #5c6bc0,\n \"500\": #3f51b5,\n \"600\": #3949ab,\n \"700\": #303f9f,\n \"800\": #283593,\n \"900\": #1a237e,\n \"a100\": #8c9eff,\n \"a200\": #536dfe,\n \"a400\": #3d5afe,\n \"a700\": #304ffe\n);\n\n$clr-indigo: map-get($clr-indigo-list, \"base\");\n\n$clr-indigo-50: map-get($clr-indigo-list, \"50\");\n$clr-indigo-100: map-get($clr-indigo-list, \"100\");\n$clr-indigo-200: map-get($clr-indigo-list, \"200\");\n$clr-indigo-300: map-get($clr-indigo-list, \"300\");\n$clr-indigo-400: map-get($clr-indigo-list, \"400\");\n$clr-indigo-500: map-get($clr-indigo-list, \"500\");\n$clr-indigo-600: map-get($clr-indigo-list, \"600\");\n$clr-indigo-700: map-get($clr-indigo-list, \"700\");\n$clr-indigo-800: map-get($clr-indigo-list, \"800\");\n$clr-indigo-900: map-get($clr-indigo-list, \"900\");\n$clr-indigo-a100: map-get($clr-indigo-list, \"a100\");\n$clr-indigo-a200: map-get($clr-indigo-list, \"a200\");\n$clr-indigo-a400: map-get($clr-indigo-list, \"a400\");\n$clr-indigo-a700: map-get($clr-indigo-list, \"a700\");\n\n\n//\n// Blue\n//\n\n$clr-blue-list: (\n \"base\": #2196f3,\n \"50\": #e3f2fd,\n \"100\": #bbdefb,\n \"200\": #90caf9,\n \"300\": #64b5f6,\n \"400\": #42a5f5,\n \"500\": #2196f3,\n \"600\": #1e88e5,\n \"700\": #1976d2,\n \"800\": #1565c0,\n \"900\": #0d47a1,\n \"a100\": #82b1ff,\n \"a200\": #448aff,\n \"a400\": #2979ff,\n \"a700\": #2962ff\n);\n\n$clr-blue: map-get($clr-blue-list, \"base\");\n\n$clr-blue-50: map-get($clr-blue-list, \"50\");\n$clr-blue-100: map-get($clr-blue-list, \"100\");\n$clr-blue-200: map-get($clr-blue-list, \"200\");\n$clr-blue-300: map-get($clr-blue-list, \"300\");\n$clr-blue-400: map-get($clr-blue-list, \"400\");\n$clr-blue-500: map-get($clr-blue-list, \"500\");\n$clr-blue-600: map-get($clr-blue-list, \"600\");\n$clr-blue-700: map-get($clr-blue-list, \"700\");\n$clr-blue-800: map-get($clr-blue-list, \"800\");\n$clr-blue-900: map-get($clr-blue-list, \"900\");\n$clr-blue-a100: map-get($clr-blue-list, \"a100\");\n$clr-blue-a200: map-get($clr-blue-list, \"a200\");\n$clr-blue-a400: map-get($clr-blue-list, \"a400\");\n$clr-blue-a700: map-get($clr-blue-list, \"a700\");\n\n\n//\n// Light Blue\n//\n\n$clr-light-blue-list: (\n \"base\": #03a9f4,\n \"50\": #e1f5fe,\n \"100\": #b3e5fc,\n \"200\": #81d4fa,\n \"300\": #4fc3f7,\n \"400\": #29b6f6,\n \"500\": #03a9f4,\n \"600\": #039be5,\n \"700\": #0288d1,\n \"800\": #0277bd,\n \"900\": #01579b,\n \"a100\": #80d8ff,\n \"a200\": #40c4ff,\n \"a400\": #00b0ff,\n \"a700\": #0091ea\n);\n\n$clr-light-blue: map-get($clr-light-blue-list, \"base\");\n\n$clr-light-blue-50: map-get($clr-light-blue-list, \"50\");\n$clr-light-blue-100: map-get($clr-light-blue-list, \"100\");\n$clr-light-blue-200: map-get($clr-light-blue-list, \"200\");\n$clr-light-blue-300: map-get($clr-light-blue-list, \"300\");\n$clr-light-blue-400: map-get($clr-light-blue-list, \"400\");\n$clr-light-blue-500: map-get($clr-light-blue-list, \"500\");\n$clr-light-blue-600: map-get($clr-light-blue-list, \"600\");\n$clr-light-blue-700: map-get($clr-light-blue-list, \"700\");\n$clr-light-blue-800: map-get($clr-light-blue-list, \"800\");\n$clr-light-blue-900: map-get($clr-light-blue-list, \"900\");\n$clr-light-blue-a100: map-get($clr-light-blue-list, \"a100\");\n$clr-light-blue-a200: map-get($clr-light-blue-list, \"a200\");\n$clr-light-blue-a400: map-get($clr-light-blue-list, \"a400\");\n$clr-light-blue-a700: map-get($clr-light-blue-list, \"a700\");\n\n\n//\n// Cyan\n//\n\n$clr-cyan-list: (\n \"base\": #00bcd4,\n \"50\": #e0f7fa,\n \"100\": #b2ebf2,\n \"200\": #80deea,\n \"300\": #4dd0e1,\n \"400\": #26c6da,\n \"500\": #00bcd4,\n \"600\": #00acc1,\n \"700\": #0097a7,\n \"800\": #00838f,\n \"900\": #006064,\n \"a100\": #84ffff,\n \"a200\": #18ffff,\n \"a400\": #00e5ff,\n \"a700\": #00b8d4\n);\n\n$clr-cyan: map-get($clr-cyan-list, \"base\");\n\n$clr-cyan-50: map-get($clr-cyan-list, \"50\");\n$clr-cyan-100: map-get($clr-cyan-list, \"100\");\n$clr-cyan-200: map-get($clr-cyan-list, \"200\");\n$clr-cyan-300: map-get($clr-cyan-list, \"300\");\n$clr-cyan-400: map-get($clr-cyan-list, \"400\");\n$clr-cyan-500: map-get($clr-cyan-list, \"500\");\n$clr-cyan-600: map-get($clr-cyan-list, \"600\");\n$clr-cyan-700: map-get($clr-cyan-list, \"700\");\n$clr-cyan-800: map-get($clr-cyan-list, \"800\");\n$clr-cyan-900: map-get($clr-cyan-list, \"900\");\n$clr-cyan-a100: map-get($clr-cyan-list, \"a100\");\n$clr-cyan-a200: map-get($clr-cyan-list, \"a200\");\n$clr-cyan-a400: map-get($clr-cyan-list, \"a400\");\n$clr-cyan-a700: map-get($clr-cyan-list, \"a700\");\n\n\n//\n// Teal\n//\n\n$clr-teal-list: (\n \"base\": #009688,\n \"50\": #e0f2f1,\n \"100\": #b2dfdb,\n \"200\": #80cbc4,\n \"300\": #4db6ac,\n \"400\": #26a69a,\n \"500\": #009688,\n \"600\": #00897b,\n \"700\": #00796b,\n \"800\": #00695c,\n \"900\": #004d40,\n \"a100\": #a7ffeb,\n \"a200\": #64ffda,\n \"a400\": #1de9b6,\n \"a700\": #00bfa5\n);\n\n$clr-teal: map-get($clr-teal-list, \"base\");\n\n$clr-teal-50: map-get($clr-teal-list, \"50\");\n$clr-teal-100: map-get($clr-teal-list, \"100\");\n$clr-teal-200: map-get($clr-teal-list, \"200\");\n$clr-teal-300: map-get($clr-teal-list, \"300\");\n$clr-teal-400: map-get($clr-teal-list, \"400\");\n$clr-teal-500: map-get($clr-teal-list, \"500\");\n$clr-teal-600: map-get($clr-teal-list, \"600\");\n$clr-teal-700: map-get($clr-teal-list, \"700\");\n$clr-teal-800: map-get($clr-teal-list, \"800\");\n$clr-teal-900: map-get($clr-teal-list, \"900\");\n$clr-teal-a100: map-get($clr-teal-list, \"a100\");\n$clr-teal-a200: map-get($clr-teal-list, \"a200\");\n$clr-teal-a400: map-get($clr-teal-list, \"a400\");\n$clr-teal-a700: map-get($clr-teal-list, \"a700\");\n\n\n//\n// Green\n//\n\n$clr-green-list: (\n \"base\": #4caf50,\n \"50\": #e8f5e9,\n \"100\": #c8e6c9,\n \"200\": #a5d6a7,\n \"300\": #81c784,\n \"400\": #66bb6a,\n \"500\": #4caf50,\n \"600\": #43a047,\n \"700\": #388e3c,\n \"800\": #2e7d32,\n \"900\": #1b5e20,\n \"a100\": #b9f6ca,\n \"a200\": #69f0ae,\n \"a400\": #00e676,\n \"a700\": #00c853\n);\n\n$clr-green: map-get($clr-green-list, \"base\");\n\n$clr-green-50: map-get($clr-green-list, \"50\");\n$clr-green-100: map-get($clr-green-list, \"100\");\n$clr-green-200: map-get($clr-green-list, \"200\");\n$clr-green-300: map-get($clr-green-list, \"300\");\n$clr-green-400: map-get($clr-green-list, \"400\");\n$clr-green-500: map-get($clr-green-list, \"500\");\n$clr-green-600: map-get($clr-green-list, \"600\");\n$clr-green-700: map-get($clr-green-list, \"700\");\n$clr-green-800: map-get($clr-green-list, \"800\");\n$clr-green-900: map-get($clr-green-list, \"900\");\n$clr-green-a100: map-get($clr-green-list, \"a100\");\n$clr-green-a200: map-get($clr-green-list, \"a200\");\n$clr-green-a400: map-get($clr-green-list, \"a400\");\n$clr-green-a700: map-get($clr-green-list, \"a700\");\n\n\n//\n// Light green\n//\n\n$clr-light-green-list: (\n \"base\": #8bc34a,\n \"50\": #f1f8e9,\n \"100\": #dcedc8,\n \"200\": #c5e1a5,\n \"300\": #aed581,\n \"400\": #9ccc65,\n \"500\": #8bc34a,\n \"600\": #7cb342,\n \"700\": #689f38,\n \"800\": #558b2f,\n \"900\": #33691e,\n \"a100\": #ccff90,\n \"a200\": #b2ff59,\n \"a400\": #76ff03,\n \"a700\": #64dd17\n);\n\n$clr-light-green: map-get($clr-light-green-list, \"base\");\n\n$clr-light-green-50: map-get($clr-light-green-list, \"50\");\n$clr-light-green-100: map-get($clr-light-green-list, \"100\");\n$clr-light-green-200: map-get($clr-light-green-list, \"200\");\n$clr-light-green-300: map-get($clr-light-green-list, \"300\");\n$clr-light-green-400: map-get($clr-light-green-list, \"400\");\n$clr-light-green-500: map-get($clr-light-green-list, \"500\");\n$clr-light-green-600: map-get($clr-light-green-list, \"600\");\n$clr-light-green-700: map-get($clr-light-green-list, \"700\");\n$clr-light-green-800: map-get($clr-light-green-list, \"800\");\n$clr-light-green-900: map-get($clr-light-green-list, \"900\");\n$clr-light-green-a100: map-get($clr-light-green-list, \"a100\");\n$clr-light-green-a200: map-get($clr-light-green-list, \"a200\");\n$clr-light-green-a400: map-get($clr-light-green-list, \"a400\");\n$clr-light-green-a700: map-get($clr-light-green-list, \"a700\");\n\n\n//\n// Lime\n//\n\n$clr-lime-list: (\n \"base\": #cddc39,\n \"50\": #f9fbe7,\n \"100\": #f0f4c3,\n \"200\": #e6ee9c,\n \"300\": #dce775,\n \"400\": #d4e157,\n \"500\": #cddc39,\n \"600\": #c0ca33,\n \"700\": #afb42b,\n \"800\": #9e9d24,\n \"900\": #827717,\n \"a100\": #f4ff81,\n \"a200\": #eeff41,\n \"a400\": #c6ff00,\n \"a700\": #aeea00\n);\n\n$clr-lime: map-get($clr-lime-list, \"base\");\n\n$clr-lime-50: map-get($clr-lime-list, \"50\");\n$clr-lime-100: map-get($clr-lime-list, \"100\");\n$clr-lime-200: map-get($clr-lime-list, \"200\");\n$clr-lime-300: map-get($clr-lime-list, \"300\");\n$clr-lime-400: map-get($clr-lime-list, \"400\");\n$clr-lime-500: map-get($clr-lime-list, \"500\");\n$clr-lime-600: map-get($clr-lime-list, \"600\");\n$clr-lime-700: map-get($clr-lime-list, \"700\");\n$clr-lime-800: map-get($clr-lime-list, \"800\");\n$clr-lime-900: map-get($clr-lime-list, \"900\");\n$clr-lime-a100: map-get($clr-lime-list, \"a100\");\n$clr-lime-a200: map-get($clr-lime-list, \"a200\");\n$clr-lime-a400: map-get($clr-lime-list, \"a400\");\n$clr-lime-a700: map-get($clr-lime-list, \"a700\");\n\n\n//\n// Yellow\n//\n\n$clr-yellow-list: (\n \"base\": #ffeb3b,\n \"50\": #fffde7,\n \"100\": #fff9c4,\n \"200\": #fff59d,\n \"300\": #fff176,\n \"400\": #ffee58,\n \"500\": #ffeb3b,\n \"600\": #fdd835,\n \"700\": #fbc02d,\n \"800\": #f9a825,\n \"900\": #f57f17,\n \"a100\": #ffff8d,\n \"a200\": #ffff00,\n \"a400\": #ffea00,\n \"a700\": #ffd600\n);\n\n$clr-yellow: map-get($clr-yellow-list, \"base\");\n\n$clr-yellow-50: map-get($clr-yellow-list, \"50\");\n$clr-yellow-100: map-get($clr-yellow-list, \"100\");\n$clr-yellow-200: map-get($clr-yellow-list, \"200\");\n$clr-yellow-300: map-get($clr-yellow-list, \"300\");\n$clr-yellow-400: map-get($clr-yellow-list, \"400\");\n$clr-yellow-500: map-get($clr-yellow-list, \"500\");\n$clr-yellow-600: map-get($clr-yellow-list, \"600\");\n$clr-yellow-700: map-get($clr-yellow-list, \"700\");\n$clr-yellow-800: map-get($clr-yellow-list, \"800\");\n$clr-yellow-900: map-get($clr-yellow-list, \"900\");\n$clr-yellow-a100: map-get($clr-yellow-list, \"a100\");\n$clr-yellow-a200: map-get($clr-yellow-list, \"a200\");\n$clr-yellow-a400: map-get($clr-yellow-list, \"a400\");\n$clr-yellow-a700: map-get($clr-yellow-list, \"a700\");\n\n\n//\n// amber\n//\n\n$clr-amber-list: (\n \"base\": #ffc107,\n \"50\": #fff8e1,\n \"100\": #ffecb3,\n \"200\": #ffe082,\n \"300\": #ffd54f,\n \"400\": #ffca28,\n \"500\": #ffc107,\n \"600\": #ffb300,\n \"700\": #ffa000,\n \"800\": #ff8f00,\n \"900\": #ff6f00,\n \"a100\": #ffe57f,\n \"a200\": #ffd740,\n \"a400\": #ffc400,\n \"a700\": #ffab00\n);\n\n$clr-amber: map-get($clr-amber-list, \"base\");\n\n$clr-amber-50: map-get($clr-amber-list, \"50\");\n$clr-amber-100: map-get($clr-amber-list, \"100\");\n$clr-amber-200: map-get($clr-amber-list, \"200\");\n$clr-amber-300: map-get($clr-amber-list, \"300\");\n$clr-amber-400: map-get($clr-amber-list, \"400\");\n$clr-amber-500: map-get($clr-amber-list, \"500\");\n$clr-amber-600: map-get($clr-amber-list, \"600\");\n$clr-amber-700: map-get($clr-amber-list, \"700\");\n$clr-amber-800: map-get($clr-amber-list, \"800\");\n$clr-amber-900: map-get($clr-amber-list, \"900\");\n$clr-amber-a100: map-get($clr-amber-list, \"a100\");\n$clr-amber-a200: map-get($clr-amber-list, \"a200\");\n$clr-amber-a400: map-get($clr-amber-list, \"a400\");\n$clr-amber-a700: map-get($clr-amber-list, \"a700\");\n\n\n//\n// Orange\n//\n\n$clr-orange-list: (\n \"base\": #ff9800,\n \"50\": #fff3e0,\n \"100\": #ffe0b2,\n \"200\": #ffcc80,\n \"300\": #ffb74d,\n \"400\": #ffa726,\n \"500\": #ff9800,\n \"600\": #fb8c00,\n \"700\": #f57c00,\n \"800\": #ef6c00,\n \"900\": #e65100,\n \"a100\": #ffd180,\n \"a200\": #ffab40,\n \"a400\": #ff9100,\n \"a700\": #ff6d00\n);\n\n$clr-orange: map-get($clr-orange-list, \"base\");\n\n$clr-orange-50: map-get($clr-orange-list, \"50\");\n$clr-orange-100: map-get($clr-orange-list, \"100\");\n$clr-orange-200: map-get($clr-orange-list, \"200\");\n$clr-orange-300: map-get($clr-orange-list, \"300\");\n$clr-orange-400: map-get($clr-orange-list, \"400\");\n$clr-orange-500: map-get($clr-orange-list, \"500\");\n$clr-orange-600: map-get($clr-orange-list, \"600\");\n$clr-orange-700: map-get($clr-orange-list, \"700\");\n$clr-orange-800: map-get($clr-orange-list, \"800\");\n$clr-orange-900: map-get($clr-orange-list, \"900\");\n$clr-orange-a100: map-get($clr-orange-list, \"a100\");\n$clr-orange-a200: map-get($clr-orange-list, \"a200\");\n$clr-orange-a400: map-get($clr-orange-list, \"a400\");\n$clr-orange-a700: map-get($clr-orange-list, \"a700\");\n\n\n//\n// Deep orange\n//\n\n$clr-deep-orange-list: (\n \"base\": #ff5722,\n \"50\": #fbe9e7,\n \"100\": #ffccbc,\n \"200\": #ffab91,\n \"300\": #ff8a65,\n \"400\": #ff7043,\n \"500\": #ff5722,\n \"600\": #f4511e,\n \"700\": #e64a19,\n \"800\": #d84315,\n \"900\": #bf360c,\n \"a100\": #ff9e80,\n \"a200\": #ff6e40,\n \"a400\": #ff3d00,\n \"a700\": #dd2c00\n);\n\n$clr-deep-orange: map-get($clr-deep-orange-list, \"base\");\n\n$clr-deep-orange-50: map-get($clr-deep-orange-list, \"50\");\n$clr-deep-orange-100: map-get($clr-deep-orange-list, \"100\");\n$clr-deep-orange-200: map-get($clr-deep-orange-list, \"200\");\n$clr-deep-orange-300: map-get($clr-deep-orange-list, \"300\");\n$clr-deep-orange-400: map-get($clr-deep-orange-list, \"400\");\n$clr-deep-orange-500: map-get($clr-deep-orange-list, \"500\");\n$clr-deep-orange-600: map-get($clr-deep-orange-list, \"600\");\n$clr-deep-orange-700: map-get($clr-deep-orange-list, \"700\");\n$clr-deep-orange-800: map-get($clr-deep-orange-list, \"800\");\n$clr-deep-orange-900: map-get($clr-deep-orange-list, \"900\");\n$clr-deep-orange-a100: map-get($clr-deep-orange-list, \"a100\");\n$clr-deep-orange-a200: map-get($clr-deep-orange-list, \"a200\");\n$clr-deep-orange-a400: map-get($clr-deep-orange-list, \"a400\");\n$clr-deep-orange-a700: map-get($clr-deep-orange-list, \"a700\");\n\n\n//\n// Brown\n//\n\n$clr-brown-list: (\n \"base\": #795548,\n \"50\": #efebe9,\n \"100\": #d7ccc8,\n \"200\": #bcaaa4,\n \"300\": #a1887f,\n \"400\": #8d6e63,\n \"500\": #795548,\n \"600\": #6d4c41,\n \"700\": #5d4037,\n \"800\": #4e342e,\n \"900\": #3e2723,\n);\n\n$clr-brown: map-get($clr-brown-list, \"base\");\n\n$clr-brown-50: map-get($clr-brown-list, \"50\");\n$clr-brown-100: map-get($clr-brown-list, \"100\");\n$clr-brown-200: map-get($clr-brown-list, \"200\");\n$clr-brown-300: map-get($clr-brown-list, \"300\");\n$clr-brown-400: map-get($clr-brown-list, \"400\");\n$clr-brown-500: map-get($clr-brown-list, \"500\");\n$clr-brown-600: map-get($clr-brown-list, \"600\");\n$clr-brown-700: map-get($clr-brown-list, \"700\");\n$clr-brown-800: map-get($clr-brown-list, \"800\");\n$clr-brown-900: map-get($clr-brown-list, \"900\");\n\n\n//\n// Grey\n//\n\n$clr-grey-list: (\n \"base\": #9e9e9e,\n \"50\": #fafafa,\n \"100\": #f5f5f5,\n \"200\": #eeeeee,\n \"300\": #e0e0e0,\n \"400\": #bdbdbd,\n \"500\": #9e9e9e,\n \"600\": #757575,\n \"700\": #616161,\n \"800\": #424242,\n \"900\": #212121,\n);\n\n$clr-grey: map-get($clr-grey-list, \"base\");\n\n$clr-grey-50: map-get($clr-grey-list, \"50\");\n$clr-grey-100: map-get($clr-grey-list, \"100\");\n$clr-grey-200: map-get($clr-grey-list, \"200\");\n$clr-grey-300: map-get($clr-grey-list, \"300\");\n$clr-grey-400: map-get($clr-grey-list, \"400\");\n$clr-grey-500: map-get($clr-grey-list, \"500\");\n$clr-grey-600: map-get($clr-grey-list, \"600\");\n$clr-grey-700: map-get($clr-grey-list, \"700\");\n$clr-grey-800: map-get($clr-grey-list, \"800\");\n$clr-grey-900: map-get($clr-grey-list, \"900\");\n\n\n//\n// Blue grey\n//\n\n$clr-blue-grey-list: (\n \"base\": #607d8b,\n \"50\": #eceff1,\n \"100\": #cfd8dc,\n \"200\": #b0bec5,\n \"300\": #90a4ae,\n \"400\": #78909c,\n \"500\": #607d8b,\n \"600\": #546e7a,\n \"700\": #455a64,\n \"800\": #37474f,\n \"900\": #263238,\n);\n\n$clr-blue-grey: map-get($clr-blue-grey-list, \"base\");\n\n$clr-blue-grey-50: map-get($clr-blue-grey-list, \"50\");\n$clr-blue-grey-100: map-get($clr-blue-grey-list, \"100\");\n$clr-blue-grey-200: map-get($clr-blue-grey-list, \"200\");\n$clr-blue-grey-300: map-get($clr-blue-grey-list, \"300\");\n$clr-blue-grey-400: map-get($clr-blue-grey-list, \"400\");\n$clr-blue-grey-500: map-get($clr-blue-grey-list, \"500\");\n$clr-blue-grey-600: map-get($clr-blue-grey-list, \"600\");\n$clr-blue-grey-700: map-get($clr-blue-grey-list, \"700\");\n$clr-blue-grey-800: map-get($clr-blue-grey-list, \"800\");\n$clr-blue-grey-900: map-get($clr-blue-grey-list, \"900\");\n\n\n//\n// Black\n//\n\n$clr-black-list: (\n \"base\": #000\n);\n\n$clr-black: map-get($clr-black-list, \"base\");\n\n\n//\n// White\n//\n\n$clr-white-list: (\n \"base\": #fff\n);\n\n$clr-white: map-get($clr-white-list, \"base\");\n\n\n//\n// List for all Colors for looping\n//\n\n$clr-list-all: (\n \"red\": $clr-red-list,\n \"pink\": $clr-pink-list,\n \"purple\": $clr-purple-list,\n \"deep-purple\": $clr-deep-purple-list,\n \"indigo\": $clr-indigo-list,\n \"blue\": $clr-blue-list,\n \"light-blue\": $clr-light-blue-list,\n \"cyan\": $clr-cyan-list,\n \"teal\": $clr-teal-list,\n \"green\": $clr-green-list,\n \"light-green\": $clr-light-green-list,\n \"lime\": $clr-lime-list,\n \"yellow\": $clr-yellow-list,\n \"amber\": $clr-amber-list,\n \"orange\": $clr-orange-list,\n \"deep-orange\": $clr-deep-orange-list,\n \"brown\": $clr-brown-list,\n \"grey\": $clr-grey-list,\n \"blue-grey\": $clr-blue-grey-list,\n \"black\": $clr-black-list,\n \"white\": $clr-white-list\n);\n\n\n//\n// Typography\n//\n\n$clr-ui-display-4: $clr-grey-600;\n$clr-ui-display-3: $clr-grey-600;\n$clr-ui-display-2: $clr-grey-600;\n$clr-ui-display-1: $clr-grey-600;\n$clr-ui-headline: $clr-grey-900;\n$clr-ui-title: $clr-grey-900;\n$clr-ui-subhead-1: $clr-grey-900;\n$clr-ui-body-2: $clr-grey-900;\n$clr-ui-body-1: $clr-grey-900;\n$clr-ui-caption: $clr-grey-600;\n$clr-ui-menu: $clr-grey-900;\n$clr-ui-button: $clr-grey-900;\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Icon definitions\n:root {\n --md-footnotes-icon: svg-load(\"material/keyboard-return.svg\");\n}\n\n// ----------------------------------------------------------------------------\n\n// Scoped in typesetted content to match specificity of regular content\n.md-typeset {\n\n // Footnote container\n .footnote {\n color: var(--md-default-fg-color--light);\n font-size: px2rem(12.8px);\n\n // Footnote list - omit left indentation\n > ol {\n margin-left: 0;\n\n // Footnote item - footnote items can contain lists, so we need to scope\n // the spacing adjustments to the top-level footnote item.\n > li {\n transition: color 125ms;\n\n // Darken color on target\n &:target {\n color: var(--md-default-fg-color);\n }\n\n // Show backreferences on footnote hover\n &:hover .footnote-backref,\n &:target .footnote-backref {\n transform: translateX(0);\n opacity: 1;\n }\n\n // Adjust spacing on first child\n > :first-child {\n margin-top: 0;\n }\n }\n }\n }\n\n // Footnote reference\n .footnote-ref {\n font-weight: 700;\n font-size: px2em(12px, 16px);\n\n // Hack: increase specificity to override default\n html & {\n outline-offset: px2rem(2px);\n }\n }\n\n // Footnote backreference\n .footnote-backref {\n display: inline-block;\n color: var(--md-typeset-a-color);\n // Hack: omit Unicode arrow for replacement with icon\n font-size: 0;\n vertical-align: text-bottom;\n transform: translateX(px2rem(5px));\n opacity: 0;\n transition:\n color 250ms,\n transform 250ms 250ms,\n opacity 125ms 250ms;\n\n // [print]: Show footnote backreferences\n @media print {\n color: var(--md-typeset-a-color);\n transform: translateX(0);\n opacity: 1;\n }\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n transform: translateX(px2rem(-5px));\n }\n\n // Adjust color on hover\n &:hover {\n color: var(--md-accent-fg-color);\n }\n\n // Footnote backreference icon\n &::before {\n display: inline-block;\n width: px2rem(16px);\n height: px2rem(16px);\n background-color: currentColor;\n mask-image: var(--md-footnotes-icon);\n mask-repeat: no-repeat;\n mask-size: contain;\n content: \"\";\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n\n // Flip icon vertically\n svg {\n transform: scaleX(-1);\n }\n }\n }\n }\n\n // Footnote reference wrapper\n [id^=\"fnref:\"]:target {\n scroll-margin-top: initial;\n margin-top: -1 * px2rem(48px + 24px - 4px);\n padding-top: px2rem(48px + 24px - 4px);\n\n // Show outline for all devices\n > .footnote-ref {\n outline: auto;\n }\n }\n\n // Footnote wrapper\n [id^=\"fn:\"]:target {\n scroll-margin-top: initial;\n margin-top: -1 * px2rem(48px + 24px - 3px);\n padding-top: px2rem(48px + 24px - 3px);\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Scoped in typesetted content to match specificity of regular content\n.md-typeset {\n\n // Headerlink\n .headerlink {\n display: inline-block;\n margin-left: px2rem(10px);\n color: var(--md-default-fg-color--lighter);\n opacity: 0;\n transition:\n color 250ms,\n opacity 125ms;\n\n // [print]: Hide headerlinks\n @media print {\n display: none;\n }\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n margin-right: px2rem(10px);\n margin-left: initial;\n }\n }\n\n // Show headerlinks on parent hover\n :hover > .headerlink,\n :target > .headerlink,\n .headerlink:focus {\n opacity: 1;\n transition:\n color 250ms,\n opacity 125ms;\n }\n\n // Adjust color on parent target or focus/hover\n :target > .headerlink,\n .headerlink:focus,\n .headerlink:hover {\n color: var(--md-accent-fg-color);\n }\n\n // Adjust scroll offset for all elements with `id` attributes - general scroll\n // margin offset for anything that can be targeted. Browser support is pretty\n // decent by now, but Edge <79 and Safari (iOS and macOS) still don't support\n // it properly, so we settle with a cross-browser anchor correction solution.\n :target {\n scroll-margin-top: px2rem(48px + 24px);\n }\n\n // Adjust scroll offset for headlines of level 1-3\n h1:target,\n h2:target,\n h3:target {\n scroll-margin-top: initial;\n\n // Anchor correction hack\n &::before {\n display: block;\n margin-top: -1 * px2rem(48px + 24px - 4px);\n padding-top: px2rem(48px + 24px - 4px);\n content: \"\";\n }\n }\n\n // Adjust scroll offset for headlines of level 4\n h4:target {\n scroll-margin-top: initial;\n\n // Anchor correction hack\n &::before {\n display: block;\n margin-top: -1 * px2rem(48px + 24px - 3px);\n padding-top: px2rem(48px + 24px - 3px);\n content: \"\";\n }\n }\n\n // Adjust scroll offset for headlines of level 5-6\n h5:target,\n h6:target {\n scroll-margin-top: initial;\n\n // Anchor correction hack\n &::before {\n display: block;\n margin-top: -1 * px2rem(48px + 24px);\n padding-top: px2rem(48px + 24px);\n content: \"\";\n }\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Scoped in typesetted content to match specificity of regular content\n.md-typeset {\n\n // Arithmatex container\n div.arithmatex {\n overflow: auto;\n\n // [mobile -]: Align with body copy\n @include break-to-device(mobile) {\n margin: 0 px2rem(-16px);\n }\n\n // Arithmatex content\n > * {\n width: min-content;\n // stylelint-disable-next-line declaration-no-important\n margin: 1em auto !important;\n padding: 0 px2rem(16px);\n touch-action: auto;\n }\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Scoped in typesetted content to match specificity of regular content\n.md-typeset {\n\n // Deletion, addition or comment\n del.critic,\n ins.critic,\n .critic.comment {\n box-decoration-break: clone;\n }\n\n // Deletion\n del.critic {\n background-color: var(--md-typeset-del-color);\n }\n\n // Addition\n ins.critic {\n background-color: var(--md-typeset-ins-color);\n }\n\n // Comment\n .critic.comment {\n color: var(--md-code-hl-comment-color);\n\n // Comment opening mark\n &::before {\n content: \"/* \";\n }\n\n // Comment closing mark\n &::after {\n content: \" */\";\n }\n }\n\n // Critic block\n .critic.block {\n display: block;\n margin: 1em 0;\n padding-right: px2rem(16px);\n padding-left: px2rem(16px);\n overflow: auto;\n box-shadow: none;\n\n // Adjust spacing on first child\n > :first-child {\n margin-top: 0.5em;\n }\n\n // Adjust spacing on last child\n > :last-child {\n margin-bottom: 0.5em;\n }\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Icon definitions\n:root {\n --md-details-icon: svg-load(\"material/chevron-right.svg\");\n}\n\n// ----------------------------------------------------------------------------\n\n// Scoped in typesetted content to match specificity of regular content\n.md-typeset {\n\n // Details\n details {\n @extend .admonition;\n\n display: flow-root;\n padding-top: 0;\n overflow: visible;\n\n // Details title icon - rotate icon on transition to open state\n &[open] > summary::after {\n transform: rotate(90deg);\n }\n\n // Adjust spacing for details in closed state\n &:not([open]) {\n padding-bottom: 0;\n box-shadow: none;\n\n // Hack: we cannot set `overflow: hidden` on the `details` element (which\n // is why we set it to `overflow: visible`, as the outline would not be\n // visible when focusing. Therefore, we must set the border radius on the\n // summary explicitly.\n > summary {\n border-radius: px2rem(2px);\n }\n }\n\n // Hack: omit margin collapse\n &::after {\n display: table;\n content: \"\";\n }\n }\n\n // Details title\n summary {\n @extend .admonition-title;\n\n display: block;\n min-height: px2rem(20px);\n padding: px2rem(8px) px2rem(36px) px2rem(8px) px2rem(40px);\n border-top-left-radius: px2rem(2px);\n border-top-right-radius: px2rem(2px);\n cursor: pointer;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n padding: px2rem(8px) px2rem(44px) px2rem(8px) px2rem(36px);\n }\n\n // Hide outline for pointer devices\n &:not(.focus-visible) {\n outline: none;\n -webkit-tap-highlight-color: transparent;\n }\n\n // Details marker\n &::after {\n position: absolute;\n top: px2rem(8px);\n right: px2rem(8px);\n width: px2rem(20px);\n height: px2rem(20px);\n background-color: currentColor;\n mask-image: var(--md-details-icon);\n mask-repeat: no-repeat;\n mask-size: contain;\n transform: rotate(0deg);\n transition: transform 250ms;\n content: \"\";\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n right: initial;\n left: px2rem(8px);\n transform: rotate(180deg);\n }\n }\n\n // Hide native details marker\n &::marker,\n &::-webkit-details-marker {\n display: none;\n }\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Scoped in typesetted content to match specificity of regular content\n.md-typeset {\n\n // Emoji and icon container\n .emojione,\n .twemoji,\n .gemoji {\n display: inline-flex;\n height: px2em(18px);\n vertical-align: text-top;\n\n // Icon - inlined via mkdocs-material-extensions\n svg {\n width: px2em(18px);\n max-height: 100%;\n fill: currentColor;\n }\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules: syntax highlighting\n// ----------------------------------------------------------------------------\n\n// Code block\n.highlight {\n .o, // Operator\n .ow { // Operator, word\n color: var(--md-code-hl-operator-color);\n }\n\n .p { // Punctuation\n color: var(--md-code-hl-punctuation-color);\n }\n\n .cpf, // Comment, preprocessor file\n .l, // Literal\n .s, // Literal, string\n .sb, // Literal, string backticks\n .sc, // Literal, string char\n .s2, // Literal, string double\n .si, // Literal, string interpol\n .s1, // Literal, string single\n .ss { // Literal, string symbol\n color: var(--md-code-hl-string-color);\n }\n\n .cp, // Comment, pre-processor\n .se, // Literal, string escape\n .sh, // Literal, string heredoc\n .sr, // Literal, string regex\n .sx { // Literal, string other\n color: var(--md-code-hl-special-color);\n }\n\n .m, // Number\n .mb, // Number, binary\n .mf, // Number, float\n .mh, // Number, hex\n .mi, // Number, integer\n .il, // Number, integer long\n .mo { // Number, octal\n color: var(--md-code-hl-number-color);\n }\n\n .k, // Keyword,\n .kd, // Keyword, declaration\n .kn, // Keyword, namespace\n .kp, // Keyword, pseudo\n .kr, // Keyword, reserved\n .kt { // Keyword, type\n color: var(--md-code-hl-keyword-color);\n }\n\n .kc, // Keyword, constant\n .n { // Name\n color: var(--md-code-hl-name-color);\n }\n\n .no, // Name, constant\n .nb, // Name, builtin\n .bp { // Name, builtin pseudo\n color: var(--md-code-hl-constant-color);\n }\n\n .nc, // Name, class\n .ne, // Name, exception\n .nf, // Name, function\n .nn { // Name, namespace\n color: var(--md-code-hl-function-color);\n }\n\n .nd, // Name, decorator\n .ni, // Name, entity\n .nl, // Name, label\n .nt { // Name, tag\n color: var(--md-code-hl-keyword-color);\n }\n\n .c, // Comment\n .cm, // Comment, multiline\n .c1, // Comment, single\n .ch, // Comment, shebang\n .cs, // Comment, special\n .sd { // Literal, string doc\n color: var(--md-code-hl-comment-color);\n }\n\n .na, // Name, attribute\n .nv, // Variable,\n .vc, // Variable, class\n .vg, // Variable, global\n .vi { // Variable, instance\n color: var(--md-code-hl-variable-color);\n }\n\n .ge, // Generic, emph\n .gr, // Generic, error\n .gh, // Generic, heading\n .go, // Generic, output\n .gp, // Generic, prompt\n .gs, // Generic, strong\n .gu, // Generic, subheading\n .gt { // Generic, traceback\n color: var(--md-code-hl-generic-color);\n }\n\n .gd, // Diff, delete\n .gi { // Diff, insert\n margin: 0 px2em(-2px);\n padding: 0 px2em(2px);\n border-radius: px2rem(2px);\n }\n\n .gd { // Diff, delete\n background-color: var(--md-typeset-del-color);\n }\n\n .gi { // Diff, insert\n background-color: var(--md-typeset-ins-color);\n }\n\n // Highlighted line\n .hll {\n display: block;\n margin: 0 px2em(-16px, 13.6px);\n padding: 0 px2em(16px, 13.6px);\n background-color: var(--md-code-hl-color);\n }\n\n // Code block line numbers (inline)\n [data-linenos]::before {\n position: sticky;\n left: px2em(-16px, 13.6px);\n float: left;\n margin-right: px2em(16px, 13.6px);\n margin-left: px2em(-16px, 13.6px);\n padding-left: px2em(16px, 13.6px);\n color: var(--md-default-fg-color--light);\n background-color: var(--md-code-bg-color);\n box-shadow: px2rem(-1px) 0 var(--md-default-fg-color--lightest) inset;\n content: attr(data-linenos);\n user-select: none;\n }\n}\n\n// ----------------------------------------------------------------------------\n// Rules: layout\n// ----------------------------------------------------------------------------\n\n// Code block with line numbers\n.highlighttable {\n display: flow-root;\n overflow: hidden;\n\n // Set table elements to block layout, because otherwise the whole flexbox\n // hacking won't work correctly\n tbody,\n td {\n display: block;\n padding: 0;\n }\n\n // We need to use flexbox layout, because otherwise it's not possible to\n // make the code container scroll while keeping the line numbers static\n tr {\n display: flex;\n }\n\n // The pre tags are nested inside a table, so we need to omit the margin\n // because it collapses below all the overflows\n pre {\n margin: 0;\n }\n\n // Code block line numbers - disable user selection, so code can be easily\n // copied without accidentally also copying the line numbers\n .linenos {\n padding: px2em(10.5px, 13.6px) px2em(16px, 13.6px);\n padding-right: 0;\n font-size: px2em(13.6px);\n background-color: var(--md-code-bg-color);\n user-select: none;\n }\n\n // Code block line numbers container\n .linenodiv {\n padding-right: px2em(8px, 13.6px);\n box-shadow: px2rem(-1px) 0 var(--md-default-fg-color--lightest) inset;\n\n // Adjust colors and alignment\n pre {\n color: var(--md-default-fg-color--light);\n text-align: right;\n }\n }\n\n // Code block container - stretch to remaining space\n .code {\n flex: 1;\n overflow: hidden;\n }\n}\n\n// ----------------------------------------------------------------------------\n\n// Scoped in typesetted content to match specificity of regular content\n.md-typeset {\n\n // Code block with line numbers\n .highlighttable {\n margin: 1em 0;\n direction: ltr;\n border-radius: px2rem(2px);\n\n // Omit rounded borders on contained code block\n code {\n border-radius: 0;\n }\n }\n\n // [mobile -]: Align with body copy\n @include break-to-device(mobile) {\n\n // Top-level code block\n > .highlight {\n margin: 1em px2rem(-16px);\n\n // Highlighted line\n .hll {\n margin: 0 px2rem(-16px);\n padding: 0 px2rem(16px);\n }\n\n // Omit rounded borders\n code {\n border-radius: 0;\n }\n }\n\n // Top-level code block with line numbers\n > .highlighttable {\n margin: 1em px2rem(-16px);\n border-radius: 0;\n\n // Highlighted line\n .hll {\n margin: 0 px2rem(-16px);\n padding: 0 px2rem(16px);\n }\n }\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Scoped in typesetted content to match specificity of regular content\n.md-typeset {\n\n // Tabbed block content\n .tabbed-content {\n display: none;\n order: 99;\n width: 100%;\n box-shadow: 0 px2rem(-1px) var(--md-default-fg-color--lightest);\n\n // [print]: Show all tabs (even hidden ones) when printing\n @media print {\n display: block;\n order: initial;\n }\n\n // Code block is the only child of a tab - remove margin and mirror\n // previous (now deprecated) SuperFences code block grouping behavior\n > pre:only-child,\n > .highlight:only-child pre,\n > .highlighttable:only-child {\n margin: 0;\n\n // Omit rounded borders\n > code {\n border-top-left-radius: 0;\n border-top-right-radius: 0;\n }\n }\n\n // Adjust spacing for nested tab\n > .tabbed-set {\n margin: 0;\n }\n }\n\n // Tabbed block container\n .tabbed-set {\n position: relative;\n display: flex;\n flex-wrap: wrap;\n margin: 1em 0;\n border-radius: px2rem(2px);\n\n // Tab radio button - the Tabbed extension will generate radio buttons with\n // labels, so tabs can be triggered without the necessity for JavaScript.\n // This is pretty cool, as it has great accessibility out-of-the box, so\n // we just hide the radio button and toggle the label color for indication.\n > input {\n position: absolute;\n width: 0;\n height: 0;\n opacity: 0;\n\n // Tab label for checked radio button\n &:checked + label {\n color: var(--md-accent-fg-color);\n border-color: var(--md-accent-fg-color);\n\n // Show tabbed block content\n + .tabbed-content {\n display: block;\n }\n }\n\n // Tab label on focus\n &:focus + label {\n outline-style: auto;\n outline-color: var(--md-accent-fg-color);\n }\n\n // Hide outline for pointer devices\n &:not(.focus-visible) + label {\n outline: none;\n -webkit-tap-highlight-color: transparent;\n }\n }\n\n // Tab label\n > label {\n z-index: 1;\n width: auto;\n padding: px2em(12px, 12.8px) 1.25em px2em(10px, 12.8px);\n color: var(--md-default-fg-color--light);\n font-weight: 700;\n font-size: px2rem(12.8px);\n border-bottom: px2rem(2px) solid transparent;\n cursor: pointer;\n transition: color 250ms;\n\n // Tab label on hover\n &:hover {\n color: var(--md-accent-fg-color);\n }\n }\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Icon definitions\n:root {\n --md-tasklist-icon:\n svg-load(\"octicons/check-circle-fill-24.svg\");\n --md-tasklist-icon--checked:\n svg-load(\"octicons/check-circle-fill-24.svg\");\n}\n\n// ----------------------------------------------------------------------------\n\n// Scoped in typesetted content to match specificity of regular content\n.md-typeset {\n\n // Tasklist item\n .task-list-item {\n position: relative;\n list-style-type: none;\n\n // Make checkbox items align with normal list items, but position\n // everything in ems for correct layout at smaller font sizes\n [type=\"checkbox\"] {\n position: absolute;\n top: 0.45em;\n left: -2em;\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n right: -2em;\n left: initial;\n }\n }\n }\n\n // Hide native checkbox, when custom classes are enabled\n .task-list-control [type=\"checkbox\"] {\n z-index: -1;\n opacity: 0;\n }\n\n // Tasklist indicator in unchecked state\n .task-list-indicator::before {\n position: absolute;\n top: 0.15em;\n left: px2em(-24px);\n width: px2em(20px);\n height: px2em(20px);\n background-color: var(--md-default-fg-color--lightest);\n mask-image: var(--md-tasklist-icon);\n mask-repeat: no-repeat;\n mask-size: contain;\n content: \"\";\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n right: px2em(-24px);\n left: initial;\n }\n }\n\n // Tasklist indicator in checked state\n [type=\"checkbox\"]:checked + .task-list-indicator::before {\n background-color: $clr-green-a400;\n mask-image: var(--md-tasklist-icon--checked);\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Scoped in typesetted content to match specificity of regular content\n.md-typeset {\n\n // [tablet +]: Allow for rendering content as sidebars\n @include break-from-device(tablet) {\n\n // Modifier to float block elements\n .inline {\n float: left;\n width: px2rem(234px);\n margin-top: 0;\n margin-right: px2rem(16px);\n margin-bottom: px2rem(16px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n float: right;\n margin-right: 0;\n margin-left: px2rem(16px);\n }\n\n // Modifier to move to end (ltr: right, rtl: left)\n &.end {\n float: right;\n margin-right: 0;\n margin-left: px2rem(16px);\n\n // Adjust for right-to-left languages\n [dir=\"rtl\"] & {\n float: left;\n margin-right: px2rem(16px);\n margin-left: 0;\n }\n }\n }\n }\n}\n"]} \ No newline at end of file diff --git a/en/2021.7/assets/stylesheets/palette.ba0d045b.min.css b/en/2021.7/assets/stylesheets/palette.ba0d045b.min.css new file mode 100644 index 000000000..fa0f7bca1 --- /dev/null +++ b/en/2021.7/assets/stylesheets/palette.ba0d045b.min.css @@ -0,0 +1,2 @@ +[data-md-color-accent=red]{--md-accent-fg-color:#ff1947;--md-accent-fg-color--transparent:rgba(255,25,71,0.1);--md-accent-bg-color:#fff;--md-accent-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-accent=pink]{--md-accent-fg-color:#f50056;--md-accent-fg-color--transparent:rgba(245,0,86,0.1);--md-accent-bg-color:#fff;--md-accent-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-accent=purple]{--md-accent-fg-color:#df41fb;--md-accent-fg-color--transparent:rgba(223,65,251,0.1);--md-accent-bg-color:#fff;--md-accent-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-accent=deep-purple]{--md-accent-fg-color:#7c4dff;--md-accent-fg-color--transparent:rgba(124,77,255,0.1);--md-accent-bg-color:#fff;--md-accent-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-accent=indigo]{--md-accent-fg-color:#526cfe;--md-accent-fg-color--transparent:rgba(82,108,254,0.1);--md-accent-bg-color:#fff;--md-accent-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-accent=blue]{--md-accent-fg-color:#4287ff;--md-accent-fg-color--transparent:rgba(66,135,255,0.1);--md-accent-bg-color:#fff;--md-accent-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-accent=light-blue]{--md-accent-fg-color:#0091eb;--md-accent-fg-color--transparent:rgba(0,145,235,0.1);--md-accent-bg-color:#fff;--md-accent-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-accent=cyan]{--md-accent-fg-color:#00bad6;--md-accent-fg-color--transparent:rgba(0,186,214,0.1);--md-accent-bg-color:#fff;--md-accent-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-accent=teal]{--md-accent-fg-color:#00bda4;--md-accent-fg-color--transparent:rgba(0,189,164,0.1);--md-accent-bg-color:#fff;--md-accent-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-accent=green]{--md-accent-fg-color:#00c753;--md-accent-fg-color--transparent:rgba(0,199,83,0.1);--md-accent-bg-color:#fff;--md-accent-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-accent=light-green]{--md-accent-fg-color:#63de17;--md-accent-fg-color--transparent:rgba(99,222,23,0.1);--md-accent-bg-color:#fff;--md-accent-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-accent=lime]{--md-accent-fg-color:#b0eb00;--md-accent-fg-color--transparent:rgba(176,235,0,0.1);--md-accent-bg-color:rgba(0,0,0,0.87);--md-accent-bg-color--light:rgba(0,0,0,0.54)}[data-md-color-accent=yellow]{--md-accent-fg-color:#ffd500;--md-accent-fg-color--transparent:rgba(255,213,0,0.1);--md-accent-bg-color:rgba(0,0,0,0.87);--md-accent-bg-color--light:rgba(0,0,0,0.54)}[data-md-color-accent=amber]{--md-accent-fg-color:#fa0;--md-accent-fg-color--transparent:rgba(255,170,0,0.1);--md-accent-bg-color:rgba(0,0,0,0.87);--md-accent-bg-color--light:rgba(0,0,0,0.54)}[data-md-color-accent=orange]{--md-accent-fg-color:#ff9100;--md-accent-fg-color--transparent:rgba(255,145,0,0.1);--md-accent-bg-color:rgba(0,0,0,0.87);--md-accent-bg-color--light:rgba(0,0,0,0.54)}[data-md-color-accent=deep-orange]{--md-accent-fg-color:#ff6e42;--md-accent-fg-color--transparent:rgba(255,110,66,0.1);--md-accent-bg-color:#fff;--md-accent-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-primary=red]{--md-primary-fg-color:#ef5552;--md-primary-fg-color--light:#e57171;--md-primary-fg-color--dark:#e53734;--md-primary-bg-color:#fff;--md-primary-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-primary=pink]{--md-primary-fg-color:#e92063;--md-primary-fg-color--light:#ec417a;--md-primary-fg-color--dark:#c3185d;--md-primary-bg-color:#fff;--md-primary-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-primary=purple]{--md-primary-fg-color:#ab47bd;--md-primary-fg-color--light:#bb69c9;--md-primary-fg-color--dark:#8c24a8;--md-primary-bg-color:#fff;--md-primary-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-primary=deep-purple]{--md-primary-fg-color:#7e56c2;--md-primary-fg-color--light:#9574cd;--md-primary-fg-color--dark:#673ab6;--md-primary-bg-color:#fff;--md-primary-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-primary=indigo]{--md-primary-fg-color:#4051b5;--md-primary-fg-color--light:#5d6cc0;--md-primary-fg-color--dark:#303fa1;--md-primary-bg-color:#fff;--md-primary-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-primary=blue]{--md-primary-fg-color:#2094f3;--md-primary-fg-color--light:#42a5f5;--md-primary-fg-color--dark:#1975d2;--md-primary-bg-color:#fff;--md-primary-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-primary=light-blue]{--md-primary-fg-color:#02a6f2;--md-primary-fg-color--light:#28b5f6;--md-primary-fg-color--dark:#0287cf;--md-primary-bg-color:#fff;--md-primary-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-primary=cyan]{--md-primary-fg-color:#00bdd6;--md-primary-fg-color--light:#25c5da;--md-primary-fg-color--dark:#0097a8;--md-primary-bg-color:#fff;--md-primary-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-primary=teal]{--md-primary-fg-color:#009485;--md-primary-fg-color--light:#26a699;--md-primary-fg-color--dark:#007a6c;--md-primary-bg-color:#fff;--md-primary-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-primary=green]{--md-primary-fg-color:#4cae4f;--md-primary-fg-color--light:#68bb6c;--md-primary-fg-color--dark:#398e3d;--md-primary-bg-color:#fff;--md-primary-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-primary=light-green]{--md-primary-fg-color:#8bc34b;--md-primary-fg-color--light:#9ccc66;--md-primary-fg-color--dark:#689f38;--md-primary-bg-color:#fff;--md-primary-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-primary=lime]{--md-primary-fg-color:#cbdc38;--md-primary-fg-color--light:#d3e156;--md-primary-fg-color--dark:#b0b52c;--md-primary-bg-color:rgba(0,0,0,0.87);--md-primary-bg-color--light:rgba(0,0,0,0.54)}[data-md-color-primary=yellow]{--md-primary-fg-color:#ffec3d;--md-primary-fg-color--light:#ffee57;--md-primary-fg-color--dark:#fbc02d;--md-primary-bg-color:rgba(0,0,0,0.87);--md-primary-bg-color--light:rgba(0,0,0,0.54)}[data-md-color-primary=amber]{--md-primary-fg-color:#ffc105;--md-primary-fg-color--light:#ffc929;--md-primary-fg-color--dark:#ffa200;--md-primary-bg-color:rgba(0,0,0,0.87);--md-primary-bg-color--light:rgba(0,0,0,0.54)}[data-md-color-primary=orange]{--md-primary-fg-color:#ffa724;--md-primary-fg-color--light:#ffa724;--md-primary-fg-color--dark:#fa8900;--md-primary-bg-color:rgba(0,0,0,0.87);--md-primary-bg-color--light:rgba(0,0,0,0.54)}[data-md-color-primary=deep-orange]{--md-primary-fg-color:#ff6e42;--md-primary-fg-color--light:#ff8a66;--md-primary-fg-color--dark:#f4511f;--md-primary-bg-color:#fff;--md-primary-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-primary=brown]{--md-primary-fg-color:#795649;--md-primary-fg-color--light:#8d6e62;--md-primary-fg-color--dark:#5d4037;--md-primary-bg-color:#fff;--md-primary-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-primary=grey]{--md-primary-fg-color:#757575;--md-primary-fg-color--light:#9e9e9e;--md-primary-fg-color--dark:#616161;--md-primary-bg-color:#fff;--md-primary-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-primary=blue-grey]{--md-primary-fg-color:#546d78;--md-primary-fg-color--light:#607c8a;--md-primary-fg-color--dark:#455a63;--md-primary-bg-color:#fff;--md-primary-bg-color--light:hsla(0,0%,100%,0.7)}[data-md-color-primary=white]{--md-primary-fg-color:#fff;--md-primary-fg-color--light:hsla(0,0%,100%,0.7);--md-primary-fg-color--dark:rgba(0,0,0,0.07);--md-primary-bg-color:rgba(0,0,0,0.87);--md-primary-bg-color--light:rgba(0,0,0,0.54);--md-typeset-a-color:#4051b5}@media screen and (min-width:60em){[data-md-color-primary=white] .md-search__form{background-color:rgba(0,0,0,.07)}[data-md-color-primary=white] .md-search__form:hover{background-color:rgba(0,0,0,.32)}[data-md-color-primary=white] .md-search__input+.md-search__icon{color:rgba(0,0,0,.87)}}@media screen and (min-width:76.25em){[data-md-color-primary=white] .md-tabs{border-bottom:.05rem solid rgba(0,0,0,.07)}}[data-md-color-primary=black]{--md-primary-fg-color:#000;--md-primary-fg-color--light:rgba(0,0,0,0.54);--md-primary-fg-color--dark:#000;--md-primary-bg-color:#fff;--md-primary-bg-color--light:hsla(0,0%,100%,0.7);--md-typeset-a-color:#4051b5}[data-md-color-primary=black] .md-header{background-color:#000}@media screen and (max-width:59.9375em){[data-md-color-primary=black] .md-nav__source{background-color:rgba(0,0,0,.87)}}@media screen and (min-width:60em){[data-md-color-primary=black] .md-search__form{background-color:hsla(0,0%,100%,.12)}[data-md-color-primary=black] .md-search__form:hover{background-color:hsla(0,0%,100%,.3)}}@media screen and (max-width:76.1875em){html [data-md-color-primary=black] .md-nav--primary .md-nav__title[for=__drawer]{background-color:#000}}@media screen and (min-width:76.25em){[data-md-color-primary=black] .md-tabs{background-color:#000}}@media screen{[data-md-color-scheme=slate]{--md-hue:232;--md-default-fg-color:hsla(var(--md-hue),75%,95%,1);--md-default-fg-color--light:hsla(var(--md-hue),75%,90%,0.62);--md-default-fg-color--lighter:hsla(var(--md-hue),75%,90%,0.32);--md-default-fg-color--lightest:hsla(var(--md-hue),75%,90%,0.12);--md-default-bg-color:hsla(var(--md-hue),15%,21%,1);--md-default-bg-color--light:hsla(var(--md-hue),15%,21%,0.54);--md-default-bg-color--lighter:hsla(var(--md-hue),15%,21%,0.26);--md-default-bg-color--lightest:hsla(var(--md-hue),15%,21%,0.07);--md-code-fg-color:hsla(var(--md-hue),18%,86%,1);--md-code-bg-color:hsla(var(--md-hue),15%,15%,1);--md-code-hl-color:rgba(66,135,255,0.15);--md-code-hl-number-color:#e6695b;--md-code-hl-special-color:#f06090;--md-code-hl-function-color:#c973d9;--md-code-hl-constant-color:#9383e2;--md-code-hl-keyword-color:#6791e0;--md-code-hl-string-color:#2fb170;--md-code-hl-name-color:var(--md-code-fg-color);--md-code-hl-operator-color:var(--md-default-fg-color--light);--md-code-hl-punctuation-color:var(--md-default-fg-color--light);--md-code-hl-comment-color:var(--md-default-fg-color--light);--md-code-hl-generic-color:var(--md-default-fg-color--light);--md-code-hl-variable-color:var(--md-default-fg-color--light);--md-typeset-color:var(--md-default-fg-color);--md-typeset-a-color:var(--md-primary-fg-color);--md-typeset-mark-color:rgba(66,135,255,0.3);--md-typeset-kbd-color:hsla(var(--md-hue),15%,94%,0.12);--md-typeset-kbd-accent-color:hsla(var(--md-hue),15%,94%,0.2);--md-typeset-kbd-border-color:hsla(var(--md-hue),15%,14%,1);--md-admonition-bg-color:hsla(var(--md-hue),0%,100%,0.025);--md-footer-bg-color:hsla(var(--md-hue),15%,12%,0.87);--md-footer-bg-color--dark:hsla(var(--md-hue),15%,10%,1)}[data-md-color-scheme=slate][data-md-color-primary=black],[data-md-color-scheme=slate][data-md-color-primary=white]{--md-typeset-a-color:#5d6cc0}} +/*# sourceMappingURL=palette.ba0d045b.min.css.map */ \ No newline at end of file diff --git a/en/2021.7/assets/stylesheets/palette.ba0d045b.min.css.map b/en/2021.7/assets/stylesheets/palette.ba0d045b.min.css.map new file mode 100644 index 000000000..325b86831 --- /dev/null +++ b/en/2021.7/assets/stylesheets/palette.ba0d045b.min.css.map @@ -0,0 +1 @@ +{"version":3,"sources":["src/assets/stylesheets/palette/_accent.scss","src/assets/stylesheets/palette.scss","src/assets/stylesheets/palette/_primary.scss","src/assets/stylesheets/utilities/_break.scss","src/assets/stylesheets/palette/_scheme.scss"],"names":[],"mappings":"AA8CE,2BACE,4BAAA,CACA,qDAAA,CAOE,yBAAA,CACA,+CCnDN,CDyCE,4BACE,4BAAA,CACA,oDAAA,CAOE,yBAAA,CACA,+CC5CN,CDkCE,8BACE,4BAAA,CACA,sDAAA,CAOE,yBAAA,CACA,+CCrCN,CD2BE,mCACE,4BAAA,CACA,sDAAA,CAOE,yBAAA,CACA,+CC9BN,CDoBE,8BACE,4BAAA,CACA,sDAAA,CAOE,yBAAA,CACA,+CCvBN,CDaE,4BACE,4BAAA,CACA,sDAAA,CAOE,yBAAA,CACA,+CChBN,CDME,kCACE,4BAAA,CACA,qDAAA,CAOE,yBAAA,CACA,+CCTN,CDDE,4BACE,4BAAA,CACA,qDAAA,CAOE,yBAAA,CACA,+CCFN,CDRE,4BACE,4BAAA,CACA,qDAAA,CAOE,yBAAA,CACA,+CCKN,CDfE,6BACE,4BAAA,CACA,oDAAA,CAOE,yBAAA,CACA,+CCYN,CDtBE,mCACE,4BAAA,CACA,qDAAA,CAOE,yBAAA,CACA,+CCmBN,CD7BE,4BACE,4BAAA,CACA,qDAAA,CAIE,qCAAA,CACA,4CC6BN,CDpCE,8BACE,4BAAA,CACA,qDAAA,CAIE,qCAAA,CACA,4CCoCN,CD3CE,6BACE,yBAAA,CACA,qDAAA,CAIE,qCAAA,CACA,4CC2CN,CDlDE,8BACE,4BAAA,CACA,qDAAA,CAIE,qCAAA,CACA,4CCkDN,CDzDE,mCACE,4BAAA,CACA,sDAAA,CAOE,yBAAA,CACA,+CCsDN,CC7DE,4BACE,6BAAA,CACA,oCAAA,CACA,mCAAA,CAOE,0BAAA,CACA,gDD0DN,CCrEE,6BACE,6BAAA,CACA,oCAAA,CACA,mCAAA,CAOE,0BAAA,CACA,gDDkEN,CC7EE,+BACE,6BAAA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A,sCAAA,CACA,6CAAA,CAGA,4BDiMF,CElFI,mCDzGA,+CACE,gCD8LJ,CC3LI,qDACE,gCD6LN,CCxLE,iEACE,qBD0LJ,CACF,CE7FI,sCDtFA,uCACE,0CDsLJ,CACF,CC7KA,8BACE,0BAAA,CACA,6CAAA,CACA,gCAAA,CACA,0BAAA,CACA,gDAAA,CAGA,4BD8KF,CC3KE,yCACE,qBD6KJ,CE3FI,wCD3EA,8CACE,gCDyKJ,CACF,CEnHI,mCD/CA,+CACE,oCDqKJ,CClKI,qDACE,mCDoKN,CACF,CExGI,wCDpDA,iFACE,qBD+JJ,CACF,CEhII,sCDxBA,uCACE,qBD2JJ,CACF,CGvSA,cAGE,6BAKE,YAAA,CAGA,mDAAA,CACA,6DAAA,CACA,+DAAA,CACA,gEAAA,CACA,mDAAA,CACA,6DAAA,CACA,+DAAA,CACA,gEAAA,CAGA,gDAAA,CACA,gDAAA,CAGA,wCAAA,CACA,iCAAA,CACA,kCAAA,CACA,mCAAA,CACA,mCAAA,CACA,kCAAA,CACA,iCAAA,CACA,+CAAA,CACA,6DAAA,CACA,gEAAA,CACA,4DAAA,CACA,4DAAA,CACA,6DAAA,CAGA,6CAAA,CAGA,+CAAA,CAGA,4CAAA,CAGA,uDAAA,CACA,6DAAA,CACA,2DAAA,CAGA,0DAAA,CAGA,qDAAA,CACA,wDHkRF,CG/QE,oHAIE,4BH8QJ,CACF","file":"src/assets/stylesheets/palette.scss","sourcesContent":["////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n@each $name, $color in (\n \"red\": $clr-red-a400,\n \"pink\": $clr-pink-a400,\n \"purple\": $clr-purple-a200,\n \"deep-purple\": $clr-deep-purple-a200,\n \"indigo\": $clr-indigo-a200,\n \"blue\": $clr-blue-a200,\n \"light-blue\": $clr-light-blue-a700,\n \"cyan\": $clr-cyan-a700,\n \"teal\": $clr-teal-a700,\n \"green\": $clr-green-a700,\n \"light-green\": $clr-light-green-a700,\n \"lime\": $clr-lime-a700,\n \"yellow\": $clr-yellow-a700,\n \"amber\": $clr-amber-a700,\n \"orange\": $clr-orange-a400,\n \"deep-orange\": $clr-deep-orange-a200\n) {\n\n // Color palette\n [data-md-color-accent=\"#{$name}\"] {\n --md-accent-fg-color: hsla(#{hex2hsl($color)}, 1);\n --md-accent-fg-color--transparent: hsla(#{hex2hsl($color)}, 0.1);\n\n // Inverted text for lighter shades\n @if index(\"lime\" \"yellow\" \"amber\" \"orange\", $name) {\n --md-accent-bg-color: hsla(0, 0%, 0%, 0.87);\n --md-accent-bg-color--light: hsla(0, 0%, 0%, 0.54);\n } @else {\n --md-accent-bg-color: hsla(0, 0%, 100%, 1);\n --md-accent-bg-color--light: hsla(0, 0%, 100%, 0.7);\n }\n }\n}\n","[data-md-color-accent=red] {\n --md-accent-fg-color: hsla(348, 100%, 55%, 1);\n --md-accent-fg-color--transparent: hsla(348, 100%, 55%, 0.1);\n --md-accent-bg-color: hsla(0, 0%, 100%, 1);\n --md-accent-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-accent=pink] {\n --md-accent-fg-color: hsla(339, 100%, 48%, 1);\n --md-accent-fg-color--transparent: hsla(339, 100%, 48%, 0.1);\n --md-accent-bg-color: hsla(0, 0%, 100%, 1);\n --md-accent-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-accent=purple] {\n --md-accent-fg-color: hsla(291, 96%, 62%, 1);\n --md-accent-fg-color--transparent: hsla(291, 96%, 62%, 0.1);\n --md-accent-bg-color: hsla(0, 0%, 100%, 1);\n --md-accent-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-accent=deep-purple] {\n --md-accent-fg-color: hsla(256, 100%, 65%, 1);\n --md-accent-fg-color--transparent: hsla(256, 100%, 65%, 0.1);\n --md-accent-bg-color: hsla(0, 0%, 100%, 1);\n --md-accent-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-accent=indigo] {\n --md-accent-fg-color: hsla(231, 99%, 66%, 1);\n --md-accent-fg-color--transparent: hsla(231, 99%, 66%, 0.1);\n --md-accent-bg-color: hsla(0, 0%, 100%, 1);\n --md-accent-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-accent=blue] {\n --md-accent-fg-color: hsla(218, 100%, 63%, 1);\n --md-accent-fg-color--transparent: hsla(218, 100%, 63%, 0.1);\n --md-accent-bg-color: hsla(0, 0%, 100%, 1);\n --md-accent-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-accent=light-blue] {\n --md-accent-fg-color: hsla(203, 100%, 46%, 1);\n --md-accent-fg-color--transparent: hsla(203, 100%, 46%, 0.1);\n --md-accent-bg-color: hsla(0, 0%, 100%, 1);\n --md-accent-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-accent=cyan] {\n --md-accent-fg-color: hsla(188, 100%, 42%, 1);\n --md-accent-fg-color--transparent: hsla(188, 100%, 42%, 0.1);\n --md-accent-bg-color: hsla(0, 0%, 100%, 1);\n --md-accent-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-accent=teal] {\n --md-accent-fg-color: hsla(172, 100%, 37%, 1);\n --md-accent-fg-color--transparent: hsla(172, 100%, 37%, 0.1);\n --md-accent-bg-color: hsla(0, 0%, 100%, 1);\n --md-accent-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-accent=green] {\n --md-accent-fg-color: hsla(145, 100%, 39%, 1);\n --md-accent-fg-color--transparent: hsla(145, 100%, 39%, 0.1);\n --md-accent-bg-color: hsla(0, 0%, 100%, 1);\n --md-accent-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-accent=light-green] {\n --md-accent-fg-color: hsla(97, 81%, 48%, 1);\n --md-accent-fg-color--transparent: hsla(97, 81%, 48%, 0.1);\n --md-accent-bg-color: hsla(0, 0%, 100%, 1);\n --md-accent-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-accent=lime] {\n --md-accent-fg-color: hsla(75, 100%, 46%, 1);\n --md-accent-fg-color--transparent: hsla(75, 100%, 46%, 0.1);\n --md-accent-bg-color: hsla(0, 0%, 0%, 0.87);\n --md-accent-bg-color--light: hsla(0, 0%, 0%, 0.54);\n}\n\n[data-md-color-accent=yellow] {\n --md-accent-fg-color: hsla(50, 100%, 50%, 1);\n --md-accent-fg-color--transparent: hsla(50, 100%, 50%, 0.1);\n --md-accent-bg-color: hsla(0, 0%, 0%, 0.87);\n --md-accent-bg-color--light: hsla(0, 0%, 0%, 0.54);\n}\n\n[data-md-color-accent=amber] {\n --md-accent-fg-color: hsla(40, 100%, 50%, 1);\n --md-accent-fg-color--transparent: hsla(40, 100%, 50%, 0.1);\n --md-accent-bg-color: hsla(0, 0%, 0%, 0.87);\n --md-accent-bg-color--light: hsla(0, 0%, 0%, 0.54);\n}\n\n[data-md-color-accent=orange] {\n --md-accent-fg-color: hsla(34, 100%, 50%, 1);\n --md-accent-fg-color--transparent: hsla(34, 100%, 50%, 0.1);\n --md-accent-bg-color: hsla(0, 0%, 0%, 0.87);\n --md-accent-bg-color--light: hsla(0, 0%, 0%, 0.54);\n}\n\n[data-md-color-accent=deep-orange] {\n --md-accent-fg-color: hsla(14, 100%, 63%, 1);\n --md-accent-fg-color--transparent: hsla(14, 100%, 63%, 0.1);\n --md-accent-bg-color: hsla(0, 0%, 100%, 1);\n --md-accent-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-primary=red] {\n --md-primary-fg-color: hsla(1, 83%, 63%, 1);\n --md-primary-fg-color--light: hsla(0, 69%, 67%, 1);\n --md-primary-fg-color--dark: hsla(1, 77%, 55%, 1);\n --md-primary-bg-color: hsla(0, 0%, 100%, 1);\n --md-primary-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-primary=pink] {\n --md-primary-fg-color: hsla(340, 82%, 52%, 1);\n --md-primary-fg-color--light: hsla(340, 82%, 59%, 1);\n --md-primary-fg-color--dark: hsla(336, 78%, 43%, 1);\n --md-primary-bg-color: hsla(0, 0%, 100%, 1);\n --md-primary-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-primary=purple] {\n --md-primary-fg-color: hsla(291, 47%, 51%, 1);\n --md-primary-fg-color--light: hsla(291, 47%, 60%, 1);\n --md-primary-fg-color--dark: hsla(287, 65%, 40%, 1);\n --md-primary-bg-color: hsla(0, 0%, 100%, 1);\n --md-primary-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-primary=deep-purple] {\n --md-primary-fg-color: hsla(262, 47%, 55%, 1);\n --md-primary-fg-color--light: hsla(262, 47%, 63%, 1);\n --md-primary-fg-color--dark: hsla(262, 52%, 47%, 1);\n --md-primary-bg-color: hsla(0, 0%, 100%, 1);\n --md-primary-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-primary=indigo] {\n --md-primary-fg-color: hsla(231, 48%, 48%, 1);\n --md-primary-fg-color--light: hsla(231, 44%, 56%, 1);\n --md-primary-fg-color--dark: hsla(232, 54%, 41%, 1);\n --md-primary-bg-color: hsla(0, 0%, 100%, 1);\n --md-primary-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-primary=blue] {\n --md-primary-fg-color: hsla(207, 90%, 54%, 1);\n --md-primary-fg-color--light: hsla(207, 90%, 61%, 1);\n --md-primary-fg-color--dark: hsla(210, 79%, 46%, 1);\n --md-primary-bg-color: hsla(0, 0%, 100%, 1);\n --md-primary-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-primary=light-blue] {\n --md-primary-fg-color: hsla(199, 98%, 48%, 1);\n --md-primary-fg-color--light: hsla(199, 92%, 56%, 1);\n --md-primary-fg-color--dark: hsla(201, 98%, 41%, 1);\n --md-primary-bg-color: hsla(0, 0%, 100%, 1);\n --md-primary-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-primary=cyan] {\n --md-primary-fg-color: hsla(187, 100%, 42%, 1);\n --md-primary-fg-color--light: hsla(187, 71%, 50%, 1);\n --md-primary-fg-color--dark: hsla(186, 100%, 33%, 1);\n --md-primary-bg-color: hsla(0, 0%, 100%, 1);\n --md-primary-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-primary=teal] {\n --md-primary-fg-color: hsla(174, 100%, 29%, 1);\n --md-primary-fg-color--light: hsla(174, 63%, 40%, 1);\n --md-primary-fg-color--dark: hsla(173, 100%, 24%, 1);\n --md-primary-bg-color: hsla(0, 0%, 100%, 1);\n --md-primary-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-primary=green] {\n --md-primary-fg-color: hsla(122, 39%, 49%, 1);\n --md-primary-fg-color--light: hsla(123, 38%, 57%, 1);\n --md-primary-fg-color--dark: hsla(123, 43%, 39%, 1);\n --md-primary-bg-color: hsla(0, 0%, 100%, 1);\n --md-primary-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-primary=light-green] {\n --md-primary-fg-color: hsla(88, 50%, 53%, 1);\n --md-primary-fg-color--light: hsla(88, 50%, 60%, 1);\n --md-primary-fg-color--dark: hsla(92, 48%, 42%, 1);\n --md-primary-bg-color: hsla(0, 0%, 100%, 1);\n --md-primary-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-primary=lime] {\n --md-primary-fg-color: hsla(66, 70%, 54%, 1);\n --md-primary-fg-color--light: hsla(66, 70%, 61%, 1);\n --md-primary-fg-color--dark: hsla(62, 61%, 44%, 1);\n --md-primary-bg-color: hsla(0, 0%, 0%, 0.87);\n --md-primary-bg-color--light: hsla(0, 0%, 0%, 0.54);\n}\n\n[data-md-color-primary=yellow] {\n --md-primary-fg-color: hsla(54, 100%, 62%, 1);\n --md-primary-fg-color--light: hsla(54, 100%, 67%, 1);\n --md-primary-fg-color--dark: hsla(43, 96%, 58%, 1);\n --md-primary-bg-color: hsla(0, 0%, 0%, 0.87);\n --md-primary-bg-color--light: hsla(0, 0%, 0%, 0.54);\n}\n\n[data-md-color-primary=amber] {\n --md-primary-fg-color: hsla(45, 100%, 51%, 1);\n --md-primary-fg-color--light: hsla(45, 100%, 58%, 1);\n --md-primary-fg-color--dark: hsla(38, 100%, 50%, 1);\n --md-primary-bg-color: hsla(0, 0%, 0%, 0.87);\n --md-primary-bg-color--light: hsla(0, 0%, 0%, 0.54);\n}\n\n[data-md-color-primary=orange] {\n --md-primary-fg-color: hsla(36, 100%, 57%, 1);\n --md-primary-fg-color--light: hsla(36, 100%, 57%, 1);\n --md-primary-fg-color--dark: hsla(33, 100%, 49%, 1);\n --md-primary-bg-color: hsla(0, 0%, 0%, 0.87);\n --md-primary-bg-color--light: hsla(0, 0%, 0%, 0.54);\n}\n\n[data-md-color-primary=deep-orange] {\n --md-primary-fg-color: hsla(14, 100%, 63%, 1);\n --md-primary-fg-color--light: hsla(14, 100%, 70%, 1);\n --md-primary-fg-color--dark: hsla(14, 91%, 54%, 1);\n --md-primary-bg-color: hsla(0, 0%, 100%, 1);\n --md-primary-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-primary=brown] {\n --md-primary-fg-color: hsla(16, 25%, 38%, 1);\n --md-primary-fg-color--light: hsla(16, 18%, 47%, 1);\n --md-primary-fg-color--dark: hsla(14, 26%, 29%, 1);\n --md-primary-bg-color: hsla(0, 0%, 100%, 1);\n --md-primary-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-primary=grey] {\n --md-primary-fg-color: hsla(0, 0%, 46%, 1);\n --md-primary-fg-color--light: hsla(0, 0%, 62%, 1);\n --md-primary-fg-color--dark: hsla(0, 0%, 38%, 1);\n --md-primary-bg-color: hsla(0, 0%, 100%, 1);\n --md-primary-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-primary=blue-grey] {\n --md-primary-fg-color: hsla(199, 18%, 40%, 1);\n --md-primary-fg-color--light: hsla(200, 18%, 46%, 1);\n --md-primary-fg-color--dark: hsla(199, 18%, 33%, 1);\n --md-primary-bg-color: hsla(0, 0%, 100%, 1);\n --md-primary-bg-color--light: hsla(0, 0%, 100%, 0.7);\n}\n\n[data-md-color-primary=white] {\n --md-primary-fg-color: hsla(0, 0%, 100%, 1);\n --md-primary-fg-color--light: hsla(0, 0%, 100%, 0.7);\n --md-primary-fg-color--dark: hsla(0, 0%, 0%, 0.07);\n --md-primary-bg-color: hsla(0, 0%, 0%, 0.87);\n --md-primary-bg-color--light: hsla(0, 0%, 0%, 0.54);\n --md-typeset-a-color: hsla(231, 48%, 48%, 1);\n}\n@media screen and (min-width: 60em) {\n [data-md-color-primary=white] .md-search__form {\n background-color: rgba(0, 0, 0, 0.07);\n }\n [data-md-color-primary=white] .md-search__form:hover {\n background-color: rgba(0, 0, 0, 0.32);\n }\n [data-md-color-primary=white] .md-search__input + .md-search__icon {\n color: rgba(0, 0, 0, 0.87);\n }\n}\n@media screen and (min-width: 76.25em) {\n [data-md-color-primary=white] .md-tabs {\n border-bottom: 0.05rem solid rgba(0, 0, 0, 0.07);\n }\n}\n\n[data-md-color-primary=black] {\n --md-primary-fg-color: hsla(0, 0%, 0%, 1);\n --md-primary-fg-color--light: hsla(0, 0%, 0%, 0.54);\n --md-primary-fg-color--dark: hsla(0, 0%, 0%, 1);\n --md-primary-bg-color: hsla(0, 0%, 100%, 1);\n --md-primary-bg-color--light: hsla(0, 0%, 100%, 0.7);\n --md-typeset-a-color: hsla(231, 48%, 48%, 1);\n}\n[data-md-color-primary=black] .md-header {\n background-color: black;\n}\n@media screen and (max-width: 59.9375em) {\n [data-md-color-primary=black] .md-nav__source {\n background-color: rgba(0, 0, 0, 0.87);\n }\n}\n@media screen and (min-width: 60em) {\n [data-md-color-primary=black] .md-search__form {\n background-color: rgba(255, 255, 255, 0.12);\n }\n [data-md-color-primary=black] .md-search__form:hover {\n background-color: rgba(255, 255, 255, 0.3);\n }\n}\n@media screen and (max-width: 76.1875em) {\n html [data-md-color-primary=black] .md-nav--primary .md-nav__title[for=__drawer] {\n background-color: black;\n }\n}\n@media screen and (min-width: 76.25em) {\n [data-md-color-primary=black] .md-tabs {\n background-color: black;\n }\n}\n\n@media screen {\n [data-md-color-scheme=slate] {\n --md-hue: 232;\n --md-default-fg-color: hsla(var(--md-hue), 75%, 95%, 1);\n --md-default-fg-color--light: hsla(var(--md-hue), 75%, 90%, 0.62);\n --md-default-fg-color--lighter: hsla(var(--md-hue), 75%, 90%, 0.32);\n --md-default-fg-color--lightest: hsla(var(--md-hue), 75%, 90%, 0.12);\n --md-default-bg-color: hsla(var(--md-hue), 15%, 21%, 1);\n --md-default-bg-color--light: hsla(var(--md-hue), 15%, 21%, 0.54);\n --md-default-bg-color--lighter: hsla(var(--md-hue), 15%, 21%, 0.26);\n --md-default-bg-color--lightest: hsla(var(--md-hue), 15%, 21%, 0.07);\n --md-code-fg-color: hsla(var(--md-hue), 18%, 86%, 1);\n --md-code-bg-color: hsla(var(--md-hue), 15%, 15%, 1);\n --md-code-hl-color: hsla(218, 100%, 63%, 0.15);\n --md-code-hl-number-color: hsla(6, 74%, 63%, 1);\n --md-code-hl-special-color: hsla(340, 83%, 66%, 1);\n --md-code-hl-function-color: hsla(291, 57%, 65%, 1);\n --md-code-hl-constant-color: hsla(250, 62%, 70%, 1);\n --md-code-hl-keyword-color: hsla(219, 66%, 64%, 1);\n --md-code-hl-string-color: hsla(150, 58%, 44%, 1);\n --md-code-hl-name-color: var(--md-code-fg-color);\n --md-code-hl-operator-color: var(--md-default-fg-color--light);\n --md-code-hl-punctuation-color: var(--md-default-fg-color--light);\n --md-code-hl-comment-color: var(--md-default-fg-color--light);\n --md-code-hl-generic-color: var(--md-default-fg-color--light);\n --md-code-hl-variable-color: var(--md-default-fg-color--light);\n --md-typeset-color: var(--md-default-fg-color);\n --md-typeset-a-color: var(--md-primary-fg-color);\n --md-typeset-mark-color: hsla(218, 100%, 63%, 0.3);\n --md-typeset-kbd-color: hsla(var(--md-hue), 15%, 94%, 0.12);\n --md-typeset-kbd-accent-color: hsla(var(--md-hue), 15%, 94%, 0.2);\n --md-typeset-kbd-border-color: hsla(var(--md-hue), 15%, 14%, 1);\n --md-admonition-bg-color: hsla(var(--md-hue), 0%, 100%, 0.025);\n --md-footer-bg-color: hsla(var(--md-hue), 15%, 12%, 0.87);\n --md-footer-bg-color--dark: hsla(var(--md-hue), 15%, 10%, 1);\n }\n [data-md-color-scheme=slate][data-md-color-primary=black], [data-md-color-scheme=slate][data-md-color-primary=white] {\n --md-typeset-a-color: hsla(231, 44%, 56%, 1);\n }\n}\n\n/*# sourceMappingURL=palette.css.map */","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n@each $name, $colors in (\n \"red\": $clr-red-400 $clr-red-300 $clr-red-600,\n \"pink\": $clr-pink-500 $clr-pink-400 $clr-pink-700,\n \"purple\": $clr-purple-400 $clr-purple-300 $clr-purple-600,\n \"deep-purple\": $clr-deep-purple-400 $clr-deep-purple-300 $clr-deep-purple-500,\n \"indigo\": $clr-indigo-500 $clr-indigo-400 $clr-indigo-700,\n \"blue\": $clr-blue-500 $clr-blue-400 $clr-blue-700,\n \"light-blue\": $clr-light-blue-500 $clr-light-blue-400 $clr-light-blue-700,\n \"cyan\": $clr-cyan-500 $clr-cyan-400 $clr-cyan-700,\n \"teal\": $clr-teal-500 $clr-teal-400 $clr-teal-700,\n \"green\": $clr-green-500 $clr-green-400 $clr-green-700,\n \"light-green\": $clr-light-green-500 $clr-light-green-400 $clr-light-green-700,\n \"lime\": $clr-lime-500 $clr-lime-400 $clr-lime-700,\n \"yellow\": $clr-yellow-500 $clr-yellow-400 $clr-yellow-700,\n \"amber\": $clr-amber-500 $clr-amber-400 $clr-amber-700,\n \"orange\": $clr-orange-400 $clr-orange-400 $clr-orange-600,\n \"deep-orange\": $clr-deep-orange-400 $clr-deep-orange-300 $clr-deep-orange-600,\n \"brown\": $clr-brown-500 $clr-brown-400 $clr-brown-700,\n \"grey\": $clr-grey-600 $clr-grey-500 $clr-grey-700,\n \"blue-grey\": $clr-blue-grey-600 $clr-blue-grey-500 $clr-blue-grey-700\n) {\n\n // Color palette\n [data-md-color-primary=\"#{$name}\"] {\n --md-primary-fg-color: hsla(#{hex2hsl(nth($colors, 1))}, 1);\n --md-primary-fg-color--light: hsla(#{hex2hsl(nth($colors, 2))}, 1);\n --md-primary-fg-color--dark: hsla(#{hex2hsl(nth($colors, 3))}, 1);\n\n // Inverted text for lighter shades\n @if index(\"lime\" \"yellow\" \"amber\" \"orange\", $name) {\n --md-primary-bg-color: hsla(0, 0%, 0%, 0.87);\n --md-primary-bg-color--light: hsla(0, 0%, 0%, 0.54);\n } @else {\n --md-primary-bg-color: hsla(0, 0%, 100%, 1);\n --md-primary-bg-color--light: hsla(0, 0%, 100%, 0.7);\n }\n }\n}\n\n// ----------------------------------------------------------------------------\n// Rules: white\n// ----------------------------------------------------------------------------\n\n// Color palette\n[data-md-color-primary=\"white\"] {\n --md-primary-fg-color: hsla(0, 0%, 100%, 1);\n --md-primary-fg-color--light: hsla(0, 0%, 100%, 0.7);\n --md-primary-fg-color--dark: hsla(0, 0%, 0%, 0.07);\n --md-primary-bg-color: hsla(0, 0%, 0%, 0.87);\n --md-primary-bg-color--light: hsla(0, 0%, 0%, 0.54);\n\n // Typeset color shades\n --md-typeset-a-color: hsla(#{hex2hsl($clr-indigo-500)}, 1);\n\n // [tablet portrait +]: Header-embedded search\n @include break-from-device(tablet landscape) {\n\n // Search form\n .md-search__form {\n background-color: hsla(0, 0%, 0%, 0.07);\n\n // Search form on hover\n &:hover {\n background-color: hsla(0, 0%, 0%, 0.32);\n }\n }\n\n // Search icon\n .md-search__input + .md-search__icon {\n color: hsla(0, 0%, 0%, 0.87);\n }\n }\n\n // [screen +]: Add bottom border for tabs\n @include break-from-device(screen) {\n\n // Navigation tabs\n .md-tabs {\n border-bottom: px2rem(1px) solid hsla(0, 0%, 0%, 0.07);\n }\n }\n}\n\n// ----------------------------------------------------------------------------\n// Rules: black\n// ----------------------------------------------------------------------------\n\n// Color palette\n[data-md-color-primary=\"black\"] {\n --md-primary-fg-color: hsla(0, 0%, 0%, 1);\n --md-primary-fg-color--light: hsla(0, 0%, 0%, 0.54);\n --md-primary-fg-color--dark: hsla(0, 0%, 0%, 1);\n --md-primary-bg-color: hsla(0, 0%, 100%, 1);\n --md-primary-bg-color--light: hsla(0, 0%, 100%, 0.7);\n\n // Text color shades\n --md-typeset-a-color: hsla(#{hex2hsl($clr-indigo-500)}, 1);\n\n // Header\n .md-header {\n background-color: hsla(0, 0%, 0%, 1);\n }\n\n // [tablet portrait -]: Layered navigation\n @include break-to-device(tablet portrait) {\n\n // Repository information container\n .md-nav__source {\n background-color: hsla(0, 0%, 0%, 0.87);\n }\n }\n\n // [tablet landscape +]: Header-embedded search\n @include break-from-device(tablet landscape) {\n\n // Search form\n .md-search__form {\n background-color: hsla(0, 0%, 100%, 0.12);\n\n // Search form on hover\n &:hover {\n background-color: hsla(0, 0%, 100%, 0.3);\n }\n }\n }\n\n // [tablet -]: Layered navigation\n @include break-to-device(tablet) {\n\n // Site title in main navigation\n html & .md-nav--primary .md-nav__title[for=\"__drawer\"] {\n background-color: hsla(0, 0%, 0%, 1);\n }\n }\n\n // [screen +]: Set background color for tabs\n @include break-from-device(screen) {\n\n // Navigation tabs\n .md-tabs {\n background-color: hsla(0, 0%, 0%, 1);\n }\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Variables\n// ----------------------------------------------------------------------------\n\n///\n/// Device-specific breakpoints\n///\n/// @example\n/// $break-devices: (\n/// mobile: (\n/// portrait: 220px 479px,\n/// landscape: 480px 719px\n/// ),\n/// tablet: (\n/// portrait: 720px 959px,\n/// landscape: 960px 1219px\n/// ),\n/// screen: (\n/// small: 1220px 1599px,\n/// medium: 1600px 1999px,\n/// large: 2000px\n/// )\n/// );\n///\n$break-devices: () !default;\n\n// ----------------------------------------------------------------------------\n// Helpers\n// ----------------------------------------------------------------------------\n\n///\n/// Choose minimum and maximum device widths\n///\n@function break-select-min-max($devices) {\n $min: 1000000;\n $max: 0;\n @each $key, $value in $devices {\n @while type-of($value) == map {\n $value: break-select-min-max($value);\n }\n @if type-of($value) == list {\n @each $number in $value {\n @if type-of($number) == number {\n $min: min($number, $min);\n @if $max {\n $max: max($number, $max);\n }\n } @else {\n @error \"Invalid number: #{$number}\";\n }\n }\n } @else if type-of($value) == number {\n $min: min($value, $min);\n $max: null;\n } @else {\n @error \"Invalid value: #{$value}\";\n }\n }\n @return $min, $max;\n}\n\n///\n/// Select minimum and maximum widths for a device breakpoint\n///\n@function break-select-device($device) {\n $current: $break-devices;\n @for $n from 1 through length($device) {\n @if type-of($current) == map {\n $current: map-get($current, nth($device, $n));\n } @else {\n @error \"Invalid device map: #{$devices}\";\n }\n }\n @if type-of($current) == list or type-of($current) == number {\n $current: (default: $current);\n }\n @return break-select-min-max($current);\n}\n\n// ----------------------------------------------------------------------------\n// Mixins\n// ----------------------------------------------------------------------------\n\n///\n/// A minimum-maximum media query breakpoint\n///\n@mixin break-at($breakpoint) {\n @if type-of($breakpoint) == number {\n @media screen and (min-width: $breakpoint) {\n @content;\n }\n } @else if type-of($breakpoint) == list {\n $min: nth($breakpoint, 1);\n $max: nth($breakpoint, 2);\n @if type-of($min) == number and type-of($max) == number {\n @media screen and (min-width: $min) and (max-width: $max) {\n @content;\n }\n } @else {\n @error \"Invalid breakpoint: #{$breakpoint}\";\n }\n } @else {\n @error \"Invalid breakpoint: #{$breakpoint}\";\n }\n}\n\n///\n/// An orientation media query breakpoint\n///\n@mixin break-at-orientation($breakpoint) {\n @if type-of($breakpoint) == string {\n @media screen and (orientation: $breakpoint) {\n @content;\n }\n } @else {\n @error \"Invalid breakpoint: #{$breakpoint}\";\n }\n}\n\n///\n/// A maximum-aspect-ratio media query breakpoint\n///\n@mixin break-at-ratio($breakpoint) {\n @if type-of($breakpoint) == number {\n @media screen and (max-aspect-ratio: $breakpoint) {\n @content;\n }\n } @else {\n @error \"Invalid breakpoint: #{$breakpoint}\";\n }\n}\n\n///\n/// A minimum-maximum media query device breakpoint\n///\n@mixin break-at-device($device) {\n @if type-of($device) == string {\n $device: $device,;\n }\n @if type-of($device) == list {\n $breakpoint: break-select-device($device);\n @if nth($breakpoint, 2) {\n $min: nth($breakpoint, 1);\n $max: nth($breakpoint, 2);\n\n @media screen and (min-width: $min) and (max-width: $max) {\n @content;\n }\n } @else {\n @error \"Invalid device: #{$device}\";\n }\n } @else {\n @error \"Invalid device: #{$device}\";\n }\n}\n\n///\n/// A minimum media query device breakpoint\n///\n@mixin break-from-device($device) {\n @if type-of($device) == string {\n $device: $device,;\n }\n @if type-of($device) == list {\n $breakpoint: break-select-device($device);\n $min: nth($breakpoint, 1);\n\n @media screen and (min-width: $min) {\n @content;\n }\n } @else {\n @error \"Invalid device: #{$device}\";\n }\n}\n\n///\n/// A maximum media query device breakpoint\n///\n@mixin break-to-device($device) {\n @if type-of($device) == string {\n $device: $device,;\n }\n @if type-of($device) == list {\n $breakpoint: break-select-device($device);\n $max: nth($breakpoint, 2);\n\n @media screen and (max-width: $max) {\n @content;\n }\n } @else {\n @error \"Invalid device: #{$device}\";\n }\n}\n","////\n/// Copyright (c) 2016-2021 Martin Donath \n///\n/// Permission is hereby granted, free of charge, to any person obtaining a\n/// copy of this software and associated documentation files (the \"Software\"),\n/// to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n/// and/or sell copies of the Software, and to permit persons to whom the\n/// Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n/// DEALINGS\n////\n\n// ----------------------------------------------------------------------------\n// Rules\n// ----------------------------------------------------------------------------\n\n// Only use dark mode on screens\n@media screen {\n\n // Slate theme, i.e. dark mode\n [data-md-color-scheme=\"slate\"] {\n\n // Slate's hue in the range [0,360] - change this variable to alter the tone\n // of the theme, e.g. to make it more redish or greenish. This is a slate-\n // specific variable, but the same approach may be adapted to custom themes.\n --md-hue: 232;\n\n // Default color shades\n --md-default-fg-color: hsla(var(--md-hue), 75%, 95%, 1);\n --md-default-fg-color--light: hsla(var(--md-hue), 75%, 90%, 0.62);\n --md-default-fg-color--lighter: hsla(var(--md-hue), 75%, 90%, 0.32);\n --md-default-fg-color--lightest: hsla(var(--md-hue), 75%, 90%, 0.12);\n --md-default-bg-color: hsla(var(--md-hue), 15%, 21%, 1);\n --md-default-bg-color--light: hsla(var(--md-hue), 15%, 21%, 0.54);\n --md-default-bg-color--lighter: hsla(var(--md-hue), 15%, 21%, 0.26);\n --md-default-bg-color--lightest: hsla(var(--md-hue), 15%, 21%, 0.07);\n\n // Code color shades\n --md-code-fg-color: hsla(var(--md-hue), 18%, 86%, 1);\n --md-code-bg-color: hsla(var(--md-hue), 15%, 15%, 1);\n\n // Code highlighting color shades\n --md-code-hl-color: hsla(#{hex2hsl($clr-blue-a200)}, 0.15);\n --md-code-hl-number-color: hsla(6, 74%, 63%, 1);\n --md-code-hl-special-color: hsla(340, 83%, 66%, 1);\n --md-code-hl-function-color: hsla(291, 57%, 65%, 1);\n --md-code-hl-constant-color: hsla(250, 62%, 70%, 1);\n --md-code-hl-keyword-color: hsla(219, 66%, 64%, 1);\n --md-code-hl-string-color: hsla(150, 58%, 44%, 1);\n --md-code-hl-name-color: var(--md-code-fg-color);\n --md-code-hl-operator-color: var(--md-default-fg-color--light);\n --md-code-hl-punctuation-color: var(--md-default-fg-color--light);\n --md-code-hl-comment-color: var(--md-default-fg-color--light);\n --md-code-hl-generic-color: var(--md-default-fg-color--light);\n --md-code-hl-variable-color: var(--md-default-fg-color--light);\n\n // Typeset color shades\n --md-typeset-color: var(--md-default-fg-color);\n\n // Typeset `a` color shades\n --md-typeset-a-color: var(--md-primary-fg-color);\n\n // Typeset `mark` color shades\n --md-typeset-mark-color: hsla(#{hex2hsl($clr-blue-a200)}, 0.3);\n\n // Typeset `kbd` color shades\n --md-typeset-kbd-color: hsla(var(--md-hue), 15%, 94%, 0.12);\n --md-typeset-kbd-accent-color: hsla(var(--md-hue), 15%, 94%, 0.2);\n --md-typeset-kbd-border-color: hsla(var(--md-hue), 15%, 14%, 1);\n\n // Admonition color shades\n --md-admonition-bg-color: hsla(var(--md-hue), 0%, 100%, 0.025);\n\n // Footer color shades\n --md-footer-bg-color: hsla(var(--md-hue), 15%, 12%, 0.87);\n --md-footer-bg-color--dark: hsla(var(--md-hue), 15%, 10%, 1);\n\n // Black and white primary colors\n &[data-md-color-primary=\"black\"],\n &[data-md-color-primary=\"white\"] {\n\n // Typeset color shades\n --md-typeset-a-color: hsla(#{hex2hsl($clr-indigo-400)}, 1);\n }\n }\n}\n"]} \ No newline at end of file diff --git a/en/2021.7/assets/telegram_forcebuy.png b/en/2021.7/assets/telegram_forcebuy.png new file mode 100644 index 000000000..b0592bff3 Binary files /dev/null and b/en/2021.7/assets/telegram_forcebuy.png differ diff --git a/en/2021.7/backtesting/index.html b/en/2021.7/backtesting/index.html new file mode 100644 index 000000000..6e2460ecd --- /dev/null +++ b/en/2021.7/backtesting/index.html @@ -0,0 +1,1580 @@ + + + + + + + + + + + + + + + + + + + Backtesting - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + + + + +
    +
    + + + + + + + +

    Backtesting

    +

    This page explains how to validate your strategy performance by using Backtesting.

    +

    Backtesting requires historic data to be available. +To learn how to get data for the pairs and exchange you're interested in, head over to the Data Downloading section of the documentation.

    +

    Backtesting command reference

    +

    ``` +usage: freqtrade backtesting [-h] [-v] [--logfile FILE] [-V] [-c PATH] + [-d PATH] [--userdir PATH] [-s NAME] + [--strategy-path PATH] [-i TIMEFRAME] + [--timerange TIMERANGE] + [--data-format-ohlcv {json,jsongz,hdf5}] + [--max-open-trades INT] + [--stake-amount STAKE_AMOUNT] [--fee FLOAT] + [-p PAIRS [PAIRS ...]] [--eps] [--dmmp] + [--enable-protections] + [--dry-run-wallet DRY_RUN_WALLET] + [--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]] + [--export {none,trades}] [--export-filename PATH]

    +

    optional arguments: + -h, --help show this help message and exit + -i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME + Specify timeframe (1m, 5m, 30m, 1h, 1d). + --timerange TIMERANGE + Specify what timerange of data to use. + --data-format-ohlcv {json,jsongz,hdf5} + Storage format for downloaded candle (OHLCV) data. + (default: None). + --max-open-trades INT + Override the value of the max_open_trades + configuration setting. + --stake-amount STAKE_AMOUNT + Override the value of the stake_amount configuration + setting. + --fee FLOAT Specify fee ratio. Will be applied twice (on trade + entry and exit). + -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] + Limit command to these pairs. Pairs are space- + separated. + --eps, --enable-position-stacking + Allow buying the same pair multiple times (position + stacking). + --dmmp, --disable-max-market-positions + Disable applying max_open_trades during backtest + (same as setting max_open_trades to a very high + number). + --enable-protections, --enableprotections + Enable protections for backtesting.Will slow + backtesting down by a considerable amount, but will + include configured protections + --dry-run-wallet DRY_RUN_WALLET, --starting-balance DRY_RUN_WALLET + Starting balance, used for backtesting / hyperopt and + dry-runs. + --strategy-list STRATEGY_LIST [STRATEGY_LIST ...] + Provide a space-separated list of strategies to + backtest. Please note that ticker-interval needs to be + set either in config or via command line. When using + this together with --export trades, the strategy- + name is injected into the filename (so backtest- + data.json becomes backtest-data- + DefaultStrategy.json + --export {none,trades} + Export backtest results (default: trades). + --export-filename PATH + Save backtest results to the file with this filename. + Requires --export to be set as well. Example: + --export-filename=user_data/backtest_results/backtest + _today.json

    +

    Common arguments: + -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). + --logfile FILE Log to the file specified. Special values are: + 'syslog', 'journald'. See the documentation for more + details. + -V, --version show program's version number and exit + -c PATH, --config PATH + Specify configuration file (default: + userdir/config.json or config.json whichever + exists). Multiple --config options may be used. Can be + set to - to read config from stdin. + -d PATH, --datadir PATH + Path to directory with historical backtesting data. + --userdir PATH, --user-data-dir PATH + Path to userdata directory.

    +

    Strategy arguments: + -s NAME, --strategy NAME + Specify strategy class name which will be used by the + bot. + --strategy-path PATH Specify additional strategy lookup path.

    +

    ```

    +

    Test your strategy with Backtesting

    +

    Now you have good Buy and Sell strategies and some historic data, you want to test it against +real data. This is what we call backtesting.

    +

    Backtesting will use the crypto-currencies (pairs) from your config file and load historical candle (OHLCV) data from user_data/data/<exchange> by default. +If no data is available for the exchange / pair / timeframe combination, backtesting will ask you to download them first using freqtrade download-data. +For details on downloading, please refer to the Data Downloading section in the documentation.

    +

    The result of backtesting will confirm if your bot has better odds of making a profit than a loss.

    +

    All profit calculations include fees, and freqtrade will use the exchange's default fees for the calculation.

    +
    +

    Using dynamic pairlists for backtesting

    +

    Using dynamic pairlists is possible, however it relies on the current market conditions - which will not reflect the historic status of the pairlist. +Also, when using pairlists other than StaticPairlist, reproducibility of backtesting-results cannot be guaranteed. +Please read the pairlists documentation for more information.

    +

    To achieve reproducible results, best generate a pairlist via the test-pairlist command and use that as static pairlist.

    +
    +
    +

    Note

    +

    By default, Freqtrade will export backtesting results to user_data/backtest_results. +The exported trades can be used for further analysis or can be used by the plotting sub-command (freqtrade plot-dataframe) in the scripts directory.

    +
    +

    Starting balance

    +

    Backtesting will require a starting balance, which can be provided as --dry-run-wallet <balance> or --starting-balance <balance> command line argument, or via dry_run_wallet configuration setting. +This amount must be higher than stake_amount, otherwise the bot will not be able to simulate any trade.

    +

    Dynamic stake amount

    +

    Backtesting supports dynamic stake amount by configuring stake_amount as "unlimited", which will split the starting balance into max_open_trades pieces. +Profits from early trades will result in subsequent higher stake amounts, resulting in compounding of profits over the backtesting period.

    +

    Example backtesting commands

    +

    With 5 min candle (OHLCV) data (per default)

    +

    bash +freqtrade backtesting --strategy AwesomeStrategy

    +

    Where --strategy AwesomeStrategy / -s AwesomeStrategy refers to the class name of the strategy, which is within a python file in the user_data/strategies directory.

    +
    +

    With 1 min candle (OHLCV) data

    +

    bash +freqtrade backtesting --strategy AwesomeStrategy --timeframe 1m

    +
    +

    Providing a custom starting balance of 1000 (in stake currency)

    +

    bash +freqtrade backtesting --strategy AwesomeStrategy --dry-run-wallet 1000

    +
    +

    Using a different on-disk historical candle (OHLCV) data source

    +

    Assume you downloaded the history data from the Bittrex exchange and kept it in the user_data/data/bittrex-20180101 directory. +You can then use this data for backtesting as follows:

    +

    bash +freqtrade backtesting --strategy AwesomeStrategy --datadir user_data/data/bittrex-20180101

    +
    +

    Comparing multiple Strategies

    +

    bash +freqtrade backtesting --strategy-list SampleStrategy1 AwesomeStrategy --timeframe 5m

    +

    Where SampleStrategy1 and AwesomeStrategy refer to class names of strategies.

    +
    +

    Prevent exporting trades to file

    +

    bash +freqtrade backtesting --strategy backtesting --export none --config config.json

    +

    Only use this if you're sure you'll not want to plot or analyze your results further.

    +
    +

    Exporting trades to file specifying a custom filename

    +

    bash +freqtrade backtesting --strategy backtesting --export trades --export-filename=backtest_samplestrategy.json

    +

    Please also read about the strategy startup period.

    +
    +

    Supplying custom fee value

    +

    Sometimes your account has certain fee rebates (fee reductions starting with a certain account size or monthly volume), which are not visible to ccxt. +To account for this in backtesting, you can use the --fee command line option to supply this value to backtesting. +This fee must be a ratio, and will be applied twice (once for trade entry, and once for trade exit).

    +

    For example, if the buying and selling commission fee is 0.1% (i.e., 0.001 written as ratio), then you would run backtesting as the following:

    +

    bash +freqtrade backtesting --fee 0.001

    +
    +

    Note

    +

    Only supply this option (or the corresponding configuration parameter) if you want to experiment with different fee values. By default, Backtesting fetches the default fee from the exchange pair/market info.

    +
    +
    +

    Running backtest with smaller test-set by using timerange

    +

    Use the --timerange argument to change how much of the test-set you want to use.

    +

    For example, running backtesting with the --timerange=20190501- option will use all available data starting with May 1st, 2019 from your input data.

    +

    bash +freqtrade backtesting --timerange=20190501-

    +

    You can also specify particular date ranges.

    +

    The full timerange specification:

    +
      +
    • Use data until 2018/01/31: --timerange=-20180131
    • +
    • Use data since 2018/01/31: --timerange=20180131-
    • +
    • Use data since 2018/01/31 till 2018/03/01 : --timerange=20180131-20180301
    • +
    • Use data between POSIX / epoch timestamps 1527595200 1527618600: --timerange=1527595200-1527618600
    • +
    +

    Understand the backtesting result

    +

    The most important in the backtesting is to understand the result.

    +

    A backtesting result will look like that:

    +

    ========================================================= BACKTESTING REPORT ========================================================== +| Pair | Buys | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Wins Draws Loss Win% | +|:---------|-------:|---------------:|---------------:|-----------------:|---------------:|:-------------|-------------------------:| +| ADA/BTC | 35 | -0.11 | -3.88 | -0.00019428 | -1.94 | 4:35:00 | 14 0 21 40.0 | +| ARK/BTC | 11 | -0.41 | -4.52 | -0.00022647 | -2.26 | 2:03:00 | 3 0 8 27.3 | +| BTS/BTC | 32 | 0.31 | 9.78 | 0.00048938 | 4.89 | 5:05:00 | 18 0 14 56.2 | +| DASH/BTC | 13 | -0.08 | -1.07 | -0.00005343 | -0.53 | 4:39:00 | 6 0 7 46.2 | +| ENG/BTC | 18 | 1.36 | 24.54 | 0.00122807 | 12.27 | 2:50:00 | 8 0 10 44.4 | +| EOS/BTC | 36 | 0.08 | 3.06 | 0.00015304 | 1.53 | 3:34:00 | 16 0 20 44.4 | +| ETC/BTC | 26 | 0.37 | 9.51 | 0.00047576 | 4.75 | 6:14:00 | 11 0 15 42.3 | +| ETH/BTC | 33 | 0.30 | 9.96 | 0.00049856 | 4.98 | 7:31:00 | 16 0 17 48.5 | +| IOTA/BTC | 32 | 0.03 | 1.09 | 0.00005444 | 0.54 | 3:12:00 | 14 0 18 43.8 | +| LSK/BTC | 15 | 1.75 | 26.26 | 0.00131413 | 13.13 | 2:58:00 | 6 0 9 40.0 | +| LTC/BTC | 32 | -0.04 | -1.38 | -0.00006886 | -0.69 | 4:49:00 | 11 0 21 34.4 | +| NANO/BTC | 17 | 1.26 | 21.39 | 0.00107058 | 10.70 | 1:55:00 | 10 0 7 58.5 | +| NEO/BTC | 23 | 0.82 | 18.97 | 0.00094936 | 9.48 | 2:59:00 | 10 0 13 43.5 | +| REQ/BTC | 9 | 1.17 | 10.54 | 0.00052734 | 5.27 | 3:47:00 | 4 0 5 44.4 | +| XLM/BTC | 16 | 1.22 | 19.54 | 0.00097800 | 9.77 | 3:15:00 | 7 0 9 43.8 | +| XMR/BTC | 23 | -0.18 | -4.13 | -0.00020696 | -2.07 | 5:30:00 | 12 0 11 52.2 | +| XRP/BTC | 35 | 0.66 | 22.96 | 0.00114897 | 11.48 | 3:49:00 | 12 0 23 34.3 | +| ZEC/BTC | 22 | -0.46 | -10.18 | -0.00050971 | -5.09 | 2:22:00 | 7 0 15 31.8 | +| TOTAL | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 0 243 43.4 | +========================================================= SELL REASON STATS ========================================================== +| Sell Reason | Sells | Wins | Draws | Losses | +|:-------------------|--------:|------:|-------:|--------:| +| trailing_stop_loss | 205 | 150 | 0 | 55 | +| stop_loss | 166 | 0 | 0 | 166 | +| sell_signal | 56 | 36 | 0 | 20 | +| force_sell | 2 | 0 | 0 | 2 | +====================================================== LEFT OPEN TRADES REPORT ====================================================== +| Pair | Buys | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Win Draw Loss Win% | +|:---------|-------:|---------------:|---------------:|-----------------:|---------------:|:---------------|--------------------:| +| ADA/BTC | 1 | 0.89 | 0.89 | 0.00004434 | 0.44 | 6:00:00 | 1 0 0 100 | +| LTC/BTC | 1 | 0.68 | 0.68 | 0.00003421 | 0.34 | 2:00:00 | 1 0 0 100 | +| TOTAL | 2 | 0.78 | 1.57 | 0.00007855 | 0.78 | 4:00:00 | 2 0 0 100 | +=============== SUMMARY METRICS =============== +| Metric | Value | +|-----------------------+---------------------| +| Backtesting from | 2019-01-01 00:00:00 | +| Backtesting to | 2019-05-01 00:00:00 | +| Max open trades | 3 | +| | | +| Total/Daily Avg Trades| 429 / 3.575 | +| Starting balance | 0.01000000 BTC | +| Final balance | 0.01762792 BTC | +| Absolute profit | 0.00762792 BTC | +| Total profit % | 76.2% | +| Trades per day | 3.575 | +| Avg. stake amount | 0.001 BTC | +| Total trade volume | 0.429 BTC | +| | | +| Best Pair | LSK/BTC 26.26% | +| Worst Pair | ZEC/BTC -10.18% | +| Best Trade | LSK/BTC 4.25% | +| Worst Trade | ZEC/BTC -10.25% | +| Best day | 0.00076 BTC | +| Worst day | -0.00036 BTC | +| Days win/draw/lose | 12 / 82 / 25 | +| Avg. Duration Winners | 4:23:00 | +| Avg. Duration Loser | 6:55:00 | +| Rejected Buy signals | 3089 | +| | | +| Min balance | 0.00945123 BTC | +| Max balance | 0.01846651 BTC | +| Drawdown | 50.63% | +| Drawdown | 0.0015 BTC | +| Drawdown high | 0.0013 BTC | +| Drawdown low | -0.0002 BTC | +| Drawdown Start | 2019-02-15 14:10:00 | +| Drawdown End | 2019-04-11 18:15:00 | +| Market change | -5.88% | +===============================================

    +

    Backtesting report table

    +

    The 1st table contains all trades the bot made, including "left open trades".

    +

    The last line will give you the overall performance of your strategy, +here:

    +

    | TOTAL | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 0 243 43.4 |

    +

    The bot has made 429 trades for an average duration of 4:12:00, with a performance of 76.20% (profit), that means it has +earned a total of 0.00762792 BTC starting with a capital of 0.01 BTC.

    +

    The column Avg Profit % shows the average profit for all trades made while the column Cum Profit % sums up all the profits/losses. +The column Tot Profit % shows instead the total profit % in relation to the starting balance. +In the above results, we have a starting balance of 0.01 BTC and an absolute profit of 0.00762792 BTC - so the Tot Profit % will be (0.00762792 / 0.01) * 100 ~= 76.2%.

    +

    Your strategy performance is influenced by your buy strategy, your sell strategy, and also by the minimal_roi and stop_loss you have set.

    +

    For example, if your minimal_roi is only "0": 0.01 you cannot expect the bot to make more profit than 1% (because it will sell every time a trade reaches 1%).

    +

    json +"minimal_roi": { + "0": 0.01 +},

    +

    On the other hand, if you set a too high minimal_roi like "0": 0.55 +(55%), there is almost no chance that the bot will ever reach this profit. +Hence, keep in mind that your performance is an integral mix of all different elements of the strategy, your configuration, and the crypto-currency pairs you have set up.

    +

    Sell reasons table

    +

    The 2nd table contains a recap of sell reasons. +This table can tell you which area needs some additional work (e.g. all or many of the sell_signal trades are losses, so you should work on improving the sell signal, or consider disabling it).

    +

    Left open trades table

    +

    The 3rd table contains all trades the bot had to forcesell at the end of the backtesting period to present you the full picture. +This is necessary to simulate realistic behavior, since the backtest period has to end at some point, while realistically, you could leave the bot running forever. +These trades are also included in the first table, but are also shown separately in this table for clarity.

    +

    Summary metrics

    +

    The last element of the backtest report is the summary metrics table. +It contains some useful key metrics about performance of your strategy on backtesting data.

    +

    ``` +=============== SUMMARY METRICS =============== +| Metric | Value | +|-----------------------+---------------------| +| Backtesting from | 2019-01-01 00:00:00 | +| Backtesting to | 2019-05-01 00:00:00 | +| Max open trades | 3 | +| | | +| Total/Daily Avg Trades| 429 / 3.575 | +| Starting balance | 0.01000000 BTC | +| Final balance | 0.01762792 BTC | +| Absolute profit | 0.00762792 BTC | +| Total profit % | 76.2% | +| Avg. stake amount | 0.001 BTC | +| Total trade volume | 0.429 BTC | +| | | +| Best Pair | LSK/BTC 26.26% | +| Worst Pair | ZEC/BTC -10.18% | +| Best Trade | LSK/BTC 4.25% | +| Worst Trade | ZEC/BTC -10.25% | +| Best day | 0.00076 BTC | +| Worst day | -0.00036 BTC | +| Days win/draw/lose | 12 / 82 / 25 | +| Avg. Duration Winners | 4:23:00 | +| Avg. Duration Loser | 6:55:00 | +| Rejected Buy signals | 3089 | +| | | +| Min balance | 0.00945123 BTC | +| Max balance | 0.01846651 BTC | +| Drawdown | 50.63% | +| Drawdown | 0.0015 BTC | +| Drawdown high | 0.0013 BTC | +| Drawdown low | -0.0002 BTC | +| Drawdown Start | 2019-02-15 14:10:00 | +| Drawdown End | 2019-04-11 18:15:00 | +| Market change | -5.88% | +===============================================

    +

    ```

    +
      +
    • Backtesting from / Backtesting to: Backtesting range (usually defined with the --timerange option).
    • +
    • Max open trades: Setting of max_open_trades (or --max-open-trades) - or number of pairs in the pairlist (whatever is lower).
    • +
    • Total/Daily Avg Trades: Identical to the total trades of the backtest output table / Total trades divided by the backtesting duration in days (this will give you information about how many trades to expect from the strategy).
    • +
    • Starting balance: Start balance - as given by dry-run-wallet (config or command line).
    • +
    • Final balance: Final balance - starting balance + absolute profit.
    • +
    • Absolute profit: Profit made in stake currency.
    • +
    • Total profit %: Total profit. Aligned to the TOTAL row's Tot Profit % from the first table. Calculated as (End capital − Starting capital) / Starting capital.
    • +
    • Avg. stake amount: Average stake amount, either stake_amount or the average when using dynamic stake amount.
    • +
    • Total trade volume: Volume generated on the exchange to reach the above profit.
    • +
    • Best Pair / Worst Pair: Best and worst performing pair, and it's corresponding Cum Profit %.
    • +
    • Best Trade / Worst Trade: Biggest single winning trade and biggest single losing trade.
    • +
    • Best day / Worst day: Best and worst day based on daily profit.
    • +
    • Days win/draw/lose: Winning / Losing days (draws are usually days without closed trade).
    • +
    • Avg. Duration Winners / Avg. Duration Loser: Average durations for winning and losing trades.
    • +
    • Rejected Buy signals: Buy signals that could not be acted upon due to max_open_trades being reached.
    • +
    • Min balance / Max balance: Lowest and Highest Wallet balance during the backtest period.
    • +
    • Drawdown: Maximum drawdown experienced. For example, the value of 50% means that from highest to subsequent lowest point, a 50% drop was experienced).
    • +
    • Drawdown high / Drawdown low: Profit at the beginning and end of the largest drawdown period. A negative low value means initial capital lost.
    • +
    • Drawdown Start / Drawdown End: Start and end datetime for this largest drawdown (can also be visualized via the plot-dataframe sub-command).
    • +
    • Market change: Change of the market during the backtest period. Calculated as average of all pairs changes from the first to the last candle using the "close" column.
    • +
    +

    Assumptions made by backtesting

    +

    Since backtesting lacks some detailed information about what happens within a candle, it needs to take a few assumptions:

    +
      +
    • Buys happen at open-price
    • +
    • All orders are filled at the requested price (no slippage, no unfilled orders)
    • +
    • Sell-signal sells happen at open-price of the consecutive candle
    • +
    • Sell-signal is favored over Stoploss, because sell-signals are assumed to trigger on candle's open
    • +
    • ROI
        +
      • sells are compared to high - but the ROI value is used (e.g. ROI = 2%, high=5% - so the sell will be at 2%)
      • +
      • sells are never "below the candle", so a ROI of 2% may result in a sell at 2.4% if low was at 2.4% profit
      • +
      • Forcesells caused by <N>=-1 ROI entries use low as sell value, unless N falls on the candle open (e.g. 120: -1 for 1h candles)
      • +
      +
    • +
    • Stoploss sells happen exactly at stoploss price, even if low was lower, but the loss will be 2 * fees higher than the stoploss price
    • +
    • Stoploss is evaluated before ROI within one candle. So you can often see more trades with the stoploss sell reason comparing to the results obtained with the same strategy in the Dry Run/Live Trade modes
    • +
    • Low happens before high for stoploss, protecting capital first
    • +
    • Trailing stoploss
        +
      • Trailing Stoploss is only adjusted if it's below the candle's low (otherwise it would be triggered)
      • +
      • High happens first - adjusting stoploss
      • +
      • Low uses the adjusted stoploss (so sells with large high-low difference are backtested correctly)
      • +
      • ROI applies before trailing-stop, ensuring profits are "top-capped" at ROI if both ROI and trailing stop applies
      • +
      +
    • +
    • Sell-reason does not explain if a trade was positive or negative, just what triggered the sell (this can look odd if negative ROI values are used)
    • +
    • Evaluation sequence (if multiple signals happen on the same candle)
        +
      • ROI (if not stoploss)
      • +
      • Sell-signal
      • +
      • Stoploss
      • +
      +
    • +
    +

    Taking these assumptions, backtesting tries to mirror real trading as closely as possible. However, backtesting will never replace running a strategy in dry-run mode. +Also, keep in mind that past results don't guarantee future success.

    +

    In addition to the above assumptions, strategy authors should carefully read the Common Mistakes section, to avoid using data in backtesting which is not available in real market conditions.

    +

    Further backtest-result analysis

    +

    To further analyze your backtest results, you can export the trades. +You can then load the trades to perform further analysis as shown in our data analysis backtesting section.

    +

    Backtesting multiple strategies

    +

    To compare multiple strategies, a list of Strategies can be provided to backtesting.

    +

    This is limited to 1 timeframe value per run. However, data is only loaded once from disk so if you have multiple +strategies you'd like to compare, this will give a nice runtime boost.

    +

    All listed Strategies need to be in the same directory.

    +

    bash +freqtrade backtesting --timerange 20180401-20180410 --timeframe 5m --strategy-list Strategy001 Strategy002 --export trades

    +

    This will save the results to user_data/backtest_results/backtest-result-<strategy>.json, injecting the strategy-name into the target filename. +There will be an additional table comparing win/losses of the different strategies (identical to the "Total" row in the first table). +Detailed output for all strategies one after the other will be available, so make sure to scroll up to see the details per strategy.

    +

    =========================================================== STRATEGY SUMMARY ========================================================================= +| Strategy | Buys | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Wins | Draws | Losses | Drawdown % | +|:------------|-------:|---------------:|---------------:|-----------------:|---------------:|:---------------|------:|-------:|-------:|-----------:| +| Strategy1 | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 0 | 243 | 45.2 | +| Strategy2 | 1487 | -0.13 | -197.58 | -0.00988917 | -98.79 | 4:43:00 | 662 | 0 | 825 | 241.68 |

    +

    Next step

    +

    Great, your strategy is profitable. What if the bot can give your the optimal parameters to use for your strategy? +Your next step is to learn how to find optimal parameters with Hyperopt

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/bot-basics/index.html b/en/2021.7/bot-basics/index.html new file mode 100644 index 000000000..b09bd0995 --- /dev/null +++ b/en/2021.7/bot-basics/index.html @@ -0,0 +1,1087 @@ + + + + + + + + + + + + + + + + + + + Freqtrade Basics - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + + + + + + +

    Freqtrade basics

    +

    This page provides you some basic concepts on how Freqtrade works and operates.

    +

    Freqtrade terminology

    +
      +
    • Strategy: Your trading strategy, telling the bot what to do.
    • +
    • Trade: Open position.
    • +
    • Open Order: Order which is currently placed on the exchange, and is not yet complete.
    • +
    • Pair: Tradable pair, usually in the format of Quote/Base (e.g. XRP/USDT).
    • +
    • Timeframe: Candle length to use (e.g. "5m", "1h", ...).
    • +
    • Indicators: Technical indicators (SMA, EMA, RSI, ...).
    • +
    • Limit order: Limit orders which execute at the defined limit price or better.
    • +
    • Market order: Guaranteed to fill, may move price depending on the order size.
    • +
    +

    Fee handling

    +

    All profit calculations of Freqtrade include fees. For Backtesting / Hyperopt / Dry-run modes, the exchange default fee is used (lowest tier on the exchange). For live operations, fees are used as applied by the exchange (this includes BNB rebates etc.).

    +

    Bot execution logic

    +

    Starting freqtrade in dry-run or live mode (using freqtrade trade) will start the bot and start the bot iteration loop. +By default, loop runs every few seconds (internals.process_throttle_secs) and does roughly the following in the following sequence:

    +
      +
    • Fetch open trades from persistence.
    • +
    • Calculate current list of tradable pairs.
    • +
    • Download ohlcv data for the pairlist including all informative pairs
      + This step is only executed once per Candle to avoid unnecessary network traffic.
    • +
    • Call bot_loop_start() strategy callback.
    • +
    • Analyze strategy per pair.
        +
      • Call populate_indicators()
      • +
      • Call populate_buy_trend()
      • +
      • Call populate_sell_trend()
      • +
      +
    • +
    • Check timeouts for open orders.
        +
      • Calls check_buy_timeout() strategy callback for open buy orders.
      • +
      • Calls check_sell_timeout() strategy callback for open sell orders.
      • +
      +
    • +
    • Verifies existing positions and eventually places sell orders.
        +
      • Considers stoploss, ROI and sell-signal.
      • +
      • Determine sell-price based on ask_strategy configuration setting.
      • +
      • Before a sell order is placed, confirm_trade_exit() strategy callback is called.
      • +
      +
    • +
    • Check if trade-slots are still available (if max_open_trades is reached).
    • +
    • Verifies buy signal trying to enter new positions.
        +
      • Determine buy-price based on bid_strategy configuration setting.
      • +
      • Before a buy order is placed, confirm_trade_entry() strategy callback is called.
      • +
      +
    • +
    +

    This loop will be repeated again and again until the bot is stopped.

    +

    Backtesting / Hyperopt execution logic

    +

    backtesting or hyperopt do only part of the above logic, since most of the trading operations are fully simulated.

    +
      +
    • Load historic data for configured pairlist.
    • +
    • Calls bot_loop_start() once.
    • +
    • Calculate indicators (calls populate_indicators() once per pair).
    • +
    • Calculate buy / sell signals (calls populate_buy_trend() and populate_sell_trend() once per pair)
    • +
    • Confirm trade buy / sell (calls confirm_trade_entry() and confirm_trade_exit() if implemented in the strategy)
    • +
    • Loops per candle simulating entry and exit points.
    • +
    • Generate backtest report output
    • +
    +
    +

    Note

    +

    Both Backtesting and Hyperopt include exchange default Fees in the calculation. Custom fees can be passed to backtesting / hyperopt by specifying the --fee argument.

    +
    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/bot-usage/index.html b/en/2021.7/bot-usage/index.html new file mode 100644 index 000000000..4ecf0e4ae --- /dev/null +++ b/en/2021.7/bot-usage/index.html @@ -0,0 +1,1291 @@ + + + + + + + + + + + + + + + + + + + Start the bot - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + + + + +
    +
    + + + + + + + +

    Start the bot

    +

    This page explains the different parameters of the bot and how to run it.

    +
    +

    Note

    +

    If you've used setup.sh, don't forget to activate your virtual environment (source .env/bin/activate) before running freqtrade commands.

    +
    +
    +

    Up-to-date clock

    +

    The clock on the system running the bot must be accurate, synchronized to a NTP server frequently enough to avoid problems with communication to the exchanges.

    +
    +

    Bot commands

    +

    ``` +usage: freqtrade [-h] [-V] + {trade,create-userdir,new-config,new-hyperopt,new-strategy,download-data,convert-data,convert-trade-data,backtesting,edge,hyperopt,hyperopt-list,hyperopt-show,list-exchanges,list-hyperopts,list-markets,list-pairs,list-strategies,list-timeframes,show-trades,test-pairlist,plot-dataframe,plot-profit} + ...

    +

    Free, open source crypto trading bot

    +

    positional arguments: + {trade,create-userdir,new-config,new-hyperopt,new-strategy,download-data,convert-data,convert-trade-data,backtesting,edge,hyperopt,hyperopt-list,hyperopt-show,list-exchanges,list-hyperopts,list-markets,list-pairs,list-strategies,list-timeframes,show-trades,test-pairlist,plot-dataframe,plot-profit} + trade Trade module. + create-userdir Create user-data directory. + new-config Create new config + new-hyperopt Create new hyperopt + new-strategy Create new strategy + download-data Download backtesting data. + convert-data Convert candle (OHLCV) data from one format to + another. + convert-trade-data Convert trade data from one format to another. + backtesting Backtesting module. + edge Edge module. + hyperopt Hyperopt module. + hyperopt-list List Hyperopt results + hyperopt-show Show details of Hyperopt results + list-exchanges Print available exchanges. + list-hyperopts Print available hyperopt classes. + list-markets Print markets on exchange. + list-pairs Print pairs on exchange. + list-strategies Print available strategies. + list-timeframes Print available timeframes for the exchange. + show-trades Show trades. + test-pairlist Test your pairlist configuration. + plot-dataframe Plot candles with indicators. + plot-profit Generate plot showing profits.

    +

    optional arguments: + -h, --help show this help message and exit + -V, --version show program's version number and exit

    +

    ```

    +

    Bot trading commands

    +

    ``` +usage: freqtrade trade [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] + [--userdir PATH] [-s NAME] [--strategy-path PATH] + [--db-url PATH] [--sd-notify] [--dry-run] + [--dry-run-wallet DRY_RUN_WALLET]

    +

    optional arguments: + -h, --help show this help message and exit + --db-url PATH Override trades database URL, this is useful in custom + deployments (default: sqlite:///tradesv3.sqlite for + Live Run mode, sqlite:///tradesv3.dryrun.sqlite for + Dry Run). + --sd-notify Notify systemd service manager. + --dry-run Enforce dry-run for trading (removes Exchange secrets + and simulates trades). + --dry-run-wallet DRY_RUN_WALLET, --starting-balance DRY_RUN_WALLET + Starting balance, used for backtesting / hyperopt and + dry-runs.

    +

    Common arguments: + -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). + --logfile FILE Log to the file specified. Special values are: + 'syslog', 'journald'. See the documentation for more + details. + -V, --version show program's version number and exit + -c PATH, --config PATH + Specify configuration file (default: + userdir/config.json or config.json whichever + exists). Multiple --config options may be used. Can be + set to - to read config from stdin. + -d PATH, --datadir PATH + Path to directory with historical backtesting data. + --userdir PATH, --user-data-dir PATH + Path to userdata directory.

    +

    Strategy arguments: + -s NAME, --strategy NAME + Specify strategy class name which will be used by the + bot. + --strategy-path PATH Specify additional strategy lookup path.

    +

    ```

    +

    How to specify which configuration file be used?

    +

    The bot allows you to select which configuration file you want to use by means of +the -c/--config command line option:

    +

    bash +freqtrade trade -c path/far/far/away/config.json

    +

    Per default, the bot loads the config.json configuration file from the current +working directory.

    +

    How to use multiple configuration files?

    +

    The bot allows you to use multiple configuration files by specifying multiple +-c/--config options in the command line. Configuration parameters +defined in the latter configuration files override parameters with the same name +defined in the previous configuration files specified in the command line earlier.

    +

    For example, you can make a separate configuration file with your key and secret +for the Exchange you use for trading, specify default configuration file with +empty key and secret values while running in the Dry Mode (which does not actually +require them):

    +

    bash +freqtrade trade -c ./config.json

    +

    and specify both configuration files when running in the normal Live Trade Mode:

    +

    bash +freqtrade trade -c ./config.json -c path/to/secrets/keys.config.json

    +

    This could help you hide your private Exchange key and Exchange secret on you local machine +by setting appropriate file permissions for the file which contains actual secrets and, additionally, +prevent unintended disclosure of sensitive private data when you publish examples +of your configuration in the project issues or in the Internet.

    +

    See more details on this technique with examples in the documentation page on +configuration.

    +

    Where to store custom data

    +

    Freqtrade allows the creation of a user-data directory using freqtrade create-userdir --userdir someDirectory. +This directory will look as follows:

    +

    user_data/ +├── backtest_results +├── data +├── hyperopts +├── hyperopt_results +├── plot +└── strategies

    +

    You can add the entry "user_data_dir" setting to your configuration, to always point your bot to this directory. +Alternatively, pass in --userdir to every command. +The bot will fail to start if the directory does not exist, but will create necessary subdirectories.

    +

    This directory should contain your custom strategies, custom hyperopts and hyperopt loss functions, backtesting historical data (downloaded using either backtesting command or the download script) and plot outputs.

    +

    It is recommended to use version control to keep track of changes to your strategies.

    +

    How to use --strategy?

    +

    This parameter will allow you to load your custom strategy class. +To test the bot installation, you can use the SampleStrategy installed by the create-userdir subcommand (usually user_data/strategy/sample_strategy.py).

    +

    The bot will search your strategy file within user_data/strategies. +To use other directories, please read the next section about --strategy-path.

    +

    To load a strategy, simply pass the class name (e.g.: CustomStrategy) in this parameter.

    +

    Example: +In user_data/strategies you have a file my_awesome_strategy.py which has +a strategy class called AwesomeStrategy to load it:

    +

    bash +freqtrade trade --strategy AwesomeStrategy

    +

    If the bot does not find your strategy file, it will display in an error +message the reason (File not found, or errors in your code).

    +

    Learn more about strategy file in +Strategy Customization.

    +

    How to use --strategy-path?

    +

    This parameter allows you to add an additional strategy lookup path, which gets +checked before the default locations (The passed path must be a directory!):

    +

    bash +freqtrade trade --strategy AwesomeStrategy --strategy-path /some/directory

    +

    How to install a strategy?

    +

    This is very simple. Copy paste your strategy file into the directory +user_data/strategies or use --strategy-path. And voila, the bot is ready to use it.

    +

    How to use --db-url?

    +

    When you run the bot in Dry-run mode, per default no transactions are +stored in a database. If you want to store your bot actions in a DB +using --db-url. This can also be used to specify a custom database +in production mode. Example command:

    +

    bash +freqtrade trade -c config.json --db-url sqlite:///tradesv3.dry_run.sqlite

    +

    Next step

    +

    The optimal strategy of the bot will change with time depending of the market trends. The next step is to +Strategy Customization.

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/configuration/index.html b/en/2021.7/configuration/index.html new file mode 100644 index 000000000..4d5935687 --- /dev/null +++ b/en/2021.7/configuration/index.html @@ -0,0 +1,2406 @@ + + + + + + + + + + + + + + + + + + + Configuration - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + + + + + + +

    Configure the bot

    +

    Freqtrade has many configurable features and possibilities. +By default, these settings are configured via the configuration file (see below).

    +

    The Freqtrade configuration file

    +

    The bot uses a set of configuration parameters during its operation that all together conform to the bot configuration. It normally reads its configuration from a file (Freqtrade configuration file).

    +

    Per default, the bot loads the configuration from the config.json file, located in the current working directory.

    +

    You can specify a different configuration file used by the bot with the -c/--config command-line option.

    +

    Multiple configuration files can be specified and used by the bot or the bot can read its configuration parameters from the process standard input stream.

    +
    +

    Use multiple configuration files to keep secrets secret

    +

    You can use a 2nd configuration file containing your secrets. That way you can share your "primary" configuration file, while still keeping your API keys for yourself.

    +

    bash +freqtrade trade --config user_data/config.json --config user_data/config-private.json <...> +The 2nd file should only specify what you intend to override. +If a key is in more than one of the configurations, then the "last specified configuration" wins (in the above example, config-private.json).

    +
    +

    If you used the Quick start method for installing +the bot, the installation script should have already created the default configuration file (config.json) for you.

    +

    If the default configuration file is not created we recommend you to use freqtrade new-config --config config.json to generate a basic configuration file.

    +

    The Freqtrade configuration file is to be written in JSON format.

    +

    Additionally to the standard JSON syntax, you may use one-line // ... and multi-line /* ... */ comments in your configuration files and trailing commas in the lists of parameters.

    +

    Do not worry if you are not familiar with JSON format -- simply open the configuration file with an editor of your choice, make some changes to the parameters you need, save your changes and, finally, restart the bot or, if it was previously stopped, run it again with the changes you made to the configuration. The bot validates the syntax of the configuration file at startup and will warn you if you made any errors editing it, pointing out problematic lines.

    +

    Configuration parameters

    +

    The table below will list all configuration parameters available.

    +

    Freqtrade can also load many options via command line (CLI) arguments (check out the commands --help output for details). +The prevalence for all Options is as follows:

    +
      +
    • CLI arguments override any other option
    • +
    • Configuration files are used in sequence (the last file wins) and override Strategy configurations.
    • +
    • Strategy configurations are only used if they are not set via configuration or command-line arguments. These options are marked with Strategy Override in the below table.
    • +
    +

    Mandatory parameters are marked as Required, which means that they are required to be set in one of the possible ways.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    ParameterDescription
    max_open_tradesRequired. Number of open trades your bot is allowed to have. Only one open trade per pair is possible, so the length of your pairlist is another limitation that can apply. If -1 then it is ignored (i.e. potentially unlimited open trades, limited by the pairlist). More information below.
    Datatype: Positive integer or -1.
    stake_currencyRequired. Crypto-currency used for trading.
    Datatype: String
    stake_amountRequired. Amount of crypto-currency your bot will use for each trade. Set it to "unlimited" to allow the bot to use all available balance. More information below.
    Datatype: Positive float or "unlimited".
    tradable_balance_ratioRatio of the total account balance the bot is allowed to trade. More information below.
    Defaults to 0.99 99%).
    Datatype: Positive float between 0.1 and 1.0.
    available_capitalAvailable starting capital for the bot. Useful when running multiple bots on the same exchange account.More information below.
    Datatype: Positive float.
    amend_last_stake_amountUse reduced last stake amount if necessary. More information below.
    Defaults to false.
    Datatype: Boolean
    last_stake_amount_min_ratioDefines minimum stake amount that has to be left and executed. Applies only to the last stake amount when it's amended to a reduced value (i.e. if amend_last_stake_amount is set to true). More information below.
    Defaults to 0.5.
    Datatype: Float (as ratio)
    amount_reserve_percentReserve some amount in min pair stake amount. The bot will reserve amount_reserve_percent + stoploss value when calculating min pair stake amount in order to avoid possible trade refusals.
    Defaults to 0.05 (5%).
    Datatype: Positive Float as ratio.
    timeframeThe timeframe (former ticker interval) to use (e.g 1m, 5m, 15m, 30m, 1h ...). Strategy Override.
    Datatype: String
    fiat_display_currencyFiat currency used to show your profits. More information below.
    Datatype: String
    dry_runRequired. Define if the bot must be in Dry Run or production mode.
    Defaults to true.
    Datatype: Boolean
    dry_run_walletDefine the starting amount in stake currency for the simulated wallet used by the bot running in Dry Run mode.
    Defaults to 1000.
    Datatype: Float
    cancel_open_orders_on_exitCancel open orders when the /stop RPC command is issued, Ctrl+C is pressed or the bot dies unexpectedly. When set to true, this allows you to use /stop to cancel unfilled and partially filled orders in the event of a market crash. It does not impact open positions.
    Defaults to false.
    Datatype: Boolean
    process_only_new_candlesEnable processing of indicators only when new candles arrive. If false each loop populates the indicators, this will mean the same candle is processed many times creating system load but can be useful of your strategy depends on tick data not only candle. Strategy Override.
    Defaults to false.
    Datatype: Boolean
    minimal_roiRequired. Set the threshold as ratio the bot will use to sell a trade. More information below. Strategy Override.
    Datatype: Dict
    stoplossRequired. Value as ratio of the stoploss used by the bot. More details in the stoploss documentation. Strategy Override.
    Datatype: Float (as ratio)
    trailing_stopEnables trailing stoploss (based on stoploss in either configuration or strategy file). More details in the stoploss documentation. Strategy Override.
    Datatype: Boolean
    trailing_stop_positiveChanges stoploss once profit has been reached. More details in the stoploss documentation. Strategy Override.
    Datatype: Float
    trailing_stop_positive_offsetOffset on when to apply trailing_stop_positive. Percentage value which should be positive. More details in the stoploss documentation. Strategy Override.
    Defaults to 0.0 (no offset).
    Datatype: Float
    trailing_only_offset_is_reachedOnly apply trailing stoploss when the offset is reached. stoploss documentation. Strategy Override.
    Defaults to false.
    Datatype: Boolean
    feeFee used during backtesting / dry-runs. Should normally not be configured, which has freqtrade fall back to the exchange default fee. Set as ratio (e.g. 0.001 = 0.1%). Fee is applied twice for each trade, once when buying, once when selling.
    Datatype: Float (as ratio)
    unfilledtimeout.buyRequired. How long (in minutes or seconds) the bot will wait for an unfilled buy order to complete, after which the order will be cancelled and repeated at current (new) price, as long as there is a signal. Strategy Override.
    Datatype: Integer
    unfilledtimeout.sellRequired. How long (in minutes or seconds) the bot will wait for an unfilled sell order to complete, after which the order will be cancelled and repeated at current (new) price, as long as there is a signal. Strategy Override.
    Datatype: Integer
    unfilledtimeout.unitUnit to use in unfilledtimeout setting. Note: If you set unfilledtimeout.unit to "seconds", "internals.process_throttle_secs" must be inferior or equal to timeout Strategy Override.
    Defaults to minutes.
    Datatype: String
    bid_strategy.price_sideSelect the side of the spread the bot should look at to get the buy rate. More information below.
    Defaults to bid.
    Datatype: String (either ask or bid).
    bid_strategy.ask_last_balanceRequired. Interpolate the bidding price. More information below.
    bid_strategy.use_order_bookEnable buying using the rates in Order Book Bids.
    Datatype: Boolean
    bid_strategy.order_book_topBot will use the top N rate in Order Book "price_side" to buy. I.e. a value of 2 will allow the bot to pick the 2nd bid rate in Order Book Bids.
    Defaults to 1.
    Datatype: Positive Integer
    bid_strategy. check_depth_of_market.enabledDo not buy if the difference of buy orders and sell orders is met in Order Book. Check market depth.
    Defaults to false.
    Datatype: Boolean
    bid_strategy. check_depth_of_market.bids_to_ask_deltaThe difference ratio of buy orders and sell orders found in Order Book. A value below 1 means sell order size is greater, while value greater than 1 means buy order size is higher. Check market depth
    Defaults to 0.
    Datatype: Float (as ratio)
    ask_strategy.price_sideSelect the side of the spread the bot should look at to get the sell rate. More information below.
    Defaults to ask.
    Datatype: String (either ask or bid).
    ask_strategy.bid_last_balanceInterpolate the selling price. More information below.
    ask_strategy.use_order_bookEnable selling of open trades using Order Book Asks.
    Datatype: Boolean
    ask_strategy.order_book_topBot will use the top N rate in Order Book "price_side" to sell. I.e. a value of 2 will allow the bot to pick the 2nd ask rate in Order Book Asks
    Defaults to 1.
    Datatype: Positive Integer
    use_sell_signalUse sell signals produced by the strategy in addition to the minimal_roi. Strategy Override.
    Defaults to true.
    Datatype: Boolean
    sell_profit_onlyWait until the bot reaches sell_profit_offset before taking a sell decision. Strategy Override.
    Defaults to false.
    Datatype: Boolean
    sell_profit_offsetSell-signal is only active above this value. Strategy Override.
    Defaults to 0.0.
    Datatype: Float (as ratio)
    ignore_roi_if_buy_signalDo not sell if the buy signal is still active. This setting takes preference over minimal_roi and use_sell_signal. Strategy Override.
    Defaults to false.
    Datatype: Boolean
    ignore_buying_expired_candle_afterSpecifies the number of seconds until a buy signal is no longer used.
    Datatype: Integer
    order_typesConfigure order-types depending on the action ("buy", "sell", "stoploss", "stoploss_on_exchange"). More information below. Strategy Override.
    Datatype: Dict
    order_time_in_forceConfigure time in force for buy and sell orders. More information below. Strategy Override.
    Datatype: Dict
    exchange.nameRequired. Name of the exchange class to use. List below.
    Datatype: String
    exchange.sandboxUse the 'sandbox' version of the exchange, where the exchange provides a sandbox for risk-free integration. See here in more details.
    Datatype: Boolean
    exchange.keyAPI key to use for the exchange. Only required when you are in production mode.
    Keep it in secret, do not disclose publicly.
    Datatype: String
    exchange.secretAPI secret to use for the exchange. Only required when you are in production mode.
    Keep it in secret, do not disclose publicly.
    Datatype: String
    exchange.passwordAPI password to use for the exchange. Only required when you are in production mode and for exchanges that use password for API requests.
    Keep it in secret, do not disclose publicly.
    Datatype: String
    exchange.pair_whitelistList of pairs to use by the bot for trading and to check for potential trades during backtesting. Supports regex pairs as .*/BTC. Not used by VolumePairList. More information.
    Datatype: List
    exchange.pair_blacklistList of pairs the bot must absolutely avoid for trading and backtesting. More information.
    Datatype: List
    exchange.ccxt_configAdditional CCXT parameters passed to both ccxt instances (sync and async). This is usually the correct place for ccxt configurations. Parameters may differ from exchange to exchange and are documented in the ccxt documentation
    Datatype: Dict
    exchange.ccxt_sync_configAdditional CCXT parameters passed to the regular (sync) ccxt instance. Parameters may differ from exchange to exchange and are documented in the ccxt documentation
    Datatype: Dict
    exchange.ccxt_async_configAdditional CCXT parameters passed to the async ccxt instance. Parameters may differ from exchange to exchange and are documented in the ccxt documentation
    Datatype: Dict
    exchange.markets_refresh_intervalThe interval in minutes in which markets are reloaded.
    Defaults to 60 minutes.
    Datatype: Positive Integer
    exchange.skip_pair_validationSkip pairlist validation on startup.
    Defaults to false
    Datatype:* Boolean
    exchange.skip_open_order_updateSkips open order updates on startup should the exchange cause problems. Only relevant in live conditions.
    Defaults to false
    Datatype:* Boolean
    exchange.log_responsesLog relevant exchange responses. For debug mode only - use with care.
    Defaults to false
    Datatype:* Boolean
    edge.*Please refer to edge configuration document for detailed explanation.
    experimental.block_bad_exchangesBlock exchanges known to not work with freqtrade. Leave on default unless you want to test if that exchange works now.
    Defaults to true.
    Datatype: Boolean
    pairlistsDefine one or more pairlists to be used. More information.
    Defaults to StaticPairList.
    Datatype: List of Dicts
    protectionsDefine one or more protections to be used. More information.
    Datatype: List of Dicts
    telegram.enabledEnable the usage of Telegram.
    Datatype: Boolean
    telegram.tokenYour Telegram bot token. Only required if telegram.enabled is true.
    Keep it in secret, do not disclose publicly.
    Datatype: String
    telegram.chat_idYour personal Telegram account id. Only required if telegram.enabled is true.
    Keep it in secret, do not disclose publicly.
    Datatype: String
    telegram.balance_dust_levelDust-level (in stake currency) - currencies with a balance below this will not be shown by /balance.
    Datatype: float
    webhook.enabledEnable usage of Webhook notifications
    Datatype: Boolean
    webhook.urlURL for the webhook. Only required if webhook.enabled is true. See the webhook documentation for more details.
    Datatype: String
    webhook.webhookbuyPayload to send on buy. Only required if webhook.enabled is true. See the webhook documentation for more details.
    Datatype: String
    webhook.webhookbuycancelPayload to send on buy order cancel. Only required if webhook.enabled is true. See the webhook documentation for more details.
    Datatype: String
    webhook.webhooksellPayload to send on sell. Only required if webhook.enabled is true. See the webhook documentation for more details.
    Datatype: String
    webhook.webhooksellcancelPayload to send on sell order cancel. Only required if webhook.enabled is true. See the webhook documentation for more details.
    Datatype: String
    webhook.webhookstatusPayload to send on status calls. Only required if webhook.enabled is true. See the webhook documentation for more details.
    Datatype: String
    api_server.enabledEnable usage of API Server. See the API Server documentation for more details.
    Datatype: Boolean
    api_server.listen_ip_addressBind IP address. See the API Server documentation for more details.
    Datatype: IPv4
    api_server.listen_portBind Port. See the API Server documentation for more details.
    Datatype: Integer between 1024 and 65535
    api_server.verbosityLogging verbosity. info will print all RPC Calls, while "error" will only display errors.
    Datatype: Enum, either info or error. Defaults to info.
    api_server.usernameUsername for API server. See the API Server documentation for more details.
    Keep it in secret, do not disclose publicly.
    Datatype: String
    api_server.passwordPassword for API server. See the API Server documentation for more details.
    Keep it in secret, do not disclose publicly.
    Datatype: String
    bot_nameName of the bot. Passed via API to a client - can be shown to distinguish / name bots.
    Defaults to freqtrade
    Datatype: String
    db_urlDeclares database URL to use. NOTE: This defaults to sqlite:///tradesv3.dryrun.sqlite if dry_run is true, and to sqlite:///tradesv3.sqlite for production instances.
    Datatype: String, SQLAlchemy connect string
    initial_stateDefines the initial application state. If set to stopped, then the bot has to be explicitly started via /start RPC command.
    Defaults to stopped.
    Datatype: Enum, either stopped or running
    forcebuy_enableEnables the RPC Commands to force a buy. More information below.
    Datatype: Boolean
    disable_dataframe_checksDisable checking the OHLCV dataframe returned from the strategy methods for correctness. Only use when intentionally changing the dataframe and understand what you are doing. Strategy Override.
    Defaults to False.
    Datatype: Boolean
    strategyRequired Defines Strategy class to use. Recommended to be set via --strategy NAME.
    Datatype: ClassName
    strategy_pathAdds an additional strategy lookup path (must be a directory).
    Datatype: String
    internals.process_throttle_secsSet the process throttle, or minimum loop duration for one bot iteration loop. Value in second.
    Defaults to 5 seconds.
    Datatype: Positive Integer
    internals.heartbeat_intervalPrint heartbeat message every N seconds. Set to 0 to disable heartbeat messages.
    Defaults to 60 seconds.
    Datatype: Positive Integer or 0
    internals.sd_notifyEnables use of the sd_notify protocol to tell systemd service manager about changes in the bot state and issue keep-alive pings. See here for more details.
    Datatype: Boolean
    logfileSpecifies logfile name. Uses a rolling strategy for log file rotation for 10 files with the 1MB limit per file.
    Datatype: String
    user_data_dirDirectory containing user data.
    Defaults to ./user_data/.
    Datatype: String
    dataformat_ohlcvData format to use to store historical candle (OHLCV) data.
    Defaults to json.
    Datatype: String
    dataformat_tradesData format to use to store historical trades data.
    Defaults to jsongz.
    Datatype: String
    +

    Parameters in the strategy

    +

    The following parameters can be set in the configuration file or strategy. +Values set in the configuration file always overwrite values set in the strategy.

    +
      +
    • minimal_roi
    • +
    • timeframe
    • +
    • stoploss
    • +
    • trailing_stop
    • +
    • trailing_stop_positive
    • +
    • trailing_stop_positive_offset
    • +
    • trailing_only_offset_is_reached
    • +
    • use_custom_stoploss
    • +
    • process_only_new_candles
    • +
    • order_types
    • +
    • order_time_in_force
    • +
    • unfilledtimeout
    • +
    • disable_dataframe_checks
    • +
    • use_sell_signal
    • +
    • sell_profit_only
    • +
    • sell_profit_offset
    • +
    • ignore_roi_if_buy_signal
    • +
    • ignore_buying_expired_candle_after
    • +
    +

    Configuring amount per trade

    +

    There are several methods to configure how much of the stake currency the bot will use to enter a trade. All methods respect the available balance configuration as explained below.

    +

    Minimum trade stake

    +

    The minimum stake amount will depend on exchange and pair and is usually listed in the exchange support pages. +Assuming the minimum tradable amount for XRP/USD is 20 XRP (given by the exchange), and the price is 0.6$.

    +

    The minimum stake amount to buy this pair is, therefore, 20 * 0.6 ~= 12. +This exchange has also a limit on USD - where all orders must be > 10$ - which however does not apply in this case.

    +

    To guarantee safe execution, freqtrade will not allow buying with a stake-amount of 10.1$, instead, it'll make sure that there's enough space to place a stoploss below the pair (+ an offset, defined by amount_reserve_percent, which defaults to 5%).

    +

    With a reserve of 5%, the minimum stake amount would be ~12.6$ (12 * (1 + 0.05)). If we take into account a stoploss of 10% on top of that - we'd end up with a value of ~14$ (12.6 / (1 - 0.1)).

    +

    To limit this calculation in case of large stoploss values, the calculated minimum stake-limit will never be more than 50% above the real limit.

    +
    +

    Warning

    +

    Since the limits on exchanges are usually stable and are not updated often, some pairs can show pretty high minimum limits, simply because the price increased a lot since the last limit adjustment by the exchange.

    +
    +

    Tradable balance

    +

    By default, the bot assumes that the complete amount - 1% is at it's disposal, and when using dynamic stake amount, it will split the complete balance into max_open_trades buckets per trade. +Freqtrade will reserve 1% for eventual fees when entering a trade and will therefore not touch that by default.

    +

    You can configure the "untouched" amount by using the tradable_balance_ratio setting.

    +

    For example, if you have 10 ETH available in your wallet on the exchange and tradable_balance_ratio=0.5 (which is 50%), then the bot will use a maximum amount of 5 ETH for trading and considers this as an available balance. The rest of the wallet is untouched by the trades.

    +
    +

    Danger

    +

    This setting should not be used when running multiple bots on the same account. Please look at Available Capital to the bot instead.

    +
    +
    +

    Warning

    +

    The tradable_balance_ratio setting applies to the current balance (free balance + tied up in trades). Therefore, assuming the starting balance of 1000, a configuration with tradable_balance_ratio=0.99 will not guarantee that 10 currency units will always remain available on the exchange. For example, the free amount may reduce to 5 units if the total balance is reduced to 500 (either by a losing streak or by withdrawing balance).

    +
    +

    Assign available Capital

    +

    To fully utilize compounding profits when using multiple bots on the same exchange account, you'll want to limit each bot to a certain starting balance. +This can be accomplished by setting available_capital to the desired starting balance.

    +

    Assuming your account has 10.000 USDT and you want to run 2 different strategies on this exchange. +You'd set available_capital=5000 - granting each bot an initial capital of 5000 USDT. +The bot will then split this starting balance equally into max_open_trades buckets. +Profitable trades will result in increased stake-sizes for this bot - without affecting the stake-sizes of the other bot.

    +
    +

    Incompatible with tradable_balance_ratio

    +

    Setting this option will replace any configuration of tradable_balance_ratio.

    +
    +

    Amend last stake amount

    +

    Assuming we have the tradable balance of 1000 USDT, stake_amount=400, and max_open_trades=3. +The bot would open 2 trades and will be unable to fill the last trading slot, since the requested 400 USDT are no longer available since 800 USDT are already tied in other trades.

    +

    To overcome this, the option amend_last_stake_amount can be set to True, which will enable the bot to reduce stake_amount to the available balance to fill the last trade slot.

    +

    In the example above this would mean:

    +
      +
    • Trade1: 400 USDT
    • +
    • Trade2: 400 USDT
    • +
    • Trade3: 200 USDT
    • +
    +
    +

    Note

    +

    This option only applies with Static stake amount - since Dynamic stake amount divides the balances evenly.

    +
    +
    +

    Note

    +

    The minimum last stake amount can be configured using last_stake_amount_min_ratio - which defaults to 0.5 (50%). This means that the minimum stake amount that's ever used is stake_amount * 0.5. This avoids very low stake amounts, that are close to the minimum tradable amount for the pair and can be refused by the exchange.

    +
    +

    Static stake amount

    +

    The stake_amount configuration statically configures the amount of stake-currency your bot will use for each trade.

    +

    The minimal configuration value is 0.0001, however, please check your exchange's trading minimums for the stake currency you're using to avoid problems.

    +

    This setting works in combination with max_open_trades. The maximum capital engaged in trades is stake_amount * max_open_trades. +For example, the bot will at most use (0.05 BTC x 3) = 0.15 BTC, assuming a configuration of max_open_trades=3 and stake_amount=0.05.

    +
    +

    Note

    +

    This setting respects the available balance configuration.

    +
    +

    Dynamic stake amount

    +

    Alternatively, you can use a dynamic stake amount, which will use the available balance on the exchange, and divide that equally by the number of allowed trades (max_open_trades).

    +

    To configure this, set stake_amount="unlimited". We also recommend to set tradable_balance_ratio=0.99 (99%) - to keep a minimum balance for eventual fees.

    +

    In this case a trade amount is calculated as:

    +

    python +currency_balance / (max_open_trades - current_open_trades)

    +

    To allow the bot to trade all the available stake_currency in your account (minus tradable_balance_ratio) set

    +

    json +"stake_amount" : "unlimited", +"tradable_balance_ratio": 0.99,

    +
    +

    Compounding profits

    +

    This configuration will allow increasing/decreasing stakes depending on the performance of the bot (lower stake if the bot is losing, higher stakes if the bot has a winning record since higher balances are available), and will result in profit compounding.

    +
    +
    +

    When using Dry-Run Mode

    +

    When using "stake_amount" : "unlimited", in combination with Dry-Run, Backtesting or Hyperopt, the balance will be simulated starting with a stake of dry_run_wallet which will evolve. +It is therefore important to set dry_run_wallet to a sensible value (like 0.05 or 0.01 for BTC and 1000 or 100 for USDT, for example), otherwise, it may simulate trades with 100 BTC (or more) or 0.05 USDT (or less) at once - which may not correspond to your real available balance or is less than the exchange minimal limit for the order amount for the stake currency.

    +
    +

    Prices used for orders

    +

    Prices for regular orders can be controlled via the parameter structures bid_strategy for buying and ask_strategy for selling. +Prices are always retrieved right before an order is placed, either by querying the exchange tickers or by using the orderbook data.

    +
    +

    Note

    +

    Orderbook data used by Freqtrade are the data retrieved from exchange by the ccxt's function fetch_order_book(), i.e. are usually data from the L2-aggregated orderbook, while the ticker data are the structures returned by the ccxt's fetch_ticker()/fetch_tickers() functions. Refer to the ccxt library documentation for more details.

    +
    +
    +

    Using market orders

    +

    Please read the section Market order pricing section when using market orders.

    +
    +

    Buy price

    +

    Check depth of market

    +

    When check depth of market is enabled (bid_strategy.check_depth_of_market.enabled=True), the buy signals are filtered based on the orderbook depth (sum of all amounts) for each orderbook side.

    +

    Orderbook bid (buy) side depth is then divided by the orderbook ask (sell) side depth and the resulting delta is compared to the value of the bid_strategy.check_depth_of_market.bids_to_ask_delta parameter. The buy order is only executed if the orderbook delta is greater than or equal to the configured delta value.

    +
    +

    Note

    +

    A delta value below 1 means that ask (sell) orderbook side depth is greater than the depth of the bid (buy) orderbook side, while a value greater than 1 means opposite (depth of the buy side is higher than the depth of the sell side).

    +
    +

    Buy price side

    +

    The configuration setting bid_strategy.price_side defines the side of the spread the bot looks for when buying.

    +

    The following displays an orderbook.

    +

    explanation +... +103 +102 +101 # ask +-------------Current spread +99 # bid +98 +97 +...

    +

    If bid_strategy.price_side is set to "bid", then the bot will use 99 as buying price.
    +In line with that, if bid_strategy.price_side is set to "ask", then the bot will use 101 as buying price.

    +

    Using ask price often guarantees quicker filled orders, but the bot can also end up paying more than what would have been necessary. +Taker fees instead of maker fees will most likely apply even when using limit buy orders. +Also, prices at the "ask" side of the spread are higher than prices at the "bid" side in the orderbook, so the order behaves similar to a market order (however with a maximum price).

    +

    Buy price with Orderbook enabled

    +

    When buying with the orderbook enabled (bid_strategy.use_order_book=True), Freqtrade fetches the bid_strategy.order_book_top entries from the orderbook and uses the entry specified as bid_strategy.order_book_top on the configured side (bid_strategy.price_side) of the orderbook. 1 specifies the topmost entry in the orderbook, while 2 would use the 2nd entry in the orderbook, and so on.

    +

    Buy price without Orderbook enabled

    +

    The following section uses side as the configured bid_strategy.price_side.

    +

    When not using orderbook (bid_strategy.use_order_book=False), Freqtrade uses the best side price from the ticker if it's below the last traded price from the ticker. Otherwise (when the side price is above the last price), it calculates a rate between side and last price.

    +

    The bid_strategy.ask_last_balance configuration parameter controls this. A value of 0.0 will use side price, while 1.0 will use the last price and values between those interpolate between ask and last price.

    +

    Sell price

    +

    Sell price side

    +

    The configuration setting ask_strategy.price_side defines the side of the spread the bot looks for when selling.

    +

    The following displays an orderbook:

    +

    explanation +... +103 +102 +101 # ask +-------------Current spread +99 # bid +98 +97 +...

    +

    If ask_strategy.price_side is set to "ask", then the bot will use 101 as selling price.
    +In line with that, if ask_strategy.price_side is set to "bid", then the bot will use 99 as selling price.

    +

    Sell price with Orderbook enabled

    +

    When selling with the orderbook enabled (ask_strategy.use_order_book=True), Freqtrade fetches the ask_strategy.order_book_top entries in the orderbook and uses the entry specified as ask_strategy.order_book_top from the configured side (ask_strategy.price_side) as selling price.

    +

    1 specifies the topmost entry in the orderbook, while 2 would use the 2nd entry in the orderbook, and so on.

    +

    Sell price without Orderbook enabled

    +

    When not using orderbook (ask_strategy.use_order_book=False), the price at the ask_strategy.price_side side (defaults to "ask") from the ticker will be used as the sell price.

    +

    When not using orderbook (ask_strategy.use_order_book=False), Freqtrade uses the best side price from the ticker if it's below the last traded price from the ticker. Otherwise (when the side price is above the last price), it calculates a rate between side and last price.

    +

    The ask_strategy.bid_last_balance configuration parameter controls this. A value of 0.0 will use side price, while 1.0 will use the last price and values between those interpolate between side and last price.

    +

    Market order pricing

    +

    When using market orders, prices should be configured to use the "correct" side of the orderbook to allow realistic pricing detection. +Assuming both buy and sell are using market orders, a configuration similar to the following might be used

    +

    jsonc + "order_types": { + "buy": "market", + "sell": "market" + // ... + }, + "bid_strategy": { + "price_side": "ask", + // ... + }, + "ask_strategy":{ + "price_side": "bid", + // ... + },

    +

    Obviously, if only one side is using limit orders, different pricing combinations can be used.

    +

    Understand minimal_roi

    +

    The minimal_roi configuration parameter is a JSON object where the key is a duration +in minutes and the value is the minimum ROI as a ratio. +See the example below:

    +

    json +"minimal_roi": { + "40": 0.0, # Sell after 40 minutes if the profit is not negative + "30": 0.01, # Sell after 30 minutes if there is at least 1% profit + "20": 0.02, # Sell after 20 minutes if there is at least 2% profit + "0": 0.04 # Sell immediately if there is at least 4% profit +},

    +

    Most of the strategy files already include the optimal minimal_roi value. +This parameter can be set in either Strategy or Configuration file. If you use it in the configuration file, it will override the +minimal_roi value from the strategy file. +If it is not set in either Strategy or Configuration, a default of 1000% {"0": 10} is used, and minimal ROI is disabled unless your trade generates 1000% profit.

    +
    +

    Special case to forcesell after a specific time

    +

    A special case presents using "<N>": -1 as ROI. This forces the bot to sell a trade after N Minutes, no matter if it's positive or negative, so represents a time-limited force-sell.

    +
    +

    Understand forcebuy_enable

    +

    The forcebuy_enable configuration parameter enables the usage of forcebuy commands via Telegram and REST API. +For security reasons, it's disabled by default, and freqtrade will show a warning message on startup if enabled. +For example, you can send /forcebuy ETH/BTC to the bot, which will result in freqtrade buying the pair and holds it until a regular sell-signal (ROI, stoploss, /forcesell) appears.

    +

    This can be dangerous with some strategies, so use with care.

    +

    See the telegram documentation for details on usage.

    +

    Ignoring expired candles

    +

    When working with larger timeframes (for example 1h or more) and using a low max_open_trades value, the last candle can be processed as soon as a trade slot becomes available. When processing the last candle, this can lead to a situation where it may not be desirable to use the buy signal on that candle. For example, when using a condition in your strategy where you use a cross-over, that point may have passed too long ago for you to start a trade on it.

    +

    In these situations, you can enable the functionality to ignore candles that are beyond a specified period by setting ignore_buying_expired_candle_after to a positive number, indicating the number of seconds after which the buy signal becomes expired.

    +

    For example, if your strategy is using a 1h timeframe, and you only want to buy within the first 5 minutes when a new candle comes in, you can add the following configuration to your strategy:

    +

    json + { + //... + "ignore_buying_expired_candle_after": 300, + // ... + }

    +
    +

    Note

    +

    This setting resets with each new candle, so it will not prevent sticking-signals from executing on the 2nd or 3rd candle they're active. Best use a "trigger" selector for buy signals, which are only active for one candle.

    +
    +

    Understand order_types

    +

    The order_types configuration parameter maps actions (buy, sell, stoploss, emergencysell, forcesell, forcebuy) to order-types (market, limit, ...) as well as configures stoploss to be on the exchange and defines stoploss on exchange update interval in seconds.

    +

    This allows to buy using limit orders, sell using +limit-orders, and create stoplosses using market orders. It also allows to set the +stoploss "on exchange" which means stoploss order would be placed immediately once +the buy order is fulfilled.

    +

    order_types set in the configuration file overwrites values set in the strategy as a whole, so you need to configure the whole order_types dictionary in one place.

    +

    If this is configured, the following 4 values (buy, sell, stoploss and +stoploss_on_exchange) need to be present, otherwise, the bot will fail to start.

    +

    For information on (emergencysell,forcesell, forcebuy, stoploss_on_exchange,stoploss_on_exchange_interval,stoploss_on_exchange_limit_ratio) please see stop loss documentation stop loss on exchange

    +

    Syntax for Strategy:

    +

    python +order_types = { + "buy": "limit", + "sell": "limit", + "emergencysell": "market", + "forcebuy": "market", + "forcesell": "market", + "stoploss": "market", + "stoploss_on_exchange": False, + "stoploss_on_exchange_interval": 60, + "stoploss_on_exchange_limit_ratio": 0.99, +}

    +

    Configuration:

    +

    json +"order_types": { + "buy": "limit", + "sell": "limit", + "emergencysell": "market", + "forcebuy": "market", + "forcesell": "market", + "stoploss": "market", + "stoploss_on_exchange": false, + "stoploss_on_exchange_interval": 60 +}

    +
    +

    Market order support

    +

    Not all exchanges support "market" orders. +The following message will be shown if your exchange does not support market orders: +"Exchange <yourexchange> does not support market orders." and the bot will refuse to start.

    +
    +
    +

    Using market orders

    +

    Please carefully read the section Market order pricing section when using market orders.

    +
    +
    +

    Stoploss on exchange

    +

    stoploss_on_exchange_interval is not mandatory. Do not change its value if you are +unsure of what you are doing. For more information about how stoploss works please +refer to the stoploss documentation.

    +

    If stoploss_on_exchange is enabled and the stoploss is cancelled manually on the exchange, then the bot will create a new stoploss order.

    +
    +
    +

    Warning: stoploss_on_exchange failures

    +

    If stoploss on exchange creation fails for some reason, then an "emergency sell" is initiated. By default, this will sell the asset using a market order. The order-type for the emergency-sell can be changed by setting the emergencysell value in the order_types dictionary - however, this is not advised.

    +
    +

    Understand order_time_in_force

    +

    The order_time_in_force configuration parameter defines the policy by which the order +is executed on the exchange. Three commonly used time in force are:

    +

    GTC (Good Till Canceled):

    +

    This is most of the time the default time in force. It means the order will remain +on exchange till it is cancelled by the user. It can be fully or partially fulfilled. +If partially fulfilled, the remaining will stay on the exchange till cancelled.

    +

    FOK (Fill Or Kill):

    +

    It means if the order is not executed immediately AND fully then it is cancelled by the exchange.

    +

    IOC (Immediate Or Canceled):

    +

    It is the same as FOK (above) except it can be partially fulfilled. The remaining part +is automatically cancelled by the exchange.

    +

    The order_time_in_force parameter contains a dict with buy and sell time in force policy values. +This can be set in the configuration file or in the strategy. +Values set in the configuration file overwrites values set in the strategy.

    +

    The possible values are: gtc (default), fok or ioc.

    +

    python +"order_time_in_force": { + "buy": "gtc", + "sell": "gtc" +},

    +
    +

    Warning

    +

    This is ongoing work. For now, it is supported only for binance. +Please don't change the default value unless you know what you are doing and have researched the impact of using different values.

    +
    +

    Exchange configuration

    +

    Freqtrade is based on CCXT library that supports over 100 cryptocurrency +exchange markets and trading APIs. The complete up-to-date list can be found in the +CCXT repo homepage. + However, the bot was tested by the development team with only Bittrex, Binance and Kraken, + so these are the only officially supported exchanges:

    + +

    Feel free to test other exchanges and submit your PR to improve the bot.

    +

    Some exchanges require special configuration, which can be found on the Exchange-specific Notes documentation page.

    +

    Sample exchange configuration

    +

    A exchange configuration for "binance" would look as follows:

    +

    json +"exchange": { + "name": "binance", + "key": "your_exchange_key", + "secret": "your_exchange_secret", + "ccxt_config": {"enableRateLimit": true}, + "ccxt_async_config": { + "enableRateLimit": true, + "rateLimit": 200 + },

    +

    This configuration enables binance, as well as rate-limiting to avoid bans from the exchange. +"rateLimit": 200 defines a wait-event of 0.2s between each call. This can also be completely disabled by setting "enableRateLimit" to false.

    +
    +

    Note

    +

    Optimal settings for rate-limiting depend on the exchange and the size of the whitelist, so an ideal parameter will vary on many other settings. +We try to provide sensible defaults per exchange where possible, if you encounter bans please make sure that "enableRateLimit" is enabled and increase the "rateLimit" parameter step by step.

    +
    +

    What values can be used for fiat_display_currency?

    +

    The fiat_display_currency configuration parameter sets the base currency to use for the +conversion from coin to fiat in the bot Telegram reports.

    +

    The valid values are:

    +

    json +"AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK", "EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY", "KRW", "MXN", "MYR", "NOK", "NZD", "PHP", "PKR", "PLN", "RUB", "SEK", "SGD", "THB", "TRY", "TWD", "ZAR", "USD"

    +

    In addition to fiat currencies, a range of crypto currencies is supported.

    +

    The valid values are:

    +

    json +"BTC", "ETH", "XRP", "LTC", "BCH", "USDT"

    +

    Using Dry-run mode

    +

    We recommend starting the bot in the Dry-run mode to see how your bot will +behave and what is the performance of your strategy. In the Dry-run mode, the +bot does not engage your money. It only runs a live simulation without +creating trades on the exchange.

    +
      +
    1. Edit your config.json configuration file.
    2. +
    3. Switch dry-run to true and specify db_url for a persistence database.
    4. +
    +

    json +"dry_run": true, +"db_url": "sqlite:///tradesv3.dryrun.sqlite",

    +
      +
    1. Remove your Exchange API key and secret (change them by empty values or fake credentials):
    2. +
    +

    json +"exchange": { + "name": "bittrex", + "key": "key", + "secret": "secret", + ... +}

    +

    Once you will be happy with your bot performance running in the Dry-run mode, you can switch it to production mode.

    +
    +

    Note

    +

    A simulated wallet is available during dry-run mode and will assume a starting capital of dry_run_wallet (defaults to 1000).

    +
    +

    Considerations for dry-run

    +
      +
    • API-keys may or may not be provided. Only Read-Only operations (i.e. operations that do not alter account state) on the exchange are performed in dry-run mode.
    • +
    • Wallets (/balance) are simulated based on dry_run_wallet.
    • +
    • Orders are simulated, and will not be posted to the exchange.
    • +
    • Market orders fill based on orderbook volume the moment the order is placed.
    • +
    • Limit orders fill once the price reaches the defined level - or time out based on unfilledtimeout settings.
    • +
    • In combination with stoploss_on_exchange, the stop_loss price is assumed to be filled.
    • +
    • Open orders (not trades, which are stored in the database) are reset on bot restart.
    • +
    +

    Switch to production mode

    +

    In production mode, the bot will engage your money. Be careful, since a wrong +strategy can lose all your money. Be aware of what you are doing when +you run it in production mode.

    +

    Setup your exchange account

    +

    You will need to create API Keys (usually you get key and secret, some exchanges require an additional password) from the Exchange website and you'll need to insert this into the appropriate fields in the configuration or when asked by the freqtrade new-config command. +API Keys are usually only required for live trading (trading for real money, bot running in "production mode", executing real orders on the exchange) and are not required for the bot running in dry-run (trade simulation) mode. When you set up the bot in dry-run mode, you may fill these fields with empty values.

    +

    To switch your bot in production mode

    +

    Edit your config.json file.

    +

    Switch dry-run to false and don't forget to adapt your database URL if set:

    +

    json +"dry_run": false,

    +

    Insert your Exchange API key (change them by fake API keys):

    +

    json +{ + "exchange": { + "name": "bittrex", + "key": "af8ddd35195e9dc500b9a6f799f6f5c93d89193b", + "secret": "08a9dc6db3d7b53e1acebd9275677f4b0a04f1a5", + //"password": "", // Optional, not needed by all exchanges) + // ... + } + //... +}

    +

    You should also make sure to read the Exchanges section of the documentation to be aware of potential configuration details specific to your exchange.

    +
    +

    Keep your secrets secret

    +

    To keep your secrets secret, we recommend using a 2nd configuration for your API keys. +Simply use the above snippet in a new configuration file (e.g. config-private.json) and keep your settings in this file. +You can then start the bot with freqtrade trade --config user_data/config.json --config user_data/config-private.json <...> to have your keys loaded.

    +

    NEVER share your private configuration file or your exchange keys with anyone!

    +
    +

    Using proxy with Freqtrade

    +

    To use a proxy with freqtrade, add the kwarg "aiohttp_trust_env"=true to the "ccxt_async_kwargs" dict in the exchange section of the configuration.

    +

    An example for this can be found in config_examples/config_full.example.json

    +

    json +"ccxt_async_config": { + "aiohttp_trust_env": true +}

    +

    Then, export your proxy settings using the variables "HTTP_PROXY" and "HTTPS_PROXY" set to the appropriate values

    +

    bash +export HTTP_PROXY="http://addr:port" +export HTTPS_PROXY="http://addr:port" +freqtrade

    +

    Next step

    +

    Now you have configured your config.json, the next step is to start your bot.

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/data-analysis/index.html b/en/2021.7/data-analysis/index.html new file mode 100644 index 000000000..924ada547 --- /dev/null +++ b/en/2021.7/data-analysis/index.html @@ -0,0 +1,1144 @@ + + + + + + + + + + + + + + + + + + + Jupyter Notebooks - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + + + + + + +

    Analyzing bot data with Jupyter notebooks

    +

    You can analyze the results of backtests and trading history easily using Jupyter notebooks. Sample notebooks are located at user_data/notebooks/ after initializing the user directory with freqtrade create-userdir --userdir user_data.

    +

    Quick start with docker

    +

    Freqtrade provides a docker-compose file which starts up a jupyter lab server. +You can run this server using the following command: docker-compose -f docker/docker-compose-jupyter.yml up

    +

    This will create a dockercontainer running jupyter lab, which will be accessible using https://127.0.0.1:8888/lab. +Please use the link that's printed in the console after startup for simplified login.

    +

    For more information, Please visit the Data analysis with Docker section.

    +

    Pro tips

    +
      +
    • See jupyter.org for usage instructions.
    • +
    • Don't forget to start a Jupyter notebook server from within your conda or venv environment or use nb_conda_kernels*
    • +
    • Copy the example notebook before use so your changes don't get overwritten with the next freqtrade update.
    • +
    +

    Using virtual environment with system-wide Jupyter installation

    +

    Sometimes it can be desired to use a system-wide installation of Jupyter notebook, and use a jupyter kernel from the virtual environment. +This prevents you from installing the full jupyter suite multiple times per system, and provides an easy way to switch between tasks (freqtrade / other analytics tasks).

    +

    For this to work, first activate your virtual environment and run the following commands:

    +

    ``` bash

    +

    Activate virtual environment

    +

    source .env/bin/activate

    +

    pip install ipykernel +ipython kernel install --user --name=freqtrade

    +

    Restart jupyter (lab / notebook)

    +

    select kernel "freqtrade" in the notebook

    +

    ```

    +
    +

    Note

    +

    This section is provided for completeness, the Freqtrade Team won't provide full support for problems with this setup and will recommend to install Jupyter in the virtual environment directly, as that is the easiest way to get jupyter notebooks up and running. For help with this setup please refer to the Project Jupyter documentation or help channels.

    +
    +
    +

    Warning

    +

    Some tasks don't work especially well in notebooks. For example, anything using asynchronous execution is a problem for Jupyter. Also, freqtrade's primary entry point is the shell cli, so using pure python in a notebook bypasses arguments that provide required objects and parameters to helper functions. You may need to set those values or create expected objects manually.

    +
    + + + + + + + + + + + + + + + + + + + + + + +
    TaskTool
    Bot operationsCLI
    Repetitive tasksShell scripts
    Data analysis & visualizationNotebook
    +
      +
    1. +

      Use the CLI to + * download historical data + * run a backtest + * run with real-time data + * export results

      +
    2. +
    3. +

      Collect these actions in shell scripts + * save complicated commands with arguments + * execute multi-step operations
      + * automate testing strategies and preparing data for analysis

      +
    4. +
    5. +

      Use a notebook to + * visualize data + * munge and plot to generate insights

      +
    6. +
    +

    Example utility snippets

    +

    Change directory to root

    +

    Jupyter notebooks execute from the notebook directory. The following snippet searches for the project root, so relative paths remain consistent.

    +

    ```python +import os +from pathlib import Path

    +

    Change directory

    +

    Modify this cell to insure that the output shows the correct path.

    +

    Define all paths relative to the project root shown in the cell output

    +

    project_root = "somedir/freqtrade" +i=0 +try: + os.chdirdir(project_root) + assert Path('LICENSE').is_file() +except: + while i<4 and (not Path('LICENSE').is_file()): + os.chdir(Path(Path.cwd(), '../')) + i+=1 + project_root = Path.cwd() +print(Path.cwd()) +```

    +

    Load multiple configuration files

    +

    This option can be useful to inspect the results of passing in multiple configs. +This will also run through the whole Configuration initialization, so the configuration is completely initialized to be passed to other methods.

    +

    ``` python +import json +from freqtrade.configuration import Configuration

    +

    Load config from multiple files

    +

    config = Configuration.from_files(["config1.json", "config2.json"])

    +

    Show the config in memory

    +

    print(json.dumps(config['original_config'], indent=2)) +```

    +

    For Interactive environments, have an additional configuration specifying user_data_dir and pass this in last, so you don't have to change directories while running the bot. +Best avoid relative paths, since this starts at the storage location of the jupyter notebook, unless the directory is changed.

    +

    json +{ + "user_data_dir": "~/.freqtrade/" +}

    +

    Further Data analysis documentation

    + +

    Feel free to submit an issue or Pull Request enhancing this document if you would like to share ideas on how to best analyze the data.

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/data-download/index.html b/en/2021.7/data-download/index.html new file mode 100644 index 000000000..98bd91eb7 --- /dev/null +++ b/en/2021.7/data-download/index.html @@ -0,0 +1,1508 @@ + + + + + + + + + + + + + + + + + + + Data Downloading - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + + + + + + +

    Data Downloading

    +

    Getting data for backtesting and hyperopt

    +

    To download data (candles / OHLCV) needed for backtesting and hyperoptimization use the freqtrade download-data command.

    +

    If no additional parameter is specified, freqtrade will download data for "1m" and "5m" timeframes for the last 30 days. +Exchange and pairs will come from config.json (if specified using -c/--config). +Otherwise --exchange becomes mandatory.

    +

    You can use a relative timerange (--days 20) or an absolute starting point (--timerange 20200101-). For incremental downloads, the relative approach should be used.

    +
    +

    Tip: Updating existing data

    +

    If you already have backtesting data available in your data-directory and would like to refresh this data up to today, do not use --days or --timerange parameters. Freqtrade will keep the available data and only download the missing data. +If you are updating existing data after inserting new pairs that you have no data for, use --new-pairs-days xx parameter. Specified number of days will be downloaded for new pairs while old pairs will be updated with missing data only. +If you use --days xx parameter alone - data for specified number of days will be downloaded for all pairs. Be careful, if specified number of days is smaller than gap between now and last downloaded candle - freqtrade will delete all existing data to avoid gaps in candle data.

    +
    +

    Usage

    +

    ``` +usage: freqtrade download-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] + [-d PATH] [--userdir PATH] + [-p PAIRS [PAIRS ...]] [--pairs-file FILE] + [--days INT] [--new-pairs-days INT] + [--timerange TIMERANGE] [--dl-trades] + [--exchange EXCHANGE] + [-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...]] + [--erase] + [--data-format-ohlcv {json,jsongz,hdf5}] + [--data-format-trades {json,jsongz,hdf5}]

    +

    optional arguments: + -h, --help show this help message and exit + -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] + Limit command to these pairs. Pairs are space- + separated. + --pairs-file FILE File containing a list of pairs to download. + --days INT Download data for given number of days. + --new-pairs-days INT Download data of new pairs for given number of days. + Default: None. + --timerange TIMERANGE + Specify what timerange of data to use. + --dl-trades Download trades instead of OHLCV data. The bot will + resample trades to the desired timeframe as specified + as --timeframes/-t. + --exchange EXCHANGE Exchange name (default: bittrex). Only valid if no + config is provided. + -t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...], --timeframes {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...] + Specify which tickers to download. Space-separated + list. Default: 1m 5m. + --erase Clean all existing data for the selected + exchange/pairs/timeframes. + --data-format-ohlcv {json,jsongz,hdf5} + Storage format for downloaded candle (OHLCV) data. + (default: None). + --data-format-trades {json,jsongz,hdf5} + Storage format for downloaded trades data. (default: + None).

    +

    Common arguments: + -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). + --logfile FILE Log to the file specified. Special values are: + 'syslog', 'journald'. See the documentation for more + details. + -V, --version show program's version number and exit + -c PATH, --config PATH + Specify configuration file (default: + userdir/config.json or config.json whichever + exists). Multiple --config options may be used. Can be + set to - to read config from stdin. + -d PATH, --datadir PATH + Path to directory with historical backtesting data. + --userdir PATH, --user-data-dir PATH + Path to userdata directory.

    +

    ```

    +
    +

    Startup period

    +

    download-data is a strategy-independent command. The idea is to download a big chunk of data once, and then iteratively increase the amount of data stored.

    +

    For that reason, download-data does not care about the "startup-period" defined in a strategy. It's up to the user to download additional days if the backtest should start at a specific point in time (while respecting startup period).

    +
    +

    Data format

    +

    Freqtrade currently supports 3 data-formats for both OHLCV and trades data:

    +
      +
    • json (plain "text" json files)
    • +
    • jsongz (a gzip-zipped version of json files)
    • +
    • hdf5 (a high performance datastore)
    • +
    +

    By default, OHLCV data is stored as json data, while trades data is stored as jsongz data.

    +

    This can be changed via the --data-format-ohlcv and --data-format-trades command line arguments respectively. +To persist this change, you can should also add the following snippet to your configuration, so you don't have to insert the above arguments each time:

    +

    jsonc + // ... + "dataformat_ohlcv": "hdf5", + "dataformat_trades": "hdf5", + // ...

    +

    If the default data-format has been changed during download, then the keys dataformat_ohlcv and dataformat_trades in the configuration file need to be adjusted to the selected dataformat as well.

    +
    +

    Note

    +

    You can convert between data-formats using the convert-data and convert-trade-data methods.

    +
    +

    Sub-command convert data

    +

    ``` +usage: freqtrade convert-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] + [-d PATH] [--userdir PATH] + [-p PAIRS [PAIRS ...]] --format-from + {json,jsongz,hdf5} --format-to + {json,jsongz,hdf5} [--erase] + [-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...]]

    +

    optional arguments: + -h, --help show this help message and exit + -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] + Show profits for only these pairs. Pairs are space- + separated. + --format-from {json,jsongz,hdf5} + Source format for data conversion. + --format-to {json,jsongz,hdf5} + Destination format for data conversion. + --erase Clean all existing data for the selected + exchange/pairs/timeframes. + -t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...], --timeframes {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...] + Specify which tickers to download. Space-separated + list. Default: 1m 5m.

    +

    Common arguments: + -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). + --logfile FILE Log to the file specified. Special values are: + 'syslog', 'journald'. See the documentation for more + details. + -V, --version show program's version number and exit + -c PATH, --config PATH + Specify configuration file (default: + userdir/config.json or config.json whichever + exists). Multiple --config options may be used. Can be + set to - to read config from stdin. + -d PATH, --datadir PATH + Path to directory with historical backtesting data. + --userdir PATH, --user-data-dir PATH + Path to userdata directory. +```

    +
    Example converting data
    +

    The following command will convert all candle (OHLCV) data available in ~/.freqtrade/data/binance from json to jsongz, saving diskspace in the process. +It'll also remove original json data files (--erase parameter).

    +

    bash +freqtrade convert-data --format-from json --format-to jsongz --datadir ~/.freqtrade/data/binance -t 5m 15m --erase

    +

    Sub-command convert trade data

    +

    ``` +usage: freqtrade convert-trade-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] + [-d PATH] [--userdir PATH] + [-p PAIRS [PAIRS ...]] --format-from + {json,jsongz,hdf5} --format-to + {json,jsongz,hdf5} [--erase]

    +

    optional arguments: + -h, --help show this help message and exit + -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] + Show profits for only these pairs. Pairs are space- + separated. + --format-from {json,jsongz,hdf5} + Source format for data conversion. + --format-to {json,jsongz,hdf5} + Destination format for data conversion. + --erase Clean all existing data for the selected + exchange/pairs/timeframes.

    +

    Common arguments: + -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). + --logfile FILE Log to the file specified. Special values are: + 'syslog', 'journald'. See the documentation for more + details. + -V, --version show program's version number and exit + -c PATH, --config PATH + Specify configuration file (default: + userdir/config.json or config.json whichever + exists). Multiple --config options may be used. Can be + set to - to read config from stdin. + -d PATH, --datadir PATH + Path to directory with historical backtesting data. + --userdir PATH, --user-data-dir PATH + Path to userdata directory.

    +

    ```

    +
    Example converting trades
    +

    The following command will convert all available trade-data in ~/.freqtrade/data/kraken from jsongz to json. +It'll also remove original jsongz data files (--erase parameter).

    +

    bash +freqtrade convert-trade-data --format-from jsongz --format-to json --datadir ~/.freqtrade/data/kraken --erase

    +

    Sub-command list-data

    +

    You can get a list of downloaded data using the list-data sub-command.

    +

    ``` +usage: freqtrade list-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] + [--userdir PATH] [--exchange EXCHANGE] + [--data-format-ohlcv {json,jsongz,hdf5}] + [-p PAIRS [PAIRS ...]]

    +

    optional arguments: + -h, --help show this help message and exit + --exchange EXCHANGE Exchange name (default: bittrex). Only valid if no + config is provided. + --data-format-ohlcv {json,jsongz,hdf5} + Storage format for downloaded candle (OHLCV) data. + (default: json). + -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] + Show profits for only these pairs. Pairs are space- + separated.

    +

    Common arguments: + -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). + --logfile FILE Log to the file specified. Special values are: + 'syslog', 'journald'. See the documentation for more + details. + -V, --version show program's version number and exit + -c PATH, --config PATH + Specify configuration file (default: + userdir/config.json or config.json whichever + exists). Multiple --config options may be used. Can be + set to - to read config from stdin. + -d PATH, --datadir PATH + Path to directory with historical backtesting data. + --userdir PATH, --user-data-dir PATH + Path to userdata directory.

    +

    ```

    +

    Example list-data

    +

    ```bash

    +
    +

    freqtrade list-data --userdir ~/.freqtrade/user_data/

    +
    +

    Found 33 pair / timeframe combinations. +pairs timeframe

    +
    +

    ADA/BTC 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d +ADA/ETH 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d +ETH/BTC 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d +ETH/USDT 5m, 15m, 30m, 1h, 2h, 4h +```

    +

    Pairs file

    +

    In alternative to the whitelist from config.json, a pairs.json file can be used.

    +

    If you are using Binance for example:

    +
      +
    • create a directory user_data/data/binance and copy or create the pairs.json file in that directory.
    • +
    • update the pairs.json file to contain the currency pairs you are interested in.
    • +
    +

    bash +mkdir -p user_data/data/binance +cp tests/testdata/pairs.json user_data/data/binance

    +

    If your configuration directory user_data was made by docker, you may get the following error:

    +

    cp: cannot create regular file 'user_data/data/binance/pairs.json': Permission denied

    +

    You can fix the permissions of your user-data directory as follows:

    +

    sudo chown -R $UID:$GID user_data

    +

    The format of the pairs.json file is a simple json list. +Mixing different stake-currencies is allowed for this file, since it's only used for downloading.

    +

    json +[ + "ETH/BTC", + "ETH/USDT", + "BTC/USDT", + "XRP/ETH" +]

    +

    Start download

    +

    Then run:

    +

    bash +freqtrade download-data --exchange binance

    +

    This will download historical candle (OHLCV) data for all the currency pairs you defined in pairs.json.

    +

    Other Notes

    +
      +
    • To use a different directory than the exchange specific default, use --datadir user_data/data/some_directory.
    • +
    • To change the exchange used to download the historical data from, please use a different configuration file (you'll probably need to adjust rate limits etc.)
    • +
    • To use pairs.json from some other directory, use --pairs-file some_other_dir/pairs.json.
    • +
    • To download historical candle (OHLCV) data for only 10 days, use --days 10 (defaults to 30 days).
    • +
    • To download historical candle (OHLCV) data from a fixed starting point, use --timerange 20200101- - which will download all data from January 1st, 2020. Eventually set end dates are ignored.
    • +
    • Use --timeframes to specify what timeframe download the historical candle (OHLCV) data for. Default is --timeframes 1m 5m which will download 1-minute and 5-minute data.
    • +
    • To use exchange, timeframe and list of pairs as defined in your configuration file, use the -c/--config option. With this, the script uses the whitelist defined in the config as the list of currency pairs to download data for and does not require the pairs.json file. You can combine -c/--config with most other options.
    • +
    +

    Trades (tick) data

    +

    By default, download-data sub-command downloads Candles (OHLCV) data. Some exchanges also provide historic trade-data via their API. +This data can be useful if you need many different timeframes, since it is only downloaded once, and then resampled locally to the desired timeframes.

    +

    Since this data is large by default, the files use gzip by default. They are stored in your data-directory with the naming convention of <pair>-trades.json.gz (ETH_BTC-trades.json.gz). Incremental mode is also supported, as for historic OHLCV data, so downloading the data once per week with --days 8 will create an incremental data-repository.

    +

    To use this mode, simply add --dl-trades to your call. This will swap the download method to download trades, and resamples the data locally.

    +
    +

    do not use

    +

    You should not use this unless you're a kraken user. Most other exchanges provide OHLCV data with sufficient history.

    +
    +

    Example call:

    +

    bash +freqtrade download-data --exchange kraken --pairs XRP/EUR ETH/EUR --days 20 --dl-trades

    +
    +

    Note

    +

    While this method uses async calls, it will be slow, since it requires the result of the previous call to generate the next request to the exchange.

    +
    +
    +

    Warning

    +

    The historic trades are not available during Freqtrade dry-run and live trade modes because all exchanges tested provide this data with a delay of few 100 candles, so it's not suitable for real-time trading.

    +
    +
    +

    Kraken user

    +

    Kraken users should read this before starting to download data.

    +
    +

    Next step

    +

    Great, you now have backtest data downloaded, so you can now start backtesting your strategy.

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/deprecated/index.html b/en/2021.7/deprecated/index.html new file mode 100644 index 000000000..ca82dcdc2 --- /dev/null +++ b/en/2021.7/deprecated/index.html @@ -0,0 +1,1101 @@ + + + + + + + + + + + + + + + + + + + Deprecated Features - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + + + + +
    +
    + + + + + + + +

    Deprecated features

    +

    This page contains description of the command line arguments, configuration parameters +and the bot features that were declared as DEPRECATED by the bot development team +and are no longer supported. Please avoid their usage in your configuration.

    +

    Removed features

    +

    the --refresh-pairs-cached command line option

    +

    --refresh-pairs-cached in the context of backtesting, hyperopt and edge allows to refresh candle data for backtesting. +Since this leads to much confusion, and slows down backtesting (while not being part of backtesting) this has been singled out as a separate freqtrade sub-command freqtrade download-data.

    +

    This command line option was deprecated in 2019.7-dev (develop branch) and removed in 2019.9.

    +

    The --dynamic-whitelist command line option

    +

    This command line option was deprecated in 2018 and removed freqtrade 2019.6-dev (develop branch) +and in freqtrade 2019.7.

    +

    the --live command line option

    +

    --live in the context of backtesting allowed to download the latest tick data for backtesting. +Did only download the latest 500 candles, so was ineffective in getting good backtest data. +Removed in 2019-7-dev (develop branch) and in freqtrade 2019.8.

    +

    Allow running multiple pairlists in sequence

    +

    The former "pairlist" section in the configuration has been removed, and is replaced by "pairlists" - being a list to specify a sequence of pairlists.

    +

    The old section of configuration parameters ("pairlist") has been deprecated in 2019.11 and has been removed in 2020.4.

    +

    deprecation of bidVolume and askVolume from volume-pairlist

    +

    Since only quoteVolume can be compared between assets, the other options (bidVolume, askVolume) have been deprecated in 2020.4, and have been removed in 2020.9.

    +

    Using order book steps for sell price

    +

    Using order_book_min and order_book_max used to allow stepping the orderbook and trying to find the next ROI slot - trying to place sell-orders early. +As this does however increase risk and provides no benefit, it's been removed for maintainability purposes in 2021.7.

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/developer/index.html b/en/2021.7/developer/index.html new file mode 100644 index 000000000..c19f01205 --- /dev/null +++ b/en/2021.7/developer/index.html @@ -0,0 +1,1652 @@ + + + + + + + + + + + + + + + + + + + Contributors Guide - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + +
    + +
    + + +
    +
    + + + + + + + +

    Development Help

    +

    This page is intended for developers of Freqtrade, people who want to contribute to the Freqtrade codebase or documentation, or people who want to understand the source code of the application they're running.

    +

    All contributions, bug reports, bug fixes, documentation improvements, enhancements and ideas are welcome. We track issues on GitHub and also have a dev channel on discord where you can ask questions.

    +

    Documentation

    +

    Documentation is available at https://freqtrade.io and needs to be provided with every new feature PR.

    +

    Special fields for the documentation (like Note boxes, ...) can be found here.

    +

    To test the documentation locally use the following commands.

    +

    bash +pip install -r docs/requirements-docs.txt +mkdocs serve

    +

    This will spin up a local server (usually on port 8000) so you can see if everything looks as you'd like it to.

    +

    Developer setup

    +

    To configure a development environment, you can either use the provided DevContainer, or use the setup.sh script and answer "y" when asked "Do you want to install dependencies for dev [y/N]? ". +Alternatively (e.g. if your system is not supported by the setup.sh script), follow the manual installation process and run pip3 install -e .[all].

    +

    This will install all required tools for development, including pytest, flake8, mypy, and coveralls.

    +

    Devcontainer setup

    +

    The fastest and easiest way to get started is to use VSCode with the Remote container extension. +This gives developers the ability to start the bot with all required dependencies without needing to install any freqtrade specific dependencies on your local machine.

    +

    Devcontainer dependencies

    + +

    For more information about the Remote container extension, best consult the documentation.

    +

    Tests

    +

    New code should be covered by basic unittests. Depending on the complexity of the feature, Reviewers may request more in-depth unittests. +If necessary, the Freqtrade team can assist and give guidance with writing good tests (however please don't expect anyone to write the tests for you).

    +

    Checking log content in tests

    +

    Freqtrade uses 2 main methods to check log content in tests, log_has() and log_has_re() (to check using regex, in case of dynamic log-messages). +These are available from conftest.py and can be imported in any test module.

    +

    A sample check looks as follows:

    +

    ``` python +from tests.conftest import log_has, log_has_re

    +

    def test_method_to_test(caplog): + method_to_test()

    +
    assert log_has("This event happened", caplog)
    +# Check regex with trailing number ...
    +assert log_has_re(r"This dynamic event happened and produced \d+", caplog)
    +
    + +

    ```

    +

    ErrorHandling

    +

    Freqtrade Exceptions all inherit from FreqtradeException. +This general class of error should however not be used directly. Instead, multiple specialized sub-Exceptions exist.

    +

    Below is an outline of exception inheritance hierarchy:

    +

    + FreqtradeException +| ++---+ OperationalException +| ++---+ DependencyException +| | +| +---+ PricingError +| | +| +---+ ExchangeError +| | +| +---+ TemporaryError +| | +| +---+ DDosProtection +| | +| +---+ InvalidOrderException +| | +| +---+ RetryableOrderError +| | +| +---+ InsufficientFundsError +| ++---+ StrategyError

    +
    +

    Plugins

    +

    Pairlists

    +

    You have a great idea for a new pair selection algorithm you would like to try out? Great. +Hopefully you also want to contribute this back upstream.

    +

    Whatever your motivations are - This should get you off the ground in trying to develop a new Pairlist Handler.

    +

    First of all, have a look at the VolumePairList Handler, and best copy this file with a name of your new Pairlist Handler.

    +

    This is a simple Handler, which however serves as a good example on how to start developing.

    +

    Next, modify the class-name of the Handler (ideally align this with the module filename).

    +

    The base-class provides an instance of the exchange (self._exchange) the pairlist manager (self._pairlistmanager), as well as the main configuration (self._config), the pairlist dedicated configuration (self._pairlistconfig) and the absolute position within the list of pairlists.

    +

    python + self._exchange = exchange + self._pairlistmanager = pairlistmanager + self._config = config + self._pairlistconfig = pairlistconfig + self._pairlist_pos = pairlist_pos

    +
    +

    Tip

    +

    Don't forget to register your pairlist in constants.py under the variable AVAILABLE_PAIRLISTS - otherwise it will not be selectable.

    +
    +

    Now, let's step through the methods which require actions:

    +

    Pairlist configuration

    +

    Configuration for the chain of Pairlist Handlers is done in the bot configuration file in the element "pairlists", an array of configuration parameters for each Pairlist Handlers in the chain.

    +

    By convention, "number_assets" is used to specify the maximum number of pairs to keep in the pairlist. Please follow this to ensure a consistent user experience.

    +

    Additional parameters can be configured as needed. For instance, VolumePairList uses "sort_key" to specify the sorting value - however feel free to specify whatever is necessary for your great algorithm to be successful and dynamic.

    +

    short_desc

    +

    Returns a description used for Telegram messages.

    +

    This should contain the name of the Pairlist Handler, as well as a short description containing the number of assets. Please follow the format "PairlistName - top/bottom X pairs".

    +

    gen_pairlist

    +

    Override this method if the Pairlist Handler can be used as the leading Pairlist Handler in the chain, defining the initial pairlist which is then handled by all Pairlist Handlers in the chain. Examples are StaticPairList and VolumePairList.

    +

    This is called with each iteration of the bot (only if the Pairlist Handler is at the first location) - so consider implementing caching for compute/network heavy calculations.

    +

    It must return the resulting pairlist (which may then be passed into the chain of Pairlist Handlers).

    +

    Validations are optional, the parent class exposes a _verify_blacklist(pairlist) and _whitelist_for_active_markets(pairlist) to do default filtering. Use this if you limit your result to a certain number of pairs - so the end-result is not shorter than expected.

    +

    filter_pairlist

    +

    This method is called for each Pairlist Handler in the chain by the pairlist manager.

    +

    This is called with each iteration of the bot - so consider implementing caching for compute/network heavy calculations.

    +

    It gets passed a pairlist (which can be the result of previous pairlists) as well as tickers, a pre-fetched version of get_tickers().

    +

    The default implementation in the base class simply calls the _validate_pair() method for each pair in the pairlist, but you may override it. So you should either implement the _validate_pair() in your Pairlist Handler or override filter_pairlist() to do something else.

    +

    If overridden, it must return the resulting pairlist (which may then be passed into the next Pairlist Handler in the chain).

    +

    Validations are optional, the parent class exposes a _verify_blacklist(pairlist) and _whitelist_for_active_markets(pairlist) to do default filters. Use this if you limit your result to a certain number of pairs - so the end result is not shorter than expected.

    +

    In VolumePairList, this implements different methods of sorting, does early validation so only the expected number of pairs is returned.

    +
    sample
    +

    python + def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]: + # Generate dynamic whitelist + pairs = self._calculate_pairlist(pairlist, tickers) + return pairs

    +

    Protections

    +

    Best read the Protection documentation to understand protections. +This Guide is directed towards Developers who want to develop a new protection.

    +

    No protection should use datetime directly, but use the provided date_now variable for date calculations. This preserves the ability to backtest protections.

    +
    +

    Writing a new Protection

    +

    Best copy one of the existing Protections to have a good example. +Don't forget to register your protection in constants.py under the variable AVAILABLE_PROTECTIONS - otherwise it will not be selectable.

    +
    +

    Implementation of a new protection

    +

    All Protection implementations must have IProtection as parent class. +For that reason, they must implement the following methods:

    +
      +
    • short_desc()
    • +
    • global_stop()
    • +
    • stop_per_pair().
    • +
    +

    global_stop() and stop_per_pair() must return a ProtectionReturn tuple, which consists of:

    +
      +
    • lock pair - boolean
    • +
    • lock until - datetime - until when should the pair be locked (will be rounded up to the next new candle)
    • +
    • reason - string, used for logging and storage in the database
    • +
    +

    The until portion should be calculated using the provided calculate_lock_end() method.

    +

    All Protections should use "stop_duration" / "stop_duration_candles" to define how long a a pair (or all pairs) should be locked. +The content of this is made available as self._stop_duration to the each Protection.

    +

    If your protection requires a look-back period, please use "lookback_period" / "lockback_period_candles" to keep all protections aligned.

    +

    Global vs. local stops

    +

    Protections can have 2 different ways to stop trading for a limited :

    +
      +
    • Per pair (local)
    • +
    • For all Pairs (globally)
    • +
    +
    Protections - per pair
    +

    Protections that implement the per pair approach must set has_local_stop=True. +The method stop_per_pair() will be called whenever a trade closed (sell order completed).

    +
    Protections - global protection
    +

    These Protections should do their evaluation across all pairs, and consequently will also lock all pairs from trading (called a global PairLock). +Global protection must set has_global_stop=True to be evaluated for global stops. +The method global_stop() will be called whenever a trade closed (sell order completed).

    +
    Protections - calculating lock end time
    +

    Protections should calculate the lock end time based on the last trade it considers. +This avoids re-locking should the lookback-period be longer than the actual lock period.

    +

    The IProtection parent class provides a helper method for this in calculate_lock_end().

    +
    +

    Implement a new Exchange (WIP)

    +
    +

    Note

    +

    This section is a Work in Progress and is not a complete guide on how to test a new exchange with Freqtrade.

    +
    +

    Most exchanges supported by CCXT should work out of the box.

    +

    To quickly test the public endpoints of an exchange, add a configuration for your exchange to test_ccxt_compat.py and run these tests with pytest --longrun tests/exchange/test_ccxt_compat.py. +Completing these tests successfully a good basis point (it's a requirement, actually), however these won't guarantee correct exchange functioning, as this only tests public endpoints, but no private endpoint (like generate order or similar).

    +

    Stoploss On Exchange

    +

    Check if the new exchange supports Stoploss on Exchange orders through their API.

    +

    Since CCXT does not provide unification for Stoploss On Exchange yet, we'll need to implement the exchange-specific parameters ourselves. Best look at binance.py for an example implementation of this. You'll need to dig through the documentation of the Exchange's API on how exactly this can be done. CCXT Issues may also provide great help, since others may have implemented something similar for their projects.

    +

    Incomplete candles

    +

    While fetching candle (OHLCV) data, we may end up getting incomplete candles (depending on the exchange). +To demonstrate this, we'll use daily candles ("1d") to keep things simple. +We query the api (ct.fetch_ohlcv()) for the timeframe and look at the date of the last entry. If this entry changes or shows the date of a "incomplete" candle, then we should drop this since having incomplete candles is problematic because indicators assume that only complete candles are passed to them, and will generate a lot of false buy signals. By default, we're therefore removing the last candle assuming it's incomplete.

    +

    To check how the new exchange behaves, you can use the following snippet:

    +

    ``` python +import ccxt +from datetime import datetime +from freqtrade.data.converter import ohlcv_to_dataframe +ct = ccxt.binance() +timeframe = "1d" +pair = "XLM/BTC" # Make sure to use a pair that exists on that exchange! +raw = ct.fetch_ohlcv(pair, timeframe=timeframe)

    +

    convert to dataframe

    +

    df1 = ohlcv_to_dataframe(raw, timeframe, pair=pair, drop_incomplete=False)

    +

    print(df1.tail(1)) +print(datetime.utcnow()) +```

    +

    output + date open high low close volume +499 2019-06-08 00:00:00+00:00 0.000007 0.000007 0.000007 0.000007 26264344.0 +2019-06-09 12:30:27.873327

    +

    The output will show the last entry from the Exchange as well as the current UTC date. +If the day shows the same day, then the last candle can be assumed as incomplete and should be dropped (leave the setting "ohlcv_partial_candle" from the exchange-class untouched / True). Otherwise, set "ohlcv_partial_candle" to False to not drop Candles (shown in the example above). +Another way is to run this command multiple times in a row and observe if the volume is changing (while the date remains the same).

    +

    Updating example notebooks

    +

    To keep the jupyter notebooks aligned with the documentation, the following should be ran after updating a example notebook.

    +

    bash +jupyter nbconvert --ClearOutputPreprocessor.enabled=True --inplace freqtrade/templates/strategy_analysis_example.ipynb +jupyter nbconvert --ClearOutputPreprocessor.enabled=True --to markdown freqtrade/templates/strategy_analysis_example.ipynb --stdout > docs/strategy_analysis_example.md

    +

    Continuous integration

    +

    This documents some decisions taken for the CI Pipeline.

    +
      +
    • CI runs on all OS variants, Linux (ubuntu), macOS and Windows.
    • +
    • Docker images are build for the branches stable and develop.
    • +
    • Docker images containing Plot dependencies are also available as stable_plot and develop_plot.
    • +
    • Raspberry PI Docker images are postfixed with _pi - so tags will be :stable_pi and develop_pi.
    • +
    • Docker images contain a file, /freqtrade/freqtrade_commit containing the commit this image is based of.
    • +
    • Full docker image rebuilds are run once a week via schedule.
    • +
    • Deployments run on ubuntu.
    • +
    • ta-lib binaries are contained in the build_helpers directory to avoid fails related to external unavailability.
    • +
    • All tests must pass for a PR to be merged to stable or develop.
    • +
    +

    Creating a release

    +

    This part of the documentation is aimed at maintainers, and shows how to create a release.

    +

    Create release branch

    +

    First, pick a commit that's about one week old (to not include latest additions to releases).

    +

    ``` bash

    +

    create new branch

    +

    git checkout -b new_release +```

    +

    Determine if crucial bugfixes have been made between this commit and the current state, and eventually cherry-pick these.

    +
      +
    • Merge the release branch (stable) into this branch.
    • +
    • Edit freqtrade/__init__.py and add the version matching the current date (for example 2019.7 for July 2019). Minor versions can be 2019.7.1 should we need to do a second release that month. Version numbers must follow allowed versions from PEP0440 to avoid failures pushing to pypi.
    • +
    • Commit this part
    • +
    • push that branch to the remote and create a PR against the stable branch
    • +
    +

    Create changelog from git commits

    +
    +

    Note

    +

    Make sure that the stable branch is up-to-date!

    +
    +

    ``` bash

    +

    Needs to be done before merging / pulling that branch.

    +

    git log --oneline --no-decorate --no-merges stable..new_release +```

    +

    To keep the release-log short, best wrap the full git changelog into a collapsible details section.

    +

    ```markdown

    +
    +Expand full changelog + +... Full git changelog + +
    +

    ```

    +

    Create github release / tag

    +

    Once the PR against stable is merged (best right after merging):

    +
      +
    • Use the button "Draft a new release" in the Github UI (subsection releases).
    • +
    • Use the version-number specified as tag.
    • +
    • Use "stable" as reference (this step comes after the above PR is merged).
    • +
    • Use the above changelog as release comment (as codeblock)
    • +
    +

    Releases

    +

    pypi

    +
    +

    Note

    +

    This process is now automated as part of Github Actions.

    +
    +

    To create a pypi release, please run the following commands:

    +

    Additional requirement: wheel, twine (for uploading), account on pypi with proper permissions.

    +

    ``` bash +python setup.py sdist bdist_wheel

    +

    For pypi test (to check if some change to the installation did work)

    +

    twine upload --repository-url https://test.pypi.org/legacy/ dist/*

    +

    For production:

    +

    twine upload dist/* +```

    +

    Please don't push non-releases to the productive / real pypi instance.

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/docker_quickstart/index.html b/en/2021.7/docker_quickstart/index.html new file mode 100644 index 000000000..92b79a692 --- /dev/null +++ b/en/2021.7/docker_quickstart/index.html @@ -0,0 +1,1150 @@ + + + + + + + + + + + + + + + + + + + Quickstart with Docker - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + + + + + + +

    Using Freqtrade with Docker

    +

    This page explains how to run the bot with Docker. It is not meant to work out of the box. You'll still need to read through the documentation and understand how to properly configure it.

    +

    Install Docker

    +

    Start by downloading and installing Docker CE for your platform:

    + +

    To simplify running freqtrade, docker-compose should be installed and available to follow the below docker quick start guide.

    +

    Freqtrade with docker-compose

    +

    Freqtrade provides an official Docker image on Dockerhub, as well as a docker-compose file ready for usage.

    +
    +

    Note

    +
      +
    • The following section assumes that docker and docker-compose are installed and available to the logged in user.
    • +
    • All below commands use relative directories and will have to be executed from the directory containing the docker-compose.yml file.
    • +
    +
    +

    Docker quick start

    +

    Create a new directory and place the docker-compose file in this directory.

    +

    ``` bash +mkdir ft_userdata +cd ft_userdata/

    +

    Download the docker-compose file from the repository

    +

    curl https://raw.githubusercontent.com/freqtrade/freqtrade/stable/docker-compose.yml -o docker-compose.yml

    +

    Pull the freqtrade image

    +

    docker-compose pull

    +

    Create user directory structure

    +

    docker-compose run --rm freqtrade create-userdir --userdir user_data

    +

    Create configuration - Requires answering interactive questions

    +

    docker-compose run --rm freqtrade new-config --config user_data/config.json +```

    +

    The above snippet creates a new directory called ft_userdata, downloads the latest compose file and pulls the freqtrade image. +The last 2 steps in the snippet create the directory with user_data, as well as (interactively) the default configuration based on your selections.

    +
    +

    How to edit the bot configuration?

    +

    You can edit the configuration at any time, which is available as user_data/config.json (within the directory ft_userdata) when using the above configuration.

    +

    You can also change the both Strategy and commands by editing the command section of your docker-compose.yml file.

    +
    +

    Adding a custom strategy

    +
      +
    1. The configuration is now available as user_data/config.json
    2. +
    3. Copy a custom strategy to the directory user_data/strategies/
    4. +
    5. Add the Strategy' class name to the docker-compose.yml file
    6. +
    +

    The SampleStrategy is run by default.

    +
    +

    SampleStrategy is just a demo!

    +

    The SampleStrategy is there for your reference and give you ideas for your own strategy. +Please always backtest your strategy and use dry-run for some time before risking real money! +You will find more information about Strategy development in the Strategy documentation.

    +
    +

    Once this is done, you're ready to launch the bot in trading mode (Dry-run or Live-trading, depending on your answer to the corresponding question you made above).

    +

    bash +docker-compose up -d

    +
    +

    Default configuration

    +

    While the configuration generated will be mostly functional, you will still need to verify that all options correspond to what you want (like Pricing, pairlist, ...) before starting the bot.

    +
    +

    Monitoring the bot

    +

    You can check for running instances with docker-compose ps. +This should list the service freqtrade as running. If that's not the case, best check the logs (see next point).

    +

    Docker-compose logs

    +

    Logs will be written to: user_data/logs/freqtrade.log.
    +You can also check the latest log with the command docker-compose logs -f.

    +

    Database

    +

    The database will be located at: user_data/tradesv3.sqlite

    +

    Updating freqtrade with docker-compose

    +

    Updating freqtrade when using docker-compose is as simple as running the following 2 commands:

    +

    ``` bash

    +

    Download the latest image

    +

    docker-compose pull

    +

    Restart the image

    +

    docker-compose up -d +```

    +

    This will first pull the latest image, and will then restart the container with the just pulled version.

    +
    +

    Check the Changelog

    +

    You should always check the changelog for breaking changes / manual interventions required and make sure the bot starts correctly after the update.

    +
    +

    Editing the docker-compose file

    +

    Advanced users may edit the docker-compose file further to include all possible options or arguments.

    +

    All freqtrade arguments will be available by running docker-compose run --rm freqtrade <command> <optional arguments>.

    +
    +

    docker-compose for trade commands

    +

    Trade commands (freqtrade trade <...>) should not be ran via docker-compose run - but should use docker-compose up -d instead. +This makes sure that the container is properly started (including port forwardings) and will make sure that the container will restart after a system reboot.

    +
    +
    +

    docker-compose run --rm

    +

    Including --rm will remove the container after completion, and is highly recommended for all modes except trading mode (running with freqtrade trade command).

    +
    +

    Example: Download data with docker-compose

    +

    Download backtesting data for 5 days for the pair ETH/BTC and 1h timeframe from Binance. The data will be stored in the directory user_data/data/ on the host.

    +

    bash +docker-compose run --rm freqtrade download-data --pairs ETH/BTC --exchange binance --days 5 -t 1h

    +

    Head over to the Data Downloading Documentation for more details on downloading data.

    +

    Example: Backtest with docker-compose

    +

    Run backtesting in docker-containers for SampleStrategy and specified timerange of historical data, on 5m timeframe:

    +

    bash +docker-compose run --rm freqtrade backtesting --config user_data/config.json --strategy SampleStrategy --timerange 20190801-20191001 -i 5m

    +

    Head over to the Backtesting Documentation to learn more.

    +

    Additional dependencies with docker-compose

    +

    If your strategy requires dependencies not included in the default image - it will be necessary to build the image on your host. +For this, please create a Dockerfile containing installation steps for the additional dependencies (have a look at docker/Dockerfile.custom for an example).

    +

    You'll then also need to modify the docker-compose.yml file and uncomment the build step, as well as rename the image to avoid naming collisions.

    +

    yaml + image: freqtrade_custom + build: + context: . + dockerfile: "./Dockerfile.<yourextension>"

    +

    You can then run docker-compose build to build the docker image, and run it using the commands described above.

    +

    Plotting with docker-compose

    +

    Commands freqtrade plot-profit and freqtrade plot-dataframe (Documentation) are available by changing the image to *_plot in your docker-compose.yml file. +You can then use these commands as follows:

    +

    bash +docker-compose run --rm freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH --timerange=20180801-20180805

    +

    The output will be stored in the user_data/plot directory, and can be opened with any modern browser.

    +

    Data analysis using docker compose

    +

    Freqtrade provides a docker-compose file which starts up a jupyter lab server. +You can run this server using the following command:

    +

    bash +docker-compose -f docker/docker-compose-jupyter.yml up

    +

    This will create a docker-container running jupyter lab, which will be accessible using https://127.0.0.1:8888/lab. +Please use the link that's printed in the console after startup for simplified login.

    +

    Since part of this image is built on your machine, it is recommended to rebuild the image from time to time to keep freqtrade (and dependencies) up-to-date.

    +

    bash +docker-compose -f docker/docker-compose-jupyter.yml build --no-cache

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/edge/index.html b/en/2021.7/edge/index.html new file mode 100644 index 000000000..602b3a39b --- /dev/null +++ b/en/2021.7/edge/index.html @@ -0,0 +1,1701 @@ + + + + + + + + + + + + + + + + + + + Edge Positioning - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + + + + +
    +
    + + + + + + + +

    Edge positioning

    +

    The Edge Positioning module uses probability to calculate your win rate and risk reward ratio. It will use these statistics to control your strategy trade entry points, position size and, stoploss.

    +
    +

    Warning

    +

    WHen using Edge positioning with a dynamic whitelist (VolumePairList), make sure to also use AgeFilter and set it to at least calculate_since_number_of_days to avoid problems with missing data.

    +
    +
    +

    Note

    +

    Edge Positioning only considers its own buy/sell/stoploss signals. It ignores the stoploss, trailing stoploss, and ROI settings in the strategy configuration file. +Edge Positioning improves the performance of some trading strategies and decreases the performance of others.

    +
    +

    Introduction

    +

    Trading strategies are not perfect. They are frameworks that are susceptible to the market and its indicators. Because the market is not at all predictable, sometimes a strategy will win and sometimes the same strategy will lose.

    +

    To obtain an edge in the market, a strategy has to make more money than it loses. Making money in trading is not only about how often the strategy makes or loses money.

    +
    +

    It doesn't matter how often, but how much!

    +

    A bad strategy might make 1 penny in ten transactions but lose 1 dollar in one transaction. If one only checks the number of winning trades, it would be misleading to think that the strategy is actually making a profit.

    +
    +

    The Edge Positioning module seeks to improve a strategy's winning probability and the money that the strategy will make on the long run.

    +

    We raise the following question1:

    +
    +

    Which trade is a better option?

    +

    a) A trade with 80% of chance of losing 100$ and 20% chance of winning 200$
    +b) A trade with 100% of chance of losing 30$

    +
    +
    +Answer +

    The expected value of a) is smaller than the expected value of b).
    +Hence, b) represents a smaller loss in the long run.
    +However, the answer is: it depends

    +
    +

    Another way to look at it is to ask a similar question:

    +
    +

    Which trade is a better option?

    +

    a) A trade with 80% of chance of winning 100$ and 20% chance of losing 200$
    +b) A trade with 100% of chance of winning 30$

    +
    +

    Edge positioning tries to answer the hard questions about risk/reward and position size automatically, seeking to minimizes the chances of losing of a given strategy.

    +

    Trading, winning and losing

    +

    Let's call \(o\) the return of a single transaction \(o\) where \(o \in \mathbb{R}\). The collection \(O = \{o_1, o_2, ..., o_N\}\) is the set of all returns of transactions made during a trading session. We say that \(N\) is the cardinality of \(O\), or, in lay terms, it is the number of transactions made in a trading session.

    +
    +

    Example

    +

    In a session where a strategy made three transactions we can say that \(O = \{3.5, -1, 15\}\). That means that \(N = 3\) and \(o_1 = 3.5\), \(o_2 = -1\), \(o_3 = 15\).

    +
    +

    A winning trade is a trade where a strategy made money. Making money means that the strategy closed the position in a value that returned a profit, after all deducted fees. Formally, a winning trade will have a return \(o_i > 0\). Similarly, a losing trade will have a return \(o_j \leq 0\). With that, we can discover the set of all winning trades, \(T_{win}\), as follows:

    +
    \[ T_{win} = \{ o \in O | o > 0 \} \]
    +

    Similarly, we can discover the set of losing trades \(T_{lose}\) as follows:

    +
    \[ T_{lose} = \{o \in O | o \leq 0\} \]
    +
    +

    Example

    +

    In a section where a strategy made four transactions \(O = \{3.5, -1, 15, 0\}\):
    +\(T_{win} = \{3.5, 15\}\)
    +\(T_{lose} = \{-1, 0\}\)

    +
    +

    Win Rate and Lose Rate

    +

    The win rate \(W\) is the proportion of winning trades with respect to all the trades made by a strategy. We use the following function to compute the win rate:

    +
    \[W = \frac{|T_{win}|}{N}\]
    +

    Where \(W\) is the win rate, \(N\) is the number of trades and, \(T_{win}\) is the set of all trades where the strategy made money.

    +

    Similarly, we can compute the rate of losing trades:

    +
    \[ + L = \frac{|T_{lose}|}{N} +\]
    +

    Where \(L\) is the lose rate, \(N\) is the amount of trades made and, \(T_{lose}\) is the set of all trades where the strategy lost money. Note that the above formula is the same as calculating \(L = 1 – W\) or \(W = 1 – L\)

    +

    Risk Reward Ratio

    +

    Risk Reward Ratio (\(R\)) is a formula used to measure the expected gains of a given investment against the risk of loss. It is basically what you potentially win divided by what you potentially lose. Formally:

    +
    \[ R = \frac{\text{potential_profit}}{\text{potential_loss}} \]
    +
    +Worked example of \(R\) calculation +

    Let's say that you think that the price of stonecoin today is 10.0$. You believe that, because they will start mining stonecoin, it will go up to 15.0$ tomorrow. There is the risk that the stone is too hard, and the GPUs can't mine it, so the price might go to 0$ tomorrow. You are planning to invest 100$, which will give you 10 shares (100 / 10).

    +

    Your potential profit is calculated as:

    +

    \(\begin{aligned} + \text{potential_profit} &= (\text{potential_price} - \text{entry_price}) * \frac{\text{investment}}{\text{entry_price}} \\ + &= (15 - 10) * (100 / 10) \\ + &= 50 +\end{aligned}\)

    +

    Since the price might go to 0$, the 100$ dollars invested could turn into 0.

    +

    We do however use a stoploss of 15% - so in the worst case, we'll sell 15% below entry price (or at 8.5$).

    +

    \(\begin{aligned} + \text{potential_loss} &= (\text{entry_price} - \text{stoploss}) * \frac{\text{investment}}{\text{entry_price}} \\ + &= (10 - 8.5) * (100 / 10)\\ + &= 15 +\end{aligned}\)

    +

    We can compute the Risk Reward Ratio as follows:

    +

    \(\begin{aligned} + R &= \frac{\text{potential_profit}}{\text{potential_loss}}\\ + &= \frac{50}{15}\\ + &= 3.33 +\end{aligned}\)
    +What it effectively means is that the strategy have the potential to make 3.33$ for each 1$ invested.

    +
    +

    On a long horizon, that is, on many trades, we can calculate the risk reward by dividing the strategy' average profit on winning trades by the strategy' average loss on losing trades. We can calculate the average profit, \(\mu_{win}\), as follows:

    +
    \[ \text{average_profit} = \mu_{win} = \frac{\text{sum_of_profits}}{\text{count_winning_trades}} = \frac{\sum^{o \in T_{win}} o}{|T_{win}|} \]
    +

    Similarly, we can calculate the average loss, \(\mu_{lose}\), as follows:

    +
    \[ \text{average_loss} = \mu_{lose} = \frac{\text{sum_of_losses}}{\text{count_losing_trades}} = \frac{\sum^{o \in T_{lose}} o}{|T_{lose}|} \]
    +

    Finally, we can calculate the Risk Reward ratio, \(R\), as follows:

    +
    \[ R = \frac{\text{average_profit}}{\text{average_loss}} = \frac{\mu_{win}}{\mu_{lose}}\\ \]
    +
    +Worked example of \(R\) calculation using mean profit/loss +

    Let's say the strategy that we are using makes an average win \(\mu_{win} = 2.06\) and an average loss \(\mu_{loss} = 4.11\).
    +We calculate the risk reward ratio as follows:
    +\(R = \frac{\mu_{win}}{\mu_{loss}} = \frac{2.06}{4.11} = 0.5012...\)

    +
    +

    Expectancy

    +

    By combining the Win Rate \(W\) and and the Risk Reward ratio \(R\) to create an expectancy ratio \(E\). A expectance ratio is the expected return of the investment made in a trade. We can compute the value of \(E\) as follows:

    +
    \[E = R * W - L\]
    +
    +

    Calculating \(E\)

    +

    Let's say that a strategy has a win rate \(W = 0.28\) and a risk reward ratio \(R = 5\). What this means is that the strategy is expected to make 5 times the investment around on 28% of the trades it makes. Working out the example:
    +\(E = R * W - L = 5 * 0.28 - 0.72 = 0.68\) +

    +
    +

    The expectancy worked out in the example above means that, on average, this strategy' trades will return 1.68 times the size of its losses. Said another way, the strategy makes 1.68$ for every 1$ it loses, on average.

    +

    This is important for two reasons: First, it may seem obvious, but you know right away that you have a positive return. Second, you now have a number you can compare to other candidate systems to make decisions about which ones you employ.

    +

    It is important to remember that any system with an expectancy greater than 0 is profitable using past data. The key is finding one that will be profitable in the future.

    +

    You can also use this value to evaluate the effectiveness of modifications to this system.

    +
    +

    Note

    +

    It's important to keep in mind that Edge is testing your expectancy using historical data, there's no guarantee that you will have a similar edge in the future. It's still vital to do this testing in order to build confidence in your methodology but be wary of "curve-fitting" your approach to the historical data as things are unlikely to play out the exact same way for future trades.

    +
    +

    How does it work?

    +

    Edge combines dynamic stoploss, dynamic positions, and whitelist generation into one isolated module which is then applied to the trading strategy. If enabled in config, Edge will go through historical data with a range of stoplosses in order to find buy and sell/stoploss signals. It then calculates win rate and expectancy over N trades for each stoploss. Here is an example:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PairStoplossWin RateRisk Reward RatioExpectancy
    XZC/ETH-0.010.501.1763840.088
    XZC/ETH-0.020.511.1159410.079
    XZC/ETH-0.030.521.3596700.228
    XZC/ETH-0.040.511.2345390.117
    +

    The goal here is to find the best stoploss for the strategy in order to have the maximum expectancy. In the above example stoploss at \(3%\) leads to the maximum expectancy according to historical data.

    +

    Edge module then forces stoploss value it evaluated to your strategy dynamically.

    +

    Position size

    +

    Edge dictates the amount at stake for each trade to the bot according to the following factors:

    +
      +
    • Allowed capital at risk
    • +
    • Stoploss
    • +
    +

    Allowed capital at risk is calculated as follows:

    +

    Allowed capital at risk = (Capital available_percentage) X (Allowed risk per trade)

    +

    Stoploss is calculated as described above with respect to historical data.

    +

    The position size is calculated as follows:

    +

    Position size = (Allowed capital at risk) / Stoploss

    +

    Example:

    +

    Let's say the stake currency is ETH and there is \(10\) ETH on the wallet. The capital available percentage is \(50%\) and the allowed risk per trade is \(1\%\). Thus, the available capital for trading is \(10 * 0.5 = 5\) ETH and the allowed capital at risk would be \(5 * 0.01 = 0.05\) ETH.

    +
      +
    • Trade 1: The strategy detects a new buy signal in the XLM/ETH market. Edge Positioning calculates a stoploss of \(2\%\) and a position of \(0.05 / 0.02 = 2.5\) ETH. The bot takes a position of \(2.5\) ETH in the XLM/ETH market.
    • +
    +
      +
    • Trade 2: The strategy detects a buy signal on the BTC/ETH market while Trade 1 is still open. Edge Positioning calculates the stoploss of \(4\%\) on this market. Thus, Trade 2 position size is \(0.05 / 0.04 = 1.25\) ETH.
    • +
    +
    +

    Available Capital \(\neq\) Available in wallet

    +

    The available capital for trading didn't change in Trade 2 even with Trade 1 still open. The available capital is not the free amount in the wallet.

    +
    +
      +
    • Trade 3: The strategy detects a buy signal in the ADA/ETH market. Edge Positioning calculates a stoploss of \(1\%\) and a position of \(0.05 / 0.01 = 5\) ETH. Since Trade 1 has \(2.5\) ETH blocked and Trade 2 has \(1.25\) ETH blocked, there is only \(5 - 1.25 - 2.5 = 1.25\) ETH available. Hence, the position size of Trade 3 is \(1.25\) ETH.
    • +
    +
    +

    Available Capital Updates

    +

    The available capital does not change before a position is sold. After a trade is closed the Available Capital goes up if the trade was profitable or goes down if the trade was a loss.

    +
    +
      +
    • The strategy detects a sell signal in the XLM/ETH market. The bot exits Trade 1 for a profit of \(1\) ETH. The total capital in the wallet becomes \(11\) ETH and the available capital for trading becomes \(5.5\) ETH.
    • +
    +
      +
    • Trade 4 The strategy detects a new buy signal int the XLM/ETH market. Edge Positioning calculates the stoploss of \(2\%\), and the position size of \(0.055 / 0.02 = 2.75\) ETH.
    • +
    +

    Edge command reference

    +

    ``` +usage: freqtrade edge [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] + [--userdir PATH] [-s NAME] [--strategy-path PATH] + [-i TIMEFRAME] [--timerange TIMERANGE] + [--data-format-ohlcv {json,jsongz,hdf5}] + [--max-open-trades INT] [--stake-amount STAKE_AMOUNT] + [--fee FLOAT] [-p PAIRS [PAIRS ...]] + [--stoplosses STOPLOSS_RANGE]

    +

    optional arguments: + -h, --help show this help message and exit + -i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME + Specify timeframe (1m, 5m, 30m, 1h, 1d). + --timerange TIMERANGE + Specify what timerange of data to use. + --data-format-ohlcv {json,jsongz,hdf5} + Storage format for downloaded candle (OHLCV) data. + (default: None). + --max-open-trades INT + Override the value of the max_open_trades + configuration setting. + --stake-amount STAKE_AMOUNT + Override the value of the stake_amount configuration + setting. + --fee FLOAT Specify fee ratio. Will be applied twice (on trade + entry and exit). + -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] + Limit command to these pairs. Pairs are space- + separated. + --stoplosses STOPLOSS_RANGE + Defines a range of stoploss values against which edge + will assess the strategy. The format is "min,max,step" + (without any space). Example: + --stoplosses=-0.01,-0.1,-0.001

    +

    Common arguments: + -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). + --logfile FILE Log to the file specified. Special values are: + 'syslog', 'journald'. See the documentation for more + details. + -V, --version show program's version number and exit + -c PATH, --config PATH + Specify configuration file (default: + userdir/config.json or config.json whichever + exists). Multiple --config options may be used. Can be + set to - to read config from stdin. + -d PATH, --datadir PATH + Path to directory with historical backtesting data. + --userdir PATH, --user-data-dir PATH + Path to userdata directory.

    +

    Strategy arguments: + -s NAME, --strategy NAME + Specify strategy class name which will be used by the + bot. + --strategy-path PATH Specify additional strategy lookup path.

    +

    ```

    +

    Configurations

    +

    Edge module has following configuration options:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    ParameterDescription
    enabledIf true, then Edge will run periodically.
    Defaults to false.
    Datatype: Boolean
    process_throttle_secsHow often should Edge run in seconds.
    Defaults to 3600 (once per hour).
    Datatype: Integer
    calculate_since_number_of_daysNumber of days of data against which Edge calculates Win Rate, Risk Reward and Expectancy.
    Note that it downloads historical data so increasing this number would lead to slowing down the bot.
    Defaults to 7.
    Datatype: Integer
    allowed_riskRatio of allowed risk per trade.
    Defaults to 0.01 (1%)).
    Datatype: Float
    stoploss_range_minMinimum stoploss.
    Defaults to -0.01.
    Datatype: Float
    stoploss_range_maxMaximum stoploss.
    Defaults to -0.10.
    Datatype: Float
    stoploss_range_stepAs an example if this is set to -0.01 then Edge will test the strategy for [-0.01, -0,02, -0,03 ..., -0.09, -0.10] ranges.
    Note than having a smaller step means having a bigger range which could lead to slow calculation.
    If you set this parameter to -0.001, you then slow down the Edge calculation by a factor of 10.
    Defaults to -0.001.
    Datatype: Float
    minimum_winrateIt filters out pairs which don't have at least minimum_winrate.
    This comes handy if you want to be conservative and don't comprise win rate in favour of risk reward ratio.
    Defaults to 0.60.
    Datatype: Float
    minimum_expectancyIt filters out pairs which have the expectancy lower than this number.
    Having an expectancy of 0.20 means if you put 10$ on a trade you expect a 12$ return.
    Defaults to 0.20.
    Datatype: Float
    min_trade_numberWhen calculating W, R and E (expectancy) against historical data, you always want to have a minimum number of trades. The more this number is the more Edge is reliable.
    Having a win rate of 100% on a single trade doesn't mean anything at all. But having a win rate of 70% over past 100 trades means clearly something.
    Defaults to 10 (it is highly recommended not to decrease this number).
    Datatype: Integer
    max_trade_duration_minuteEdge will filter out trades with long duration. If a trade is profitable after 1 month, it is hard to evaluate the strategy based on it. But if most of trades are profitable and they have maximum duration of 30 minutes, then it is clearly a good sign.
    NOTICE: While configuring this value, you should take into consideration your timeframe. As an example filtering out trades having duration less than one day for a strategy which has 4h interval does not make sense. Default value is set assuming your strategy interval is relatively small (1m or 5m, etc.).
    Defaults to 1440 (one day).
    Datatype: Integer
    remove_pumpsEdge will remove sudden pumps in a given market while going through historical data. However, given that pumps happen very often in crypto markets, we recommend you keep this off.
    Defaults to false.
    Datatype: Boolean
    +

    Running Edge independently

    +

    You can run Edge independently in order to see in details the result. Here is an example:

    +

    bash +freqtrade edge

    +

    An example of its output:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    pairstoplosswin raterisk reward ratiorequired risk rewardexpectancytotal number of tradesaverage duration (min)
    AGI/BTC-0.020.645.860.563.411454
    NXS/BTC-0.030.642.990.571.541126
    LEND/BTC-0.020.822.050.221.501136
    VIA/BTC-0.010.553.010.831.191148
    MTH/BTC-0.090.562.820.801.121852
    ARDR/BTC-0.040.423.141.400.731242
    BCPT/BTC-0.010.711.340.400.671430
    WINGS/BTC-0.020.561.970.800.652742
    VIBE/BTC-0.020.830.910.200.591235
    MCO/BTC-0.020.790.970.270.551431
    GNT/BTC-0.020.502.061.000.531824
    HOT/BTC-0.010.177.724.810.502097
    SNM/BTC-0.030.711.060.420.451738
    APPC/BTC-0.020.442.281.270.442543
    NEBL/BTC-0.030.631.290.580.441959
    +

    Edge produced the above table by comparing calculate_since_number_of_days to minimum_expectancy to find min_trade_number historical information based on the config file. The timerange Edge uses for its comparisons can be further limited by using the --timerange switch.

    +

    In live and dry-run modes, after the process_throttle_secs has passed, Edge will again process calculate_since_number_of_days against minimum_expectancy to find min_trade_number. If no min_trade_number is found, the bot will return "whitelist empty". Depending on the trade strategy being deployed, "whitelist empty" may be return much of the time - or all of the time. The use of Edge may also cause trading to occur in bursts, though this is rare.

    +

    If you encounter "whitelist empty" a lot, condsider tuning calculate_since_number_of_days, minimum_expectancy and min_trade_number to align to the trading frequency of your strategy.

    +

    Update cached pairs with the latest data

    +

    Edge requires historic data the same way as backtesting does. +Please refer to the Data Downloading section of the documentation for details.

    +

    Precising stoploss range

    +

    bash +freqtrade edge --stoplosses=-0.01,-0.1,-0.001 #min,max,step

    +

    Advanced use of timerange

    +

    bash +freqtrade edge --timerange=20181110-20181113

    +

    Doing --timerange=-20190901 will get all available data until September 1st (excluding September 1st 2019).

    +

    The full timerange specification:

    +
      +
    • Use tickframes till 2018/01/31: --timerange=-20180131
    • +
    • Use tickframes since 2018/01/31: --timerange=20180131-
    • +
    • Use tickframes since 2018/01/31 till 2018/03/01 : --timerange=20180131-20180301
    • +
    • Use tickframes between POSIX timestamps 1527595200 1527618600: --timerange=1527595200-1527618600
    • +
    +
    +
    +
      +
    1. +

      Question extracted from MIT Opencourseware S096 - Mathematics with applications in Finance: https://ocw.mit.edu/courses/mathematics/18-s096-topics-in-mathematics-with-applications-in-finance-fall-2013/ 

      +
    2. +
    +
    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/exchanges/index.html b/en/2021.7/exchanges/index.html new file mode 100644 index 000000000..72e08c94b --- /dev/null +++ b/en/2021.7/exchanges/index.html @@ -0,0 +1,1382 @@ + + + + + + + + + + + + + + + + + + + Exchange-specific Notes - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + + + + + + +

    Exchange-specific Notes

    +

    This page combines common gotchas and informations which are exchange-specific and most likely don't apply to other exchanges.

    +

    Binance

    +
    +

    Stoploss on Exchange

    +

    Binance supports stoploss_on_exchange and uses stop-loss-limit orders. It provides great advantages, so we recommend to benefit from it.

    +
    +

    Binance Blacklist

    +

    For Binance, please add "BNB/<STAKE>" to your blacklist to avoid issues. +Accounts having BNB accounts use this to pay for fees - if your first trade happens to be on BNB, further trades will consume this position and make the initial BNB trade unsellable as the expected amount is not there anymore.

    +

    Binance sites

    +

    Binance has been split into 2, and users must use the correct ccxt exchange ID for their exchange, otherwise API keys are not recognized.

    +
      +
    • binance.com - International users. Use exchange id: binance.
    • +
    • binance.us - US based users. Use exchange id: binanceus.
    • +
    +

    Kraken

    +
    +

    Stoploss on Exchange

    +

    Kraken supports stoploss_on_exchange and can use both stop-loss-market and stop-loss-limit orders. It provides great advantages, so we recommend to benefit from it. +You can use either "limit" or "market" in the order_types.stoploss configuration setting to decide which type to use.

    +
    +

    Historic Kraken data

    +

    The Kraken API does only provide 720 historic candles, which is sufficient for Freqtrade dry-run and live trade modes, but is a problem for backtesting. +To download data for the Kraken exchange, using --dl-trades is mandatory, otherwise the bot will download the same 720 candles over and over, and you'll not have enough backtest data.

    +

    Due to the heavy rate-limiting applied by Kraken, the following configuration section should be used to download data:

    +

    json + "ccxt_async_config": { + "enableRateLimit": true, + "rateLimit": 3100 + },

    +
    +

    Downloading data from kraken

    +

    Downloading kraken data will require significantly more memory (RAM) than any other exchange, as the trades-data needs to be converted into candles on your machine. +It will also take a long time, as freqtrade will need to download every single trade that happened on the exchange for the pair / timerange combination, therefore please be patient.

    +
    +
    +

    rateLimit tuning

    +

    Please pay attention that rateLimit configuration entry holds delay in milliseconds between requests, NOT requests\sec rate. +So, in order to mitigate Kraken API "Rate limit exceeded" exception, this configuration should be increased, NOT decreased.

    +
    +

    Bittrex

    +

    Order types

    +

    Bittrex does not support market orders. If you have a message at the bot startup about this, you should change order type values set in your configuration and/or in the strategy from "market" to "limit". See some more details on this here in the FAQ.

    +

    Bittrex also does not support VolumePairlist due to limited / split API constellation at the moment. +Please use StaticPairlist. Other pairlists (other than VolumePairlist) should not be affected.

    +

    Restricted markets

    +

    Bittrex split its exchange into US and International versions. +The International version has more pairs available, however the API always returns all pairs, so there is currently no automated way to detect if you're affected by the restriction.

    +

    If you have restricted pairs in your whitelist, you'll get a warning message in the log on Freqtrade startup for each restricted pair.

    +

    The warning message will look similar to the following:

    +

    output +[...] Message: bittrex {"success":false,"message":"RESTRICTED_MARKET","result":null,"explanation":null}"

    +

    If you're an "International" customer on the Bittrex exchange, then this warning will probably not impact you. +If you're a US customer, the bot will fail to create orders for these pairs, and you should remove them from your whitelist.

    +

    You can get a list of restricted markets by using the following snippet:

    +

    ``` python +import ccxt +ct = ccxt.bittrex() +lm = ct.load_markets()

    +

    res = [p for p, x in lm.items() if 'US' in x['info']['prohibitedIn']] +print(res) +```

    +

    FTX

    +
    +

    Stoploss on Exchange

    +

    FTX supports stoploss_on_exchange and can use both stop-loss-market and stop-loss-limit orders. It provides great advantages, so we recommend to benefit from it. +You can use either "limit" or "market" in the order_types.stoploss configuration setting to decide which type of stoploss shall be used.

    +
    +

    Using subaccounts

    +

    To use subaccounts with FTX, you need to edit the configuration and add the following:

    +

    json +"exchange": { + "ccxt_config": { + "headers": { + "FTX-SUBACCOUNT": "name" + } + }, +}

    +

    Kucoin

    +

    Kucoin requries a passphrase for each api key, you will therefore need to add this key into the configuration so your exchange section looks as follows:

    +

    json +"exchange": { + "name": "kucoin", + "key": "your_exchange_key", + "secret": "your_exchange_secret", + "password": "your_exchange_api_key_password",

    +

    Kucoin Blacklists

    +

    For Kucoin, please add "KCS/<STAKE>" to your blacklist to avoid issues. +Accounts having KCS accounts use this to pay for fees - if your first trade happens to be on KCS, further trades will consume this position and make the initial KCS trade unsellable as the expected amount is not there anymore.

    +

    All exchanges

    +

    Should you experience constant errors with Nonce (like InvalidNonce), it is best to regenerate the API keys. Resetting Nonce is difficult and it's usually easier to regenerate the API keys.

    +

    Random notes for other exchanges

    +
      +
    • The Ocean (exchange id: theocean) exchange uses Web3 functionality and requires web3 python package to be installed:
    • +
    +

    shell +$ pip3 install web3

    +

    Getting latest price / Incomplete candles

    +

    Most exchanges return current incomplete candle via their OHLCV/klines API interface. +By default, Freqtrade assumes that incomplete candle is fetched from the exchange and removes the last candle assuming it's the incomplete candle.

    +

    Whether your exchange returns incomplete candles or not can be checked using the helper script from the Contributor documentation.

    +

    Due to the danger of repainting, Freqtrade does not allow you to use this incomplete candle.

    +

    However, if it is based on the need for the latest price for your strategy - then this requirement can be acquired using the data provider from within the strategy.

    +

    Advanced Freqtrade Exchange configuration

    +

    Advanced options can be configured using the _ft_has_params setting, which will override Defaults and exchange-specific behavior.

    +

    Available options are listed in the exchange-class as _ft_has_default.

    +

    For example, to test the order type FOK with Kraken, and modify candle limit to 200 (so you only get 200 candles per API call):

    +

    json +"exchange": { + "name": "kraken", + "_ft_has_params": { + "order_time_in_force": ["gtc", "fok"], + "ohlcv_candle_limit": 200 + }

    +
    +

    Warning

    +

    Please make sure to fully understand the impacts of these settings before modifying them.

    +
    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/faq/index.html b/en/2021.7/faq/index.html new file mode 100644 index 000000000..3ef988ae8 --- /dev/null +++ b/en/2021.7/faq/index.html @@ -0,0 +1,1484 @@ + + + + + + + + + + + + + + + + + + + FAQ - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + + + + +
    +
    + + + + + + + +

    Freqtrade FAQ

    +

    Supported Markets

    +

    Freqtrade supports spot trading only.

    +

    Can I open short positions?

    +

    No, Freqtrade does not support trading with margin / leverage, and cannot open short positions.

    +

    In some cases, your exchange may provide leveraged spot tokens which can be traded with Freqtrade eg. BTCUP/USD, BTCDOWN/USD, ETHBULL/USD, ETHBEAR/USD, etc...

    +

    Can I trade options or futures?

    +

    No, options and futures trading are not supported.

    +

    Beginner Tips & Tricks

    +
      +
    • When you work with your strategy & hyperopt file you should use a proper code editor like VSCode or PyCharm. A good code editor will provide syntax highlighting as well as line numbers, making it easy to find syntax errors (most likely pointed out by Freqtrade during startup).
    • +
    +

    Freqtrade common issues

    +

    The bot does not start

    +

    Running the bot with freqtrade trade --config config.json shows the output freqtrade: command not found.

    +

    This could be caused by the following reasons:

    +
      +
    • The virtual environment is not active.
        +
      • Run source .env/bin/activate to activate the virtual environment.
      • +
      +
    • +
    • The installation did not work correctly. +
    • +
    +

    I have waited 5 minutes, why hasn't the bot made any trades yet?

    +
      +
    • Depending on the buy strategy, the amount of whitelisted coins, the +situation of the market etc, it can take up to hours to find a good entry +position for a trade. Be patient!
    • +
    +
      +
    • It may be because of a configuration error. It's best to check the logs, they usually tell you if the bot is simply not getting buy signals (only heartbeat messages), or if there is something wrong (errors / exceptions in the log).
    • +
    +

    I have made 12 trades already, why is my total profit negative?

    +

    I understand your disappointment but unfortunately 12 trades is just +not enough to say anything. If you run backtesting, you can see that our +current algorithm does leave you on the plus side, but that is after +thousands of trades and even there, you will be left with losses on +specific coins that you have traded tens if not hundreds of times. We +of course constantly aim to improve the bot but it will always be a +gamble, which should leave you with modest wins on monthly basis but +you can't say much from few trades.

    +

    I’d like to make changes to the config. Can I do that without having to kill the bot?

    +

    Yes. You can edit your config and use the /reload_config command to reload the configuration. The bot will stop, reload the configuration and strategy and will restart with the new configuration and strategy.

    +

    I want to improve the bot with a new strategy

    +

    That's great. We have a nice backtesting and hyperoptimization setup. See the tutorial here|Testing-new-strategies-with-Hyperopt.

    +

    Is there a setting to only SELL the coins being held and not perform anymore BUYS?

    +

    You can use the /stopbuy command in Telegram to prevent future buys, followed by /forcesell all (sell all open trades).

    +

    I want to run multiple bots on the same machine

    +

    Please look at the advanced setup documentation Page.

    +

    I'm getting "Missing data fillup" messages in the log

    +

    This message is just a warning that the latest candles had missing candles in them. +Depending on the exchange, this can indicate that the pair didn't have a trade for the timeframe you are using - and the exchange does only return candles with volume. +On low volume pairs, this is a rather common occurrence.

    +

    If this happens for all pairs in the pairlist, this might indicate a recent exchange downtime. Please check your exchange's public channels for details.

    +

    Irrespectively of the reason, Freqtrade will fill up these candles with "empty" candles, where open, high, low and close are set to the previous candle close - and volume is empty. In a chart, this will look like a _ - and is aligned with how exchanges usually represent 0 volume candles.

    +

    I'm getting the "RESTRICTED_MARKET" message in the log

    +

    Currently known to happen for US Bittrex users.

    +

    Read the Bittrex section about restricted markets for more information.

    +

    I'm getting the "Exchange Bittrex does not support market orders." message and cannot run my strategy

    +

    As the message says, Bittrex does not support market orders and you have one of the order types set to "market". Your strategy was probably written with other exchanges in mind and sets "market" orders for "stoploss" orders, which is correct and preferable for most of the exchanges supporting market orders (but not for Bittrex).

    +

    To fix it for Bittrex, redefine order types in the strategy to use "limit" instead of "market":

    +

    order_types = { + ... + 'stoploss': 'limit', + ... + }

    +

    The same fix should be applied in the configuration file, if order types are defined in your custom config rather than in the strategy.

    +

    How do I search the bot logs for something?

    +

    By default, the bot writes its log into stderr stream. This is implemented this way so that you can easily separate the bot's diagnostics messages from Backtesting, Edge and Hyperopt results, output from other various Freqtrade utility sub-commands, as well as from the output of your custom print()'s you may have inserted into your strategy. So if you need to search the log messages with the grep utility, you need to redirect stderr to stdout and disregard stdout.

    +
      +
    • In unix shells, this normally can be done as simple as: +shell +$ freqtrade --some-options 2>&1 >/dev/null | grep 'something' +(note, 2>&1 and >/dev/null should be written in this order)
    • +
    +
      +
    • Bash interpreter also supports so called process substitution syntax, you can grep the log for a string with it as: +shell +$ freqtrade --some-options 2> >(grep 'something') >/dev/null +or +shell +$ freqtrade --some-options 2> >(grep -v 'something' 1>&2)
    • +
    +
      +
    • You can also write the copy of Freqtrade log messages to a file with the --logfile option: +shell +$ freqtrade --logfile /path/to/mylogfile.log --some-options +and then grep it as: +shell +$ cat /path/to/mylogfile.log | grep 'something' +or even on the fly, as the bot works and the log file grows: +shell +$ tail -f /path/to/mylogfile.log | grep 'something' +from a separate terminal window.
    • +
    +

    On Windows, the --logfile option is also supported by Freqtrade and you can use the findstr command to search the log for the string of interest: +```

    +
    +

    type \path\to\mylogfile.log | findstr "something" +```

    +
    +

    Why does freqtrade not have GPU support?

    +

    First of all, most indicator libraries don't have GPU support - as such, there would be little benefit for indicator calculations. +The GPU improvements would only apply to pandas-native calculations - or ones written by yourself.

    +

    For hyperopt, freqtrade is using scikit-optimize, which is built on top of scikit-learn. +Their statement about GPU support is pretty clear.

    +

    GPU's also are only good at crunching numbers (floating point operations). +For hyperopt, we need both number-crunching (find next parameters) and running python code (running backtesting). +As such, GPU's are not too well suited for most parts of hyperopt.

    +

    The benefit of using GPU would therefore be pretty slim - and will not justify the complexity introduced by trying to add GPU support.

    +

    There is however nothing preventing you from using GPU-enabled indicators within your strategy if you think you must have this - you will however probably be disappointed by the slim gain that will give you (compared to the complexity).

    +

    Hyperopt module

    +

    How many epochs do I need to get a good Hyperopt result?

    +

    Per default Hyperopt called without the -e/--epochs command line option will only +run 100 epochs, means 100 evaluations of your triggers, guards, ... Too few +to find a great result (unless if you are very lucky), so you probably +have to run it for 10.000 or more. But it will take an eternity to +compute.

    +

    Since hyperopt uses Bayesian search, running for too many epochs may not produce greater results.

    +

    It's therefore recommended to run between 500-1000 epochs over and over until you hit at least 10.000 epochs in total (or are satisfied with the result). You can best judge by looking at the results - if the bot keeps discovering better strategies, it's best to keep on going.

    +

    bash +freqtrade hyperopt --hyperopt SampleHyperopt --hyperopt-loss SharpeHyperOptLossDaily --strategy SampleStrategy -e 1000

    +

    Why does it take a long time to run hyperopt?

    +
      +
    • Discovering a great strategy with Hyperopt takes time. Study www.freqtrade.io, the Freqtrade Documentation page, join the Freqtrade discord community. While you patiently wait for the most advanced, free crypto bot in the world, to hand you a possible golden strategy specially designed just for you.
    • +
    +
      +
    • If you wonder why it can take from 20 minutes to days to do 1000 epochs here are some answers:
    • +
    +

    This answer was written during the release 0.15.1, when we had:

    +
      +
    • 8 triggers
    • +
    • 9 guards: let's say we evaluate even 10 values from each
    • +
    • 1 stoploss calculation: let's say we want 10 values from that too to be evaluated
    • +
    +

    The following calculation is still very rough and not very precise +but it will give the idea. With only these triggers and guards there is +already 8*10^9*10 evaluations. A roughly total of 80 billion evaluations. +Did you run 100 000 evaluations? Congrats, you've done roughly 1 / 100 000 th +of the search space, assuming that the bot never tests the same parameters more than once.

    +
      +
    • The time it takes to run 1000 hyperopt epochs depends on things like: The available cpu, hard-disk, ram, timeframe, timerange, indicator settings, indicator count, amount of coins that hyperopt test strategies on and the resulting trade count - which can be 650 trades in a year or 10.0000 trades depending if the strategy aims for big profits by trading rarely or for many low profit trades.
    • +
    +

    Example: 4% profit 650 times vs 0,3% profit a trade 10.000 times in a year. If we assume you set the --timerange to 365 days.

    +

    Example: +freqtrade --config config.json --strategy SampleStrategy --hyperopt SampleHyperopt -e 1000 --timerange 20190601-20200601

    +

    Edge module

    +

    Edge implements interesting approach for controlling position size, is there any theory behind it?

    +

    The Edge module is mostly a result of brainstorming of @mishaker and @creslinux freqtrade team members.

    +

    You can find further info on expectancy, win rate, risk management and position size in the following sources:

    + + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/hyperopt/index.html b/en/2021.7/hyperopt/index.html new file mode 100644 index 000000000..98b5ee262 --- /dev/null +++ b/en/2021.7/hyperopt/index.html @@ -0,0 +1,1742 @@ + + + + + + + + + + + + + + + + + + + Hyperopt - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + + + + + + +

    Hyperopt

    +

    This page explains how to tune your strategy by finding the optimal +parameters, a process called hyperparameter optimization. The bot uses algorithms included in the scikit-optimize package to accomplish this. +The search will burn all your CPU cores, make your laptop sound like a fighter jet and still take a long time.

    +

    In general, the search for best parameters starts with a few random combinations (see below for more details) and then uses Bayesian search with a ML regressor algorithm (currently ExtraTreesRegressor) to quickly find a combination of parameters in the search hyperspace that minimizes the value of the loss function.

    +

    Hyperopt requires historic data to be available, just as backtesting does (hyperopt runs backtesting many times with different parameters). +To learn how to get data for the pairs and exchange you're interested in, head over to the Data Downloading section of the documentation.

    +
    +

    Bug

    +

    Hyperopt can crash when used with only 1 CPU Core as found out in Issue #1133

    +
    +
    +

    Note

    +

    Since 2021.4 release you no longer have to write a separate hyperopt class, but can configure the parameters directly in the strategy. +The legacy method is still supported, but it is no longer the recommended way of setting up hyperopt. +The legacy documentation is available at Legacy Hyperopt.

    +
    +

    Install hyperopt dependencies

    +

    Since Hyperopt dependencies are not needed to run the bot itself, are heavy, can not be easily built on some platforms (like Raspberry PI), they are not installed by default. Before you run Hyperopt, you need to install the corresponding dependencies, as described in this section below.

    +
    +

    Note

    +

    Since Hyperopt is a resource intensive process, running it on a Raspberry Pi is not recommended nor supported.

    +
    +

    Docker

    +

    The docker-image includes hyperopt dependencies, no further action needed.

    +

    Easy installation script (setup.sh) / Manual installation

    +

    bash +source .env/bin/activate +pip install -r requirements-hyperopt.txt

    +

    Hyperopt command reference

    +

    ``` +usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] + [--userdir PATH] [-s NAME] [--strategy-path PATH] + [-i TIMEFRAME] [--timerange TIMERANGE] + [--data-format-ohlcv {json,jsongz,hdf5}] + [--max-open-trades INT] + [--stake-amount STAKE_AMOUNT] [--fee FLOAT] + [-p PAIRS [PAIRS ...]] [--hyperopt NAME] + [--hyperopt-path PATH] [--eps] [--dmmp] + [--enable-protections] + [--dry-run-wallet DRY_RUN_WALLET] [-e INT] + [--spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...]] + [--print-all] [--no-color] [--print-json] [-j JOBS] + [--random-state INT] [--min-trades INT] + [--hyperopt-loss NAME] [--disable-param-export]

    +

    optional arguments: + -h, --help show this help message and exit + -i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME + Specify timeframe (1m, 5m, 30m, 1h, 1d). + --timerange TIMERANGE + Specify what timerange of data to use. + --data-format-ohlcv {json,jsongz,hdf5} + Storage format for downloaded candle (OHLCV) data. + (default: None). + --max-open-trades INT + Override the value of the max_open_trades + configuration setting. + --stake-amount STAKE_AMOUNT + Override the value of the stake_amount configuration + setting. + --fee FLOAT Specify fee ratio. Will be applied twice (on trade + entry and exit). + -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] + Limit command to these pairs. Pairs are space- + separated. + --hyperopt NAME Specify hyperopt class name which will be used by the + bot. + --hyperopt-path PATH Specify additional lookup path for Hyperopt and + Hyperopt Loss functions. + --eps, --enable-position-stacking + Allow buying the same pair multiple times (position + stacking). + --dmmp, --disable-max-market-positions + Disable applying max_open_trades during backtest + (same as setting max_open_trades to a very high + number). + --enable-protections, --enableprotections + Enable protections for backtesting.Will slow + backtesting down by a considerable amount, but will + include configured protections + --dry-run-wallet DRY_RUN_WALLET, --starting-balance DRY_RUN_WALLET + Starting balance, used for backtesting / hyperopt and + dry-runs. + -e INT, --epochs INT Specify number of epochs (default: 100). + --spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...] + Specify which parameters to hyperopt. Space-separated + list. + --print-all Print all results, not only the best ones. + --no-color Disable colorization of hyperopt results. May be + useful if you are redirecting output to a file. + --print-json Print output in JSON format. + -j JOBS, --job-workers JOBS + The number of concurrently running jobs for + hyperoptimization (hyperopt worker processes). If -1 + (default), all CPUs are used, for -2, all CPUs but one + are used, etc. If 1 is given, no parallel computing + code is used at all. + --random-state INT Set random state to some positive integer for + reproducible hyperopt results. + --min-trades INT Set minimal desired number of trades for evaluations + in the hyperopt optimization path (default: 1). + --hyperopt-loss NAME, --hyperoptloss NAME + Specify the class name of the hyperopt loss function + class (IHyperOptLoss). Different functions can + generate completely different results, since the + target for optimization is different. Built-in + Hyperopt-loss-functions are: + ShortTradeDurHyperOptLoss, OnlyProfitHyperOptLoss, + SharpeHyperOptLoss, SharpeHyperOptLossDaily, + SortinoHyperOptLoss, SortinoHyperOptLossDaily + --disable-param-export + Disable automatic hyperopt parameter export.

    +

    Common arguments: + -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). + --logfile FILE Log to the file specified. Special values are: + 'syslog', 'journald'. See the documentation for more + details. + -V, --version show program's version number and exit + -c PATH, --config PATH + Specify configuration file (default: + userdir/config.json or config.json whichever + exists). Multiple --config options may be used. Can be + set to - to read config from stdin. + -d PATH, --datadir PATH + Path to directory with historical backtesting data. + --userdir PATH, --user-data-dir PATH + Path to userdata directory.

    +

    Strategy arguments: + -s NAME, --strategy NAME + Specify strategy class name which will be used by the + bot. + --strategy-path PATH Specify additional strategy lookup path.

    +

    ```

    +

    Hyperopt checklist

    +

    Checklist on all tasks / possibilities in hyperopt

    +

    Depending on the space you want to optimize, only some of the below are required:

    +
      +
    • define parameters with space='buy' - for buy signal optimization
    • +
    • define parameters with space='sell' - for sell signal optimization
    • +
    +
    +

    Note

    +

    populate_indicators needs to create all indicators any of the spaces may use, otherwise hyperopt will not work.

    +
    +

    Rarely you may also need to create a nested class named HyperOpt and implement

    +
      +
    • roi_space - for custom ROI optimization (if you need the ranges for the ROI parameters in the optimization hyperspace that differ from default)
    • +
    • generate_roi_table - for custom ROI optimization (if you need the ranges for the values in the ROI table that differ from default or the number of entries (steps) in the ROI table which differs from the default 4 steps)
    • +
    • stoploss_space - for custom stoploss optimization (if you need the range for the stoploss parameter in the optimization hyperspace that differs from default)
    • +
    • trailing_space - for custom trailing stop optimization (if you need the ranges for the trailing stop parameters in the optimization hyperspace that differ from default)
    • +
    +
    +

    Quickly optimize ROI, stoploss and trailing stoploss

    +

    You can quickly optimize the spaces roi, stoploss and trailing without changing anything in your strategy.

    +

    ``` bash

    +

    Have a working strategy at hand.

    +

    freqtrade hyperopt --hyperopt-loss SharpeHyperOptLossDaily --spaces roi stoploss trailing --strategy MyWorkingStrategy --config config.json -e 100 +```

    +
    +

    Hyperopt execution logic

    +

    Hyperopt will first load your data into memory and will then run populate_indicators() once per Pair to generate all indicators.

    +

    Hyperopt will then spawn into different processes (number of processors, or -j <n>), and run backtesting over and over again, changing the parameters that are part of the --spaces defined.

    +

    For every new set of parameters, freqtrade will run first populate_buy_trend() followed by populate_sell_trend(), and then run the regular backtesting process to simulate trades.

    +

    After backtesting, the results are passed into the loss function, which will evaluate if this result was better or worse than previous results.
    +Based on the loss function result, hyperopt will determine the next set of parameters to try in the next round of backtesting.

    +

    Configure your Guards and Triggers

    +

    There are two places you need to change in your strategy file to add a new buy hyperopt for testing:

    +
      +
    • Define the parameters at the class level hyperopt shall be optimizing.
    • +
    • Within populate_buy_trend() - use defined parameter values instead of raw constants.
    • +
    +

    There you have two different types of indicators: 1. guards and 2. triggers.

    +
      +
    1. Guards are conditions like "never buy if ADX < 10", or never buy if current price is over EMA10.
    2. +
    3. Triggers are ones that actually trigger buy in specific moment, like "buy when EMA5 crosses over EMA10" or "buy when close price touches lower Bollinger band".
    4. +
    +
    +

    Guards and Triggers

    +

    Technically, there is no difference between Guards and Triggers.
    +However, this guide will make this distinction to make it clear that signals should not be "sticking". +Sticking signals are signals that are active for multiple candles. This can lead into buying a signal late (right before the signal disappears - which means that the chance of success is a lot lower than right at the beginning).

    +
    +

    Hyper-optimization will, for each epoch round, pick one trigger and possibly multiple guards.

    +

    Sell optimization

    +

    Similar to the buy-signal above, sell-signals can also be optimized. +Place the corresponding settings into the following methods

    +
      +
    • Define the parameters at the class level hyperopt shall be optimizing, either naming them sell_*, or by explicitly defining space='sell'.
    • +
    • Within populate_sell_trend() - use defined parameter values instead of raw constants.
    • +
    +

    The configuration and rules are the same than for buy signals.

    +

    Solving a Mystery

    +

    Let's say you are curious: should you use MACD crossings or lower Bollinger Bands to trigger your buys. +And you also wonder should you use RSI or ADX to help with those buy decisions. +If you decide to use RSI or ADX, which values should I use for them?

    +

    So let's use hyperparameter optimization to solve this mystery.

    +

    Defining indicators to be used

    +

    We start by calculating the indicators our strategy is going to use.

    +

    ``` python +class MyAwesomeStrategy(IStrategy):

    +
    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
    +    """
    +    Generate all indicators used by the strategy
    +    """
    +    dataframe['adx'] = ta.ADX(dataframe)
    +    dataframe['rsi'] = ta.RSI(dataframe)
    +    macd = ta.MACD(dataframe)
    +    dataframe['macd'] = macd['macd']
    +    dataframe['macdsignal'] = macd['macdsignal']
    +    dataframe['macdhist'] = macd['macdhist']
    +
    +    bollinger = ta.BBANDS(dataframe, timeperiod=20, nbdevup=2.0, nbdevdn=2.0)
    +    dataframe['bb_lowerband'] = bollinger['lowerband']
    +    dataframe['bb_middleband'] = bollinger['middleband']
    +    dataframe['bb_upperband'] = bollinger['upperband']
    +    return dataframe
    +
    + +

    ```

    +

    Hyperoptable parameters

    +

    We continue to define hyperoptable parameters:

    +

    python +class MyAwesomeStrategy(IStrategy): + buy_adx = DecimalParameter(20, 40, decimals=1, default=30.1, space="buy") + buy_rsi = IntParameter(20, 40, default=30, space="buy") + buy_adx_enabled = CategoricalParameter([True, False], default=True, space="buy") + buy_rsi_enabled = CategoricalParameter([True, False], default=False, space="buy") + buy_trigger = CategoricalParameter(["bb_lower", "macd_cross_signal"], default="bb_lower", space="buy")

    +

    The above definition says: I have five parameters I want to randomly combine to find the best combination.
    +buy_rsi is an integer parameter, which will be tested between 20 and 40. This space has a size of 20.
    +buy_adx is a decimal parameter, which will be evaluated between 20 and 40 with 1 decimal place (so values are 20.1, 20.2, ...). This space has a size of 200.
    +Then we have three category variables. First two are either True or False. +We use these to either enable or disable the ADX and RSI guards. +The last one we call trigger and use it to decide which buy trigger we want to use.

    +
    +

    Parameter space assignment

    +

    Parameters must either be assigned to a variable named buy_* or sell_* - or contain space='buy' | space='sell' to be assigned to a space correctly. +If no parameter is available for a space, you'll receive the error that no space was found when running hyperopt.

    +
    +

    So let's write the buy strategy using these values:

    +

    ```python + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: + conditions = [] + # GUARDS AND TRENDS + if self.buy_adx_enabled.value: + conditions.append(dataframe['adx'] > self.buy_adx.value) + if self.buy_rsi_enabled.value: + conditions.append(dataframe['rsi'] < self.buy_rsi.value)

    +
        # TRIGGERS
    +    if self.buy_trigger.value == 'bb_lower':
    +        conditions.append(dataframe['close'] < dataframe['bb_lowerband'])
    +    if self.buy_trigger.value == 'macd_cross_signal':
    +        conditions.append(qtpylib.crossed_above(
    +            dataframe['macd'], dataframe['macdsignal']
    +        ))
    +
    +    # Check that volume is not 0
    +    conditions.append(dataframe['volume'] > 0)
    +
    +    if conditions:
    +        dataframe.loc[
    +            reduce(lambda x, y: x & y, conditions),
    +            'buy'] = 1
    +
    +    return dataframe
    +
    + +

    ```

    +

    Hyperopt will now call populate_buy_trend() many times (epochs) with different value combinations.
    +It will use the given historical data and simulate buys based on the buy signals generated with the above function.
    +Based on the results, hyperopt will tell you which parameter combination produced the best results (based on the configured loss function).

    +
    +

    Note

    +

    The above setup expects to find ADX, RSI and Bollinger Bands in the populated indicators. +When you want to test an indicator that isn't used by the bot currently, remember to +add it to the populate_indicators() method in your strategy or hyperopt file.

    +
    +

    Parameter types

    +

    There are four parameter types each suited for different purposes.

    +
      +
    • IntParameter - defines an integral parameter with upper and lower boundaries of search space.
    • +
    • DecimalParameter - defines a floating point parameter with a limited number of decimals (default 3). Should be preferred instead of RealParameter in most cases.
    • +
    • RealParameter - defines a floating point parameter with upper and lower boundaries and no precision limit. Rarely used as it creates a space with a near infinite number of possibilities.
    • +
    • CategoricalParameter - defines a parameter with a predetermined number of choices.
    • +
    +
    +

    Disabling parameter optimization

    +

    Each parameter takes two boolean parameters: +* load - when set to False it will not load values configured in buy_params and sell_params. +* optimize - when set to False parameter will not be included in optimization process. +Use these parameters to quickly prototype various ideas.

    +
    +
    +

    Warning

    +

    Hyperoptable parameters cannot be used in populate_indicators - as hyperopt does not recalculate indicators for each epoch, so the starting value would be used in this case.

    +
    +

    Optimizing an indicator parameter

    +

    Assuming you have a simple strategy in mind - a EMA cross strategy (2 Moving averages crossing) - and you'd like to find the ideal parameters for this strategy.

    +

    ``` python +from pandas import DataFrame +from functools import reduce

    +

    import talib.abstract as ta

    +

    from freqtrade.strategy import IStrategy +from freqtrade.strategy import CategoricalParameter, DecimalParameter, IntParameter +import freqtrade.vendor.qtpylib.indicators as qtpylib

    +

    class MyAwesomeStrategy(IStrategy): + stoploss = -0.05 + timeframe = '15m' + # Define the parameter spaces + buy_ema_short = IntParameter(3, 50, default=5) + buy_ema_long = IntParameter(15, 200, default=50)

    +
    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
    +    """Generate all indicators used by the strategy"""
    +
    +    # Calculate all ema_short values
    +    for val in self.buy_ema_short.range:
    +        dataframe[f'ema_short_{val}'] = ta.EMA(dataframe, timeperiod=val)
    +
    +    # Calculate all ema_long values
    +    for val in self.buy_ema_long.range:
    +        dataframe[f'ema_long_{val}'] = ta.EMA(dataframe, timeperiod=val)
    +
    +    return dataframe
    +
    +def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
    +    conditions = []
    +    conditions.append(qtpylib.crossed_above(
    +            dataframe[f'ema_short_{self.buy_ema_short.value}'], dataframe[f'ema_long_{self.buy_ema_long.value}']
    +        ))
    +
    +    # Check that volume is not 0
    +    conditions.append(dataframe['volume'] > 0)
    +
    +    if conditions:
    +        dataframe.loc[
    +            reduce(lambda x, y: x & y, conditions),
    +            'buy'] = 1
    +    return dataframe
    +
    +def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
    +    conditions = []
    +    conditions.append(qtpylib.crossed_above(
    +            dataframe[f'ema_long_{self.buy_ema_long.value}'], dataframe[f'ema_short_{self.buy_ema_short.value}']
    +        ))
    +
    +    # Check that volume is not 0
    +    conditions.append(dataframe['volume'] > 0)
    +
    +    if conditions:
    +        dataframe.loc[
    +            reduce(lambda x, y: x & y, conditions),
    +            'sell'] = 1
    +    return dataframe
    +
    + +

    ```

    +

    Breaking it down:

    +

    Using self.buy_ema_short.range will return a range object containing all entries between the Parameters low and high value. +In this case (IntParameter(3, 50, default=5)), the loop would run for all numbers between 3 and 50 ([3, 4, 5, ... 49, 50]). +By using this in a loop, hyperopt will generate 48 new columns (['buy_ema_3', 'buy_ema_4', ... , 'buy_ema_50']).

    +

    Hyperopt itself will then use the selected value to create the buy and sell signals

    +

    While this strategy is most likely too simple to provide consistent profit, it should serve as an example how optimize indicator parameters.

    +
    +

    Note

    +

    self.buy_ema_short.range will act differently between hyperopt and other modes. For hyperopt, the above example may generate 48 new columns, however for all other modes (backtesting, dry/live), it will only generate the column for the selected value. You should therefore avoid using the resulting column with explicit values (values other than self.buy_ema_short.value).

    +
    +
    +

    Note

    +

    range property may also be used with DecimalParameter and CategoricalParameter. RealParameter does not provide this property due to infinite search space.

    +
    +
    +Performance tip +

    By doing the calculation of all possible indicators in populate_indicators(), the calculation of the indicator happens only once for every parameter.
    +While this may slow down the hyperopt startup speed, the overall performance will increase as the Hyperopt execution itself may pick the same value for multiple epochs (changing other values). +You should however try to use space ranges as small as possible. Every new column will require more memory, and every possibility hyperopt can try will increase the search space.

    +
    +

    Loss-functions

    +

    Each hyperparameter tuning requires a target. This is usually defined as a loss function (sometimes also called objective function), which should decrease for more desirable results, and increase for bad results.

    +

    A loss function must be specified via the --hyperopt-loss <Class-name> argument (or optionally via the configuration under the "hyperopt_loss" key). +This class should be in its own file within the user_data/hyperopts/ directory.

    +

    Currently, the following loss functions are builtin:

    +
      +
    • ShortTradeDurHyperOptLoss (default legacy Freqtrade hyperoptimization loss function) - Mostly for short trade duration and avoiding losses.
    • +
    • OnlyProfitHyperOptLoss (which takes only amount of profit into consideration)
    • +
    • SharpeHyperOptLoss (optimizes Sharpe Ratio calculated on trade returns relative to standard deviation)
    • +
    • SharpeHyperOptLossDaily (optimizes Sharpe Ratio calculated on daily trade returns relative to standard deviation)
    • +
    • SortinoHyperOptLoss (optimizes Sortino Ratio calculated on trade returns relative to downside standard deviation)
    • +
    • SortinoHyperOptLossDaily (optimizes Sortino Ratio calculated on daily trade returns relative to downside standard deviation)
    • +
    +

    Creation of a custom loss function is covered in the Advanced Hyperopt part of the documentation.

    +

    Execute Hyperopt

    +

    Once you have updated your hyperopt configuration you can run it. +Because hyperopt tries a lot of combinations to find the best parameters it will take time to get a good result.

    +

    We strongly recommend to use screen or tmux to prevent any connection loss.

    +

    bash +freqtrade hyperopt --config config.json --hyperopt-loss <hyperoptlossname> --strategy <strategyname> -e 500 --spaces all

    +

    The -e option will set how many evaluations hyperopt will do. Since hyperopt uses Bayesian search, running too many epochs at once may not produce greater results. Experience has shown that best results are usually not improving much after 500-1000 epochs.
    +Doing multiple runs (executions) with a few 1000 epochs and different random state will most likely produce different results.

    +

    The --spaces all option determines that all possible parameters should be optimized. Possibilities are listed below.

    +
    +

    Note

    +

    Hyperopt will store hyperopt results with the timestamp of the hyperopt start time. +Reading commands (hyperopt-list, hyperopt-show) can use --hyperopt-filename <filename> to read and display older hyperopt results. +You can find a list of filenames with ls -l user_data/hyperopt_results/.

    +
    +

    Execute Hyperopt with different historical data source

    +

    If you would like to hyperopt parameters using an alternate historical data set that +you have on-disk, use the --datadir PATH option. By default, hyperopt uses data from directory user_data/data.

    +

    Running Hyperopt with a smaller test-set

    +

    Use the --timerange argument to change how much of the test-set you want to use. +For example, to use one month of data, pass --timerange 20210101-20210201 (from january 2021 - february 2021) to the hyperopt call.

    +

    Full command:

    +

    bash +freqtrade hyperopt --hyperopt <hyperoptname> --strategy <strategyname> --timerange 20210101-20210201

    +

    Running Hyperopt with Smaller Search Space

    +

    Use the --spaces option to limit the search space used by hyperopt. +Letting Hyperopt optimize everything is a huuuuge search space. +Often it might make more sense to start by just searching for initial buy algorithm. +Or maybe you just want to optimize your stoploss or roi table for that awesome new buy strategy you have.

    +

    Legal values are:

    +
      +
    • all: optimize everything
    • +
    • buy: just search for a new buy strategy
    • +
    • sell: just search for a new sell strategy
    • +
    • roi: just optimize the minimal profit table for your strategy
    • +
    • stoploss: search for the best stoploss value
    • +
    • trailing: search for the best trailing stop values
    • +
    • default: all except trailing
    • +
    • space-separated list of any of the above values for example --spaces roi stoploss
    • +
    +

    The default Hyperopt Search Space, used when no --space command line option is specified, does not include the trailing hyperspace. We recommend you to run optimization for the trailing hyperspace separately, when the best parameters for other hyperspaces were found, validated and pasted into your custom strategy.

    +

    Understand the Hyperopt Result

    +

    Once Hyperopt is completed you can use the result to update your strategy. +Given the following result from hyperopt:

    +

    ``` +Best result:

    +
    44/100:    135 trades. Avg profit  0.57%. Total profit  0.03871918 BTC (0.7722%). Avg duration 180.4 mins. Objective: 1.94367
    +
    +# Buy hyperspace params:
    +buy_params = {
    +    'buy_adx': 44,
    +    'buy_rsi': 29,
    +    'buy_adx_enabled': False,
    +    'buy_rsi_enabled': True,
    +    'buy_trigger': 'bb_lower'
    +}
    +
    + +

    ```

    +

    You should understand this result like:

    +
      +
    • The buy trigger that worked best was bb_lower.
    • +
    • You should not use ADX because 'buy_adx_enabled': False.
    • +
    • You should consider using the RSI indicator ('buy_rsi_enabled': True) and the best value is 29.0 ('buy_rsi': 29.0)
    • +
    +

    Automatic parameter application to the strategy

    +

    When using Hyperoptable parameters, the result of your hyperopt-run will be written to a json file next to your strategy (so for MyAwesomeStrategy.py, the file would be MyAwesomeStrategy.json).
    +This file is also updated when using the hyperopt-show sub-command, unless --disable-param-export is provided to either of the 2 commands.

    +

    Your strategy class can also contain these results explicitly. Simply copy hyperopt results block and paste them at class level, replacing old parameters (if any). New parameters will automatically be loaded next time strategy is executed.

    +

    Transferring your whole hyperopt result to your strategy would then look like:

    +

    python +class MyAwesomeStrategy(IStrategy): + # Buy hyperspace params: + buy_params = { + 'buy_adx': 44, + 'buy_rsi': 29, + 'buy_adx_enabled': False, + 'buy_rsi_enabled': True, + 'buy_trigger': 'bb_lower' + }

    +
    +

    Note

    +

    Values in the configuration file will overwrite Parameter-file level parameters - and both will overwrite parameters within the strategy. +The prevalence is therefore: config > parameter file > strategy

    +
    +

    Understand Hyperopt ROI results

    +

    If you are optimizing ROI (i.e. if optimization search-space contains 'all', 'default' or 'roi'), your result will look as follows and include a ROI table:

    +

    ``` +Best result:

    +
    44/100:    135 trades. Avg profit  0.57%. Total profit  0.03871918 BTC (0.7722%). Avg duration 180.4 mins. Objective: 1.94367
    +
    +# ROI table:
    +minimal_roi = {
    +    0: 0.10674,
    +    21: 0.09158,
    +    78: 0.03634,
    +    118: 0
    +}
    +
    + +

    ```

    +

    In order to use this best ROI table found by Hyperopt in backtesting and for live trades/dry-run, copy-paste it as the value of the minimal_roi attribute of your custom strategy:

    +

    # Minimal ROI designed for the strategy. + # This attribute will be overridden if the config file contains "minimal_roi" + minimal_roi = { + 0: 0.10674, + 21: 0.09158, + 78: 0.03634, + 118: 0 + }

    +

    As stated in the comment, you can also use it as the value of the minimal_roi setting in the configuration file.

    +

    Default ROI Search Space

    +

    If you are optimizing ROI, Freqtrade creates the 'roi' optimization hyperspace for you -- it's the hyperspace of components for the ROI tables. By default, each ROI table generated by the Freqtrade consists of 4 rows (steps). Hyperopt implements adaptive ranges for ROI tables with ranges for values in the ROI steps that depend on the timeframe used. By default the values vary in the following ranges (for some of the most used timeframes, values are rounded to 3 digits after the decimal point):

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    # step1m5m1h1d
    100.011...0.11900.03...0.3100.068...0.71100.121...1.258
    22...80.007...0.04210...400.02...0.11120...4800.045...0.2522880...115200.081...0.446
    34...200.003...0.01520...1000.01...0.04240...12000.022...0.0915760...288000.040...0.162
    46...440.030...2200.0360...26400.08640...633600.0
    +

    These ranges should be sufficient in most cases. The minutes in the steps (ROI dict keys) are scaled linearly depending on the timeframe used. The ROI values in the steps (ROI dict values) are scaled logarithmically depending on the timeframe used.

    +

    If you have the generate_roi_table() and roi_space() methods in your custom hyperopt file, remove them in order to utilize these adaptive ROI tables and the ROI hyperoptimization space generated by Freqtrade by default.

    +

    Override the roi_space() method if you need components of the ROI tables to vary in other ranges. Override the generate_roi_table() and roi_space() methods and implement your own custom approach for generation of the ROI tables during hyperoptimization if you need a different structure of the ROI tables or other amount of rows (steps).

    +

    A sample for these methods can be found in sample_hyperopt_advanced.py.

    +
    +

    Reduced search space

    +

    To limit the search space further, Decimals are limited to 3 decimal places (a precision of 0.001). This is usually sufficient, every value more precise than this will usually result in overfitted results. You can however overriding pre-defined spaces to change this to your needs.

    +
    +

    Understand Hyperopt Stoploss results

    +

    If you are optimizing stoploss values (i.e. if optimization search-space contains 'all', 'default' or 'stoploss'), your result will look as follows and include stoploss:

    +

    ``` +Best result:

    +
    44/100:    135 trades. Avg profit  0.57%. Total profit  0.03871918 BTC (0.7722%). Avg duration 180.4 mins. Objective: 1.94367
    +
    +# Buy hyperspace params:
    +buy_params = {
    +    'buy_adx': 44,
    +    'buy_rsi': 29,
    +    'buy_adx_enabled': False,
    +    'buy_rsi_enabled': True,
    +    'buy_trigger': 'bb_lower'
    +}
    +
    +stoploss: -0.27996
    +
    + +

    ```

    +

    In order to use this best stoploss value found by Hyperopt in backtesting and for live trades/dry-run, copy-paste it as the value of the stoploss attribute of your custom strategy:

    +

    python + # Optimal stoploss designed for the strategy + # This attribute will be overridden if the config file contains "stoploss" + stoploss = -0.27996

    +

    As stated in the comment, you can also use it as the value of the stoploss setting in the configuration file.

    +

    Default Stoploss Search Space

    +

    If you are optimizing stoploss values, Freqtrade creates the 'stoploss' optimization hyperspace for you. By default, the stoploss values in that hyperspace vary in the range -0.35...-0.02, which is sufficient in most cases.

    +

    If you have the stoploss_space() method in your custom hyperopt file, remove it in order to utilize Stoploss hyperoptimization space generated by Freqtrade by default.

    +

    Override the stoploss_space() method and define the desired range in it if you need stoploss values to vary in other range during hyperoptimization. A sample for this method can be found in user_data/hyperopts/sample_hyperopt_advanced.py.

    +
    +

    Reduced search space

    +

    To limit the search space further, Decimals are limited to 3 decimal places (a precision of 0.001). This is usually sufficient, every value more precise than this will usually result in overfitted results. You can however overriding pre-defined spaces to change this to your needs.

    +
    +

    Understand Hyperopt Trailing Stop results

    +

    If you are optimizing trailing stop values (i.e. if optimization search-space contains 'all' or 'trailing'), your result will look as follows and include trailing stop parameters:

    +

    ``` +Best result:

    +
    45/100:    606 trades. Avg profit  1.04%. Total profit  0.31555614 BTC ( 630.48%). Avg duration 150.3 mins. Objective: -1.10161
    +
    +# Trailing stop:
    +trailing_stop = True
    +trailing_stop_positive = 0.02001
    +trailing_stop_positive_offset = 0.06038
    +trailing_only_offset_is_reached = True
    +
    + +

    ```

    +

    In order to use these best trailing stop parameters found by Hyperopt in backtesting and for live trades/dry-run, copy-paste them as the values of the corresponding attributes of your custom strategy:

    +

    python + # Trailing stop + # These attributes will be overridden if the config file contains corresponding values. + trailing_stop = True + trailing_stop_positive = 0.02001 + trailing_stop_positive_offset = 0.06038 + trailing_only_offset_is_reached = True

    +

    As stated in the comment, you can also use it as the values of the corresponding settings in the configuration file.

    +

    Default Trailing Stop Search Space

    +

    If you are optimizing trailing stop values, Freqtrade creates the 'trailing' optimization hyperspace for you. By default, the trailing_stop parameter is always set to True in that hyperspace, the value of the trailing_only_offset_is_reached vary between True and False, the values of the trailing_stop_positive and trailing_stop_positive_offset parameters vary in the ranges 0.02...0.35 and 0.01...0.1 correspondingly, which is sufficient in most cases.

    +

    Override the trailing_space() method and define the desired range in it if you need values of the trailing stop parameters to vary in other ranges during hyperoptimization. A sample for this method can be found in user_data/hyperopts/sample_hyperopt_advanced.py.

    +
    +

    Reduced search space

    +

    To limit the search space further, Decimals are limited to 3 decimal places (a precision of 0.001). This is usually sufficient, every value more precise than this will usually result in overfitted results. You can however overriding pre-defined spaces to change this to your needs.

    +
    +

    Reproducible results

    +

    The search for optimal parameters starts with a few (currently 30) random combinations in the hyperspace of parameters, random Hyperopt epochs. These random epochs are marked with an asterisk character (*) in the first column in the Hyperopt output.

    +

    The initial state for generation of these random values (random state) is controlled by the value of the --random-state command line option. You can set it to some arbitrary value of your choice to obtain reproducible results.

    +

    If you have not set this value explicitly in the command line options, Hyperopt seeds the random state with some random value for you. The random state value for each Hyperopt run is shown in the log, so you can copy and paste it into the --random-state command line option to repeat the set of the initial random epochs used.

    +

    If you have not changed anything in the command line options, configuration, timerange, Strategy and Hyperopt classes, historical data and the Loss Function -- you should obtain same hyper-optimization results with same random state value used.

    +

    Output formatting

    +

    By default, hyperopt prints colorized results -- epochs with positive profit are printed in the green color. This highlighting helps you find epochs that can be interesting for later analysis. Epochs with zero total profit or with negative profits (losses) are printed in the normal color. If you do not need colorization of results (for instance, when you are redirecting hyperopt output to a file) you can switch colorization off by specifying the --no-color option in the command line.

    +

    You can use the --print-all command line option if you would like to see all results in the hyperopt output, not only the best ones. When --print-all is used, current best results are also colorized by default -- they are printed in bold (bright) style. This can also be switched off with the --no-color command line option.

    +
    +

    Windows and color output

    +

    Windows does not support color-output natively, therefore it is automatically disabled. To have color-output for hyperopt running under windows, please consider using WSL.

    +
    +

    Position stacking and disabling max market positions

    +

    In some situations, you may need to run Hyperopt (and Backtesting) with the +--eps/--enable-position-staking and --dmmp/--disable-max-market-positions arguments.

    +

    By default, hyperopt emulates the behavior of the Freqtrade Live Run/Dry Run, where only one +open trade is allowed for every traded pair. The total number of trades open for all pairs +is also limited by the max_open_trades setting. During Hyperopt/Backtesting this may lead to +some potential trades to be hidden (or masked) by previously open trades.

    +

    The --eps/--enable-position-stacking argument allows emulation of buying the same pair multiple times, +while --dmmp/--disable-max-market-positions disables applying max_open_trades +during Hyperopt/Backtesting (which is equal to setting max_open_trades to a very high +number).

    +
    +

    Note

    +

    Dry/live runs will NOT use position stacking - therefore it does make sense to also validate the strategy without this as it's closer to reality.

    +
    +

    You can also enable position stacking in the configuration file by explicitly setting +"position_stacking"=true.

    +

    Out of Memory errors

    +

    As hyperopt consumes a lot of memory (the complete data needs to be in memory once per parallel backtesting process), it's likely that you run into "out of memory" errors. +To combat these, you have multiple options:

    +
      +
    • reduce the amount of pairs
    • +
    • reduce the timerange used (--timerange <timerange>)
    • +
    • reduce the number of parallel processes (-j <n>)
    • +
    • Increase the memory of your machine
    • +
    +

    Show details of Hyperopt results

    +

    After you run Hyperopt for the desired amount of epochs, you can later list all results for analysis, select only best or profitable once, and show the details for any of the epochs previously evaluated. This can be done with the hyperopt-list and hyperopt-show sub-commands. The usage of these sub-commands is described in the Utils chapter.

    +

    Validate backtesting results

    +

    Once the optimized strategy has been implemented into your strategy, you should backtest this strategy to make sure everything is working as expected.

    +

    To achieve same results (number of trades, their durations, profit, etc.) than during Hyperopt, please use same configuration and parameters (timerange, timeframe, ...) used for hyperopt --dmmp/--disable-max-market-positions and --eps/--enable-position-stacking for Backtesting.

    +

    Should results don't match, please double-check to make sure you transferred all conditions correctly. +Pay special care to the stoploss (and trailing stoploss) parameters, as these are often set in configuration files, which override changes to the strategy. +You should also carefully review the log of your backtest to ensure that there were no parameters inadvertently set by the configuration (like stoploss or trailing_stop).

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/images/logo.png b/en/2021.7/images/logo.png new file mode 100644 index 000000000..8a7ffdd70 Binary files /dev/null and b/en/2021.7/images/logo.png differ diff --git a/en/2021.7/includes/pairlists/index.html b/en/2021.7/includes/pairlists/index.html new file mode 100644 index 000000000..09c5edb8d --- /dev/null +++ b/en/2021.7/includes/pairlists/index.html @@ -0,0 +1,1254 @@ + + + + + + + + + + + + + + + + + + + Pairlists - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + + + + +
    +
    + + + + + + + +

    Pairlists

    + +

    Pairlists and Pairlist Handlers

    +

    Pairlist Handlers define the list of pairs (pairlist) that the bot should trade. They are configured in the pairlists section of the configuration settings.

    +

    In your configuration, you can use Static Pairlist (defined by the StaticPairList Pairlist Handler) and Dynamic Pairlist (defined by the VolumePairList Pairlist Handler).

    +

    Additionally, AgeFilter, PrecisionFilter, PriceFilter, ShuffleFilter, SpreadFilter and VolatilityFilter act as Pairlist Filters, removing certain pairs and/or moving their positions in the pairlist.

    +

    If multiple Pairlist Handlers are used, they are chained and a combination of all Pairlist Handlers forms the resulting pairlist the bot uses for trading and backtesting. Pairlist Handlers are executed in the sequence they are configured. You should always configure either StaticPairList or VolumePairList as the starting Pairlist Handler.

    +

    Inactive markets are always removed from the resulting pairlist. Explicitly blacklisted pairs (those in the pair_blacklist configuration setting) are also always removed from the resulting pairlist.

    +

    Pair blacklist

    +

    The pair blacklist (configured via exchange.pair_blacklist in the configuration) disallows certain pairs from trading. +This can be as simple as excluding DOGE/BTC - which will remove exactly this pair.

    +

    The pair-blacklist does also support wildcards (in regex-style) - so BNB/.* will exclude ALL pairs that start with BNB. +You may also use something like .*DOWN/BTC or .*UP/BTC to exclude leveraged tokens (check Pair naming conventions for your exchange!)

    +

    Available Pairlist Handlers

    + +
    +

    Testing pairlists

    +

    Pairlist configurations can be quite tricky to get right. Best use the test-pairlist utility sub-command to test your configuration quickly.

    +
    +

    Static Pair List

    +

    By default, the StaticPairList method is used, which uses a statically defined pair whitelist from the configuration. The pairlist also supports wildcards (in regex-style) - so .*/BTC will include all pairs with BTC as a stake.

    +

    It uses configuration from exchange.pair_whitelist and exchange.pair_blacklist.

    +

    json +"pairlists": [ + {"method": "StaticPairList"} + ],

    +

    By default, only currently enabled pairs are allowed. +To skip pair validation against active markets, set "allow_inactive": true within the StaticPairList configuration. +This can be useful for backtesting expired pairs (like quarterly spot-markets). +This option must be configured along with exchange.skip_pair_validation in the exchange configuration.

    +

    Volume Pair List

    +

    VolumePairList employs sorting/filtering of pairs by their trading volume. It selects number_assets top pairs with sorting based on the sort_key (which can only be quoteVolume).

    +

    When used in the chain of Pairlist Handlers in a non-leading position (after StaticPairList and other Pairlist Filters), VolumePairList considers outputs of previous Pairlist Handlers, adding its sorting/selection of the pairs by the trading volume.

    +

    When used on the leading position of the chain of Pairlist Handlers, it does not consider pair_whitelist configuration setting, but selects the top assets from all available markets (with matching stake-currency) on the exchange.

    +

    The refresh_period setting allows to define the period (in seconds), at which the pairlist will be refreshed. Defaults to 1800s (30 minutes). +The pairlist cache (refresh_period) on VolumePairList is only applicable to generating pairlists. +Filtering instances (not the first position in the list) will not apply any cache and will always use up-to-date data.

    +

    VolumePairList is per default based on the ticker data from exchange, as reported by the ccxt library:

    +
      +
    • The quoteVolume is the amount of quote (stake) currency traded (bought or sold) in last 24 hours.
    • +
    +

    json +"pairlists": [ + { + "method": "VolumePairList", + "number_assets": 20, + "sort_key": "quoteVolume", + "refresh_period": 1800 + } +],

    +

    VolumePairList can also operate in an advanced mode to build volume over a given timerange of specified candle size. It utilizes exchange historical candle data, builds a typical price (calculated by (open+high+low)/3) and multiplies the typical price with every candle's volume. The sum is the quoteVolume over the given range. This allows different scenarios, for a more smoothened volume, when using longer ranges with larger candle sizes, or the opposite when using a short range with small candles.

    +

    For convenience lookback_days can be specified, which will imply that 1d candles will be used for the lookback. In the example below the pairlist would be created based on the last 7 days:

    +

    json +"pairlists": [ + { + "method": "VolumePairList", + "number_assets": 20, + "sort_key": "quoteVolume", + "refresh_period": 86400, + "lookback_days": 7 + } +],

    +
    +

    Range look back and refresh period

    +

    When used in conjunction with lookback_days and lookback_timeframe the refresh_period can not be smaller than the candle size in seconds. As this will result in unnecessary requests to the exchanges API.

    +
    +
    +

    Performance implications when using lookback range

    +

    If used in first position in combination with lookback, the computation of the range based volume can be time and resource consuming, as it downloads candles for all tradable pairs. Hence it's highly advised to use the standard approach with VolumeFilter to narrow the pairlist down for further range volume calculation.

    +
    +

    More sophisticated approach can be used, by using lookback_timeframe for candle size and lookback_period which specifies the amount of candles. This example will build the volume pairs based on a rolling period of 3 days of 1h candles:

    +

    json +"pairlists": [ + { + "method": "VolumePairList", + "number_assets": 20, + "sort_key": "quoteVolume", + "refresh_period": 3600, + "lookback_timeframe": "1h", + "lookback_period": 72 + } +],

    +
    +

    Note

    +

    VolumePairList does not support backtesting mode.

    +
    +

    AgeFilter

    +

    Removes pairs that have been listed on the exchange for less than min_days_listed days (defaults to 10) or more than max_days_listed days (defaults None mean infinity).

    +

    When pairs are first listed on an exchange they can suffer huge price drops and volatility +in the first few days while the pair goes through its price-discovery period. Bots can often +be caught out buying before the pair has finished dropping in price.

    +

    This filter allows freqtrade to ignore pairs until they have been listed for at least min_days_listed days and listed before max_days_listed.

    +

    OffsetFilter

    +

    Offsets an incoming pairlist by a given offset value.

    +

    As an example it can be used in conjunction with VolumeFilter to remove the top X volume pairs. Or to split +a larger pairlist on two bot instances.

    +

    Example to remove the first 10 pairs from the pairlist:

    +

    json +"pairlists": [ + { + "method": "OffsetFilter", + "offset": 10 + } +],

    +
    +

    Warning

    +

    When OffsetFilter is used to split a larger pairlist among multiple bots in combination with VolumeFilter +it can not be guaranteed that pairs won't overlap due to slightly different refresh intervals for the +VolumeFilter.

    +
    +
    +

    Note

    +

    An offset larger then the total length of the incoming pairlist will result in an empty pairlist.

    +
    +

    PerformanceFilter

    +

    Sorts pairs by past trade performance, as follows:

    +
      +
    1. Positive performance.
    2. +
    3. No closed trades yet.
    4. +
    5. Negative performance.
    6. +
    +

    Trade count is used as a tie breaker.

    +
    +

    Note

    +

    PerformanceFilter does not support backtesting mode.

    +
    +

    PrecisionFilter

    +

    Filters low-value coins which would not allow setting stoplosses.

    +

    PriceFilter

    +

    The PriceFilter allows filtering of pairs by price. Currently the following price filters are supported:

    +
      +
    • min_price
    • +
    • max_price
    • +
    • max_value
    • +
    • low_price_ratio
    • +
    +

    The min_price setting removes pairs where the price is below the specified price. This is useful if you wish to avoid trading very low-priced pairs. +This option is disabled by default, and will only apply if set to > 0.

    +

    The max_price setting removes pairs where the price is above the specified price. This is useful if you wish to trade only low-priced pairs. +This option is disabled by default, and will only apply if set to > 0.

    +

    The max_value setting removes pairs where the minimum value change is above a specified value. +This is useful when an exchange has unbalanced limits. For example, if step-size = 1 (so you can only buy 1, or 2, or 3, but not 1.1 Coins) - and the price is pretty high (like 20$) as the coin has risen sharply since the last limit adaption. +As a result of the above, you can only buy for 20$, or 40$ - but not for 25$. +On exchanges that deduct fees from the receiving currency (e.g. FTX) - this can result in high value coins / amounts that are unsellable as the amount is slightly below the limit.

    +

    The low_price_ratio setting removes pairs where a raise of 1 price unit (pip) is above the low_price_ratio ratio. +This option is disabled by default, and will only apply if set to > 0.

    +

    For PriceFiler at least one of its min_price, max_price or low_price_ratio settings must be applied.

    +

    Calculation example:

    +

    Min price precision for SHITCOIN/BTC is 8 decimals. If its price is 0.00000011 - one price step above would be 0.00000012, which is ~9% higher than the previous price value. You may filter out this pair by using PriceFilter with low_price_ratio set to 0.09 (9%) or with min_price set to 0.00000011, correspondingly.

    +
    +

    Low priced pairs

    +

    Low priced pairs with high "1 pip movements" are dangerous since they are often illiquid and it may also be impossible to place the desired stoploss, which can often result in high losses since price needs to be rounded to the next tradable price - so instead of having a stoploss of -5%, you could end up with a stoploss of -9% simply due to price rounding.

    +
    +

    ShuffleFilter

    +

    Shuffles (randomizes) pairs in the pairlist. It can be used for preventing the bot from trading some of the pairs more frequently then others when you want all pairs be treated with the same priority.

    +
    +

    Tip

    +

    You may set the seed value for this Pairlist to obtain reproducible results, which can be useful for repeated backtesting sessions. If seed is not set, the pairs are shuffled in the non-repeatable random order.

    +
    +

    SpreadFilter

    +

    Removes pairs that have a difference between asks and bids above the specified ratio, max_spread_ratio (defaults to 0.005).

    +

    Example:

    +

    If DOGE/BTC maximum bid is 0.00000026 and minimum ask is 0.00000027, the ratio is calculated as: 1 - bid/ask ~= 0.037 which is > 0.005 and this pair will be filtered out.

    +

    RangeStabilityFilter

    +

    Removes pairs where the difference between lowest low and highest high over lookback_days days is below min_rate_of_change. Since this is a filter that requires additional data, the results are cached for refresh_period.

    +

    In the below example: +If the trading range over the last 10 days is <1%, remove the pair from the whitelist.

    +

    json +"pairlists": [ + { + "method": "RangeStabilityFilter", + "lookback_days": 10, + "min_rate_of_change": 0.01, + "refresh_period": 1440 + } +]

    +
    +

    Tip

    +

    This Filter can be used to automatically remove stable coin pairs, which have a very low trading range, and are therefore extremely difficult to trade with profit.

    +
    +

    VolatilityFilter

    +

    Volatility is the degree of historical variation of a pairs over time, is is measured by the standard deviation of logarithmic daily returns. Returns are assumed to be normally distributed, although actual distribution might be different. In a normal distribution, 68% of observations fall within one standard deviation and 95% of observations fall within two standard deviations. Assuming a volatility of 0.05 means that the expected returns for 20 out of 30 days is expected to be less than 5% (one standard deviation). Volatility is a positive ratio of the expected deviation of return and can be greater than 1.00. Please refer to the wikipedia definition of volatility.

    +

    This filter removes pairs if the average volatility over a lookback_days days is below min_volatility or above max_volatility. Since this is a filter that requires additional data, the results are cached for refresh_period.

    +

    This filter can be used to narrow down your pairs to a certain volatility or avoid very volatile pairs.

    +

    In the below example: +If the volatility over the last 10 days is not in the range of 0.05-0.50, remove the pair from the whitelist. The filter is applied every 24h.

    +

    json +"pairlists": [ + { + "method": "VolatilityFilter", + "lookback_days": 10, + "min_volatility": 0.05, + "max_volatility": 0.50, + "refresh_period": 86400 + } +]

    +

    Full example of Pairlist Handlers

    +

    The below example blacklists BNB/BTC, uses VolumePairList with 20 assets, sorting pairs by quoteVolume and applies PrecisionFilter and PriceFilter, filtering all assets where 1 price unit is > 1%. Then the SpreadFilter and VolatilityFilter is applied and pairs are finally shuffled with the random seed set to some predefined value.

    +

    json +"exchange": { + "pair_whitelist": [], + "pair_blacklist": ["BNB/BTC"] +}, +"pairlists": [ + { + "method": "VolumePairList", + "number_assets": 20, + "sort_key": "quoteVolume" + }, + {"method": "AgeFilter", "min_days_listed": 10}, + {"method": "PrecisionFilter"}, + {"method": "PriceFilter", "low_price_ratio": 0.01}, + {"method": "SpreadFilter", "max_spread_ratio": 0.005}, + { + "method": "RangeStabilityFilter", + "lookback_days": 10, + "min_rate_of_change": 0.01, + "refresh_period": 1440 + }, + { + "method": "VolatilityFilter", + "lookback_days": 10, + "min_volatility": 0.05, + "max_volatility": 0.50, + "refresh_period": 86400 + }, + {"method": "ShuffleFilter", "seed": 42} + ],

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/includes/pricing/index.html b/en/2021.7/includes/pricing/index.html new file mode 100644 index 000000000..392d94713 --- /dev/null +++ b/en/2021.7/includes/pricing/index.html @@ -0,0 +1,1078 @@ + + + + + + + + + + + + + + + + + + + Pricing - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + + + + +
    +
    + + + + + + + +

    Pricing

    + +

    Prices used for orders

    +

    Prices for regular orders can be controlled via the parameter structures bid_strategy for buying and ask_strategy for selling. +Prices are always retrieved right before an order is placed, either by querying the exchange tickers or by using the orderbook data.

    +
    +

    Note

    +

    Orderbook data used by Freqtrade are the data retrieved from exchange by the ccxt's function fetch_order_book(), i.e. are usually data from the L2-aggregated orderbook, while the ticker data are the structures returned by the ccxt's fetch_ticker()/fetch_tickers() functions. Refer to the ccxt library documentation for more details.

    +
    +
    +

    Using market orders

    +

    Please read the section Market order pricing section when using market orders.

    +
    +

    Buy price

    +

    Check depth of market

    +

    When check depth of market is enabled (bid_strategy.check_depth_of_market.enabled=True), the buy signals are filtered based on the orderbook depth (sum of all amounts) for each orderbook side.

    +

    Orderbook bid (buy) side depth is then divided by the orderbook ask (sell) side depth and the resulting delta is compared to the value of the bid_strategy.check_depth_of_market.bids_to_ask_delta parameter. The buy order is only executed if the orderbook delta is greater than or equal to the configured delta value.

    +
    +

    Note

    +

    A delta value below 1 means that ask (sell) orderbook side depth is greater than the depth of the bid (buy) orderbook side, while a value greater than 1 means opposite (depth of the buy side is higher than the depth of the sell side).

    +
    +

    Buy price side

    +

    The configuration setting bid_strategy.price_side defines the side of the spread the bot looks for when buying.

    +

    The following displays an orderbook.

    +

    explanation +... +103 +102 +101 # ask +-------------Current spread +99 # bid +98 +97 +...

    +

    If bid_strategy.price_side is set to "bid", then the bot will use 99 as buying price.
    +In line with that, if bid_strategy.price_side is set to "ask", then the bot will use 101 as buying price.

    +

    Using ask price often guarantees quicker filled orders, but the bot can also end up paying more than what would have been necessary. +Taker fees instead of maker fees will most likely apply even when using limit buy orders. +Also, prices at the "ask" side of the spread are higher than prices at the "bid" side in the orderbook, so the order behaves similar to a market order (however with a maximum price).

    +

    Buy price with Orderbook enabled

    +

    When buying with the orderbook enabled (bid_strategy.use_order_book=True), Freqtrade fetches the bid_strategy.order_book_top entries from the orderbook and uses the entry specified as bid_strategy.order_book_top on the configured side (bid_strategy.price_side) of the orderbook. 1 specifies the topmost entry in the orderbook, while 2 would use the 2nd entry in the orderbook, and so on.

    +

    Buy price without Orderbook enabled

    +

    The following section uses side as the configured bid_strategy.price_side.

    +

    When not using orderbook (bid_strategy.use_order_book=False), Freqtrade uses the best side price from the ticker if it's below the last traded price from the ticker. Otherwise (when the side price is above the last price), it calculates a rate between side and last price.

    +

    The bid_strategy.ask_last_balance configuration parameter controls this. A value of 0.0 will use side price, while 1.0 will use the last price and values between those interpolate between ask and last price.

    +

    Sell price

    +

    Sell price side

    +

    The configuration setting ask_strategy.price_side defines the side of the spread the bot looks for when selling.

    +

    The following displays an orderbook:

    +

    explanation +... +103 +102 +101 # ask +-------------Current spread +99 # bid +98 +97 +...

    +

    If ask_strategy.price_side is set to "ask", then the bot will use 101 as selling price.
    +In line with that, if ask_strategy.price_side is set to "bid", then the bot will use 99 as selling price.

    +

    Sell price with Orderbook enabled

    +

    When selling with the orderbook enabled (ask_strategy.use_order_book=True), Freqtrade fetches the ask_strategy.order_book_top entries in the orderbook and uses the entry specified as ask_strategy.order_book_top from the configured side (ask_strategy.price_side) as selling price.

    +

    1 specifies the topmost entry in the orderbook, while 2 would use the 2nd entry in the orderbook, and so on.

    +

    Sell price without Orderbook enabled

    +

    When not using orderbook (ask_strategy.use_order_book=False), the price at the ask_strategy.price_side side (defaults to "ask") from the ticker will be used as the sell price.

    +

    When not using orderbook (ask_strategy.use_order_book=False), Freqtrade uses the best side price from the ticker if it's below the last traded price from the ticker. Otherwise (when the side price is above the last price), it calculates a rate between side and last price.

    +

    The ask_strategy.bid_last_balance configuration parameter controls this. A value of 0.0 will use side price, while 1.0 will use the last price and values between those interpolate between side and last price.

    +

    Market order pricing

    +

    When using market orders, prices should be configured to use the "correct" side of the orderbook to allow realistic pricing detection. +Assuming both buy and sell are using market orders, a configuration similar to the following might be used

    +

    jsonc + "order_types": { + "buy": "market", + "sell": "market" + // ... + }, + "bid_strategy": { + "price_side": "ask", + // ... + }, + "ask_strategy":{ + "price_side": "bid", + // ... + },

    +

    Obviously, if only one side is using limit orders, different pricing combinations can be used.

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/includes/protections/index.html b/en/2021.7/includes/protections/index.html new file mode 100644 index 000000000..a9f6a92c6 --- /dev/null +++ b/en/2021.7/includes/protections/index.html @@ -0,0 +1,1146 @@ + + + + + + + + + + + + + + + + + + + Protections - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + + + + + + +

    Protections

    + +

    Protections

    +
    +

    Beta feature

    +

    This feature is still in it's testing phase. Should you notice something you think is wrong please let us know via Discord or via Github Issue.

    +
    +

    Protections will protect your strategy from unexpected events and market conditions by temporarily stop trading for either one pair, or for all pairs. +All protection end times are rounded up to the next candle to avoid sudden, unexpected intra-candle buys.

    +
    +

    Note

    +

    Not all Protections will work for all strategies, and parameters will need to be tuned for your strategy to improve performance.

    +
    +
    +

    Tip

    +

    Each Protection can be configured multiple times with different parameters, to allow different levels of protection (short-term / long-term).

    +
    +
    +

    Backtesting

    +

    Protections are supported by backtesting and hyperopt, but must be explicitly enabled by using the --enable-protections flag.

    +
    +

    Available Protections

    +
      +
    • StoplossGuard Stop trading if a certain amount of stoploss occurred within a certain time window.
    • +
    • MaxDrawdown Stop trading if max-drawdown is reached.
    • +
    • LowProfitPairs Lock pairs with low profits
    • +
    • CooldownPeriod Don't enter a trade right after selling a trade.
    • +
    +

    Common settings to all Protections

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    ParameterDescription
    methodProtection name to use.
    Datatype: String, selected from available Protections
    stop_duration_candlesFor how many candles should the lock be set?
    Datatype: Positive integer (in candles)
    stop_durationhow many minutes should protections be locked.
    Cannot be used together with stop_duration_candles.
    Datatype: Float (in minutes)
    lookback_period_candlesOnly trades that completed within the last lookback_period_candles candles will be considered. This setting may be ignored by some Protections.
    Datatype: Positive integer (in candles).
    lookback_periodOnly trades that completed after current_time - lookback_period will be considered.
    Cannot be used together with lookback_period_candles.
    This setting may be ignored by some Protections.
    Datatype: Float (in minutes)
    trade_limitNumber of trades required at minimum (not used by all Protections).
    Datatype: Positive integer
    +
    +

    Durations

    +

    Durations (stop_duration* and lookback_period* can be defined in either minutes or candles). +For more flexibility when testing different timeframes, all below examples will use the "candle" definition.

    +
    +

    Stoploss Guard

    +

    StoplossGuard selects all trades within lookback_period in minutes (or in candles when using lookback_period_candles). +If trade_limit or more trades resulted in stoploss, trading will stop for stop_duration in minutes (or in candles when using stop_duration_candles).

    +

    This applies across all pairs, unless only_per_pair is set to true, which will then only look at one pair at a time.

    +

    The below example stops trading for all pairs for 4 candles after the last trade if the bot hit stoploss 4 times within the last 24 candles.

    +

    python +protections = [ + { + "method": "StoplossGuard", + "lookback_period_candles": 24, + "trade_limit": 4, + "stop_duration_candles": 4, + "only_per_pair": False + } +]

    +
    +

    Note

    +

    StoplossGuard considers all trades with the results "stop_loss", "stoploss_on_exchange" and "trailing_stop_loss" if the resulting profit was negative. +trade_limit and lookback_period will need to be tuned for your strategy.

    +
    +

    MaxDrawdown

    +

    MaxDrawdown uses all trades within lookback_period in minutes (or in candles when using lookback_period_candles) to determine the maximum drawdown. If the drawdown is below max_allowed_drawdown, trading will stop for stop_duration in minutes (or in candles when using stop_duration_candles) after the last trade - assuming that the bot needs some time to let markets recover.

    +

    The below sample stops trading for 12 candles if max-drawdown is > 20% considering all pairs - with a minimum of trade_limit trades - within the last 48 candles. If desired, lookback_period and/or stop_duration can be used.

    +

    python +protections = [ + { + "method": "MaxDrawdown", + "lookback_period_candles": 48, + "trade_limit": 20, + "stop_duration_candles": 12, + "max_allowed_drawdown": 0.2 + }, +]

    +

    Low Profit Pairs

    +

    LowProfitPairs uses all trades for a pair within lookback_period in minutes (or in candles when using lookback_period_candles) to determine the overall profit ratio. +If that ratio is below required_profit, that pair will be locked for stop_duration in minutes (or in candles when using stop_duration_candles).

    +

    The below example will stop trading a pair for 60 minutes if the pair does not have a required profit of 2% (and a minimum of 2 trades) within the last 6 candles.

    +

    python +protections = [ + { + "method": "LowProfitPairs", + "lookback_period_candles": 6, + "trade_limit": 2, + "stop_duration": 60, + "required_profit": 0.02 + } +]

    +

    Cooldown Period

    +

    CooldownPeriod locks a pair for stop_duration in minutes (or in candles when using stop_duration_candles) after selling, avoiding a re-entry for this pair for stop_duration minutes.

    +

    The below example will stop trading a pair for 2 candles after closing a trade, allowing this pair to "cool down".

    +

    python +protections = [ + { + "method": "CooldownPeriod", + "stop_duration_candles": 2 + } +]

    +
    +

    Note

    +

    This Protection applies only at pair-level, and will never lock all pairs globally. +This Protection does not consider lookback_period as it only looks at the latest trade.

    +
    +

    Full example of Protections

    +

    All protections can be combined at will, also with different parameters, creating a increasing wall for under-performing pairs. +All protections are evaluated in the sequence they are defined.

    +

    The below example assumes a timeframe of 1 hour:

    +
      +
    • Locks each pair after selling for an additional 5 candles (CooldownPeriod), giving other pairs a chance to get filled.
    • +
    • Stops trading for 4 hours (4 * 1h candles) if the last 2 days (48 * 1h candles) had 20 trades, which caused a max-drawdown of more than 20%. (MaxDrawdown).
    • +
    • Stops trading if more than 4 stoploss occur for all pairs within a 1 day (24 * 1h candles) limit (StoplossGuard).
    • +
    • Locks all pairs that had 4 Trades within the last 6 hours (6 * 1h candles) with a combined profit ratio of below 0.02 (<2%) (LowProfitPairs).
    • +
    • Locks all pairs for 2 candles that had a profit of below 0.01 (<1%) within the last 24h (24 * 1h candles), a minimum of 4 trades.
    • +
    +

    ``` python +from freqtrade.strategy import IStrategy

    +

    class AwesomeStrategy(IStrategy) + timeframe = '1h' + protections = [ + { + "method": "CooldownPeriod", + "stop_duration_candles": 5 + }, + { + "method": "MaxDrawdown", + "lookback_period_candles": 48, + "trade_limit": 20, + "stop_duration_candles": 4, + "max_allowed_drawdown": 0.2 + }, + { + "method": "StoplossGuard", + "lookback_period_candles": 24, + "trade_limit": 4, + "stop_duration_candles": 2, + "only_per_pair": False + }, + { + "method": "LowProfitPairs", + "lookback_period_candles": 6, + "trade_limit": 2, + "stop_duration_candles": 60, + "required_profit": 0.02 + }, + { + "method": "LowProfitPairs", + "lookback_period_candles": 24, + "trade_limit": 4, + "stop_duration_candles": 2, + "required_profit": 0.01 + } + ] + # ... +```

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/index.html b/en/2021.7/index.html new file mode 100644 index 000000000..cc86dc778 --- /dev/null +++ b/en/2021.7/index.html @@ -0,0 +1,1192 @@ + + + + + + + + + + + + + + + + + + + Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + + + + + + +

    Home

    + +

    freqtrade

    +

    Freqtrade CI +Coverage Status +Maintainability

    + +

    Star +Fork +Download

    +

    Introduction

    +

    Freqtrade is a crypto-currency algorithmic trading software developed in python (3.7+) and supported on Windows, macOS and Linux.

    +
    +

    DISCLAIMER

    +

    This software is for educational purposes only. Do not risk money which you are afraid to lose. USE THE SOFTWARE AT YOUR OWN RISK. THE AUTHORS AND ALL AFFILIATES ASSUME NO RESPONSIBILITY FOR YOUR TRADING RESULTS.

    +

    Always start by running a trading bot in Dry-run and do not engage money before you understand how it works and what profit/loss you should expect.

    +

    We strongly recommend you to have basic coding skills and Python knowledge. Do not hesitate to read the source code and understand the mechanisms of this bot, algorithms and techniques implemented in it.

    +
    +

    Features

    +
      +
    • Develop your Strategy: Write your strategy in python, using pandas. Example strategies to inspire you are available in the strategy repository.
    • +
    • Download market data: Download historical data of the exchange and the markets your may want to trade with.
    • +
    • Backtest: Test your strategy on downloaded historical data.
    • +
    • Optimize: Find the best parameters for your strategy using hyperoptimization which employs machining learning methods. You can optimize buy, sell, take profit (ROI), stop-loss and trailing stop-loss parameters for your strategy.
    • +
    • Select markets: Create your static list or use an automatic one based on top traded volumes and/or prices (not available during backtesting). You can also explicitly blacklist markets you don't want to trade.
    • +
    • Run: Test your strategy with simulated money (Dry-Run mode) or deploy it with real money (Live-Trade mode).
    • +
    • Run using Edge (optional module): The concept is to find the best historical trade expectancy by markets based on variation of the stop-loss and then allow/reject markets to trade. The sizing of the trade is based on a risk of a percentage of your capital.
    • +
    • Control/Monitor: Use Telegram or a REST API (start/stop the bot, show profit/loss, daily summary, current open trades results, etc.).
    • +
    • Analyse: Further analysis can be performed on either Backtesting data or Freqtrade trading history (SQL database), including automated standard plots, and methods to load the data into interactive environments.
    • +
    +

    Supported exchange marketplaces

    +

    Please read the exchange specific notes to learn about eventual, special configurations needed for each exchange.

    + +

    Community tested

    +

    Exchanges confirmed working by the community:

    + +

    Requirements

    +

    Hardware requirements

    +

    To run this bot we recommend you a linux cloud instance with a minimum of:

    +
      +
    • 2GB RAM
    • +
    • 1GB disk space
    • +
    • 2vCPU
    • +
    +

    Software requirements

    +
      +
    • Docker (Recommended)
    • +
    +

    Alternatively

    +
      +
    • Python 3.7+
    • +
    • pip (pip3)
    • +
    • git
    • +
    • TA-Lib
    • +
    • virtualenv (Recommended)
    • +
    +

    Support

    +

    Help / Discord

    +

    For any questions not covered by the documentation or for further information about the bot, or to simply engage with like-minded individuals, we encourage you to join the Freqtrade discord server.

    +

    Ready to try?

    +

    Begin by reading our installation guide for docker (recommended), or for installation without docker.

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/installation/index.html b/en/2021.7/installation/index.html new file mode 100644 index 000000000..a1eab8e67 --- /dev/null +++ b/en/2021.7/installation/index.html @@ -0,0 +1,1363 @@ + + + + + + + + + + + + + + + + + + + Linux/MacOS/Raspberry - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + + + + + + +

    Installation

    +

    This page explains how to prepare your environment for running the bot.

    +

    The freqtrade documentation describes various ways to install freqtrade

    + +

    Please consider using the prebuilt docker images to get started quickly while evaluating how freqtrade works.

    +
    +

    Information

    +

    For Windows installation, please use the windows installation guide.

    +

    The easiest way to install and run Freqtrade is to clone the bot Github repository and then run the ./setup.sh script, if it's available for your platform.

    +
    +

    Version considerations

    +

    When cloning the repository the default working branch has the name develop. This branch contains all last features (can be considered as relatively stable, thanks to automated tests). +The stable branch contains the code of the last release (done usually once per month on an approximately one week old snapshot of the develop branch to prevent packaging bugs, so potentially it's more stable).

    +
    +
    +

    Note

    +

    Python3.7 or higher and the corresponding pip are assumed to be available. The install-script will warn you and stop if that's not the case. git is also needed to clone the Freqtrade repository.
    +Also, python headers (python<yourversion>-dev / python<yourversion>-devel) must be available for the installation to complete successfully.

    +
    +
    +

    Up-to-date clock

    +

    The clock on the system running the bot must be accurate, synchronized to a NTP server frequently enough to avoid problems with communication to the exchanges.

    +
    +
    +

    Requirements

    +

    These requirements apply to both Script Installation and Manual Installation.

    +

    Install guide

    + +

    Install code

    +

    We've included/collected install instructions for Ubuntu, MacOS, and Windows. These are guidelines and your success may vary with other distros. +OS Specific steps are listed first, the Common section below is necessary for all systems.

    +
    +

    Note

    +

    Python3.7 or higher and the corresponding pip are assumed to be available.

    +
    +
    +

    Install necessary dependencies

    +

    ```bash

    +

    update repository

    +

    sudo apt-get update

    +

    install packages

    +

    sudo apt install -y python3-pip python3-venv python3-dev python3-pandas git +```

    +
    +
    +

    The following assumes the latest Raspbian Buster lite image. +This image comes with python3.7 preinstalled, making it easy to get freqtrade up and running.

    +

    Tested using a Raspberry Pi 3 with the Raspbian Buster lite image, all updates applied.

    +

    ```bash +sudo apt-get install python3-venv libatlas-base-dev cmake

    +

    Use pywheels.org to speed up installation

    +

    sudo echo "[global]\nextra-index-url=https://www.piwheels.org/simple" > tee /etc/pip.conf

    +

    git clone https://github.com/freqtrade/freqtrade.git +cd freqtrade

    +

    bash setup.sh -i +```

    +
    +

    Installation duration

    +

    Depending on your internet speed and the Raspberry Pi version, installation can take multiple hours to complete. +Due to this, we recommend to use the pre-build docker-image for Raspberry, by following the Docker quickstart documentation

    +
    +
    +

    Note

    +

    The above does not install hyperopt dependencies. To install these, please use python3 -m pip install -e .[hyperopt]. +We do not advise to run hyperopt on a Raspberry Pi, since this is a very resource-heavy operation, which should be done on powerful machine.

    +
    +
    +
    +
    +

    Freqtrade repository

    +

    Freqtrade is an open source crypto-currency trading bot, whose code is hosted on github.com

    +

    ```bash

    +

    Download develop branch of freqtrade repository

    +

    git clone https://github.com/freqtrade/freqtrade.git

    +

    Enter downloaded directory

    +

    cd freqtrade

    +

    your choice (1): novice user

    +

    git checkout stable

    +

    your choice (2): advanced user

    +

    git checkout develop +```

    +

    (1) This command switches the cloned repository to the use of the stable branch. It's not needed, if you wish to stay on the (2) develop branch.

    +

    You may later switch between branches at any time with the git checkout stable/git checkout develop commands.

    +
    +

    Script Installation

    +

    First of the ways to install Freqtrade, is to use provided the Linux/MacOS ./setup.sh script, which install all dependencies and help you configure the bot.

    +

    Make sure you fulfill the Requirements and have downloaded the Freqtrade repository.

    +

    Use /setup.sh -install (Linux/MacOS)

    +

    If you are on Debian, Ubuntu or MacOS, freqtrade provides the script to install freqtrade.

    +

    ```bash

    +

    --install, Install freqtrade from scratch

    +

    ./setup.sh -i +```

    +

    Activate your virtual environment

    +

    Each time you open a new terminal, you must run source .env/bin/activate to activate your virtual environment.

    +

    ```bash

    +

    then activate your .env

    +

    source ./.env/bin/activate +```

    +

    Congratulations

    +

    You are ready, and run the bot

    +

    Other options of /setup.sh script

    +

    You can as well update, configure and reset the codebase of your bot with ./script.sh

    +

    ```bash

    +

    --update, Command git pull to update.

    +

    ./setup.sh -u

    +

    --reset, Hard reset your develop/stable branch.

    +

    ./setup.sh -r +```

    +

    ``` + --install

    +

    With this option, the script will install the bot and most dependencies: +You will need to have git and python3.7+ installed beforehand for this to work.

    +
      +
    • Mandatory software as: ta-lib
    • +
    • Setup your virtualenv under .env/
    • +
    +

    This option is a combination of installation tasks and --reset

    +

    --update

    +

    This option will pull the last version of your current branch and update your virtualenv. Run the script with this option periodically to update your bot.

    +

    --reset

    +

    This option will hard reset your branch (only if you are on either stable or develop) and recreate your virtualenv. +```

    +
    +

    Manual Installation

    +

    Make sure you fulfill the Requirements and have downloaded the Freqtrade repository.

    +

    Install TA-Lib

    +

    TA-Lib script installation

    +

    bash +sudo ./build_helpers/install_ta-lib.sh

    +
    +

    Note

    +

    This will use the ta-lib tar.gz included in this repository.

    +
    +
    TA-Lib manual installation
    +

    Official webpage: https://mrjbq7.github.io/ta-lib/install.html

    +

    ```bash +wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz +tar xvzf ta-lib-0.4.0-src.tar.gz +cd ta-lib +sed -i.bak "s|0.00000001|0.000000000000000001 |g" src/ta_func/ta_utility.h +./configure --prefix=/usr/local +make +sudo make install

    +

    On debian based systems (debian, ubuntu, ...) - updating ldconfig might be necessary.

    +

    sudo ldconfig
    +cd .. +rm -rf ./ta-lib* +```

    +

    Setup Python virtual environment (virtualenv)

    +

    You will run freqtrade in separated virtual environment

    +

    ```bash

    +

    create virtualenv in directory /freqtrade/.env

    +

    python3 -m venv .env

    +

    run virtualenv

    +

    source .env/bin/activate +```

    +

    Install python dependencies

    +

    bash +python3 -m pip install --upgrade pip +python3 -m pip install -e .

    +

    Congratulations

    +

    You are ready, and run the bot

    +

    (Optional) Post-installation Tasks

    +
    +

    Note

    +

    If you run the bot on a server, you should consider using Docker or a terminal multiplexer like screen or tmux to avoid that the bot is stopped on logout.

    +
    +

    On Linux with software suite systemd, as an optional post-installation task, you may wish to setup the bot to run as a systemd service or configure it to send the log messages to the syslog/rsyslog or journald daemons. See Advanced Logging for details.

    +
    +

    Installation with Conda

    +

    Freqtrade can also be installed with Miniconda or Anaconda. We recommend using Miniconda as it's installation footprint is smaller. Conda will automatically prepare and manage the extensive library-dependencies of the Freqtrade program.

    +

    What is Conda?

    +

    Conda is a package, dependency and environment manager for multiple programming languages: conda docs

    +

    Installation with conda

    +

    Install Conda

    +

    Installing on linux

    +

    Installing on windows

    +

    Answer all questions. After installation, it is mandatory to turn your terminal OFF and ON again.

    +

    Freqtrade download

    +

    Download and install freqtrade.

    +

    ```bash

    +

    download freqtrade

    +

    git clone https://github.com/freqtrade/freqtrade.git

    +

    enter downloaded directory 'freqtrade'

    +

    cd freqtrade
    +```

    +

    Freqtrade install: Conda Environment

    +

    Prepare conda-freqtrade environment, using file environment.yml, which exist in main freqtrade directory

    +

    bash +conda env create -n freqtrade-conda -f environment.yml

    +
    +

    Creating Conda Environment

    +

    The conda command create -n automatically installs all nested dependencies for the selected libraries, general structure of installation command is:

    +

    ```bash

    +

    choose your own packages

    +

    conda env create -n [name of the environment] [python version] [packages]

    +

    point to file with packages

    +

    conda env create -n [name of the environment] -f [file] +```

    +
    +

    Enter/exit freqtrade-conda environment

    +

    To check available environments, type

    +

    bash +conda env list

    +

    Enter installed environment

    +

    ```bash

    +

    enter conda environment

    +

    conda activate freqtrade-conda

    +

    exit conda environment - don't do it now

    +

    conda deactivate +```

    +

    Install last python dependencies with pip

    +

    bash +python3 -m pip install --upgrade pip +python3 -m pip install -e .

    +

    Congratulations

    +

    You are ready, and run the bot

    +

    Important shortcuts

    +

    ```bash

    +

    list installed conda environments

    +

    conda env list

    +

    activate base environment

    +

    conda activate

    +

    activate freqtrade-conda environment

    +

    conda activate freqtrade-conda

    +

    deactivate any conda environments

    +

    conda deactivate
    +```

    +

    Further info on anaconda

    +
    +

    New heavy packages

    +

    It may happen that creating a new Conda environment, populated with selected packages at the moment of creation takes less time than installing a large, heavy library or application, into previously set environment.

    +
    +
    +

    pip install within conda

    +

    The documentation of conda says that pip should NOT be used within conda, because internal problems can occur. +However, they are rare. Anaconda Blogpost

    +

    Nevertheless, that is why, the conda-forge channel is preferred:

    +
      +
    • more libraries are available (less need for pip)
    • +
    • conda-forge works better with pip
    • +
    • the libraries are newer
    • +
    +
    +

    Happy trading!

    +
    +

    You are ready

    +

    You've made it this far, so you have successfully installed freqtrade.

    +

    Initialize the configuration

    +

    ```bash

    +

    Step 1 - Initialize user folder

    +

    freqtrade create-userdir --userdir user_data

    +

    Step 2 - Create a new configuration file

    +

    freqtrade new-config --config config.json +```

    +

    You are ready to run, read Bot Configuration, remember to start with dry_run: True and verify that everything is working.

    +

    To learn how to setup your configuration, please refer to the Bot Configuration documentation page.

    +

    Start the Bot

    +

    bash +freqtrade trade --config config.json --strategy SampleStrategy

    +
    +

    Warning

    +

    You should read through the rest of the documentation, backtest the strategy you're going to use, and use dry-run before enabling trading with real money.

    +
    +
    +

    Troubleshooting

    +

    Common problem: "command not found"

    +

    If you used (1)Script or (2)Manual installation, you need to run the bot in virtual environment. If you get error as below, make sure venv is active.

    +

    ```bash

    +

    if:

    +

    bash: freqtrade: command not found

    +

    then activate your .env

    +

    source ./.env/bin/activate +```

    +

    MacOS installation error

    +

    Newer versions of MacOS may have installation failed with errors like error: command 'g++' failed with exit status 1.

    +

    This error will require explicit installation of the SDK Headers, which are not installed by default in this version of MacOS. +For MacOS 10.14, this can be accomplished with the below command.

    +

    bash +open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

    +

    If this file is inexistent, then you're probably on a different version of MacOS, so you may need to consult the internet for specific resolution details.

    +

    MacOS installation error with python 3.9

    +

    When using python 3.9 on macOS, it's currently necessary to install some os-level modules to allow dependencies to compile. +The errors you'll see happen during installation and are related to the installation of tables or blosc.

    +

    You can install the necessary libraries with the following command:

    +

    bash +brew install hdf5 c-blosc

    +

    After this, please run the installation (script) again.

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/javascripts/config.js b/en/2021.7/javascripts/config.js new file mode 100644 index 000000000..95d619efc --- /dev/null +++ b/en/2021.7/javascripts/config.js @@ -0,0 +1,12 @@ +window.MathJax = { + tex: { + inlineMath: [["\\(", "\\)"]], + displayMath: [["\\[", "\\]"]], + processEscapes: true, + processEnvironments: true + }, + options: { + ignoreHtmlClass: ".*|", + processHtmlClass: "arithmatex" + } +}; \ No newline at end of file diff --git a/en/2021.7/overrides/main.html b/en/2021.7/overrides/main.html new file mode 100644 index 000000000..dfc5264be --- /dev/null +++ b/en/2021.7/overrides/main.html @@ -0,0 +1,68 @@ +{% extends "base.html" %} + + + +{% block site_nav %} + + + {% if nav %} + {% if page and page.meta and page.meta.hide %} + {% set hidden = "hidden" if "navigation" in page.meta.hide %} + {% endif %} + + {% endif %} + + + {% if page.toc and not "toc.integrate" in features %} + {% if page and page.meta and page.meta.hide %} + {% set hidden = "hidden" if "toc" in page.meta.hide %} + {% endif %} + + {% endif %} +{% endblock %} + +{% block footer %} + {{ super() }} + + + + + + + + + +{% endblock %} diff --git a/en/2021.7/plotting/index.html b/en/2021.7/plotting/index.html new file mode 100644 index 000000000..7a1ffdcc7 --- /dev/null +++ b/en/2021.7/plotting/index.html @@ -0,0 +1,1337 @@ + + + + + + + + + + + + + + + + + + + Plotting - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + + + + + + +

    Plotting

    +

    This page explains how to plot prices, indicators and profits.

    +

    Installation / Setup

    +

    Plotting modules use the Plotly library. You can install / upgrade this by running the following command:

    +

    bash +pip install -U -r requirements-plot.txt

    +

    Plot price and indicators

    +

    The freqtrade plot-dataframe subcommand shows an interactive graph with three subplots:

    +
      +
    • Main plot with candlestics and indicators following price (sma/ema)
    • +
    • Volume bars
    • +
    • Additional indicators as specified by --indicators2
    • +
    +

    plot-dataframe

    +

    Possible arguments:

    +

    ``` +usage: freqtrade plot-dataframe [-h] [-v] [--logfile FILE] [-V] [-c PATH] + [-d PATH] [--userdir PATH] [-s NAME] + [--strategy-path PATH] [-p PAIRS [PAIRS ...]] + [--indicators1 INDICATORS1 [INDICATORS1 ...]] + [--indicators2 INDICATORS2 [INDICATORS2 ...]] + [--plot-limit INT] [--db-url PATH] + [--trade-source {DB,file}] [--export EXPORT] + [--export-filename PATH] + [--timerange TIMERANGE] [-i TIMEFRAME] + [--no-trades]

    +

    optional arguments: + -h, --help show this help message and exit + -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] + Limit command to these pairs. Pairs are space- + separated. + --indicators1 INDICATORS1 [INDICATORS1 ...] + Set indicators from your strategy you want in the + first row of the graph. Space-separated list. Example: + ema3 ema5. Default: ['sma', 'ema3', 'ema5']. + --indicators2 INDICATORS2 [INDICATORS2 ...] + Set indicators from your strategy you want in the + third row of the graph. Space-separated list. Example: + fastd fastk. Default: ['macd', 'macdsignal']. + --plot-limit INT Specify tick limit for plotting. Notice: too high + values cause huge files. Default: 750. + --db-url PATH Override trades database URL, this is useful in custom + deployments (default: sqlite:///tradesv3.sqlite for + Live Run mode, sqlite:///tradesv3.dryrun.sqlite for + Dry Run). + --trade-source {DB,file} + Specify the source for trades (Can be DB or file + (backtest file)) Default: file + --export EXPORT Export backtest results, argument are: trades. + Example: --export=trades + --export-filename PATH + Save backtest results to the file with this filename. + Requires --export to be set as well. Example: + --export-filename=user_data/backtest_results/backtest + _today.json + --timerange TIMERANGE + Specify what timerange of data to use. + -i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME + Specify timeframe (1m, 5m, 30m, 1h, 1d). + --no-trades Skip using trades from backtesting file and DB.

    +

    Common arguments: + -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). + --logfile FILE Log to the file specified. Special values are: + 'syslog', 'journald'. See the documentation for more + details. + -V, --version show program's version number and exit + -c PATH, --config PATH + Specify configuration file (default: + userdir/config.json or config.json whichever + exists). Multiple --config options may be used. Can be + set to - to read config from stdin. + -d PATH, --datadir PATH + Path to directory with historical backtesting data. + --userdir PATH, --user-data-dir PATH + Path to userdata directory.

    +

    Strategy arguments: + -s NAME, --strategy NAME + Specify strategy class name which will be used by the + bot. + --strategy-path PATH Specify additional strategy lookup path.

    +

    ```

    +

    Example:

    +

    bash +freqtrade plot-dataframe -p BTC/ETH

    +

    The -p/--pairs argument can be used to specify pairs you would like to plot.

    +
    +

    Note

    +

    The freqtrade plot-dataframe subcommand generates one plot-file per pair.

    +
    +

    Specify custom indicators. +Use --indicators1 for the main plot and --indicators2 for the subplot below (if values are in a different range than prices).

    +
    +

    Tip

    +

    You will almost certainly want to specify a custom strategy! This can be done by adding -s Classname / --strategy ClassName to the command.

    +
    +

    bash +freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH --indicators1 sma ema --indicators2 macd

    +

    Further usage examples

    +

    To plot multiple pairs, separate them with a space:

    +

    bash +freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH XRP/ETH

    +

    To plot a timerange (to zoom in)

    +

    bash +freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH --timerange=20180801-20180805

    +

    To plot trades stored in a database use --db-url in combination with --trade-source DB:

    +

    bash +freqtrade plot-dataframe --strategy AwesomeStrategy --db-url sqlite:///tradesv3.dry_run.sqlite -p BTC/ETH --trade-source DB

    +

    To plot trades from a backtesting result, use --export-filename <filename>

    +

    bash +freqtrade plot-dataframe --strategy AwesomeStrategy --export-filename user_data/backtest_results/backtest-result.json -p BTC/ETH

    +

    Plot dataframe basics

    +

    plot-dataframe2

    +

    The plot-dataframe subcommand requires backtesting data, a strategy and either a backtesting-results file or a database, containing trades corresponding to the strategy.

    +

    The resulting plot will have the following elements:

    +
      +
    • Green triangles: Buy signals from the strategy. (Note: not every buy signal generates a trade, compare to cyan circles.)
    • +
    • Red triangles: Sell signals from the strategy. (Also, not every sell signal terminates a trade, compare to red and green squares.)
    • +
    • Cyan circles: Trade entry points.
    • +
    • Red squares: Trade exit points for trades with loss or 0% profit.
    • +
    • Green squares: Trade exit points for profitable trades.
    • +
    • Indicators with values corresponding to the candle scale (e.g. SMA/EMA), as specified with --indicators1.
    • +
    • Volume (bar chart at the bottom of the main chart).
    • +
    • Indicators with values in different scales (e.g. MACD, RSI) below the volume bars, as specified with --indicators2.
    • +
    +
    +

    Bollinger Bands

    +

    Bollinger bands are automatically added to the plot if the columns bb_lowerband and bb_upperband exist, and are painted as a light blue area spanning from the lower band to the upper band.

    +
    +

    Advanced plot configuration

    +

    An advanced plot configuration can be specified in the strategy in the plot_config parameter.

    +

    Additional features when using plot_config include:

    +
      +
    • Specify colors per indicator
    • +
    • Specify additional subplots
    • +
    • Specify indicator pairs to fill area in between
    • +
    +

    The sample plot configuration below specifies fixed colors for the indicators. Otherwise, consecutive plots may produce different color schemes each time, making comparisons difficult. +It also allows multiple subplots to display both MACD and RSI at the same time.

    +

    Plot type can be configured using type key. Possible types are: +* scatter corresponding to plotly.graph_objects.Scatter class (default). +* bar corresponding to plotly.graph_objects.Bar class.

    +

    Extra parameters to plotly.graph_objects.* constructor can be specified in plotly dict.

    +

    Sample configuration with inline comments explaining the process:

    +

    `` python + plot_config = { + 'main_plot': { + # Configuration for main plot indicators. + # Specifiesema10to be red, andema50` to be a shade of gray + 'ema10': {'color': 'red'}, + 'ema50': {'color': '#CCCCCC'}, + # By omitting color, a random color is selected. + 'sar': {}, + # fill area between senkou_a and senkou_b + 'senkou_a': { + 'color': 'green', #optional + 'fill_to': 'senkou_b', + 'fill_label': 'Ichimoku Cloud', #optional + 'fill_color': 'rgba(255,76,46,0.2)', #optional + }, + # plot senkou_b, too. Not only the area to it. + 'senkou_b': {} + }, + 'subplots': { + # Create subplot MACD + "MACD": { + 'macd': {'color': 'blue', 'fill_to': 'macdhist'}, + 'macdsignal': {'color': 'orange'}, + 'macdhist': {'type': 'bar', 'plotly': {'opacity': 0.9}} + }, + # Additional subplot RSI + "RSI": { + 'rsi': {'color': 'red'} + } + } + }

    +

    ```

    +
    +

    Note

    +

    The above configuration assumes that ema10, ema50, senkou_a, senkou_b, +macd, macdsignal, macdhist and rsi are columns in the DataFrame created by the strategy.

    +
    +
    +

    Warning

    +

    plotly arguments are only supported with plotly library and will not work with freq-ui.

    +
    +

    Plot profit

    +

    plot-profit

    +

    The plot-profit subcommand shows an interactive graph with three plots:

    +
      +
    • Average closing price for all pairs.
    • +
    • The summarized profit made by backtesting. +Note that this is not the real-world profit, but more of an estimate.
    • +
    • Profit for each individual pair.
    • +
    +

    The first graph is good to get a grip of how the overall market progresses.

    +

    The second graph will show if your algorithm works or doesn't. +Perhaps you want an algorithm that steadily makes small profits, or one that acts less often, but makes big swings. +This graph will also highlight the start (and end) of the Max drawdown period.

    +

    The third graph can be useful to spot outliers, events in pairs that cause profit spikes.

    +

    Possible options for the freqtrade plot-profit subcommand:

    +

    ``` +usage: freqtrade plot-profit [-h] [-v] [--logfile FILE] [-V] [-c PATH] + [-d PATH] [--userdir PATH] [-s NAME] + [--strategy-path PATH] [-p PAIRS [PAIRS ...]] + [--timerange TIMERANGE] [--export EXPORT] + [--export-filename PATH] [--db-url PATH] + [--trade-source {DB,file}] [-i TIMEFRAME]

    +

    optional arguments: + -h, --help show this help message and exit + -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] + Limit command to these pairs. Pairs are space- + separated. + --timerange TIMERANGE + Specify what timerange of data to use. + --export EXPORT Export backtest results, argument are: trades. + Example: --export=trades + --export-filename PATH + Save backtest results to the file with this filename. + Requires --export to be set as well. Example: + --export-filename=user_data/backtest_results/backtest + _today.json + --db-url PATH Override trades database URL, this is useful in custom + deployments (default: sqlite:///tradesv3.sqlite for + Live Run mode, sqlite:///tradesv3.dryrun.sqlite for + Dry Run). + --trade-source {DB,file} + Specify the source for trades (Can be DB or file + (backtest file)) Default: file + -i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME + Specify timeframe (1m, 5m, 30m, 1h, 1d). + --auto-open Automatically open generated plot.

    +

    Common arguments: + -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). + --logfile FILE Log to the file specified. Special values are: + 'syslog', 'journald'. See the documentation for more + details. + -V, --version show program's version number and exit + -c PATH, --config PATH + Specify configuration file (default: + userdir/config.json or config.json whichever + exists). Multiple --config options may be used. Can be + set to - to read config from stdin. + -d PATH, --datadir PATH + Path to directory with historical backtesting data. + --userdir PATH, --user-data-dir PATH + Path to userdata directory.

    +

    Strategy arguments: + -s NAME, --strategy NAME + Specify strategy class name which will be used by the + bot. + --strategy-path PATH Specify additional strategy lookup path.

    +

    ```

    +

    The -p/--pairs argument, can be used to limit the pairs that are considered for this calculation.

    +

    Examples:

    +

    Use custom backtest-export file

    +

    bash +freqtrade plot-profit -p LTC/BTC --export-filename user_data/backtest_results/backtest-result.json

    +

    Use custom database

    +

    bash +freqtrade plot-profit -p LTC/BTC --db-url sqlite:///tradesv3.sqlite --trade-source DB

    +

    bash +freqtrade --datadir user_data/data/binance_save/ plot-profit -p LTC/BTC

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/plugins/index.html b/en/2021.7/plugins/index.html new file mode 100644 index 000000000..bf6944dba --- /dev/null +++ b/en/2021.7/plugins/index.html @@ -0,0 +1,1755 @@ + + + + + + + + + + + + + + + + + + + Plugins - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + + + + +
    +
    + + + + + + + +

    Plugins

    +

    Pairlists and Pairlist Handlers

    +

    Pairlist Handlers define the list of pairs (pairlist) that the bot should trade. They are configured in the pairlists section of the configuration settings.

    +

    In your configuration, you can use Static Pairlist (defined by the StaticPairList Pairlist Handler) and Dynamic Pairlist (defined by the VolumePairList Pairlist Handler).

    +

    Additionally, AgeFilter, PrecisionFilter, PriceFilter, ShuffleFilter, SpreadFilter and VolatilityFilter act as Pairlist Filters, removing certain pairs and/or moving their positions in the pairlist.

    +

    If multiple Pairlist Handlers are used, they are chained and a combination of all Pairlist Handlers forms the resulting pairlist the bot uses for trading and backtesting. Pairlist Handlers are executed in the sequence they are configured. You should always configure either StaticPairList or VolumePairList as the starting Pairlist Handler.

    +

    Inactive markets are always removed from the resulting pairlist. Explicitly blacklisted pairs (those in the pair_blacklist configuration setting) are also always removed from the resulting pairlist.

    +

    Pair blacklist

    +

    The pair blacklist (configured via exchange.pair_blacklist in the configuration) disallows certain pairs from trading. +This can be as simple as excluding DOGE/BTC - which will remove exactly this pair.

    +

    The pair-blacklist does also support wildcards (in regex-style) - so BNB/.* will exclude ALL pairs that start with BNB. +You may also use something like .*DOWN/BTC or .*UP/BTC to exclude leveraged tokens (check Pair naming conventions for your exchange!)

    +

    Available Pairlist Handlers

    + +
    +

    Testing pairlists

    +

    Pairlist configurations can be quite tricky to get right. Best use the test-pairlist utility sub-command to test your configuration quickly.

    +
    +

    Static Pair List

    +

    By default, the StaticPairList method is used, which uses a statically defined pair whitelist from the configuration. The pairlist also supports wildcards (in regex-style) - so .*/BTC will include all pairs with BTC as a stake.

    +

    It uses configuration from exchange.pair_whitelist and exchange.pair_blacklist.

    +

    json +"pairlists": [ + {"method": "StaticPairList"} + ],

    +

    By default, only currently enabled pairs are allowed. +To skip pair validation against active markets, set "allow_inactive": true within the StaticPairList configuration. +This can be useful for backtesting expired pairs (like quarterly spot-markets). +This option must be configured along with exchange.skip_pair_validation in the exchange configuration.

    +

    Volume Pair List

    +

    VolumePairList employs sorting/filtering of pairs by their trading volume. It selects number_assets top pairs with sorting based on the sort_key (which can only be quoteVolume).

    +

    When used in the chain of Pairlist Handlers in a non-leading position (after StaticPairList and other Pairlist Filters), VolumePairList considers outputs of previous Pairlist Handlers, adding its sorting/selection of the pairs by the trading volume.

    +

    When used on the leading position of the chain of Pairlist Handlers, it does not consider pair_whitelist configuration setting, but selects the top assets from all available markets (with matching stake-currency) on the exchange.

    +

    The refresh_period setting allows to define the period (in seconds), at which the pairlist will be refreshed. Defaults to 1800s (30 minutes). +The pairlist cache (refresh_period) on VolumePairList is only applicable to generating pairlists. +Filtering instances (not the first position in the list) will not apply any cache and will always use up-to-date data.

    +

    VolumePairList is per default based on the ticker data from exchange, as reported by the ccxt library:

    +
      +
    • The quoteVolume is the amount of quote (stake) currency traded (bought or sold) in last 24 hours.
    • +
    +

    json +"pairlists": [ + { + "method": "VolumePairList", + "number_assets": 20, + "sort_key": "quoteVolume", + "refresh_period": 1800 + } +],

    +

    VolumePairList can also operate in an advanced mode to build volume over a given timerange of specified candle size. It utilizes exchange historical candle data, builds a typical price (calculated by (open+high+low)/3) and multiplies the typical price with every candle's volume. The sum is the quoteVolume over the given range. This allows different scenarios, for a more smoothened volume, when using longer ranges with larger candle sizes, or the opposite when using a short range with small candles.

    +

    For convenience lookback_days can be specified, which will imply that 1d candles will be used for the lookback. In the example below the pairlist would be created based on the last 7 days:

    +

    json +"pairlists": [ + { + "method": "VolumePairList", + "number_assets": 20, + "sort_key": "quoteVolume", + "refresh_period": 86400, + "lookback_days": 7 + } +],

    +
    +

    Range look back and refresh period

    +

    When used in conjunction with lookback_days and lookback_timeframe the refresh_period can not be smaller than the candle size in seconds. As this will result in unnecessary requests to the exchanges API.

    +
    +
    +

    Performance implications when using lookback range

    +

    If used in first position in combination with lookback, the computation of the range based volume can be time and resource consuming, as it downloads candles for all tradable pairs. Hence it's highly advised to use the standard approach with VolumeFilter to narrow the pairlist down for further range volume calculation.

    +
    +

    More sophisticated approach can be used, by using lookback_timeframe for candle size and lookback_period which specifies the amount of candles. This example will build the volume pairs based on a rolling period of 3 days of 1h candles:

    +

    json +"pairlists": [ + { + "method": "VolumePairList", + "number_assets": 20, + "sort_key": "quoteVolume", + "refresh_period": 3600, + "lookback_timeframe": "1h", + "lookback_period": 72 + } +],

    +
    +

    Note

    +

    VolumePairList does not support backtesting mode.

    +
    +

    AgeFilter

    +

    Removes pairs that have been listed on the exchange for less than min_days_listed days (defaults to 10) or more than max_days_listed days (defaults None mean infinity).

    +

    When pairs are first listed on an exchange they can suffer huge price drops and volatility +in the first few days while the pair goes through its price-discovery period. Bots can often +be caught out buying before the pair has finished dropping in price.

    +

    This filter allows freqtrade to ignore pairs until they have been listed for at least min_days_listed days and listed before max_days_listed.

    +

    OffsetFilter

    +

    Offsets an incoming pairlist by a given offset value.

    +

    As an example it can be used in conjunction with VolumeFilter to remove the top X volume pairs. Or to split +a larger pairlist on two bot instances.

    +

    Example to remove the first 10 pairs from the pairlist:

    +

    json +"pairlists": [ + { + "method": "OffsetFilter", + "offset": 10 + } +],

    +
    +

    Warning

    +

    When OffsetFilter is used to split a larger pairlist among multiple bots in combination with VolumeFilter +it can not be guaranteed that pairs won't overlap due to slightly different refresh intervals for the +VolumeFilter.

    +
    +
    +

    Note

    +

    An offset larger then the total length of the incoming pairlist will result in an empty pairlist.

    +
    +

    PerformanceFilter

    +

    Sorts pairs by past trade performance, as follows:

    +
      +
    1. Positive performance.
    2. +
    3. No closed trades yet.
    4. +
    5. Negative performance.
    6. +
    +

    Trade count is used as a tie breaker.

    +
    +

    Note

    +

    PerformanceFilter does not support backtesting mode.

    +
    +

    PrecisionFilter

    +

    Filters low-value coins which would not allow setting stoplosses.

    +

    PriceFilter

    +

    The PriceFilter allows filtering of pairs by price. Currently the following price filters are supported:

    +
      +
    • min_price
    • +
    • max_price
    • +
    • max_value
    • +
    • low_price_ratio
    • +
    +

    The min_price setting removes pairs where the price is below the specified price. This is useful if you wish to avoid trading very low-priced pairs. +This option is disabled by default, and will only apply if set to > 0.

    +

    The max_price setting removes pairs where the price is above the specified price. This is useful if you wish to trade only low-priced pairs. +This option is disabled by default, and will only apply if set to > 0.

    +

    The max_value setting removes pairs where the minimum value change is above a specified value. +This is useful when an exchange has unbalanced limits. For example, if step-size = 1 (so you can only buy 1, or 2, or 3, but not 1.1 Coins) - and the price is pretty high (like 20$) as the coin has risen sharply since the last limit adaption. +As a result of the above, you can only buy for 20$, or 40$ - but not for 25$. +On exchanges that deduct fees from the receiving currency (e.g. FTX) - this can result in high value coins / amounts that are unsellable as the amount is slightly below the limit.

    +

    The low_price_ratio setting removes pairs where a raise of 1 price unit (pip) is above the low_price_ratio ratio. +This option is disabled by default, and will only apply if set to > 0.

    +

    For PriceFiler at least one of its min_price, max_price or low_price_ratio settings must be applied.

    +

    Calculation example:

    +

    Min price precision for SHITCOIN/BTC is 8 decimals. If its price is 0.00000011 - one price step above would be 0.00000012, which is ~9% higher than the previous price value. You may filter out this pair by using PriceFilter with low_price_ratio set to 0.09 (9%) or with min_price set to 0.00000011, correspondingly.

    +
    +

    Low priced pairs

    +

    Low priced pairs with high "1 pip movements" are dangerous since they are often illiquid and it may also be impossible to place the desired stoploss, which can often result in high losses since price needs to be rounded to the next tradable price - so instead of having a stoploss of -5%, you could end up with a stoploss of -9% simply due to price rounding.

    +
    +

    ShuffleFilter

    +

    Shuffles (randomizes) pairs in the pairlist. It can be used for preventing the bot from trading some of the pairs more frequently then others when you want all pairs be treated with the same priority.

    +
    +

    Tip

    +

    You may set the seed value for this Pairlist to obtain reproducible results, which can be useful for repeated backtesting sessions. If seed is not set, the pairs are shuffled in the non-repeatable random order.

    +
    +

    SpreadFilter

    +

    Removes pairs that have a difference between asks and bids above the specified ratio, max_spread_ratio (defaults to 0.005).

    +

    Example:

    +

    If DOGE/BTC maximum bid is 0.00000026 and minimum ask is 0.00000027, the ratio is calculated as: 1 - bid/ask ~= 0.037 which is > 0.005 and this pair will be filtered out.

    +

    RangeStabilityFilter

    +

    Removes pairs where the difference between lowest low and highest high over lookback_days days is below min_rate_of_change. Since this is a filter that requires additional data, the results are cached for refresh_period.

    +

    In the below example: +If the trading range over the last 10 days is <1%, remove the pair from the whitelist.

    +

    json +"pairlists": [ + { + "method": "RangeStabilityFilter", + "lookback_days": 10, + "min_rate_of_change": 0.01, + "refresh_period": 1440 + } +]

    +
    +

    Tip

    +

    This Filter can be used to automatically remove stable coin pairs, which have a very low trading range, and are therefore extremely difficult to trade with profit.

    +
    +

    VolatilityFilter

    +

    Volatility is the degree of historical variation of a pairs over time, is is measured by the standard deviation of logarithmic daily returns. Returns are assumed to be normally distributed, although actual distribution might be different. In a normal distribution, 68% of observations fall within one standard deviation and 95% of observations fall within two standard deviations. Assuming a volatility of 0.05 means that the expected returns for 20 out of 30 days is expected to be less than 5% (one standard deviation). Volatility is a positive ratio of the expected deviation of return and can be greater than 1.00. Please refer to the wikipedia definition of volatility.

    +

    This filter removes pairs if the average volatility over a lookback_days days is below min_volatility or above max_volatility. Since this is a filter that requires additional data, the results are cached for refresh_period.

    +

    This filter can be used to narrow down your pairs to a certain volatility or avoid very volatile pairs.

    +

    In the below example: +If the volatility over the last 10 days is not in the range of 0.05-0.50, remove the pair from the whitelist. The filter is applied every 24h.

    +

    json +"pairlists": [ + { + "method": "VolatilityFilter", + "lookback_days": 10, + "min_volatility": 0.05, + "max_volatility": 0.50, + "refresh_period": 86400 + } +]

    +

    Full example of Pairlist Handlers

    +

    The below example blacklists BNB/BTC, uses VolumePairList with 20 assets, sorting pairs by quoteVolume and applies PrecisionFilter and PriceFilter, filtering all assets where 1 price unit is > 1%. Then the SpreadFilter and VolatilityFilter is applied and pairs are finally shuffled with the random seed set to some predefined value.

    +

    json +"exchange": { + "pair_whitelist": [], + "pair_blacklist": ["BNB/BTC"] +}, +"pairlists": [ + { + "method": "VolumePairList", + "number_assets": 20, + "sort_key": "quoteVolume" + }, + {"method": "AgeFilter", "min_days_listed": 10}, + {"method": "PrecisionFilter"}, + {"method": "PriceFilter", "low_price_ratio": 0.01}, + {"method": "SpreadFilter", "max_spread_ratio": 0.005}, + { + "method": "RangeStabilityFilter", + "lookback_days": 10, + "min_rate_of_change": 0.01, + "refresh_period": 1440 + }, + { + "method": "VolatilityFilter", + "lookback_days": 10, + "min_volatility": 0.05, + "max_volatility": 0.50, + "refresh_period": 86400 + }, + {"method": "ShuffleFilter", "seed": 42} + ],

    +

    Protections

    +
    +

    Beta feature

    +

    This feature is still in it's testing phase. Should you notice something you think is wrong please let us know via Discord or via Github Issue.

    +
    +

    Protections will protect your strategy from unexpected events and market conditions by temporarily stop trading for either one pair, or for all pairs. +All protection end times are rounded up to the next candle to avoid sudden, unexpected intra-candle buys.

    +
    +

    Note

    +

    Not all Protections will work for all strategies, and parameters will need to be tuned for your strategy to improve performance.

    +
    +
    +

    Tip

    +

    Each Protection can be configured multiple times with different parameters, to allow different levels of protection (short-term / long-term).

    +
    +
    +

    Backtesting

    +

    Protections are supported by backtesting and hyperopt, but must be explicitly enabled by using the --enable-protections flag.

    +
    +

    Available Protections

    +
      +
    • StoplossGuard Stop trading if a certain amount of stoploss occurred within a certain time window.
    • +
    • MaxDrawdown Stop trading if max-drawdown is reached.
    • +
    • LowProfitPairs Lock pairs with low profits
    • +
    • CooldownPeriod Don't enter a trade right after selling a trade.
    • +
    +

    Common settings to all Protections

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    ParameterDescription
    methodProtection name to use.
    Datatype: String, selected from available Protections
    stop_duration_candlesFor how many candles should the lock be set?
    Datatype: Positive integer (in candles)
    stop_durationhow many minutes should protections be locked.
    Cannot be used together with stop_duration_candles.
    Datatype: Float (in minutes)
    lookback_period_candlesOnly trades that completed within the last lookback_period_candles candles will be considered. This setting may be ignored by some Protections.
    Datatype: Positive integer (in candles).
    lookback_periodOnly trades that completed after current_time - lookback_period will be considered.
    Cannot be used together with lookback_period_candles.
    This setting may be ignored by some Protections.
    Datatype: Float (in minutes)
    trade_limitNumber of trades required at minimum (not used by all Protections).
    Datatype: Positive integer
    +
    +

    Durations

    +

    Durations (stop_duration* and lookback_period* can be defined in either minutes or candles). +For more flexibility when testing different timeframes, all below examples will use the "candle" definition.

    +
    +

    Stoploss Guard

    +

    StoplossGuard selects all trades within lookback_period in minutes (or in candles when using lookback_period_candles). +If trade_limit or more trades resulted in stoploss, trading will stop for stop_duration in minutes (or in candles when using stop_duration_candles).

    +

    This applies across all pairs, unless only_per_pair is set to true, which will then only look at one pair at a time.

    +

    The below example stops trading for all pairs for 4 candles after the last trade if the bot hit stoploss 4 times within the last 24 candles.

    +

    python +protections = [ + { + "method": "StoplossGuard", + "lookback_period_candles": 24, + "trade_limit": 4, + "stop_duration_candles": 4, + "only_per_pair": False + } +]

    +
    +

    Note

    +

    StoplossGuard considers all trades with the results "stop_loss", "stoploss_on_exchange" and "trailing_stop_loss" if the resulting profit was negative. +trade_limit and lookback_period will need to be tuned for your strategy.

    +
    +

    MaxDrawdown

    +

    MaxDrawdown uses all trades within lookback_period in minutes (or in candles when using lookback_period_candles) to determine the maximum drawdown. If the drawdown is below max_allowed_drawdown, trading will stop for stop_duration in minutes (or in candles when using stop_duration_candles) after the last trade - assuming that the bot needs some time to let markets recover.

    +

    The below sample stops trading for 12 candles if max-drawdown is > 20% considering all pairs - with a minimum of trade_limit trades - within the last 48 candles. If desired, lookback_period and/or stop_duration can be used.

    +

    python +protections = [ + { + "method": "MaxDrawdown", + "lookback_period_candles": 48, + "trade_limit": 20, + "stop_duration_candles": 12, + "max_allowed_drawdown": 0.2 + }, +]

    +

    Low Profit Pairs

    +

    LowProfitPairs uses all trades for a pair within lookback_period in minutes (or in candles when using lookback_period_candles) to determine the overall profit ratio. +If that ratio is below required_profit, that pair will be locked for stop_duration in minutes (or in candles when using stop_duration_candles).

    +

    The below example will stop trading a pair for 60 minutes if the pair does not have a required profit of 2% (and a minimum of 2 trades) within the last 6 candles.

    +

    python +protections = [ + { + "method": "LowProfitPairs", + "lookback_period_candles": 6, + "trade_limit": 2, + "stop_duration": 60, + "required_profit": 0.02 + } +]

    +

    Cooldown Period

    +

    CooldownPeriod locks a pair for stop_duration in minutes (or in candles when using stop_duration_candles) after selling, avoiding a re-entry for this pair for stop_duration minutes.

    +

    The below example will stop trading a pair for 2 candles after closing a trade, allowing this pair to "cool down".

    +

    python +protections = [ + { + "method": "CooldownPeriod", + "stop_duration_candles": 2 + } +]

    +
    +

    Note

    +

    This Protection applies only at pair-level, and will never lock all pairs globally. +This Protection does not consider lookback_period as it only looks at the latest trade.

    +
    +

    Full example of Protections

    +

    All protections can be combined at will, also with different parameters, creating a increasing wall for under-performing pairs. +All protections are evaluated in the sequence they are defined.

    +

    The below example assumes a timeframe of 1 hour:

    +
      +
    • Locks each pair after selling for an additional 5 candles (CooldownPeriod), giving other pairs a chance to get filled.
    • +
    • Stops trading for 4 hours (4 * 1h candles) if the last 2 days (48 * 1h candles) had 20 trades, which caused a max-drawdown of more than 20%. (MaxDrawdown).
    • +
    • Stops trading if more than 4 stoploss occur for all pairs within a 1 day (24 * 1h candles) limit (StoplossGuard).
    • +
    • Locks all pairs that had 4 Trades within the last 6 hours (6 * 1h candles) with a combined profit ratio of below 0.02 (<2%) (LowProfitPairs).
    • +
    • Locks all pairs for 2 candles that had a profit of below 0.01 (<1%) within the last 24h (24 * 1h candles), a minimum of 4 trades.
    • +
    +

    ``` python +from freqtrade.strategy import IStrategy

    +

    class AwesomeStrategy(IStrategy) + timeframe = '1h' + protections = [ + { + "method": "CooldownPeriod", + "stop_duration_candles": 5 + }, + { + "method": "MaxDrawdown", + "lookback_period_candles": 48, + "trade_limit": 20, + "stop_duration_candles": 4, + "max_allowed_drawdown": 0.2 + }, + { + "method": "StoplossGuard", + "lookback_period_candles": 24, + "trade_limit": 4, + "stop_duration_candles": 2, + "only_per_pair": False + }, + { + "method": "LowProfitPairs", + "lookback_period_candles": 6, + "trade_limit": 2, + "stop_duration_candles": 60, + "required_profit": 0.02 + }, + { + "method": "LowProfitPairs", + "lookback_period_candles": 24, + "trade_limit": 4, + "stop_duration_candles": 2, + "required_profit": 0.01 + } + ] + # ... +```

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/requirements-docs.txt b/en/2021.7/requirements-docs.txt new file mode 100644 index 000000000..6a904c951 --- /dev/null +++ b/en/2021.7/requirements-docs.txt @@ -0,0 +1,4 @@ +mkdocs==1.2.2 +mkdocs-material==7.2.1 +mdx_truly_sane_lists==1.2 +pymdown-extensions==8.2 diff --git a/en/2021.7/rest-api/index.html b/en/2021.7/rest-api/index.html new file mode 100644 index 000000000..5abd612df --- /dev/null +++ b/en/2021.7/rest-api/index.html @@ -0,0 +1,1540 @@ + + + + + + + + + + + + + + + + + + + REST API & FreqUI - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + + + + + + +

    REST API & FreqUI

    +

    FreqUI

    +

    Freqtrade provides a builtin webserver, which can serve FreqUI, the freqtrade UI.

    +

    By default, the UI is not included in the installation (except for docker images), and must be installed explicitly with freqtrade install-ui. +This same command can also be used to update freqUI, should there be a new release.

    +

    Once the bot is started in trade / dry-run mode (with freqtrade trade) - the UI will be available under the configured port below (usually http://127.0.0.1:8080).

    +
    +

    Alpha release

    +

    FreqUI is still considered an alpha release - if you encounter bugs or inconsistencies please open a FreqUI issue.

    +
    +
    +

    developers

    +

    Developers should not use this method, but instead use the method described in the freqUI repository to get the source-code of freqUI.

    +
    +

    Configuration

    +

    Enable the rest API by adding the api_server section to your configuration and setting api_server.enabled to true.

    +

    Sample configuration:

    +

    json + "api_server": { + "enabled": true, + "listen_ip_address": "127.0.0.1", + "listen_port": 8080, + "verbosity": "error", + "enable_openapi": false, + "jwt_secret_key": "somethingrandom", + "CORS_origins": [], + "username": "Freqtrader", + "password": "SuperSecret1!" + },

    +
    +

    Security warning

    +

    By default, the configuration listens on localhost only (so it's not reachable from other systems). We strongly recommend to not expose this API to the internet and choose a strong, unique password, since others will potentially be able to control your bot.

    +
    +

    You can then access the API by going to http://127.0.0.1:8080/api/v1/ping in a browser to check if the API is running correctly. +This should return the response:

    +

    output +{"status":"pong"}

    +

    All other endpoints return sensitive info and require authentication and are therefore not available through a web browser.

    +

    Security

    +

    To generate a secure password, best use a password manager, or use the below code.

    +

    python +import secrets +secrets.token_hex()

    +
    +

    JWT token

    +

    Use the same method to also generate a JWT secret key (jwt_secret_key).

    +
    +
    +

    Password selection

    +

    Please make sure to select a very strong, unique password to protect your bot from unauthorized access. +Also change jwt_secret_key to something random (no need to remember this, but it'll be used to encrypt your session, so it better be something unique!).

    +
    +

    Configuration with docker

    +

    If you run your bot using docker, you'll need to have the bot listen to incoming connections. The security is then handled by docker.

    +

    json + "api_server": { + "enabled": true, + "listen_ip_address": "0.0.0.0", + "listen_port": 8080, + "username": "Freqtrader", + "password": "SuperSecret1!", + //... + },

    +

    Uncomment the following from your docker-compose file:

    +

    yml + ports: + - "127.0.0.1:8080:8080"

    +
    +

    Security warning

    +

    By using 8080:8080 in the docker port mapping, the API will be available to everyone connecting to the server under the correct port, so others may be able to control your bot.

    +
    +

    Rest API

    +

    Consuming the API

    +

    You can consume the API by using the script scripts/rest_client.py. +The client script only requires the requests module, so Freqtrade does not need to be installed on the system.

    +

    bash +python3 scripts/rest_client.py <command> [optional parameters]

    +

    By default, the script assumes 127.0.0.1 (localhost) and port 8080 to be used, however you can specify a configuration file to override this behaviour.

    +

    Minimalistic client config

    +

    json +{ + "api_server": { + "enabled": true, + "listen_ip_address": "0.0.0.0", + "listen_port": 8080, + "username": "Freqtrader", + "password": "SuperSecret1!", + //... + } +}

    +

    bash +python3 scripts/rest_client.py --config rest_config.json <command> [optional parameters]

    +

    Available endpoints

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    CommandDescription
    pingSimple command testing the API Readiness - requires no authentication.
    startStarts the trader.
    stopStops the trader.
    stopbuyStops the trader from opening new trades. Gracefully closes open trades according to their rules.
    reload_configReloads the configuration file.
    tradesList last trades. Limited to 500 trades per call.
    trade/<tradeid>Get specific trade.
    delete_trade <trade_id>Remove trade from the database. Tries to close open orders. Requires manual handling of this trade on the exchange.
    show_configShows part of the current configuration with relevant settings to operation.
    logsShows last log messages.
    statusLists all open trades.
    countDisplays number of trades used and available.
    locksDisplays currently locked pairs.
    delete_lock <lock_id>Deletes (disables) the lock by id.
    profitDisplay a summary of your profit/loss from close trades and some stats about your performance.
    forcesell <trade_id>Instantly sells the given trade (Ignoring minimum_roi).
    forcesell allInstantly sells all open trades (Ignoring minimum_roi).
    forcebuy <pair> [rate]Instantly buys the given pair. Rate is optional. (forcebuy_enable must be set to True)
    performanceShow performance of each finished trade grouped by pair.
    balanceShow account balance per currency.
    daily <n>Shows profit or loss per day, over the last n days (n defaults to 7).
    statsDisplay a summary of profit / loss reasons as well as average holding times.
    whitelistShow the current whitelist.
    blacklist [pair]Show the current blacklist, or adds a pair to the blacklist.
    edgeShow validated pairs by Edge if it is enabled.
    pair_candlesReturns dataframe for a pair / timeframe combination while the bot is running. Alpha
    pair_historyReturns an analyzed dataframe for a given timerange, analyzed by a given strategy. Alpha
    plot_configGet plot config from the strategy (or nothing if not configured). Alpha
    strategiesList strategies in strategy directory. Alpha
    strategy <strategy>Get specific Strategy content. Alpha
    available_pairsList available backtest data. Alpha
    versionShow version.
    +
    +

    Alpha status

    +

    Endpoints labeled with Alpha status above may change at any time without notice.

    +
    +

    Possible commands can be listed from the rest-client script using the help command.

    +

    bash +python3 scripts/rest_client.py help

    +

    ``` output +Possible commands:

    +

    available_pairs + Return available pair (backtest data) based on timeframe / stake_currency selection

    +
        :param timeframe: Only pairs with this timeframe available.
    +    :param stake_currency: Only pairs that include this timeframe
    +
    + +

    balance + Get the account balance.

    +

    blacklist + Show the current blacklist.

    +
        :param add: List of coins to add (example: "BNB/BTC")
    +
    + +

    count + Return the amount of open trades.

    +

    daily + Return the profits for each day, and amount of trades.

    +

    delete_lock + Delete (disable) lock from the database.

    +
        :param lock_id: ID for the lock to delete
    +
    + +

    delete_trade + Delete trade from the database. + Tries to close open orders. Requires manual handling of this asset on the exchange.

    +
        :param trade_id: Deletes the trade with this ID from the database.
    +
    + +

    edge + Return information about edge.

    +

    forcebuy + Buy an asset.

    +
        :param pair: Pair to buy (ETH/BTC)
    +    :param price: Optional - price to buy
    +
    + +

    forcesell + Force-sell a trade.

    +
        :param tradeid: Id of the trade (can be received via status command)
    +
    + +

    locks + Return current locks

    +

    logs + Show latest logs.

    +
        :param limit: Limits log messages to the last <limit> logs. No limit to get the entire log.
    +
    + +

    pair_candles + Return live dataframe for .

    +
        :param pair: Pair to get data for
    +    :param timeframe: Only pairs with this timeframe available.
    +    :param limit: Limit result to the last n candles.
    +
    + +

    pair_history + Return historic, analyzed dataframe

    +
        :param pair: Pair to get data for
    +    :param timeframe: Only pairs with this timeframe available.
    +    :param strategy: Strategy to analyze and get values for
    +    :param timerange: Timerange to get data for (same format than --timerange endpoints)
    +
    + +

    performance + Return the performance of the different coins.

    +

    ping + simple ping

    +

    plot_config + Return plot configuration if the strategy defines one.

    +

    profit + Return the profit summary.

    +

    reload_config + Reload configuration.

    +

    show_config

    +
        Returns part of the configuration, relevant for trading operations.
    +
    + +

    start + Start the bot if it's in the stopped state.

    +

    stats + Return the stats report (durations, sell-reasons).

    +

    status + Get the status of open trades.

    +

    stop + Stop the bot. Use start to restart.

    +

    stopbuy + Stop buying (but handle sells gracefully). Use reload_config to reset.

    +

    strategies + Lists available strategies

    +

    strategy + Get strategy details

    +
        :param strategy: Strategy class name
    +
    + +

    trade + Return specific trade

    +
        :param trade_id: Specify which trade to get.
    +
    + +

    trades + Return trades history, sorted by id

    +
        :param limit: Limits trades to the X last trades. Max 500 trades.
    +    :param offset: Offset by this amount of trades.
    +
    + +

    version + Return the version of the bot.

    +

    whitelist + Show the current whitelist. +```

    +

    OpenAPI interface

    +

    To enable the builtin openAPI interface (Swagger UI), specify "enable_openapi": true in the api_server configuration. +This will enable the Swagger UI at the /docs endpoint. By default, that's running at http://localhost:8080/docs/ - but it'll depend on your settings.

    +

    Advanced API usage using JWT tokens

    +
    +

    Note

    +

    The below should be done in an application (a Freqtrade REST API client, which fetches info via API), and is not intended to be used on a regular basis.

    +
    +

    Freqtrade's REST API also offers JWT (JSON Web Tokens). +You can login using the following command, and subsequently use the resulting access_token.

    +

    ``` bash

    +
    +

    curl -X POST --user Freqtrader http://localhost:8080/api/v1/token/login

    +

    access_token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1ODkxMTk2ODEsIm5iZiI6MTU4OTExOTY4MSwianRpIjoiMmEwYmY0NWUtMjhmOS00YTUzLTlmNzItMmM5ZWVlYThkNzc2IiwiZXhwIjoxNTg5MTIwNTgxLCJpZGVudGl0eSI6eyJ1IjoiRnJlcXRyYWRlciJ9LCJmcmVzaCI6ZmFsc2UsInR5cGUiOiJhY2Nlc3MifQ.qt6MAXYIa-l556OM7arBvYJ0SDI9J8bIk3_glDujF5g"

    +
    +

    Use access_token for authentication

    +
    +

    curl -X GET --header "Authorization: Bearer ${access_token}" http://localhost:8080/api/v1/count

    +
    +

    ```

    +

    Since the access token has a short timeout (15 min) - the token/refresh request should be used periodically to get a fresh access token:

    +

    ``` bash

    +
    +

    curl -X POST --header "Authorization: Bearer ${refresh_token}"http://localhost:8080/api/v1/token/refresh +{"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1ODkxMTk5NzQsIm5iZiI6MTU4OTExOTk3NCwianRpIjoiMDBjNTlhMWUtMjBmYS00ZTk0LTliZjAtNWQwNTg2MTdiZDIyIiwiZXhwIjoxNTg5MTIwODc0LCJpZGVudGl0eSI6eyJ1IjoiRnJlcXRyYWRlciJ9LCJmcmVzaCI6ZmFsc2UsInR5cGUiOiJhY2Nlc3MifQ.1seHlII3WprjjclY6DpRhen0rqdF4j6jbvxIhUFaSbs"} +```

    +
    +

    CORS

    +

    All web-based front-ends are subject to CORS - Cross-Origin Resource Sharing. +Since most of the requests to the Freqtrade API must be authenticated, a proper CORS policy is key to avoid security problems. +Also, the standard disallows * CORS policies for requests with credentials, so this setting must be set appropriately.

    +

    Users can configure this themselves via the CORS_origins configuration setting. +It consists of a list of allowed sites that are allowed to consume resources from the bot's API.

    +

    Assuming your application is deployed as https://frequi.freqtrade.io/home/ - this would mean that the following configuration becomes necessary:

    +

    jsonc +{ + //... + "jwt_secret_key": "somethingrandom", + "CORS_origins": ["https://frequi.freqtrade.io"], + //... +}

    +
    +

    Note

    +

    We strongly recommend to also set jwt_secret_key to something random and known only to yourself to avoid unauthorized access to your bot.

    +
    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/sandbox-testing/index.html b/en/2021.7/sandbox-testing/index.html new file mode 100644 index 000000000..2ac27d31b --- /dev/null +++ b/en/2021.7/sandbox-testing/index.html @@ -0,0 +1,1231 @@ + + + + + + + + + + + + + + + + + + + Sandbox Testing - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + + + + +
    +
    + + + + + + + +

    Sandbox API testing

    +

    Some exchanges provide sandboxes or testbeds for risk-free testing, while running the bot against a real exchange. +With some configuration, freqtrade (in combination with ccxt) provides access to these.

    +

    This document is an overview to configure Freqtrade to be used with sandboxes. +This can be useful to developers and trader alike.

    +
    +

    Warning

    +

    Sandboxes usually have very low volume, and either a very wide spread, or no orders available at all. +Therefore, sandboxes will usually not do a good job of showing you how a strategy would work in real trading.

    +
    +

    Exchanges known to have a sandbox / testnet

    + +
    +

    Note

    +

    We did not test correct functioning of all of the above testnets. Please report your experiences with each sandbox.

    +
    +
    +

    Configure a Sandbox account

    +

    When testing your API connectivity, make sure to use the appropriate sandbox / testnet URL.

    +

    In general, you should follow these steps to enable an exchange's sandbox:

    +
      +
    • Figure out if an exchange has a sandbox (most likely by using google or the exchange's support documents)
    • +
    • Create a sandbox account (often the sandbox-account requires separate registration)
    • +
    • Add some test assets to account
    • +
    • Create API keys
    • +
    +

    Add test funds

    +

    Usually, sandbox exchanges allow depositing funds directly via web-interface. +You should make sure to have a realistic amount of funds available to your test-account, so results are representable of your real account funds.

    +
    +

    Warning

    +

    Test exchanges will NEVER require your real credit card or banking details!

    +
    +

    Configure freqtrade to use a exchange's sandbox

    +

    Sandbox URLs

    +

    Freqtrade makes use of CCXT which in turn provides a list of URLs to Freqtrade. +These include ['test'] and ['api'].

    +
      +
    • [Test] if available will point to an Exchanges sandbox.
    • +
    • [Api] normally used, and resolves to live API target on the exchange.
    • +
    +

    To make use of sandbox / test add "sandbox": true, to your config.json

    +

    json + "exchange": { + "name": "coinbasepro", + "sandbox": true, + "key": "5wowfxemogxeowo;heiohgmd", + "secret": "/ZMH1P62rCVmwefewrgcewX8nh4gob+lywxfwfxwwfxwfNsH1ySgvWCUR/w==", + "password": "1bkjfkhfhfu6sr", + "outdated_offset": 5 + "pair_whitelist": [ + "BTC/USD" + ] + }, + "datadir": "user_data/data/coinbasepro_sandbox"

    +

    Also the following information:

    +
      +
    • api-key (created for the sandbox webpage)
    • +
    • api-secret (noted earlier)
    • +
    • password (the passphrase - noted earlier)
    • +
    +
    +

    Different data directory

    +

    We also recommend to set datadir to something identifying downloaded data as sandbox data, to avoid having sandbox data mixed with data from the real exchange. +This can be done by adding the "datadir" key to the configuration. +Now, whenever you use this configuration, your data directory will be set to this directory.

    +
    +
    +

    You should now be ready to test your sandbox

    +

    Ensure Freqtrade logs show the sandbox URL, and trades made are shown in sandbox. Also make sure to select a pair which shows at least some decent value (which very often is BTC/).

    +

    Common problems with sandbox exchanges

    +

    Sandbox exchange instances often have very low volume, which can cause some problems which usually are not seen on a real exchange instance.

    +

    Old Candles problem

    +

    Since Sandboxes often have low volume, candles can be quite old and show no volume. +To disable the error "Outdated history for pair ...", best increase the parameter "outdated_offset" to a number that seems realistic for the sandbox you're using.

    +

    Unfilled orders

    +

    Sandboxes often have very low volumes - which means that many trades can go unfilled, or can go unfilled for a very long time.

    +

    To mitigate this, you can try to match the first order on the opposite orderbook side using the following configuration:

    +

    jsonc + "order_types": { + "buy": "limit", + "sell": "limit" + // ... + }, + "bid_strategy": { + "price_side": "ask", + // ... + }, + "ask_strategy":{ + "price_side": "bid", + // ... + },

    +

    The configuration is similar to the suggested configuration for market orders - however by using limit-orders you can avoid moving the price too much, and you can set the worst price you might get.

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/search/search_index.json b/en/2021.7/search/search_index.json new file mode 100644 index 000000000..0d86789f6 --- /dev/null +++ b/en/2021.7/search/search_index.json @@ -0,0 +1 @@ +{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Star Fork Download Introduction \u00b6 Freqtrade is a crypto-currency algorithmic trading software developed in python (3.7+) and supported on Windows, macOS and Linux. DISCLAIMER This software is for educational purposes only. Do not risk money which you are afraid to lose. USE THE SOFTWARE AT YOUR OWN RISK. THE AUTHORS AND ALL AFFILIATES ASSUME NO RESPONSIBILITY FOR YOUR TRADING RESULTS. Always start by running a trading bot in Dry-run and do not engage money before you understand how it works and what profit/loss you should expect. We strongly recommend you to have basic coding skills and Python knowledge. Do not hesitate to read the source code and understand the mechanisms of this bot, algorithms and techniques implemented in it. Features \u00b6 Develop your Strategy: Write your strategy in python, using pandas . Example strategies to inspire you are available in the strategy repository . Download market data: Download historical data of the exchange and the markets your may want to trade with. Backtest: Test your strategy on downloaded historical data. Optimize: Find the best parameters for your strategy using hyperoptimization which employs machining learning methods. You can optimize buy, sell, take profit (ROI), stop-loss and trailing stop-loss parameters for your strategy. Select markets: Create your static list or use an automatic one based on top traded volumes and/or prices (not available during backtesting). You can also explicitly blacklist markets you don't want to trade. Run: Test your strategy with simulated money (Dry-Run mode) or deploy it with real money (Live-Trade mode). Run using Edge (optional module): The concept is to find the best historical trade expectancy by markets based on variation of the stop-loss and then allow/reject markets to trade. The sizing of the trade is based on a risk of a percentage of your capital. Control/Monitor: Use Telegram or a REST API (start/stop the bot, show profit/loss, daily summary, current open trades results, etc.). Analyse: Further analysis can be performed on either Backtesting data or Freqtrade trading history (SQL database), including automated standard plots, and methods to load the data into interactive environments . Supported exchange marketplaces \u00b6 Please read the exchange specific notes to learn about eventual, special configurations needed for each exchange. Binance ( *Note for binance users ) Bittrex FTX Kraken potentially many others through . (We cannot guarantee they will work) Community tested \u00b6 Exchanges confirmed working by the community: Bitvavo Kukoin Requirements \u00b6 Hardware requirements \u00b6 To run this bot we recommend you a linux cloud instance with a minimum of: 2GB RAM 1GB disk space 2vCPU Software requirements \u00b6 Docker (Recommended) Alternatively Python 3.7+ pip (pip3) git TA-Lib virtualenv (Recommended) Support \u00b6 Help / Discord \u00b6 For any questions not covered by the documentation or for further information about the bot, or to simply engage with like-minded individuals, we encourage you to join the Freqtrade discord server . Ready to try? \u00b6 Begin by reading our installation guide for docker (recommended), or for installation without docker .","title":"Home"},{"location":"#introduction","text":"Freqtrade is a crypto-currency algorithmic trading software developed in python (3.7+) and supported on Windows, macOS and Linux. DISCLAIMER This software is for educational purposes only. Do not risk money which you are afraid to lose. USE THE SOFTWARE AT YOUR OWN RISK. THE AUTHORS AND ALL AFFILIATES ASSUME NO RESPONSIBILITY FOR YOUR TRADING RESULTS. Always start by running a trading bot in Dry-run and do not engage money before you understand how it works and what profit/loss you should expect. We strongly recommend you to have basic coding skills and Python knowledge. Do not hesitate to read the source code and understand the mechanisms of this bot, algorithms and techniques implemented in it.","title":"Introduction"},{"location":"#features","text":"Develop your Strategy: Write your strategy in python, using pandas . Example strategies to inspire you are available in the strategy repository . Download market data: Download historical data of the exchange and the markets your may want to trade with. Backtest: Test your strategy on downloaded historical data. Optimize: Find the best parameters for your strategy using hyperoptimization which employs machining learning methods. You can optimize buy, sell, take profit (ROI), stop-loss and trailing stop-loss parameters for your strategy. Select markets: Create your static list or use an automatic one based on top traded volumes and/or prices (not available during backtesting). You can also explicitly blacklist markets you don't want to trade. Run: Test your strategy with simulated money (Dry-Run mode) or deploy it with real money (Live-Trade mode). Run using Edge (optional module): The concept is to find the best historical trade expectancy by markets based on variation of the stop-loss and then allow/reject markets to trade. The sizing of the trade is based on a risk of a percentage of your capital. Control/Monitor: Use Telegram or a REST API (start/stop the bot, show profit/loss, daily summary, current open trades results, etc.). Analyse: Further analysis can be performed on either Backtesting data or Freqtrade trading history (SQL database), including automated standard plots, and methods to load the data into interactive environments .","title":"Features"},{"location":"#supported-exchange-marketplaces","text":"Please read the exchange specific notes to learn about eventual, special configurations needed for each exchange. Binance ( *Note for binance users ) Bittrex FTX Kraken potentially many others through . (We cannot guarantee they will work)","title":"Supported exchange marketplaces"},{"location":"#community-tested","text":"Exchanges confirmed working by the community: Bitvavo Kukoin","title":"Community tested"},{"location":"#requirements","text":"","title":"Requirements"},{"location":"#hardware-requirements","text":"To run this bot we recommend you a linux cloud instance with a minimum of: 2GB RAM 1GB disk space 2vCPU","title":"Hardware requirements"},{"location":"#software-requirements","text":"Docker (Recommended) Alternatively Python 3.7+ pip (pip3) git TA-Lib virtualenv (Recommended)","title":"Software requirements"},{"location":"#support","text":"","title":"Support"},{"location":"#help-discord","text":"For any questions not covered by the documentation or for further information about the bot, or to simply engage with like-minded individuals, we encourage you to join the Freqtrade discord server .","title":"Help / Discord"},{"location":"#ready-to-try","text":"Begin by reading our installation guide for docker (recommended), or for installation without docker .","title":"Ready to try?"},{"location":"advanced-hyperopt/","text":"Advanced Hyperopt \u00b6 This page explains some advanced Hyperopt topics that may require higher coding skills and Python knowledge than creation of an ordinal hyperoptimization class. Creating and using a custom loss function \u00b6 To use a custom loss function class, make sure that the function hyperopt_loss_function is defined in your custom hyperopt loss class. For the sample below, you then need to add the command line parameter --hyperopt-loss SuperDuperHyperOptLoss to your hyperopt call so this function is being used. A sample of this can be found below, which is identical to the Default Hyperopt loss implementation. A full sample can be found in userdata/hyperopts . ``` python from datetime import datetime from typing import Dict from pandas import DataFrame from freqtrade.optimize.hyperopt import IHyperOptLoss TARGET_TRADES = 600 EXPECTED_MAX_PROFIT = 3.0 MAX_ACCEPTED_TRADE_DURATION = 300 class SuperDuperHyperOptLoss(IHyperOptLoss): \"\"\" Defines the default loss function for hyperopt \"\"\" @staticmethod def hyperopt_loss_function(results: DataFrame, trade_count: int, min_date: datetime, max_date: datetime, config: Dict, processed: Dict[str, DataFrame], backtest_stats: Dict[str, Any], *args, **kwargs) -> float: \"\"\" Objective function, returns smaller number for better results This is the legacy algorithm (used until now in freqtrade). Weights are distributed as follows: * 0.4 to trade duration * 0.25: Avoiding trade loss * 1.0 to total profit, compared to the expected value (`EXPECTED_MAX_PROFIT`) defined above \"\"\" total_profit = results['profit_ratio'].sum() trade_duration = results['trade_duration'].mean() trade_loss = 1 - 0.25 * exp(-(trade_count - TARGET_TRADES) ** 2 / 10 ** 5.8) profit_loss = max(0, 1 - total_profit / EXPECTED_MAX_PROFIT) duration_loss = 0.4 * min(trade_duration / MAX_ACCEPTED_TRADE_DURATION, 1) result = trade_loss + profit_loss + duration_loss return result ``` Currently, the arguments are: results : DataFrame containing the resulting trades. The following columns are available in results (corresponds to the output-file of backtesting when used with --export trades ): pair, profit_ratio, profit_abs, open_date, open_rate, fee_open, close_date, close_rate, fee_close, amount, trade_duration, is_open, sell_reason, stake_amount, min_rate, max_rate, stop_loss_ratio, stop_loss_abs trade_count : Amount of trades (identical to len(results) ) min_date : Start date of the timerange used min_date : End date of the timerange used config : Config object used (Note: Not all strategy-related parameters will be updated here if they are part of a hyperopt space). processed : Dict of Dataframes with the pair as keys containing the data used for backtesting. backtest_stats : Backtesting statistics using the same format as the backtesting file \"strategy\" substructure. Available fields can be seen in generate_strategy_stats() in optimize_reports.py . This function needs to return a floating point number ( float ). Smaller numbers will be interpreted as better results. The parameters and balancing for this is up to you. Note This function is called once per iteration - so please make sure to have this as optimized as possible to not slow hyperopt down unnecessarily. Note Please keep the arguments *args and **kwargs in the interface to allow us to extend this interface later. Overriding pre-defined spaces \u00b6 To override a pre-defined space ( roi_space , generate_roi_table , stoploss_space , trailing_space ), define a nested class called Hyperopt and define the required spaces as follows: python class MyAwesomeStrategy(IStrategy): class HyperOpt: # Define a custom stoploss space. def stoploss_space(self): return [SKDecimal(-0.05, -0.01, decimals=3, name='stoploss')] Space options \u00b6 For the additional spaces, scikit-optimize (in combination with Freqtrade) provides the following space types: Categorical - Pick from a list of categories (e.g. Categorical(['a', 'b', 'c'], name=\"cat\") ) Integer - Pick from a range of whole numbers (e.g. Integer(1, 10, name='rsi') ) SKDecimal - Pick from a range of decimal numbers with limited precision (e.g. SKDecimal(0.1, 0.5, decimals=3, name='adx') ). Available only with freqtrade . Real - Pick from a range of decimal numbers with full precision (e.g. Real(0.1, 0.5, name='adx') You can import all of these from freqtrade.optimize.space , although Categorical , Integer and Real are only aliases for their corresponding scikit-optimize Spaces. SKDecimal is provided by freqtrade for faster optimizations. python from freqtrade.optimize.space import Categorical, Dimension, Integer, SKDecimal, Real # noqa SKDecimal vs. Real We recommend to use SKDecimal instead of the Real space in almost all cases. While the Real space provides full accuracy (up to ~16 decimal places) - this precision is rarely needed, and leads to unnecessary long hyperopt times. Assuming the definition of a rather small space ( SKDecimal(0.10, 0.15, decimals=2, name='xxx') ) - SKDecimal will have 5 possibilities ( [0.10, 0.11, 0.12, 0.13, 0.14, 0.15] ). A corresponding real space Real(0.10, 0.15 name='xxx') on the other hand has an almost unlimited number of possibilities ( [0.10, 0.010000000001, 0.010000000002, ... 0.014999999999, 0.01500000000] ). Legacy Hyperopt \u00b6 This Section explains the configuration of an explicit Hyperopt file (separate to the strategy). Deprecated / legacy mode Since the 2021.4 release you no longer have to write a separate hyperopt class, but all strategies can be hyperopted. Please read the main hyperopt page for more details. Prepare hyperopt file \u00b6 Configuring an explicit hyperopt file is similar to writing your own strategy, and many tasks will be similar. About this page For this page, we will be using a fictional strategy called AwesomeStrategy - which will be optimized using the AwesomeHyperopt class. Create a Custom Hyperopt File \u00b6 The simplest way to get started is to use the following command, which will create a new hyperopt file from a template, which will be located under user_data/hyperopts/AwesomeHyperopt.py . Let assume you want a hyperopt file AwesomeHyperopt.py : bash freqtrade new-hyperopt --hyperopt AwesomeHyperopt Legacy Hyperopt checklist \u00b6 Checklist on all tasks / possibilities in hyperopt Depending on the space you want to optimize, only some of the below are required: fill buy_strategy_generator - for buy signal optimization fill indicator_space - for buy signal optimization fill sell_strategy_generator - for sell signal optimization fill sell_indicator_space - for sell signal optimization Note populate_indicators needs to create all indicators any of thee spaces may use, otherwise hyperopt will not work. Optional in hyperopt - can also be loaded from a strategy (recommended): populate_indicators - fallback to create indicators populate_buy_trend - fallback if not optimizing for buy space. should come from strategy populate_sell_trend - fallback if not optimizing for sell space. should come from strategy Note You always have to provide a strategy to Hyperopt, even if your custom Hyperopt class contains all methods. Assuming the optional methods are not in your hyperopt file, please use --strategy AweSomeStrategy which contains these methods so hyperopt can use these methods instead. Rarely you may also need to override: roi_space - for custom ROI optimization (if you need the ranges for the ROI parameters in the optimization hyperspace that differ from default) generate_roi_table - for custom ROI optimization (if you need the ranges for the values in the ROI table that differ from default or the number of entries (steps) in the ROI table which differs from the default 4 steps) stoploss_space - for custom stoploss optimization (if you need the range for the stoploss parameter in the optimization hyperspace that differs from default) trailing_space - for custom trailing stop optimization (if you need the ranges for the trailing stop parameters in the optimization hyperspace that differ from default) Defining a buy signal optimization \u00b6 Let's say you are curious: should you use MACD crossings or lower Bollinger Bands to trigger your buys. And you also wonder should you use RSI or ADX to help with those buy decisions. If you decide to use RSI or ADX, which values should I use for them? So let's use hyperparameter optimization to solve this mystery. We will start by defining a search space: python def indicator_space() -> List[Dimension]: \"\"\" Define your Hyperopt space for searching strategy parameters \"\"\" return [ Integer(20, 40, name='adx-value'), Integer(20, 40, name='rsi-value'), Categorical([True, False], name='adx-enabled'), Categorical([True, False], name='rsi-enabled'), Categorical(['bb_lower', 'macd_cross_signal'], name='trigger') ] Above definition says: I have five parameters I want you to randomly combine to find the best combination. Two of them are integer values ( adx-value and rsi-value ) and I want you test in the range of values 20 to 40. Then we have three category variables. First two are either True or False . We use these to either enable or disable the ADX and RSI guards. The last one we call trigger and use it to decide which buy trigger we want to use. So let's write the buy strategy generator using these values: ```python @staticmethod def buy_strategy_generator(params: Dict[str, Any]) -> Callable: \"\"\" Define the buy strategy parameters to be used by Hyperopt. \"\"\" def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: conditions = [] # GUARDS AND TRENDS if 'adx-enabled' in params and params['adx-enabled']: conditions.append(dataframe['adx'] > params['adx-value']) if 'rsi-enabled' in params and params['rsi-enabled']: conditions.append(dataframe['rsi'] < params['rsi-value']) # TRIGGERS if 'trigger' in params: if params['trigger'] == 'bb_lower': conditions.append(dataframe['close'] < dataframe['bb_lowerband']) if params['trigger'] == 'macd_cross_signal': conditions.append(qtpylib.crossed_above( dataframe['macd'], dataframe['macdsignal'] )) # Check that volume is not 0 conditions.append(dataframe['volume'] > 0) if conditions: dataframe.loc[ reduce(lambda x, y: x & y, conditions), 'buy'] = 1 return dataframe return populate_buy_trend ``` Hyperopt will now call populate_buy_trend() many times ( epochs ) with different value combinations. It will use the given historical data and make buys based on the buy signals generated with the above function. Based on the results, hyperopt will tell you which parameter combination produced the best results (based on the configured loss function ). Note The above setup expects to find ADX, RSI and Bollinger Bands in the populated indicators. When you want to test an indicator that isn't used by the bot currently, remember to add it to the populate_indicators() method in your strategy or hyperopt file. Sell optimization \u00b6 Similar to the buy-signal above, sell-signals can also be optimized. Place the corresponding settings into the following methods Inside sell_indicator_space() - the parameters hyperopt shall be optimizing. Within sell_strategy_generator() - populate the nested method populate_sell_trend() to apply the parameters. The configuration and rules are the same than for buy signals. To avoid naming collisions in the search-space, please prefix all sell-spaces with sell- . Execute Hyperopt \u00b6 Once you have updated your hyperopt configuration you can run it. Because hyperopt tries a lot of combinations to find the best parameters it will take time to get a good result. More time usually results in better results. We strongly recommend to use screen or tmux to prevent any connection loss. bash freqtrade hyperopt --config config.json --hyperopt --hyperopt-loss --strategy -e 500 --spaces all Use as the name of the custom hyperopt used. The -e option will set how many evaluations hyperopt will do. Since hyperopt uses Bayesian search, running too many epochs at once may not produce greater results. Experience has shown that best results are usually not improving much after 500-1000 epochs. Doing multiple runs (executions) with a few 1000 epochs and different random state will most likely produce different results. The --spaces all option determines that all possible parameters should be optimized. Possibilities are listed below. Note Hyperopt will store hyperopt results with the timestamp of the hyperopt start time. Reading commands ( hyperopt-list , hyperopt-show ) can use --hyperopt-filename to read and display older hyperopt results. You can find a list of filenames with ls -l user_data/hyperopt_results/ . Running Hyperopt using methods from a strategy \u00b6 Hyperopt can reuse populate_indicators , populate_buy_trend , populate_sell_trend from your strategy, assuming these methods are not in your custom hyperopt file, and a strategy is provided. bash freqtrade hyperopt --hyperopt AwesomeHyperopt --hyperopt-loss SharpeHyperOptLossDaily --strategy AwesomeStrategy Understand the Hyperopt Result \u00b6 Once Hyperopt is completed you can use the result to create a new strategy. Given the following result from hyperopt: ``` Best result: 44/100: 135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722%). Avg duration 180.4 mins. Objective: 1.94367 Buy hyperspace params: { 'adx-value': 44, 'rsi-value': 29, 'adx-enabled': False, 'rsi-enabled': True, 'trigger': 'bb_lower'} ``` You should understand this result like: The buy trigger that worked best was bb_lower . You should not use ADX because adx-enabled: False ) You should consider using the RSI indicator ( rsi-enabled: True and the best value is 29.0 ( rsi-value: 29.0 ) You have to look inside your strategy file into buy_strategy_generator() method, what those values match to. So for example you had rsi-value: 29.0 so we would look at rsi -block, that translates to the following code block: python (dataframe['rsi'] < 29.0) Translating your whole hyperopt result as the new buy-signal would then look like: python def populate_buy_trend(self, dataframe: DataFrame) -> DataFrame: dataframe.loc[ ( (dataframe['rsi'] < 29.0) & # rsi-value dataframe['close'] < dataframe['bb_lowerband'] # trigger ), 'buy'] = 1 return dataframe Validate backtesting results \u00b6 Once the optimized parameters and conditions have been implemented into your strategy, you should backtest the strategy to make sure everything is working as expected. To achieve same results (number of trades, their durations, profit, etc.) than during Hyperopt, please use same configuration and parameters (timerange, timeframe, ...) used for hyperopt --dmmp / --disable-max-market-positions and --eps / --enable-position-stacking for Backtesting. Should results don't match, please double-check to make sure you transferred all conditions correctly. Pay special care to the stoploss (and trailing stoploss) parameters, as these are often set in configuration files, which override changes to the strategy. You should also carefully review the log of your backtest to ensure that there were no parameters inadvertently set by the configuration (like stoploss or trailing_stop ). Sharing methods with your strategy \u00b6 Hyperopt classes provide access to the Strategy via the strategy class attribute. This can be a great way to reduce code duplication if used correctly, but will also complicate usage for inexperienced users. ``` python from pandas import DataFrame from freqtrade.strategy.interface import IStrategy import freqtrade.vendor.qtpylib.indicators as qtpylib class MyAwesomeStrategy(IStrategy): buy_params = { 'rsi-value': 30, 'adx-value': 35, } def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: return self.buy_strategy_generator(self.buy_params, dataframe, metadata) @staticmethod def buy_strategy_generator(params, dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe.loc[ ( qtpylib.crossed_above(dataframe['rsi'], params['rsi-value']) & dataframe['adx'] > params['adx-value']) & dataframe['volume'] > 0 ) , 'buy'] = 1 return dataframe class MyAwesomeHyperOpt(IHyperOpt): ... @staticmethod def buy_strategy_generator(params: Dict[str, Any]) -> Callable: \"\"\" Define the buy strategy parameters to be used by Hyperopt. \"\"\" def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: # Call strategy's buy strategy generator return self.StrategyClass.buy_strategy_generator(params, dataframe, metadata) return populate_buy_trend ```","title":"Advanced Hyperopt"},{"location":"advanced-hyperopt/#advanced-hyperopt","text":"This page explains some advanced Hyperopt topics that may require higher coding skills and Python knowledge than creation of an ordinal hyperoptimization class.","title":"Advanced Hyperopt"},{"location":"advanced-hyperopt/#creating-and-using-a-custom-loss-function","text":"To use a custom loss function class, make sure that the function hyperopt_loss_function is defined in your custom hyperopt loss class. For the sample below, you then need to add the command line parameter --hyperopt-loss SuperDuperHyperOptLoss to your hyperopt call so this function is being used. A sample of this can be found below, which is identical to the Default Hyperopt loss implementation. A full sample can be found in userdata/hyperopts . ``` python from datetime import datetime from typing import Dict from pandas import DataFrame from freqtrade.optimize.hyperopt import IHyperOptLoss TARGET_TRADES = 600 EXPECTED_MAX_PROFIT = 3.0 MAX_ACCEPTED_TRADE_DURATION = 300 class SuperDuperHyperOptLoss(IHyperOptLoss): \"\"\" Defines the default loss function for hyperopt \"\"\" @staticmethod def hyperopt_loss_function(results: DataFrame, trade_count: int, min_date: datetime, max_date: datetime, config: Dict, processed: Dict[str, DataFrame], backtest_stats: Dict[str, Any], *args, **kwargs) -> float: \"\"\" Objective function, returns smaller number for better results This is the legacy algorithm (used until now in freqtrade). Weights are distributed as follows: * 0.4 to trade duration * 0.25: Avoiding trade loss * 1.0 to total profit, compared to the expected value (`EXPECTED_MAX_PROFIT`) defined above \"\"\" total_profit = results['profit_ratio'].sum() trade_duration = results['trade_duration'].mean() trade_loss = 1 - 0.25 * exp(-(trade_count - TARGET_TRADES) ** 2 / 10 ** 5.8) profit_loss = max(0, 1 - total_profit / EXPECTED_MAX_PROFIT) duration_loss = 0.4 * min(trade_duration / MAX_ACCEPTED_TRADE_DURATION, 1) result = trade_loss + profit_loss + duration_loss return result ``` Currently, the arguments are: results : DataFrame containing the resulting trades. The following columns are available in results (corresponds to the output-file of backtesting when used with --export trades ): pair, profit_ratio, profit_abs, open_date, open_rate, fee_open, close_date, close_rate, fee_close, amount, trade_duration, is_open, sell_reason, stake_amount, min_rate, max_rate, stop_loss_ratio, stop_loss_abs trade_count : Amount of trades (identical to len(results) ) min_date : Start date of the timerange used min_date : End date of the timerange used config : Config object used (Note: Not all strategy-related parameters will be updated here if they are part of a hyperopt space). processed : Dict of Dataframes with the pair as keys containing the data used for backtesting. backtest_stats : Backtesting statistics using the same format as the backtesting file \"strategy\" substructure. Available fields can be seen in generate_strategy_stats() in optimize_reports.py . This function needs to return a floating point number ( float ). Smaller numbers will be interpreted as better results. The parameters and balancing for this is up to you. Note This function is called once per iteration - so please make sure to have this as optimized as possible to not slow hyperopt down unnecessarily. Note Please keep the arguments *args and **kwargs in the interface to allow us to extend this interface later.","title":"Creating and using a custom loss function"},{"location":"advanced-hyperopt/#overriding-pre-defined-spaces","text":"To override a pre-defined space ( roi_space , generate_roi_table , stoploss_space , trailing_space ), define a nested class called Hyperopt and define the required spaces as follows: python class MyAwesomeStrategy(IStrategy): class HyperOpt: # Define a custom stoploss space. def stoploss_space(self): return [SKDecimal(-0.05, -0.01, decimals=3, name='stoploss')]","title":"Overriding pre-defined spaces"},{"location":"advanced-hyperopt/#space-options","text":"For the additional spaces, scikit-optimize (in combination with Freqtrade) provides the following space types: Categorical - Pick from a list of categories (e.g. Categorical(['a', 'b', 'c'], name=\"cat\") ) Integer - Pick from a range of whole numbers (e.g. Integer(1, 10, name='rsi') ) SKDecimal - Pick from a range of decimal numbers with limited precision (e.g. SKDecimal(0.1, 0.5, decimals=3, name='adx') ). Available only with freqtrade . Real - Pick from a range of decimal numbers with full precision (e.g. Real(0.1, 0.5, name='adx') You can import all of these from freqtrade.optimize.space , although Categorical , Integer and Real are only aliases for their corresponding scikit-optimize Spaces. SKDecimal is provided by freqtrade for faster optimizations. python from freqtrade.optimize.space import Categorical, Dimension, Integer, SKDecimal, Real # noqa SKDecimal vs. Real We recommend to use SKDecimal instead of the Real space in almost all cases. While the Real space provides full accuracy (up to ~16 decimal places) - this precision is rarely needed, and leads to unnecessary long hyperopt times. Assuming the definition of a rather small space ( SKDecimal(0.10, 0.15, decimals=2, name='xxx') ) - SKDecimal will have 5 possibilities ( [0.10, 0.11, 0.12, 0.13, 0.14, 0.15] ). A corresponding real space Real(0.10, 0.15 name='xxx') on the other hand has an almost unlimited number of possibilities ( [0.10, 0.010000000001, 0.010000000002, ... 0.014999999999, 0.01500000000] ).","title":"Space options"},{"location":"advanced-hyperopt/#legacy-hyperopt","text":"This Section explains the configuration of an explicit Hyperopt file (separate to the strategy). Deprecated / legacy mode Since the 2021.4 release you no longer have to write a separate hyperopt class, but all strategies can be hyperopted. Please read the main hyperopt page for more details.","title":"Legacy Hyperopt"},{"location":"advanced-hyperopt/#prepare-hyperopt-file","text":"Configuring an explicit hyperopt file is similar to writing your own strategy, and many tasks will be similar. About this page For this page, we will be using a fictional strategy called AwesomeStrategy - which will be optimized using the AwesomeHyperopt class.","title":"Prepare hyperopt file"},{"location":"advanced-hyperopt/#create-a-custom-hyperopt-file","text":"The simplest way to get started is to use the following command, which will create a new hyperopt file from a template, which will be located under user_data/hyperopts/AwesomeHyperopt.py . Let assume you want a hyperopt file AwesomeHyperopt.py : bash freqtrade new-hyperopt --hyperopt AwesomeHyperopt","title":"Create a Custom Hyperopt File"},{"location":"advanced-hyperopt/#legacy-hyperopt-checklist","text":"Checklist on all tasks / possibilities in hyperopt Depending on the space you want to optimize, only some of the below are required: fill buy_strategy_generator - for buy signal optimization fill indicator_space - for buy signal optimization fill sell_strategy_generator - for sell signal optimization fill sell_indicator_space - for sell signal optimization Note populate_indicators needs to create all indicators any of thee spaces may use, otherwise hyperopt will not work. Optional in hyperopt - can also be loaded from a strategy (recommended): populate_indicators - fallback to create indicators populate_buy_trend - fallback if not optimizing for buy space. should come from strategy populate_sell_trend - fallback if not optimizing for sell space. should come from strategy Note You always have to provide a strategy to Hyperopt, even if your custom Hyperopt class contains all methods. Assuming the optional methods are not in your hyperopt file, please use --strategy AweSomeStrategy which contains these methods so hyperopt can use these methods instead. Rarely you may also need to override: roi_space - for custom ROI optimization (if you need the ranges for the ROI parameters in the optimization hyperspace that differ from default) generate_roi_table - for custom ROI optimization (if you need the ranges for the values in the ROI table that differ from default or the number of entries (steps) in the ROI table which differs from the default 4 steps) stoploss_space - for custom stoploss optimization (if you need the range for the stoploss parameter in the optimization hyperspace that differs from default) trailing_space - for custom trailing stop optimization (if you need the ranges for the trailing stop parameters in the optimization hyperspace that differ from default)","title":"Legacy Hyperopt checklist"},{"location":"advanced-hyperopt/#defining-a-buy-signal-optimization","text":"Let's say you are curious: should you use MACD crossings or lower Bollinger Bands to trigger your buys. And you also wonder should you use RSI or ADX to help with those buy decisions. If you decide to use RSI or ADX, which values should I use for them? So let's use hyperparameter optimization to solve this mystery. We will start by defining a search space: python def indicator_space() -> List[Dimension]: \"\"\" Define your Hyperopt space for searching strategy parameters \"\"\" return [ Integer(20, 40, name='adx-value'), Integer(20, 40, name='rsi-value'), Categorical([True, False], name='adx-enabled'), Categorical([True, False], name='rsi-enabled'), Categorical(['bb_lower', 'macd_cross_signal'], name='trigger') ] Above definition says: I have five parameters I want you to randomly combine to find the best combination. Two of them are integer values ( adx-value and rsi-value ) and I want you test in the range of values 20 to 40. Then we have three category variables. First two are either True or False . We use these to either enable or disable the ADX and RSI guards. The last one we call trigger and use it to decide which buy trigger we want to use. So let's write the buy strategy generator using these values: ```python @staticmethod def buy_strategy_generator(params: Dict[str, Any]) -> Callable: \"\"\" Define the buy strategy parameters to be used by Hyperopt. \"\"\" def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: conditions = [] # GUARDS AND TRENDS if 'adx-enabled' in params and params['adx-enabled']: conditions.append(dataframe['adx'] > params['adx-value']) if 'rsi-enabled' in params and params['rsi-enabled']: conditions.append(dataframe['rsi'] < params['rsi-value']) # TRIGGERS if 'trigger' in params: if params['trigger'] == 'bb_lower': conditions.append(dataframe['close'] < dataframe['bb_lowerband']) if params['trigger'] == 'macd_cross_signal': conditions.append(qtpylib.crossed_above( dataframe['macd'], dataframe['macdsignal'] )) # Check that volume is not 0 conditions.append(dataframe['volume'] > 0) if conditions: dataframe.loc[ reduce(lambda x, y: x & y, conditions), 'buy'] = 1 return dataframe return populate_buy_trend ``` Hyperopt will now call populate_buy_trend() many times ( epochs ) with different value combinations. It will use the given historical data and make buys based on the buy signals generated with the above function. Based on the results, hyperopt will tell you which parameter combination produced the best results (based on the configured loss function ). Note The above setup expects to find ADX, RSI and Bollinger Bands in the populated indicators. When you want to test an indicator that isn't used by the bot currently, remember to add it to the populate_indicators() method in your strategy or hyperopt file.","title":"Defining a buy signal optimization"},{"location":"advanced-hyperopt/#sell-optimization","text":"Similar to the buy-signal above, sell-signals can also be optimized. Place the corresponding settings into the following methods Inside sell_indicator_space() - the parameters hyperopt shall be optimizing. Within sell_strategy_generator() - populate the nested method populate_sell_trend() to apply the parameters. The configuration and rules are the same than for buy signals. To avoid naming collisions in the search-space, please prefix all sell-spaces with sell- .","title":"Sell optimization"},{"location":"advanced-hyperopt/#execute-hyperopt","text":"Once you have updated your hyperopt configuration you can run it. Because hyperopt tries a lot of combinations to find the best parameters it will take time to get a good result. More time usually results in better results. We strongly recommend to use screen or tmux to prevent any connection loss. bash freqtrade hyperopt --config config.json --hyperopt --hyperopt-loss --strategy -e 500 --spaces all Use as the name of the custom hyperopt used. The -e option will set how many evaluations hyperopt will do. Since hyperopt uses Bayesian search, running too many epochs at once may not produce greater results. Experience has shown that best results are usually not improving much after 500-1000 epochs. Doing multiple runs (executions) with a few 1000 epochs and different random state will most likely produce different results. The --spaces all option determines that all possible parameters should be optimized. Possibilities are listed below. Note Hyperopt will store hyperopt results with the timestamp of the hyperopt start time. Reading commands ( hyperopt-list , hyperopt-show ) can use --hyperopt-filename to read and display older hyperopt results. You can find a list of filenames with ls -l user_data/hyperopt_results/ .","title":"Execute Hyperopt"},{"location":"advanced-hyperopt/#running-hyperopt-using-methods-from-a-strategy","text":"Hyperopt can reuse populate_indicators , populate_buy_trend , populate_sell_trend from your strategy, assuming these methods are not in your custom hyperopt file, and a strategy is provided. bash freqtrade hyperopt --hyperopt AwesomeHyperopt --hyperopt-loss SharpeHyperOptLossDaily --strategy AwesomeStrategy","title":"Running Hyperopt using methods from a strategy"},{"location":"advanced-hyperopt/#understand-the-hyperopt-result","text":"Once Hyperopt is completed you can use the result to create a new strategy. Given the following result from hyperopt: ``` Best result: 44/100: 135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722%). Avg duration 180.4 mins. Objective: 1.94367 Buy hyperspace params: { 'adx-value': 44, 'rsi-value': 29, 'adx-enabled': False, 'rsi-enabled': True, 'trigger': 'bb_lower'} ``` You should understand this result like: The buy trigger that worked best was bb_lower . You should not use ADX because adx-enabled: False ) You should consider using the RSI indicator ( rsi-enabled: True and the best value is 29.0 ( rsi-value: 29.0 ) You have to look inside your strategy file into buy_strategy_generator() method, what those values match to. So for example you had rsi-value: 29.0 so we would look at rsi -block, that translates to the following code block: python (dataframe['rsi'] < 29.0) Translating your whole hyperopt result as the new buy-signal would then look like: python def populate_buy_trend(self, dataframe: DataFrame) -> DataFrame: dataframe.loc[ ( (dataframe['rsi'] < 29.0) & # rsi-value dataframe['close'] < dataframe['bb_lowerband'] # trigger ), 'buy'] = 1 return dataframe","title":"Understand the Hyperopt Result"},{"location":"advanced-hyperopt/#validate-backtesting-results","text":"Once the optimized parameters and conditions have been implemented into your strategy, you should backtest the strategy to make sure everything is working as expected. To achieve same results (number of trades, their durations, profit, etc.) than during Hyperopt, please use same configuration and parameters (timerange, timeframe, ...) used for hyperopt --dmmp / --disable-max-market-positions and --eps / --enable-position-stacking for Backtesting. Should results don't match, please double-check to make sure you transferred all conditions correctly. Pay special care to the stoploss (and trailing stoploss) parameters, as these are often set in configuration files, which override changes to the strategy. You should also carefully review the log of your backtest to ensure that there were no parameters inadvertently set by the configuration (like stoploss or trailing_stop ).","title":"Validate backtesting results"},{"location":"advanced-hyperopt/#sharing-methods-with-your-strategy","text":"Hyperopt classes provide access to the Strategy via the strategy class attribute. This can be a great way to reduce code duplication if used correctly, but will also complicate usage for inexperienced users. ``` python from pandas import DataFrame from freqtrade.strategy.interface import IStrategy import freqtrade.vendor.qtpylib.indicators as qtpylib class MyAwesomeStrategy(IStrategy): buy_params = { 'rsi-value': 30, 'adx-value': 35, } def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: return self.buy_strategy_generator(self.buy_params, dataframe, metadata) @staticmethod def buy_strategy_generator(params, dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe.loc[ ( qtpylib.crossed_above(dataframe['rsi'], params['rsi-value']) & dataframe['adx'] > params['adx-value']) & dataframe['volume'] > 0 ) , 'buy'] = 1 return dataframe class MyAwesomeHyperOpt(IHyperOpt): ... @staticmethod def buy_strategy_generator(params: Dict[str, Any]) -> Callable: \"\"\" Define the buy strategy parameters to be used by Hyperopt. \"\"\" def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: # Call strategy's buy strategy generator return self.StrategyClass.buy_strategy_generator(params, dataframe, metadata) return populate_buy_trend ```","title":"Sharing methods with your strategy"},{"location":"advanced-setup/","text":"Advanced Post-installation Tasks \u00b6 This page explains some advanced tasks and configuration options that can be performed after the bot installation and may be uselful in some environments. If you do not know what things mentioned here mean, you probably do not need it. Running multiple instances of Freqtrade \u00b6 This section will show you how to run multiple bots at the same time, on the same machine. Things to consider \u00b6 Use different database files. Use different Telegram bots (requires multiple different configuration files; applies only when Telegram is enabled). Use different ports (applies only when Freqtrade REST API webserver is enabled). Different database files \u00b6 In order to keep track of your trades, profits, etc., freqtrade is using a SQLite database where it stores various types of information such as the trades you performed in the past and the current position(s) you are holding at any time. This allows you to keep track of your profits, but most importantly, keep track of ongoing activity if the bot process would be restarted or would be terminated unexpectedly. Freqtrade will, by default, use separate database files for dry-run and live bots (this assumes no database-url is given in either configuration nor via command line argument). For live trading mode, the default database will be tradesv3.sqlite and for dry-run it will be tradesv3.dryrun.sqlite . The optional argument to the trade command used to specify the path of these files is --db-url , which requires a valid SQLAlchemy url. So when you are starting a bot with only the config and strategy arguments in dry-run mode, the following 2 commands would have the same outcome. ``` bash freqtrade trade -c MyConfig.json -s MyStrategy is equivalent to \u00b6 freqtrade trade -c MyConfig.json -s MyStrategy --db-url sqlite:///tradesv3.dryrun.sqlite ``` It means that if you are running the trade command in two different terminals, for example to test your strategy both for trades in USDT and in another instance for trades in BTC, you will have to run them with different databases. If you specify the URL of a database which does not exist, freqtrade will create one with the name you specified. So to test your custom strategy with BTC and USDT stake currencies, you could use the following commands (in 2 separate terminals): ``` bash Terminal 1: \u00b6 freqtrade trade -c MyConfigBTC.json -s MyCustomStrategy --db-url sqlite:///user_data/tradesBTC.dryrun.sqlite Terminal 2: \u00b6 freqtrade trade -c MyConfigUSDT.json -s MyCustomStrategy --db-url sqlite:///user_data/tradesUSDT.dryrun.sqlite ``` Conversely, if you wish to do the same thing in production mode, you will also have to create at least one new database (in addition to the default one) and specify the path to the \"live\" databases, for example: ``` bash Terminal 1: \u00b6 freqtrade trade -c MyConfigBTC.json -s MyCustomStrategy --db-url sqlite:///user_data/tradesBTC.live.sqlite Terminal 2: \u00b6 freqtrade trade -c MyConfigUSDT.json -s MyCustomStrategy --db-url sqlite:///user_data/tradesUSDT.live.sqlite ``` For more information regarding usage of the sqlite databases, for example to manually enter or remove trades, please refer to the SQL Cheatsheet . Configure the bot running as a systemd service \u00b6 Copy the freqtrade.service file to your systemd user directory (usually ~/.config/systemd/user ) and update WorkingDirectory and ExecStart to match your setup. Note Certain systems (like Raspbian) don't load service unit files from the user directory. In this case, copy freqtrade.service into /etc/systemd/user/ (requires superuser permissions). After that you can start the daemon with: bash systemctl --user start freqtrade For this to be persistent (run when user is logged out) you'll need to enable linger for your freqtrade user. bash sudo loginctl enable-linger \"$USER\" If you run the bot as a service, you can use systemd service manager as a software watchdog monitoring freqtrade bot state and restarting it in the case of failures. If the internals.sd_notify parameter is set to true in the configuration or the --sd-notify command line option is used, the bot will send keep-alive ping messages to systemd using the sd_notify (systemd notifications) protocol and will also tell systemd its current state (Running or Stopped) when it changes. The freqtrade.service.watchdog file contains an example of the service unit configuration file which uses systemd as the watchdog. Note The sd_notify communication between the bot and the systemd service manager will not work if the bot runs in a Docker container. Advanced Logging \u00b6 On many Linux systems the bot can be configured to send its log messages to syslog or journald system services. Logging to a remote syslog server is also available on Windows. The special values for the --logfile command line option can be used for this. Logging to syslog \u00b6 To send Freqtrade log messages to a local or remote syslog service use the --logfile command line option with the value in the following format: --logfile syslog: -- send log messages to syslog service using the as the syslog address. The syslog address can be either a Unix domain socket (socket filename) or a UDP socket specification, consisting of IP address and UDP port, separated by the : character. So, the following are the examples of possible usages: --logfile syslog:/dev/log -- log to syslog (rsyslog) using the /dev/log socket, suitable for most systems. --logfile syslog -- same as above, the shortcut for /dev/log . --logfile syslog:/var/run/syslog -- log to syslog (rsyslog) using the /var/run/syslog socket. Use this on MacOS. --logfile syslog:localhost:514 -- log to local syslog using UDP socket, if it listens on port 514. --logfile syslog::514 -- log to remote syslog at IP address and port 514. This may be used on Windows for remote logging to an external syslog server. Log messages are send to syslog with the user facility. So you can see them with the following commands: tail -f /var/log/user , or install a comprehensive graphical viewer (for instance, 'Log File Viewer' for Ubuntu). On many systems syslog ( rsyslog ) fetches data from journald (and vice versa), so both --logfile syslog or --logfile journald can be used and the messages be viewed with both journalctl and a syslog viewer utility. You can combine this in any way which suites you better. For rsyslog the messages from the bot can be redirected into a separate dedicated log file. To achieve this, add if $programname startswith \"freqtrade\" then -/var/log/freqtrade.log to one of the rsyslog configuration files, for example at the end of the /etc/rsyslog.d/50-default.conf . For syslog ( rsyslog ), the reduction mode can be switched on. This will reduce the number of repeating messages. For instance, multiple bot Heartbeat messages will be reduced to a single message when nothing else happens with the bot. To achieve this, set in /etc/rsyslog.conf : ``` Filter duplicated messages \u00b6 $RepeatedMsgReduction on ``` Logging to journald \u00b6 This needs the systemd python package installed as the dependency, which is not available on Windows. Hence, the whole journald logging functionality is not available for a bot running on Windows. To send Freqtrade log messages to journald system service use the --logfile command line option with the value in the following format: --logfile journald -- send log messages to journald . Log messages are send to journald with the user facility. So you can see them with the following commands: journalctl -f -- shows Freqtrade log messages sent to journald along with other log messages fetched by journald . journalctl -f -u freqtrade.service -- this command can be used when the bot is run as a systemd service. There are many other options in the journalctl utility to filter the messages, see manual pages for this utility. On many systems syslog ( rsyslog ) fetches data from journald (and vice versa), so both --logfile syslog or --logfile journald can be used and the messages be viewed with both journalctl and a syslog viewer utility. You can combine this in any way which suites you better.","title":"Advanced Post-installation Tasks"},{"location":"advanced-setup/#advanced-post-installation-tasks","text":"This page explains some advanced tasks and configuration options that can be performed after the bot installation and may be uselful in some environments. If you do not know what things mentioned here mean, you probably do not need it.","title":"Advanced Post-installation Tasks"},{"location":"advanced-setup/#running-multiple-instances-of-freqtrade","text":"This section will show you how to run multiple bots at the same time, on the same machine.","title":"Running multiple instances of Freqtrade"},{"location":"advanced-setup/#things-to-consider","text":"Use different database files. Use different Telegram bots (requires multiple different configuration files; applies only when Telegram is enabled). Use different ports (applies only when Freqtrade REST API webserver is enabled).","title":"Things to consider"},{"location":"advanced-setup/#different-database-files","text":"In order to keep track of your trades, profits, etc., freqtrade is using a SQLite database where it stores various types of information such as the trades you performed in the past and the current position(s) you are holding at any time. This allows you to keep track of your profits, but most importantly, keep track of ongoing activity if the bot process would be restarted or would be terminated unexpectedly. Freqtrade will, by default, use separate database files for dry-run and live bots (this assumes no database-url is given in either configuration nor via command line argument). For live trading mode, the default database will be tradesv3.sqlite and for dry-run it will be tradesv3.dryrun.sqlite . The optional argument to the trade command used to specify the path of these files is --db-url , which requires a valid SQLAlchemy url. So when you are starting a bot with only the config and strategy arguments in dry-run mode, the following 2 commands would have the same outcome. ``` bash freqtrade trade -c MyConfig.json -s MyStrategy","title":"Different database files"},{"location":"advanced-setup/#is-equivalent-to","text":"freqtrade trade -c MyConfig.json -s MyStrategy --db-url sqlite:///tradesv3.dryrun.sqlite ``` It means that if you are running the trade command in two different terminals, for example to test your strategy both for trades in USDT and in another instance for trades in BTC, you will have to run them with different databases. If you specify the URL of a database which does not exist, freqtrade will create one with the name you specified. So to test your custom strategy with BTC and USDT stake currencies, you could use the following commands (in 2 separate terminals): ``` bash","title":"is equivalent to"},{"location":"advanced-setup/#terminal-1","text":"freqtrade trade -c MyConfigBTC.json -s MyCustomStrategy --db-url sqlite:///user_data/tradesBTC.dryrun.sqlite","title":"Terminal 1:"},{"location":"advanced-setup/#terminal-2","text":"freqtrade trade -c MyConfigUSDT.json -s MyCustomStrategy --db-url sqlite:///user_data/tradesUSDT.dryrun.sqlite ``` Conversely, if you wish to do the same thing in production mode, you will also have to create at least one new database (in addition to the default one) and specify the path to the \"live\" databases, for example: ``` bash","title":"Terminal 2:"},{"location":"advanced-setup/#terminal-1_1","text":"freqtrade trade -c MyConfigBTC.json -s MyCustomStrategy --db-url sqlite:///user_data/tradesBTC.live.sqlite","title":"Terminal 1:"},{"location":"advanced-setup/#terminal-2_1","text":"freqtrade trade -c MyConfigUSDT.json -s MyCustomStrategy --db-url sqlite:///user_data/tradesUSDT.live.sqlite ``` For more information regarding usage of the sqlite databases, for example to manually enter or remove trades, please refer to the SQL Cheatsheet .","title":"Terminal 2:"},{"location":"advanced-setup/#configure-the-bot-running-as-a-systemd-service","text":"Copy the freqtrade.service file to your systemd user directory (usually ~/.config/systemd/user ) and update WorkingDirectory and ExecStart to match your setup. Note Certain systems (like Raspbian) don't load service unit files from the user directory. In this case, copy freqtrade.service into /etc/systemd/user/ (requires superuser permissions). After that you can start the daemon with: bash systemctl --user start freqtrade For this to be persistent (run when user is logged out) you'll need to enable linger for your freqtrade user. bash sudo loginctl enable-linger \"$USER\" If you run the bot as a service, you can use systemd service manager as a software watchdog monitoring freqtrade bot state and restarting it in the case of failures. If the internals.sd_notify parameter is set to true in the configuration or the --sd-notify command line option is used, the bot will send keep-alive ping messages to systemd using the sd_notify (systemd notifications) protocol and will also tell systemd its current state (Running or Stopped) when it changes. The freqtrade.service.watchdog file contains an example of the service unit configuration file which uses systemd as the watchdog. Note The sd_notify communication between the bot and the systemd service manager will not work if the bot runs in a Docker container.","title":"Configure the bot running as a systemd service"},{"location":"advanced-setup/#advanced-logging","text":"On many Linux systems the bot can be configured to send its log messages to syslog or journald system services. Logging to a remote syslog server is also available on Windows. The special values for the --logfile command line option can be used for this.","title":"Advanced Logging"},{"location":"advanced-setup/#logging-to-syslog","text":"To send Freqtrade log messages to a local or remote syslog service use the --logfile command line option with the value in the following format: --logfile syslog: -- send log messages to syslog service using the as the syslog address. The syslog address can be either a Unix domain socket (socket filename) or a UDP socket specification, consisting of IP address and UDP port, separated by the : character. So, the following are the examples of possible usages: --logfile syslog:/dev/log -- log to syslog (rsyslog) using the /dev/log socket, suitable for most systems. --logfile syslog -- same as above, the shortcut for /dev/log . --logfile syslog:/var/run/syslog -- log to syslog (rsyslog) using the /var/run/syslog socket. Use this on MacOS. --logfile syslog:localhost:514 -- log to local syslog using UDP socket, if it listens on port 514. --logfile syslog::514 -- log to remote syslog at IP address and port 514. This may be used on Windows for remote logging to an external syslog server. Log messages are send to syslog with the user facility. So you can see them with the following commands: tail -f /var/log/user , or install a comprehensive graphical viewer (for instance, 'Log File Viewer' for Ubuntu). On many systems syslog ( rsyslog ) fetches data from journald (and vice versa), so both --logfile syslog or --logfile journald can be used and the messages be viewed with both journalctl and a syslog viewer utility. You can combine this in any way which suites you better. For rsyslog the messages from the bot can be redirected into a separate dedicated log file. To achieve this, add if $programname startswith \"freqtrade\" then -/var/log/freqtrade.log to one of the rsyslog configuration files, for example at the end of the /etc/rsyslog.d/50-default.conf . For syslog ( rsyslog ), the reduction mode can be switched on. This will reduce the number of repeating messages. For instance, multiple bot Heartbeat messages will be reduced to a single message when nothing else happens with the bot. To achieve this, set in /etc/rsyslog.conf : ```","title":"Logging to syslog"},{"location":"advanced-setup/#filter-duplicated-messages","text":"$RepeatedMsgReduction on ```","title":"Filter duplicated messages"},{"location":"advanced-setup/#logging-to-journald","text":"This needs the systemd python package installed as the dependency, which is not available on Windows. Hence, the whole journald logging functionality is not available for a bot running on Windows. To send Freqtrade log messages to journald system service use the --logfile command line option with the value in the following format: --logfile journald -- send log messages to journald . Log messages are send to journald with the user facility. So you can see them with the following commands: journalctl -f -- shows Freqtrade log messages sent to journald along with other log messages fetched by journald . journalctl -f -u freqtrade.service -- this command can be used when the bot is run as a systemd service. There are many other options in the journalctl utility to filter the messages, see manual pages for this utility. On many systems syslog ( rsyslog ) fetches data from journald (and vice versa), so both --logfile syslog or --logfile journald can be used and the messages be viewed with both journalctl and a syslog viewer utility. You can combine this in any way which suites you better.","title":"Logging to journald"},{"location":"backtesting/","text":"Backtesting \u00b6 This page explains how to validate your strategy performance by using Backtesting. Backtesting requires historic data to be available. To learn how to get data for the pairs and exchange you're interested in, head over to the Data Downloading section of the documentation. Backtesting command reference \u00b6 ``` usage: freqtrade backtesting [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-s NAME] [--strategy-path PATH] [-i TIMEFRAME] [--timerange TIMERANGE] [--data-format-ohlcv {json,jsongz,hdf5}] [--max-open-trades INT] [--stake-amount STAKE_AMOUNT] [--fee FLOAT] [-p PAIRS [PAIRS ...]] [--eps] [--dmmp] [--enable-protections] [--dry-run-wallet DRY_RUN_WALLET] [--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]] [--export {none,trades}] [--export-filename PATH] optional arguments: -h, --help show this help message and exit -i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME Specify timeframe ( 1m , 5m , 30m , 1h , 1d ). --timerange TIMERANGE Specify what timerange of data to use. --data-format-ohlcv {json,jsongz,hdf5} Storage format for downloaded candle (OHLCV) data. (default: None ). --max-open-trades INT Override the value of the max_open_trades configuration setting. --stake-amount STAKE_AMOUNT Override the value of the stake_amount configuration setting. --fee FLOAT Specify fee ratio. Will be applied twice (on trade entry and exit). -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] Limit command to these pairs. Pairs are space- separated. --eps, --enable-position-stacking Allow buying the same pair multiple times (position stacking). --dmmp, --disable-max-market-positions Disable applying max_open_trades during backtest (same as setting max_open_trades to a very high number). --enable-protections, --enableprotections Enable protections for backtesting.Will slow backtesting down by a considerable amount, but will include configured protections --dry-run-wallet DRY_RUN_WALLET, --starting-balance DRY_RUN_WALLET Starting balance, used for backtesting / hyperopt and dry-runs. --strategy-list STRATEGY_LIST [STRATEGY_LIST ...] Provide a space-separated list of strategies to backtest. Please note that ticker-interval needs to be set either in config or via command line. When using this together with --export trades , the strategy- name is injected into the filename (so backtest- data.json becomes backtest-data- DefaultStrategy.json --export {none,trades} Export backtest results (default: trades). --export-filename PATH Save backtest results to the file with this filename. Requires --export to be set as well. Example: --export-filename=user_data/backtest_results/backtest _today.json Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. Strategy arguments: -s NAME, --strategy NAME Specify strategy class name which will be used by the bot. --strategy-path PATH Specify additional strategy lookup path. ``` Test your strategy with Backtesting \u00b6 Now you have good Buy and Sell strategies and some historic data, you want to test it against real data. This is what we call backtesting . Backtesting will use the crypto-currencies (pairs) from your config file and load historical candle (OHLCV) data from user_data/data/ by default. If no data is available for the exchange / pair / timeframe combination, backtesting will ask you to download them first using freqtrade download-data . For details on downloading, please refer to the Data Downloading section in the documentation. The result of backtesting will confirm if your bot has better odds of making a profit than a loss. All profit calculations include fees, and freqtrade will use the exchange's default fees for the calculation. Using dynamic pairlists for backtesting Using dynamic pairlists is possible, however it relies on the current market conditions - which will not reflect the historic status of the pairlist. Also, when using pairlists other than StaticPairlist, reproducibility of backtesting-results cannot be guaranteed. Please read the pairlists documentation for more information. To achieve reproducible results, best generate a pairlist via the test-pairlist command and use that as static pairlist. Note By default, Freqtrade will export backtesting results to user_data/backtest_results . The exported trades can be used for further analysis or can be used by the plotting sub-command ( freqtrade plot-dataframe ) in the scripts directory. Starting balance \u00b6 Backtesting will require a starting balance, which can be provided as --dry-run-wallet or --starting-balance command line argument, or via dry_run_wallet configuration setting. This amount must be higher than stake_amount , otherwise the bot will not be able to simulate any trade. Dynamic stake amount \u00b6 Backtesting supports dynamic stake amount by configuring stake_amount as \"unlimited\" , which will split the starting balance into max_open_trades pieces. Profits from early trades will result in subsequent higher stake amounts, resulting in compounding of profits over the backtesting period. Example backtesting commands \u00b6 With 5 min candle (OHLCV) data (per default) bash freqtrade backtesting --strategy AwesomeStrategy Where --strategy AwesomeStrategy / -s AwesomeStrategy refers to the class name of the strategy, which is within a python file in the user_data/strategies directory. With 1 min candle (OHLCV) data bash freqtrade backtesting --strategy AwesomeStrategy --timeframe 1m Providing a custom starting balance of 1000 (in stake currency) bash freqtrade backtesting --strategy AwesomeStrategy --dry-run-wallet 1000 Using a different on-disk historical candle (OHLCV) data source Assume you downloaded the history data from the Bittrex exchange and kept it in the user_data/data/bittrex-20180101 directory. You can then use this data for backtesting as follows: bash freqtrade backtesting --strategy AwesomeStrategy --datadir user_data/data/bittrex-20180101 Comparing multiple Strategies bash freqtrade backtesting --strategy-list SampleStrategy1 AwesomeStrategy --timeframe 5m Where SampleStrategy1 and AwesomeStrategy refer to class names of strategies. Prevent exporting trades to file bash freqtrade backtesting --strategy backtesting --export none --config config.json Only use this if you're sure you'll not want to plot or analyze your results further. Exporting trades to file specifying a custom filename bash freqtrade backtesting --strategy backtesting --export trades --export-filename=backtest_samplestrategy.json Please also read about the strategy startup period . Supplying custom fee value Sometimes your account has certain fee rebates (fee reductions starting with a certain account size or monthly volume), which are not visible to ccxt. To account for this in backtesting, you can use the --fee command line option to supply this value to backtesting. This fee must be a ratio, and will be applied twice (once for trade entry, and once for trade exit). For example, if the buying and selling commission fee is 0.1% (i.e., 0.001 written as ratio), then you would run backtesting as the following: bash freqtrade backtesting --fee 0.001 Note Only supply this option (or the corresponding configuration parameter) if you want to experiment with different fee values. By default, Backtesting fetches the default fee from the exchange pair/market info. Running backtest with smaller test-set by using timerange Use the --timerange argument to change how much of the test-set you want to use. For example, running backtesting with the --timerange=20190501- option will use all available data starting with May 1 st , 2019 from your input data. bash freqtrade backtesting --timerange=20190501- You can also specify particular date ranges. The full timerange specification: Use data until 2018/01/31: --timerange=-20180131 Use data since 2018/01/31: --timerange=20180131- Use data since 2018/01/31 till 2018/03/01 : --timerange=20180131-20180301 Use data between POSIX / epoch timestamps 1527595200 1527618600: --timerange=1527595200-1527618600 Understand the backtesting result \u00b6 The most important in the backtesting is to understand the result. A backtesting result will look like that: ========================================================= BACKTESTING REPORT ========================================================== | Pair | Buys | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Wins Draws Loss Win% | |:---------|-------:|---------------:|---------------:|-----------------:|---------------:|:-------------|-------------------------:| | ADA/BTC | 35 | -0.11 | -3.88 | -0.00019428 | -1.94 | 4:35:00 | 14 0 21 40.0 | | ARK/BTC | 11 | -0.41 | -4.52 | -0.00022647 | -2.26 | 2:03:00 | 3 0 8 27.3 | | BTS/BTC | 32 | 0.31 | 9.78 | 0.00048938 | 4.89 | 5:05:00 | 18 0 14 56.2 | | DASH/BTC | 13 | -0.08 | -1.07 | -0.00005343 | -0.53 | 4:39:00 | 6 0 7 46.2 | | ENG/BTC | 18 | 1.36 | 24.54 | 0.00122807 | 12.27 | 2:50:00 | 8 0 10 44.4 | | EOS/BTC | 36 | 0.08 | 3.06 | 0.00015304 | 1.53 | 3:34:00 | 16 0 20 44.4 | | ETC/BTC | 26 | 0.37 | 9.51 | 0.00047576 | 4.75 | 6:14:00 | 11 0 15 42.3 | | ETH/BTC | 33 | 0.30 | 9.96 | 0.00049856 | 4.98 | 7:31:00 | 16 0 17 48.5 | | IOTA/BTC | 32 | 0.03 | 1.09 | 0.00005444 | 0.54 | 3:12:00 | 14 0 18 43.8 | | LSK/BTC | 15 | 1.75 | 26.26 | 0.00131413 | 13.13 | 2:58:00 | 6 0 9 40.0 | | LTC/BTC | 32 | -0.04 | -1.38 | -0.00006886 | -0.69 | 4:49:00 | 11 0 21 34.4 | | NANO/BTC | 17 | 1.26 | 21.39 | 0.00107058 | 10.70 | 1:55:00 | 10 0 7 58.5 | | NEO/BTC | 23 | 0.82 | 18.97 | 0.00094936 | 9.48 | 2:59:00 | 10 0 13 43.5 | | REQ/BTC | 9 | 1.17 | 10.54 | 0.00052734 | 5.27 | 3:47:00 | 4 0 5 44.4 | | XLM/BTC | 16 | 1.22 | 19.54 | 0.00097800 | 9.77 | 3:15:00 | 7 0 9 43.8 | | XMR/BTC | 23 | -0.18 | -4.13 | -0.00020696 | -2.07 | 5:30:00 | 12 0 11 52.2 | | XRP/BTC | 35 | 0.66 | 22.96 | 0.00114897 | 11.48 | 3:49:00 | 12 0 23 34.3 | | ZEC/BTC | 22 | -0.46 | -10.18 | -0.00050971 | -5.09 | 2:22:00 | 7 0 15 31.8 | | TOTAL | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 0 243 43.4 | ========================================================= SELL REASON STATS ========================================================== | Sell Reason | Sells | Wins | Draws | Losses | |:-------------------|--------:|------:|-------:|--------:| | trailing_stop_loss | 205 | 150 | 0 | 55 | | stop_loss | 166 | 0 | 0 | 166 | | sell_signal | 56 | 36 | 0 | 20 | | force_sell | 2 | 0 | 0 | 2 | ====================================================== LEFT OPEN TRADES REPORT ====================================================== | Pair | Buys | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Win Draw Loss Win% | |:---------|-------:|---------------:|---------------:|-----------------:|---------------:|:---------------|--------------------:| | ADA/BTC | 1 | 0.89 | 0.89 | 0.00004434 | 0.44 | 6:00:00 | 1 0 0 100 | | LTC/BTC | 1 | 0.68 | 0.68 | 0.00003421 | 0.34 | 2:00:00 | 1 0 0 100 | | TOTAL | 2 | 0.78 | 1.57 | 0.00007855 | 0.78 | 4:00:00 | 2 0 0 100 | =============== SUMMARY METRICS =============== | Metric | Value | |-----------------------+---------------------| | Backtesting from | 2019-01-01 00:00:00 | | Backtesting to | 2019-05-01 00:00:00 | | Max open trades | 3 | | | | | Total/Daily Avg Trades| 429 / 3.575 | | Starting balance | 0.01000000 BTC | | Final balance | 0.01762792 BTC | | Absolute profit | 0.00762792 BTC | | Total profit % | 76.2% | | Trades per day | 3.575 | | Avg. stake amount | 0.001 BTC | | Total trade volume | 0.429 BTC | | | | | Best Pair | LSK/BTC 26.26% | | Worst Pair | ZEC/BTC -10.18% | | Best Trade | LSK/BTC 4.25% | | Worst Trade | ZEC/BTC -10.25% | | Best day | 0.00076 BTC | | Worst day | -0.00036 BTC | | Days win/draw/lose | 12 / 82 / 25 | | Avg. Duration Winners | 4:23:00 | | Avg. Duration Loser | 6:55:00 | | Rejected Buy signals | 3089 | | | | | Min balance | 0.00945123 BTC | | Max balance | 0.01846651 BTC | | Drawdown | 50.63% | | Drawdown | 0.0015 BTC | | Drawdown high | 0.0013 BTC | | Drawdown low | -0.0002 BTC | | Drawdown Start | 2019-02-15 14:10:00 | | Drawdown End | 2019-04-11 18:15:00 | | Market change | -5.88% | =============================================== Backtesting report table \u00b6 The 1 st table contains all trades the bot made, including \"left open trades\". The last line will give you the overall performance of your strategy, here: | TOTAL | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 0 243 43.4 | The bot has made 429 trades for an average duration of 4:12:00 , with a performance of 76.20% (profit), that means it has earned a total of 0.00762792 BTC starting with a capital of 0.01 BTC. The column Avg Profit % shows the average profit for all trades made while the column Cum Profit % sums up all the profits/losses. The column Tot Profit % shows instead the total profit % in relation to the starting balance. In the above results, we have a starting balance of 0.01 BTC and an absolute profit of 0.00762792 BTC - so the Tot Profit % will be (0.00762792 / 0.01) * 100 ~= 76.2% . Your strategy performance is influenced by your buy strategy, your sell strategy, and also by the minimal_roi and stop_loss you have set. For example, if your minimal_roi is only \"0\": 0.01 you cannot expect the bot to make more profit than 1% (because it will sell every time a trade reaches 1%). json \"minimal_roi\": { \"0\": 0.01 }, On the other hand, if you set a too high minimal_roi like \"0\": 0.55 (55%), there is almost no chance that the bot will ever reach this profit. Hence, keep in mind that your performance is an integral mix of all different elements of the strategy, your configuration, and the crypto-currency pairs you have set up. Sell reasons table \u00b6 The 2 nd table contains a recap of sell reasons. This table can tell you which area needs some additional work (e.g. all or many of the sell_signal trades are losses, so you should work on improving the sell signal, or consider disabling it). Left open trades table \u00b6 The 3 rd table contains all trades the bot had to forcesell at the end of the backtesting period to present you the full picture. This is necessary to simulate realistic behavior, since the backtest period has to end at some point, while realistically, you could leave the bot running forever. These trades are also included in the first table, but are also shown separately in this table for clarity. Summary metrics \u00b6 The last element of the backtest report is the summary metrics table. It contains some useful key metrics about performance of your strategy on backtesting data. ``` =============== SUMMARY METRICS =============== | Metric | Value | |-----------------------+---------------------| | Backtesting from | 2019-01-01 00:00:00 | | Backtesting to | 2019-05-01 00:00:00 | | Max open trades | 3 | | | | | Total/Daily Avg Trades| 429 / 3.575 | | Starting balance | 0.01000000 BTC | | Final balance | 0.01762792 BTC | | Absolute profit | 0.00762792 BTC | | Total profit % | 76.2% | | Avg. stake amount | 0.001 BTC | | Total trade volume | 0.429 BTC | | | | | Best Pair | LSK/BTC 26.26% | | Worst Pair | ZEC/BTC -10.18% | | Best Trade | LSK/BTC 4.25% | | Worst Trade | ZEC/BTC -10.25% | | Best day | 0.00076 BTC | | Worst day | -0.00036 BTC | | Days win/draw/lose | 12 / 82 / 25 | | Avg. Duration Winners | 4:23:00 | | Avg. Duration Loser | 6:55:00 | | Rejected Buy signals | 3089 | | | | | Min balance | 0.00945123 BTC | | Max balance | 0.01846651 BTC | | Drawdown | 50.63% | | Drawdown | 0.0015 BTC | | Drawdown high | 0.0013 BTC | | Drawdown low | -0.0002 BTC | | Drawdown Start | 2019-02-15 14:10:00 | | Drawdown End | 2019-04-11 18:15:00 | | Market change | -5.88% | =============================================== ``` Backtesting from / Backtesting to : Backtesting range (usually defined with the --timerange option). Max open trades : Setting of max_open_trades (or --max-open-trades ) - or number of pairs in the pairlist (whatever is lower). Total/Daily Avg Trades : Identical to the total trades of the backtest output table / Total trades divided by the backtesting duration in days (this will give you information about how many trades to expect from the strategy). Starting balance : Start balance - as given by dry-run-wallet (config or command line). Final balance : Final balance - starting balance + absolute profit. Absolute profit : Profit made in stake currency. Total profit % : Total profit. Aligned to the TOTAL row's Tot Profit % from the first table. Calculated as (End capital \u2212 Starting capital) / Starting capital . Avg. stake amount : Average stake amount, either stake_amount or the average when using dynamic stake amount. Total trade volume : Volume generated on the exchange to reach the above profit. Best Pair / Worst Pair : Best and worst performing pair, and it's corresponding Cum Profit % . Best Trade / Worst Trade : Biggest single winning trade and biggest single losing trade. Best day / Worst day : Best and worst day based on daily profit. Days win/draw/lose : Winning / Losing days (draws are usually days without closed trade). Avg. Duration Winners / Avg. Duration Loser : Average durations for winning and losing trades. Rejected Buy signals : Buy signals that could not be acted upon due to max_open_trades being reached. Min balance / Max balance : Lowest and Highest Wallet balance during the backtest period. Drawdown : Maximum drawdown experienced. For example, the value of 50% means that from highest to subsequent lowest point, a 50% drop was experienced). Drawdown high / Drawdown low : Profit at the beginning and end of the largest drawdown period. A negative low value means initial capital lost. Drawdown Start / Drawdown End : Start and end datetime for this largest drawdown (can also be visualized via the plot-dataframe sub-command). Market change : Change of the market during the backtest period. Calculated as average of all pairs changes from the first to the last candle using the \"close\" column. Assumptions made by backtesting \u00b6 Since backtesting lacks some detailed information about what happens within a candle, it needs to take a few assumptions: Buys happen at open-price All orders are filled at the requested price (no slippage, no unfilled orders) Sell-signal sells happen at open-price of the consecutive candle Sell-signal is favored over Stoploss, because sell-signals are assumed to trigger on candle's open ROI sells are compared to high - but the ROI value is used (e.g. ROI = 2%, high=5% - so the sell will be at 2%) sells are never \"below the candle\", so a ROI of 2% may result in a sell at 2.4% if low was at 2.4% profit Forcesells caused by =-1 ROI entries use low as sell value, unless N falls on the candle open (e.g. 120: -1 for 1h candles) Stoploss sells happen exactly at stoploss price, even if low was lower, but the loss will be 2 * fees higher than the stoploss price Stoploss is evaluated before ROI within one candle. So you can often see more trades with the stoploss sell reason comparing to the results obtained with the same strategy in the Dry Run/Live Trade modes Low happens before high for stoploss, protecting capital first Trailing stoploss Trailing Stoploss is only adjusted if it's below the candle's low (otherwise it would be triggered) High happens first - adjusting stoploss Low uses the adjusted stoploss (so sells with large high-low difference are backtested correctly) ROI applies before trailing-stop, ensuring profits are \"top-capped\" at ROI if both ROI and trailing stop applies Sell-reason does not explain if a trade was positive or negative, just what triggered the sell (this can look odd if negative ROI values are used) Evaluation sequence (if multiple signals happen on the same candle) ROI (if not stoploss) Sell-signal Stoploss Taking these assumptions, backtesting tries to mirror real trading as closely as possible. However, backtesting will never replace running a strategy in dry-run mode. Also, keep in mind that past results don't guarantee future success. In addition to the above assumptions, strategy authors should carefully read the Common Mistakes section, to avoid using data in backtesting which is not available in real market conditions. Further backtest-result analysis \u00b6 To further analyze your backtest results, you can export the trades . You can then load the trades to perform further analysis as shown in our data analysis backtesting section. Backtesting multiple strategies \u00b6 To compare multiple strategies, a list of Strategies can be provided to backtesting. This is limited to 1 timeframe value per run. However, data is only loaded once from disk so if you have multiple strategies you'd like to compare, this will give a nice runtime boost. All listed Strategies need to be in the same directory. bash freqtrade backtesting --timerange 20180401-20180410 --timeframe 5m --strategy-list Strategy001 Strategy002 --export trades This will save the results to user_data/backtest_results/backtest-result-.json , injecting the strategy-name into the target filename. There will be an additional table comparing win/losses of the different strategies (identical to the \"Total\" row in the first table). Detailed output for all strategies one after the other will be available, so make sure to scroll up to see the details per strategy. =========================================================== STRATEGY SUMMARY ========================================================================= | Strategy | Buys | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Wins | Draws | Losses | Drawdown % | |:------------|-------:|---------------:|---------------:|-----------------:|---------------:|:---------------|------:|-------:|-------:|-----------:| | Strategy1 | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 0 | 243 | 45.2 | | Strategy2 | 1487 | -0.13 | -197.58 | -0.00988917 | -98.79 | 4:43:00 | 662 | 0 | 825 | 241.68 | Next step \u00b6 Great, your strategy is profitable. What if the bot can give your the optimal parameters to use for your strategy? Your next step is to learn how to find optimal parameters with Hyperopt","title":"Backtesting"},{"location":"backtesting/#backtesting","text":"This page explains how to validate your strategy performance by using Backtesting. Backtesting requires historic data to be available. To learn how to get data for the pairs and exchange you're interested in, head over to the Data Downloading section of the documentation.","title":"Backtesting"},{"location":"backtesting/#backtesting-command-reference","text":"``` usage: freqtrade backtesting [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-s NAME] [--strategy-path PATH] [-i TIMEFRAME] [--timerange TIMERANGE] [--data-format-ohlcv {json,jsongz,hdf5}] [--max-open-trades INT] [--stake-amount STAKE_AMOUNT] [--fee FLOAT] [-p PAIRS [PAIRS ...]] [--eps] [--dmmp] [--enable-protections] [--dry-run-wallet DRY_RUN_WALLET] [--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]] [--export {none,trades}] [--export-filename PATH] optional arguments: -h, --help show this help message and exit -i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME Specify timeframe ( 1m , 5m , 30m , 1h , 1d ). --timerange TIMERANGE Specify what timerange of data to use. --data-format-ohlcv {json,jsongz,hdf5} Storage format for downloaded candle (OHLCV) data. (default: None ). --max-open-trades INT Override the value of the max_open_trades configuration setting. --stake-amount STAKE_AMOUNT Override the value of the stake_amount configuration setting. --fee FLOAT Specify fee ratio. Will be applied twice (on trade entry and exit). -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] Limit command to these pairs. Pairs are space- separated. --eps, --enable-position-stacking Allow buying the same pair multiple times (position stacking). --dmmp, --disable-max-market-positions Disable applying max_open_trades during backtest (same as setting max_open_trades to a very high number). --enable-protections, --enableprotections Enable protections for backtesting.Will slow backtesting down by a considerable amount, but will include configured protections --dry-run-wallet DRY_RUN_WALLET, --starting-balance DRY_RUN_WALLET Starting balance, used for backtesting / hyperopt and dry-runs. --strategy-list STRATEGY_LIST [STRATEGY_LIST ...] Provide a space-separated list of strategies to backtest. Please note that ticker-interval needs to be set either in config or via command line. When using this together with --export trades , the strategy- name is injected into the filename (so backtest- data.json becomes backtest-data- DefaultStrategy.json --export {none,trades} Export backtest results (default: trades). --export-filename PATH Save backtest results to the file with this filename. Requires --export to be set as well. Example: --export-filename=user_data/backtest_results/backtest _today.json Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. Strategy arguments: -s NAME, --strategy NAME Specify strategy class name which will be used by the bot. --strategy-path PATH Specify additional strategy lookup path. ```","title":"Backtesting command reference"},{"location":"backtesting/#test-your-strategy-with-backtesting","text":"Now you have good Buy and Sell strategies and some historic data, you want to test it against real data. This is what we call backtesting . Backtesting will use the crypto-currencies (pairs) from your config file and load historical candle (OHLCV) data from user_data/data/ by default. If no data is available for the exchange / pair / timeframe combination, backtesting will ask you to download them first using freqtrade download-data . For details on downloading, please refer to the Data Downloading section in the documentation. The result of backtesting will confirm if your bot has better odds of making a profit than a loss. All profit calculations include fees, and freqtrade will use the exchange's default fees for the calculation. Using dynamic pairlists for backtesting Using dynamic pairlists is possible, however it relies on the current market conditions - which will not reflect the historic status of the pairlist. Also, when using pairlists other than StaticPairlist, reproducibility of backtesting-results cannot be guaranteed. Please read the pairlists documentation for more information. To achieve reproducible results, best generate a pairlist via the test-pairlist command and use that as static pairlist. Note By default, Freqtrade will export backtesting results to user_data/backtest_results . The exported trades can be used for further analysis or can be used by the plotting sub-command ( freqtrade plot-dataframe ) in the scripts directory.","title":"Test your strategy with Backtesting"},{"location":"backtesting/#starting-balance","text":"Backtesting will require a starting balance, which can be provided as --dry-run-wallet or --starting-balance command line argument, or via dry_run_wallet configuration setting. This amount must be higher than stake_amount , otherwise the bot will not be able to simulate any trade.","title":"Starting balance"},{"location":"backtesting/#dynamic-stake-amount","text":"Backtesting supports dynamic stake amount by configuring stake_amount as \"unlimited\" , which will split the starting balance into max_open_trades pieces. Profits from early trades will result in subsequent higher stake amounts, resulting in compounding of profits over the backtesting period.","title":"Dynamic stake amount"},{"location":"backtesting/#example-backtesting-commands","text":"With 5 min candle (OHLCV) data (per default) bash freqtrade backtesting --strategy AwesomeStrategy Where --strategy AwesomeStrategy / -s AwesomeStrategy refers to the class name of the strategy, which is within a python file in the user_data/strategies directory. With 1 min candle (OHLCV) data bash freqtrade backtesting --strategy AwesomeStrategy --timeframe 1m Providing a custom starting balance of 1000 (in stake currency) bash freqtrade backtesting --strategy AwesomeStrategy --dry-run-wallet 1000 Using a different on-disk historical candle (OHLCV) data source Assume you downloaded the history data from the Bittrex exchange and kept it in the user_data/data/bittrex-20180101 directory. You can then use this data for backtesting as follows: bash freqtrade backtesting --strategy AwesomeStrategy --datadir user_data/data/bittrex-20180101 Comparing multiple Strategies bash freqtrade backtesting --strategy-list SampleStrategy1 AwesomeStrategy --timeframe 5m Where SampleStrategy1 and AwesomeStrategy refer to class names of strategies. Prevent exporting trades to file bash freqtrade backtesting --strategy backtesting --export none --config config.json Only use this if you're sure you'll not want to plot or analyze your results further. Exporting trades to file specifying a custom filename bash freqtrade backtesting --strategy backtesting --export trades --export-filename=backtest_samplestrategy.json Please also read about the strategy startup period . Supplying custom fee value Sometimes your account has certain fee rebates (fee reductions starting with a certain account size or monthly volume), which are not visible to ccxt. To account for this in backtesting, you can use the --fee command line option to supply this value to backtesting. This fee must be a ratio, and will be applied twice (once for trade entry, and once for trade exit). For example, if the buying and selling commission fee is 0.1% (i.e., 0.001 written as ratio), then you would run backtesting as the following: bash freqtrade backtesting --fee 0.001 Note Only supply this option (or the corresponding configuration parameter) if you want to experiment with different fee values. By default, Backtesting fetches the default fee from the exchange pair/market info. Running backtest with smaller test-set by using timerange Use the --timerange argument to change how much of the test-set you want to use. For example, running backtesting with the --timerange=20190501- option will use all available data starting with May 1 st , 2019 from your input data. bash freqtrade backtesting --timerange=20190501- You can also specify particular date ranges. The full timerange specification: Use data until 2018/01/31: --timerange=-20180131 Use data since 2018/01/31: --timerange=20180131- Use data since 2018/01/31 till 2018/03/01 : --timerange=20180131-20180301 Use data between POSIX / epoch timestamps 1527595200 1527618600: --timerange=1527595200-1527618600","title":"Example backtesting commands"},{"location":"backtesting/#understand-the-backtesting-result","text":"The most important in the backtesting is to understand the result. A backtesting result will look like that: ========================================================= BACKTESTING REPORT ========================================================== | Pair | Buys | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Wins Draws Loss Win% | |:---------|-------:|---------------:|---------------:|-----------------:|---------------:|:-------------|-------------------------:| | ADA/BTC | 35 | -0.11 | -3.88 | -0.00019428 | -1.94 | 4:35:00 | 14 0 21 40.0 | | ARK/BTC | 11 | -0.41 | -4.52 | -0.00022647 | -2.26 | 2:03:00 | 3 0 8 27.3 | | BTS/BTC | 32 | 0.31 | 9.78 | 0.00048938 | 4.89 | 5:05:00 | 18 0 14 56.2 | | DASH/BTC | 13 | -0.08 | -1.07 | -0.00005343 | -0.53 | 4:39:00 | 6 0 7 46.2 | | ENG/BTC | 18 | 1.36 | 24.54 | 0.00122807 | 12.27 | 2:50:00 | 8 0 10 44.4 | | EOS/BTC | 36 | 0.08 | 3.06 | 0.00015304 | 1.53 | 3:34:00 | 16 0 20 44.4 | | ETC/BTC | 26 | 0.37 | 9.51 | 0.00047576 | 4.75 | 6:14:00 | 11 0 15 42.3 | | ETH/BTC | 33 | 0.30 | 9.96 | 0.00049856 | 4.98 | 7:31:00 | 16 0 17 48.5 | | IOTA/BTC | 32 | 0.03 | 1.09 | 0.00005444 | 0.54 | 3:12:00 | 14 0 18 43.8 | | LSK/BTC | 15 | 1.75 | 26.26 | 0.00131413 | 13.13 | 2:58:00 | 6 0 9 40.0 | | LTC/BTC | 32 | -0.04 | -1.38 | -0.00006886 | -0.69 | 4:49:00 | 11 0 21 34.4 | | NANO/BTC | 17 | 1.26 | 21.39 | 0.00107058 | 10.70 | 1:55:00 | 10 0 7 58.5 | | NEO/BTC | 23 | 0.82 | 18.97 | 0.00094936 | 9.48 | 2:59:00 | 10 0 13 43.5 | | REQ/BTC | 9 | 1.17 | 10.54 | 0.00052734 | 5.27 | 3:47:00 | 4 0 5 44.4 | | XLM/BTC | 16 | 1.22 | 19.54 | 0.00097800 | 9.77 | 3:15:00 | 7 0 9 43.8 | | XMR/BTC | 23 | -0.18 | -4.13 | -0.00020696 | -2.07 | 5:30:00 | 12 0 11 52.2 | | XRP/BTC | 35 | 0.66 | 22.96 | 0.00114897 | 11.48 | 3:49:00 | 12 0 23 34.3 | | ZEC/BTC | 22 | -0.46 | -10.18 | -0.00050971 | -5.09 | 2:22:00 | 7 0 15 31.8 | | TOTAL | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 0 243 43.4 | ========================================================= SELL REASON STATS ========================================================== | Sell Reason | Sells | Wins | Draws | Losses | |:-------------------|--------:|------:|-------:|--------:| | trailing_stop_loss | 205 | 150 | 0 | 55 | | stop_loss | 166 | 0 | 0 | 166 | | sell_signal | 56 | 36 | 0 | 20 | | force_sell | 2 | 0 | 0 | 2 | ====================================================== LEFT OPEN TRADES REPORT ====================================================== | Pair | Buys | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Win Draw Loss Win% | |:---------|-------:|---------------:|---------------:|-----------------:|---------------:|:---------------|--------------------:| | ADA/BTC | 1 | 0.89 | 0.89 | 0.00004434 | 0.44 | 6:00:00 | 1 0 0 100 | | LTC/BTC | 1 | 0.68 | 0.68 | 0.00003421 | 0.34 | 2:00:00 | 1 0 0 100 | | TOTAL | 2 | 0.78 | 1.57 | 0.00007855 | 0.78 | 4:00:00 | 2 0 0 100 | =============== SUMMARY METRICS =============== | Metric | Value | |-----------------------+---------------------| | Backtesting from | 2019-01-01 00:00:00 | | Backtesting to | 2019-05-01 00:00:00 | | Max open trades | 3 | | | | | Total/Daily Avg Trades| 429 / 3.575 | | Starting balance | 0.01000000 BTC | | Final balance | 0.01762792 BTC | | Absolute profit | 0.00762792 BTC | | Total profit % | 76.2% | | Trades per day | 3.575 | | Avg. stake amount | 0.001 BTC | | Total trade volume | 0.429 BTC | | | | | Best Pair | LSK/BTC 26.26% | | Worst Pair | ZEC/BTC -10.18% | | Best Trade | LSK/BTC 4.25% | | Worst Trade | ZEC/BTC -10.25% | | Best day | 0.00076 BTC | | Worst day | -0.00036 BTC | | Days win/draw/lose | 12 / 82 / 25 | | Avg. Duration Winners | 4:23:00 | | Avg. Duration Loser | 6:55:00 | | Rejected Buy signals | 3089 | | | | | Min balance | 0.00945123 BTC | | Max balance | 0.01846651 BTC | | Drawdown | 50.63% | | Drawdown | 0.0015 BTC | | Drawdown high | 0.0013 BTC | | Drawdown low | -0.0002 BTC | | Drawdown Start | 2019-02-15 14:10:00 | | Drawdown End | 2019-04-11 18:15:00 | | Market change | -5.88% | ===============================================","title":"Understand the backtesting result"},{"location":"backtesting/#backtesting-report-table","text":"The 1 st table contains all trades the bot made, including \"left open trades\". The last line will give you the overall performance of your strategy, here: | TOTAL | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 0 243 43.4 | The bot has made 429 trades for an average duration of 4:12:00 , with a performance of 76.20% (profit), that means it has earned a total of 0.00762792 BTC starting with a capital of 0.01 BTC. The column Avg Profit % shows the average profit for all trades made while the column Cum Profit % sums up all the profits/losses. The column Tot Profit % shows instead the total profit % in relation to the starting balance. In the above results, we have a starting balance of 0.01 BTC and an absolute profit of 0.00762792 BTC - so the Tot Profit % will be (0.00762792 / 0.01) * 100 ~= 76.2% . Your strategy performance is influenced by your buy strategy, your sell strategy, and also by the minimal_roi and stop_loss you have set. For example, if your minimal_roi is only \"0\": 0.01 you cannot expect the bot to make more profit than 1% (because it will sell every time a trade reaches 1%). json \"minimal_roi\": { \"0\": 0.01 }, On the other hand, if you set a too high minimal_roi like \"0\": 0.55 (55%), there is almost no chance that the bot will ever reach this profit. Hence, keep in mind that your performance is an integral mix of all different elements of the strategy, your configuration, and the crypto-currency pairs you have set up.","title":"Backtesting report table"},{"location":"backtesting/#sell-reasons-table","text":"The 2 nd table contains a recap of sell reasons. This table can tell you which area needs some additional work (e.g. all or many of the sell_signal trades are losses, so you should work on improving the sell signal, or consider disabling it).","title":"Sell reasons table"},{"location":"backtesting/#left-open-trades-table","text":"The 3 rd table contains all trades the bot had to forcesell at the end of the backtesting period to present you the full picture. This is necessary to simulate realistic behavior, since the backtest period has to end at some point, while realistically, you could leave the bot running forever. These trades are also included in the first table, but are also shown separately in this table for clarity.","title":"Left open trades table"},{"location":"backtesting/#summary-metrics","text":"The last element of the backtest report is the summary metrics table. It contains some useful key metrics about performance of your strategy on backtesting data. ``` =============== SUMMARY METRICS =============== | Metric | Value | |-----------------------+---------------------| | Backtesting from | 2019-01-01 00:00:00 | | Backtesting to | 2019-05-01 00:00:00 | | Max open trades | 3 | | | | | Total/Daily Avg Trades| 429 / 3.575 | | Starting balance | 0.01000000 BTC | | Final balance | 0.01762792 BTC | | Absolute profit | 0.00762792 BTC | | Total profit % | 76.2% | | Avg. stake amount | 0.001 BTC | | Total trade volume | 0.429 BTC | | | | | Best Pair | LSK/BTC 26.26% | | Worst Pair | ZEC/BTC -10.18% | | Best Trade | LSK/BTC 4.25% | | Worst Trade | ZEC/BTC -10.25% | | Best day | 0.00076 BTC | | Worst day | -0.00036 BTC | | Days win/draw/lose | 12 / 82 / 25 | | Avg. Duration Winners | 4:23:00 | | Avg. Duration Loser | 6:55:00 | | Rejected Buy signals | 3089 | | | | | Min balance | 0.00945123 BTC | | Max balance | 0.01846651 BTC | | Drawdown | 50.63% | | Drawdown | 0.0015 BTC | | Drawdown high | 0.0013 BTC | | Drawdown low | -0.0002 BTC | | Drawdown Start | 2019-02-15 14:10:00 | | Drawdown End | 2019-04-11 18:15:00 | | Market change | -5.88% | =============================================== ``` Backtesting from / Backtesting to : Backtesting range (usually defined with the --timerange option). Max open trades : Setting of max_open_trades (or --max-open-trades ) - or number of pairs in the pairlist (whatever is lower). Total/Daily Avg Trades : Identical to the total trades of the backtest output table / Total trades divided by the backtesting duration in days (this will give you information about how many trades to expect from the strategy). Starting balance : Start balance - as given by dry-run-wallet (config or command line). Final balance : Final balance - starting balance + absolute profit. Absolute profit : Profit made in stake currency. Total profit % : Total profit. Aligned to the TOTAL row's Tot Profit % from the first table. Calculated as (End capital \u2212 Starting capital) / Starting capital . Avg. stake amount : Average stake amount, either stake_amount or the average when using dynamic stake amount. Total trade volume : Volume generated on the exchange to reach the above profit. Best Pair / Worst Pair : Best and worst performing pair, and it's corresponding Cum Profit % . Best Trade / Worst Trade : Biggest single winning trade and biggest single losing trade. Best day / Worst day : Best and worst day based on daily profit. Days win/draw/lose : Winning / Losing days (draws are usually days without closed trade). Avg. Duration Winners / Avg. Duration Loser : Average durations for winning and losing trades. Rejected Buy signals : Buy signals that could not be acted upon due to max_open_trades being reached. Min balance / Max balance : Lowest and Highest Wallet balance during the backtest period. Drawdown : Maximum drawdown experienced. For example, the value of 50% means that from highest to subsequent lowest point, a 50% drop was experienced). Drawdown high / Drawdown low : Profit at the beginning and end of the largest drawdown period. A negative low value means initial capital lost. Drawdown Start / Drawdown End : Start and end datetime for this largest drawdown (can also be visualized via the plot-dataframe sub-command). Market change : Change of the market during the backtest period. Calculated as average of all pairs changes from the first to the last candle using the \"close\" column.","title":"Summary metrics"},{"location":"backtesting/#assumptions-made-by-backtesting","text":"Since backtesting lacks some detailed information about what happens within a candle, it needs to take a few assumptions: Buys happen at open-price All orders are filled at the requested price (no slippage, no unfilled orders) Sell-signal sells happen at open-price of the consecutive candle Sell-signal is favored over Stoploss, because sell-signals are assumed to trigger on candle's open ROI sells are compared to high - but the ROI value is used (e.g. ROI = 2%, high=5% - so the sell will be at 2%) sells are never \"below the candle\", so a ROI of 2% may result in a sell at 2.4% if low was at 2.4% profit Forcesells caused by =-1 ROI entries use low as sell value, unless N falls on the candle open (e.g. 120: -1 for 1h candles) Stoploss sells happen exactly at stoploss price, even if low was lower, but the loss will be 2 * fees higher than the stoploss price Stoploss is evaluated before ROI within one candle. So you can often see more trades with the stoploss sell reason comparing to the results obtained with the same strategy in the Dry Run/Live Trade modes Low happens before high for stoploss, protecting capital first Trailing stoploss Trailing Stoploss is only adjusted if it's below the candle's low (otherwise it would be triggered) High happens first - adjusting stoploss Low uses the adjusted stoploss (so sells with large high-low difference are backtested correctly) ROI applies before trailing-stop, ensuring profits are \"top-capped\" at ROI if both ROI and trailing stop applies Sell-reason does not explain if a trade was positive or negative, just what triggered the sell (this can look odd if negative ROI values are used) Evaluation sequence (if multiple signals happen on the same candle) ROI (if not stoploss) Sell-signal Stoploss Taking these assumptions, backtesting tries to mirror real trading as closely as possible. However, backtesting will never replace running a strategy in dry-run mode. Also, keep in mind that past results don't guarantee future success. In addition to the above assumptions, strategy authors should carefully read the Common Mistakes section, to avoid using data in backtesting which is not available in real market conditions.","title":"Assumptions made by backtesting"},{"location":"backtesting/#further-backtest-result-analysis","text":"To further analyze your backtest results, you can export the trades . You can then load the trades to perform further analysis as shown in our data analysis backtesting section.","title":"Further backtest-result analysis"},{"location":"backtesting/#backtesting-multiple-strategies","text":"To compare multiple strategies, a list of Strategies can be provided to backtesting. This is limited to 1 timeframe value per run. However, data is only loaded once from disk so if you have multiple strategies you'd like to compare, this will give a nice runtime boost. All listed Strategies need to be in the same directory. bash freqtrade backtesting --timerange 20180401-20180410 --timeframe 5m --strategy-list Strategy001 Strategy002 --export trades This will save the results to user_data/backtest_results/backtest-result-.json , injecting the strategy-name into the target filename. There will be an additional table comparing win/losses of the different strategies (identical to the \"Total\" row in the first table). Detailed output for all strategies one after the other will be available, so make sure to scroll up to see the details per strategy. =========================================================== STRATEGY SUMMARY ========================================================================= | Strategy | Buys | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Wins | Draws | Losses | Drawdown % | |:------------|-------:|---------------:|---------------:|-----------------:|---------------:|:---------------|------:|-------:|-------:|-----------:| | Strategy1 | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 0 | 243 | 45.2 | | Strategy2 | 1487 | -0.13 | -197.58 | -0.00988917 | -98.79 | 4:43:00 | 662 | 0 | 825 | 241.68 |","title":"Backtesting multiple strategies"},{"location":"backtesting/#next-step","text":"Great, your strategy is profitable. What if the bot can give your the optimal parameters to use for your strategy? Your next step is to learn how to find optimal parameters with Hyperopt","title":"Next step"},{"location":"bot-basics/","text":"Freqtrade basics \u00b6 This page provides you some basic concepts on how Freqtrade works and operates. Freqtrade terminology \u00b6 Strategy : Your trading strategy, telling the bot what to do. Trade : Open position. Open Order : Order which is currently placed on the exchange, and is not yet complete. Pair : Tradable pair, usually in the format of Quote/Base (e.g. XRP/USDT). Timeframe : Candle length to use (e.g. \"5m\" , \"1h\" , ...). Indicators : Technical indicators (SMA, EMA, RSI, ...). Limit order : Limit orders which execute at the defined limit price or better. Market order : Guaranteed to fill, may move price depending on the order size. Fee handling \u00b6 All profit calculations of Freqtrade include fees. For Backtesting / Hyperopt / Dry-run modes, the exchange default fee is used (lowest tier on the exchange). For live operations, fees are used as applied by the exchange (this includes BNB rebates etc.). Bot execution logic \u00b6 Starting freqtrade in dry-run or live mode (using freqtrade trade ) will start the bot and start the bot iteration loop. By default, loop runs every few seconds ( internals.process_throttle_secs ) and does roughly the following in the following sequence: Fetch open trades from persistence. Calculate current list of tradable pairs. Download ohlcv data for the pairlist including all informative pairs This step is only executed once per Candle to avoid unnecessary network traffic. Call bot_loop_start() strategy callback. Analyze strategy per pair. Call populate_indicators() Call populate_buy_trend() Call populate_sell_trend() Check timeouts for open orders. Calls check_buy_timeout() strategy callback for open buy orders. Calls check_sell_timeout() strategy callback for open sell orders. Verifies existing positions and eventually places sell orders. Considers stoploss, ROI and sell-signal. Determine sell-price based on ask_strategy configuration setting. Before a sell order is placed, confirm_trade_exit() strategy callback is called. Check if trade-slots are still available (if max_open_trades is reached). Verifies buy signal trying to enter new positions. Determine buy-price based on bid_strategy configuration setting. Before a buy order is placed, confirm_trade_entry() strategy callback is called. This loop will be repeated again and again until the bot is stopped. Backtesting / Hyperopt execution logic \u00b6 backtesting or hyperopt do only part of the above logic, since most of the trading operations are fully simulated. Load historic data for configured pairlist. Calls bot_loop_start() once. Calculate indicators (calls populate_indicators() once per pair). Calculate buy / sell signals (calls populate_buy_trend() and populate_sell_trend() once per pair) Confirm trade buy / sell (calls confirm_trade_entry() and confirm_trade_exit() if implemented in the strategy) Loops per candle simulating entry and exit points. Generate backtest report output Note Both Backtesting and Hyperopt include exchange default Fees in the calculation. Custom fees can be passed to backtesting / hyperopt by specifying the --fee argument.","title":"Freqtrade Basics"},{"location":"bot-basics/#freqtrade-basics","text":"This page provides you some basic concepts on how Freqtrade works and operates.","title":"Freqtrade basics"},{"location":"bot-basics/#freqtrade-terminology","text":"Strategy : Your trading strategy, telling the bot what to do. Trade : Open position. Open Order : Order which is currently placed on the exchange, and is not yet complete. Pair : Tradable pair, usually in the format of Quote/Base (e.g. XRP/USDT). Timeframe : Candle length to use (e.g. \"5m\" , \"1h\" , ...). Indicators : Technical indicators (SMA, EMA, RSI, ...). Limit order : Limit orders which execute at the defined limit price or better. Market order : Guaranteed to fill, may move price depending on the order size.","title":"Freqtrade terminology"},{"location":"bot-basics/#fee-handling","text":"All profit calculations of Freqtrade include fees. For Backtesting / Hyperopt / Dry-run modes, the exchange default fee is used (lowest tier on the exchange). For live operations, fees are used as applied by the exchange (this includes BNB rebates etc.).","title":"Fee handling"},{"location":"bot-basics/#bot-execution-logic","text":"Starting freqtrade in dry-run or live mode (using freqtrade trade ) will start the bot and start the bot iteration loop. By default, loop runs every few seconds ( internals.process_throttle_secs ) and does roughly the following in the following sequence: Fetch open trades from persistence. Calculate current list of tradable pairs. Download ohlcv data for the pairlist including all informative pairs This step is only executed once per Candle to avoid unnecessary network traffic. Call bot_loop_start() strategy callback. Analyze strategy per pair. Call populate_indicators() Call populate_buy_trend() Call populate_sell_trend() Check timeouts for open orders. Calls check_buy_timeout() strategy callback for open buy orders. Calls check_sell_timeout() strategy callback for open sell orders. Verifies existing positions and eventually places sell orders. Considers stoploss, ROI and sell-signal. Determine sell-price based on ask_strategy configuration setting. Before a sell order is placed, confirm_trade_exit() strategy callback is called. Check if trade-slots are still available (if max_open_trades is reached). Verifies buy signal trying to enter new positions. Determine buy-price based on bid_strategy configuration setting. Before a buy order is placed, confirm_trade_entry() strategy callback is called. This loop will be repeated again and again until the bot is stopped.","title":"Bot execution logic"},{"location":"bot-basics/#backtesting-hyperopt-execution-logic","text":"backtesting or hyperopt do only part of the above logic, since most of the trading operations are fully simulated. Load historic data for configured pairlist. Calls bot_loop_start() once. Calculate indicators (calls populate_indicators() once per pair). Calculate buy / sell signals (calls populate_buy_trend() and populate_sell_trend() once per pair) Confirm trade buy / sell (calls confirm_trade_entry() and confirm_trade_exit() if implemented in the strategy) Loops per candle simulating entry and exit points. Generate backtest report output Note Both Backtesting and Hyperopt include exchange default Fees in the calculation. Custom fees can be passed to backtesting / hyperopt by specifying the --fee argument.","title":"Backtesting / Hyperopt execution logic"},{"location":"bot-usage/","text":"Start the bot \u00b6 This page explains the different parameters of the bot and how to run it. Note If you've used setup.sh , don't forget to activate your virtual environment ( source .env/bin/activate ) before running freqtrade commands. Up-to-date clock The clock on the system running the bot must be accurate, synchronized to a NTP server frequently enough to avoid problems with communication to the exchanges. Bot commands \u00b6 ``` usage: freqtrade [-h] [-V] {trade,create-userdir,new-config,new-hyperopt,new-strategy,download-data,convert-data,convert-trade-data,backtesting,edge,hyperopt,hyperopt-list,hyperopt-show,list-exchanges,list-hyperopts,list-markets,list-pairs,list-strategies,list-timeframes,show-trades,test-pairlist,plot-dataframe,plot-profit} ... Free, open source crypto trading bot positional arguments: {trade,create-userdir,new-config,new-hyperopt,new-strategy,download-data,convert-data,convert-trade-data,backtesting,edge,hyperopt,hyperopt-list,hyperopt-show,list-exchanges,list-hyperopts,list-markets,list-pairs,list-strategies,list-timeframes,show-trades,test-pairlist,plot-dataframe,plot-profit} trade Trade module. create-userdir Create user-data directory. new-config Create new config new-hyperopt Create new hyperopt new-strategy Create new strategy download-data Download backtesting data. convert-data Convert candle (OHLCV) data from one format to another. convert-trade-data Convert trade data from one format to another. backtesting Backtesting module. edge Edge module. hyperopt Hyperopt module. hyperopt-list List Hyperopt results hyperopt-show Show details of Hyperopt results list-exchanges Print available exchanges. list-hyperopts Print available hyperopt classes. list-markets Print markets on exchange. list-pairs Print pairs on exchange. list-strategies Print available strategies. list-timeframes Print available timeframes for the exchange. show-trades Show trades. test-pairlist Test your pairlist configuration. plot-dataframe Plot candles with indicators. plot-profit Generate plot showing profits. optional arguments: -h, --help show this help message and exit -V, --version show program's version number and exit ``` Bot trading commands \u00b6 ``` usage: freqtrade trade [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-s NAME] [--strategy-path PATH] [--db-url PATH] [--sd-notify] [--dry-run] [--dry-run-wallet DRY_RUN_WALLET] optional arguments: -h, --help show this help message and exit --db-url PATH Override trades database URL, this is useful in custom deployments (default: sqlite:///tradesv3.sqlite for Live Run mode, sqlite:///tradesv3.dryrun.sqlite for Dry Run). --sd-notify Notify systemd service manager. --dry-run Enforce dry-run for trading (removes Exchange secrets and simulates trades). --dry-run-wallet DRY_RUN_WALLET, --starting-balance DRY_RUN_WALLET Starting balance, used for backtesting / hyperopt and dry-runs. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. Strategy arguments: -s NAME, --strategy NAME Specify strategy class name which will be used by the bot. --strategy-path PATH Specify additional strategy lookup path. ``` How to specify which configuration file be used? \u00b6 The bot allows you to select which configuration file you want to use by means of the -c/--config command line option: bash freqtrade trade -c path/far/far/away/config.json Per default, the bot loads the config.json configuration file from the current working directory. How to use multiple configuration files? \u00b6 The bot allows you to use multiple configuration files by specifying multiple -c/--config options in the command line. Configuration parameters defined in the latter configuration files override parameters with the same name defined in the previous configuration files specified in the command line earlier. For example, you can make a separate configuration file with your key and secret for the Exchange you use for trading, specify default configuration file with empty key and secret values while running in the Dry Mode (which does not actually require them): bash freqtrade trade -c ./config.json and specify both configuration files when running in the normal Live Trade Mode: bash freqtrade trade -c ./config.json -c path/to/secrets/keys.config.json This could help you hide your private Exchange key and Exchange secret on you local machine by setting appropriate file permissions for the file which contains actual secrets and, additionally, prevent unintended disclosure of sensitive private data when you publish examples of your configuration in the project issues or in the Internet. See more details on this technique with examples in the documentation page on configuration . Where to store custom data \u00b6 Freqtrade allows the creation of a user-data directory using freqtrade create-userdir --userdir someDirectory . This directory will look as follows: user_data/ \u251c\u2500\u2500 backtest_results \u251c\u2500\u2500 data \u251c\u2500\u2500 hyperopts \u251c\u2500\u2500 hyperopt_results \u251c\u2500\u2500 plot \u2514\u2500\u2500 strategies You can add the entry \"user_data_dir\" setting to your configuration, to always point your bot to this directory. Alternatively, pass in --userdir to every command. The bot will fail to start if the directory does not exist, but will create necessary subdirectories. This directory should contain your custom strategies, custom hyperopts and hyperopt loss functions, backtesting historical data (downloaded using either backtesting command or the download script) and plot outputs. It is recommended to use version control to keep track of changes to your strategies. How to use --strategy ? \u00b6 This parameter will allow you to load your custom strategy class. To test the bot installation, you can use the SampleStrategy installed by the create-userdir subcommand (usually user_data/strategy/sample_strategy.py ). The bot will search your strategy file within user_data/strategies . To use other directories, please read the next section about --strategy-path . To load a strategy, simply pass the class name (e.g.: CustomStrategy ) in this parameter. Example: In user_data/strategies you have a file my_awesome_strategy.py which has a strategy class called AwesomeStrategy to load it: bash freqtrade trade --strategy AwesomeStrategy If the bot does not find your strategy file, it will display in an error message the reason (File not found, or errors in your code). Learn more about strategy file in Strategy Customization . How to use --strategy-path ? \u00b6 This parameter allows you to add an additional strategy lookup path, which gets checked before the default locations (The passed path must be a directory!): bash freqtrade trade --strategy AwesomeStrategy --strategy-path /some/directory How to install a strategy? \u00b6 This is very simple. Copy paste your strategy file into the directory user_data/strategies or use --strategy-path . And voila, the bot is ready to use it. How to use --db-url ? \u00b6 When you run the bot in Dry-run mode, per default no transactions are stored in a database. If you want to store your bot actions in a DB using --db-url . This can also be used to specify a custom database in production mode. Example command: bash freqtrade trade -c config.json --db-url sqlite:///tradesv3.dry_run.sqlite Next step \u00b6 The optimal strategy of the bot will change with time depending of the market trends. The next step is to Strategy Customization .","title":"Start the bot"},{"location":"bot-usage/#start-the-bot","text":"This page explains the different parameters of the bot and how to run it. Note If you've used setup.sh , don't forget to activate your virtual environment ( source .env/bin/activate ) before running freqtrade commands. Up-to-date clock The clock on the system running the bot must be accurate, synchronized to a NTP server frequently enough to avoid problems with communication to the exchanges.","title":"Start the bot"},{"location":"bot-usage/#bot-commands","text":"``` usage: freqtrade [-h] [-V] {trade,create-userdir,new-config,new-hyperopt,new-strategy,download-data,convert-data,convert-trade-data,backtesting,edge,hyperopt,hyperopt-list,hyperopt-show,list-exchanges,list-hyperopts,list-markets,list-pairs,list-strategies,list-timeframes,show-trades,test-pairlist,plot-dataframe,plot-profit} ... Free, open source crypto trading bot positional arguments: {trade,create-userdir,new-config,new-hyperopt,new-strategy,download-data,convert-data,convert-trade-data,backtesting,edge,hyperopt,hyperopt-list,hyperopt-show,list-exchanges,list-hyperopts,list-markets,list-pairs,list-strategies,list-timeframes,show-trades,test-pairlist,plot-dataframe,plot-profit} trade Trade module. create-userdir Create user-data directory. new-config Create new config new-hyperopt Create new hyperopt new-strategy Create new strategy download-data Download backtesting data. convert-data Convert candle (OHLCV) data from one format to another. convert-trade-data Convert trade data from one format to another. backtesting Backtesting module. edge Edge module. hyperopt Hyperopt module. hyperopt-list List Hyperopt results hyperopt-show Show details of Hyperopt results list-exchanges Print available exchanges. list-hyperopts Print available hyperopt classes. list-markets Print markets on exchange. list-pairs Print pairs on exchange. list-strategies Print available strategies. list-timeframes Print available timeframes for the exchange. show-trades Show trades. test-pairlist Test your pairlist configuration. plot-dataframe Plot candles with indicators. plot-profit Generate plot showing profits. optional arguments: -h, --help show this help message and exit -V, --version show program's version number and exit ```","title":"Bot commands"},{"location":"bot-usage/#bot-trading-commands","text":"``` usage: freqtrade trade [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-s NAME] [--strategy-path PATH] [--db-url PATH] [--sd-notify] [--dry-run] [--dry-run-wallet DRY_RUN_WALLET] optional arguments: -h, --help show this help message and exit --db-url PATH Override trades database URL, this is useful in custom deployments (default: sqlite:///tradesv3.sqlite for Live Run mode, sqlite:///tradesv3.dryrun.sqlite for Dry Run). --sd-notify Notify systemd service manager. --dry-run Enforce dry-run for trading (removes Exchange secrets and simulates trades). --dry-run-wallet DRY_RUN_WALLET, --starting-balance DRY_RUN_WALLET Starting balance, used for backtesting / hyperopt and dry-runs. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. Strategy arguments: -s NAME, --strategy NAME Specify strategy class name which will be used by the bot. --strategy-path PATH Specify additional strategy lookup path. ```","title":"Bot trading commands"},{"location":"bot-usage/#how-to-specify-which-configuration-file-be-used","text":"The bot allows you to select which configuration file you want to use by means of the -c/--config command line option: bash freqtrade trade -c path/far/far/away/config.json Per default, the bot loads the config.json configuration file from the current working directory.","title":"How to specify which configuration file be used?"},{"location":"bot-usage/#how-to-use-multiple-configuration-files","text":"The bot allows you to use multiple configuration files by specifying multiple -c/--config options in the command line. Configuration parameters defined in the latter configuration files override parameters with the same name defined in the previous configuration files specified in the command line earlier. For example, you can make a separate configuration file with your key and secret for the Exchange you use for trading, specify default configuration file with empty key and secret values while running in the Dry Mode (which does not actually require them): bash freqtrade trade -c ./config.json and specify both configuration files when running in the normal Live Trade Mode: bash freqtrade trade -c ./config.json -c path/to/secrets/keys.config.json This could help you hide your private Exchange key and Exchange secret on you local machine by setting appropriate file permissions for the file which contains actual secrets and, additionally, prevent unintended disclosure of sensitive private data when you publish examples of your configuration in the project issues or in the Internet. See more details on this technique with examples in the documentation page on configuration .","title":"How to use multiple configuration files?"},{"location":"bot-usage/#where-to-store-custom-data","text":"Freqtrade allows the creation of a user-data directory using freqtrade create-userdir --userdir someDirectory . This directory will look as follows: user_data/ \u251c\u2500\u2500 backtest_results \u251c\u2500\u2500 data \u251c\u2500\u2500 hyperopts \u251c\u2500\u2500 hyperopt_results \u251c\u2500\u2500 plot \u2514\u2500\u2500 strategies You can add the entry \"user_data_dir\" setting to your configuration, to always point your bot to this directory. Alternatively, pass in --userdir to every command. The bot will fail to start if the directory does not exist, but will create necessary subdirectories. This directory should contain your custom strategies, custom hyperopts and hyperopt loss functions, backtesting historical data (downloaded using either backtesting command or the download script) and plot outputs. It is recommended to use version control to keep track of changes to your strategies.","title":"Where to store custom data"},{"location":"bot-usage/#how-to-use-strategy","text":"This parameter will allow you to load your custom strategy class. To test the bot installation, you can use the SampleStrategy installed by the create-userdir subcommand (usually user_data/strategy/sample_strategy.py ). The bot will search your strategy file within user_data/strategies . To use other directories, please read the next section about --strategy-path . To load a strategy, simply pass the class name (e.g.: CustomStrategy ) in this parameter. Example: In user_data/strategies you have a file my_awesome_strategy.py which has a strategy class called AwesomeStrategy to load it: bash freqtrade trade --strategy AwesomeStrategy If the bot does not find your strategy file, it will display in an error message the reason (File not found, or errors in your code). Learn more about strategy file in Strategy Customization .","title":"How to use --strategy?"},{"location":"bot-usage/#how-to-use-strategy-path","text":"This parameter allows you to add an additional strategy lookup path, which gets checked before the default locations (The passed path must be a directory!): bash freqtrade trade --strategy AwesomeStrategy --strategy-path /some/directory","title":"How to use --strategy-path?"},{"location":"bot-usage/#how-to-install-a-strategy","text":"This is very simple. Copy paste your strategy file into the directory user_data/strategies or use --strategy-path . And voila, the bot is ready to use it.","title":"How to install a strategy?"},{"location":"bot-usage/#how-to-use-db-url","text":"When you run the bot in Dry-run mode, per default no transactions are stored in a database. If you want to store your bot actions in a DB using --db-url . This can also be used to specify a custom database in production mode. Example command: bash freqtrade trade -c config.json --db-url sqlite:///tradesv3.dry_run.sqlite","title":"How to use --db-url?"},{"location":"bot-usage/#next-step","text":"The optimal strategy of the bot will change with time depending of the market trends. The next step is to Strategy Customization .","title":"Next step"},{"location":"configuration/","text":"Configure the bot \u00b6 Freqtrade has many configurable features and possibilities. By default, these settings are configured via the configuration file (see below). The Freqtrade configuration file \u00b6 The bot uses a set of configuration parameters during its operation that all together conform to the bot configuration. It normally reads its configuration from a file (Freqtrade configuration file). Per default, the bot loads the configuration from the config.json file, located in the current working directory. You can specify a different configuration file used by the bot with the -c/--config command-line option. Multiple configuration files can be specified and used by the bot or the bot can read its configuration parameters from the process standard input stream. Use multiple configuration files to keep secrets secret You can use a 2 nd configuration file containing your secrets. That way you can share your \"primary\" configuration file, while still keeping your API keys for yourself. bash freqtrade trade --config user_data/config.json --config user_data/config-private.json <...> The 2 nd file should only specify what you intend to override. If a key is in more than one of the configurations, then the \"last specified configuration\" wins (in the above example, config-private.json ). If you used the Quick start method for installing the bot, the installation script should have already created the default configuration file ( config.json ) for you. If the default configuration file is not created we recommend you to use freqtrade new-config --config config.json to generate a basic configuration file. The Freqtrade configuration file is to be written in JSON format. Additionally to the standard JSON syntax, you may use one-line // ... and multi-line /* ... */ comments in your configuration files and trailing commas in the lists of parameters. Do not worry if you are not familiar with JSON format -- simply open the configuration file with an editor of your choice, make some changes to the parameters you need, save your changes and, finally, restart the bot or, if it was previously stopped, run it again with the changes you made to the configuration. The bot validates the syntax of the configuration file at startup and will warn you if you made any errors editing it, pointing out problematic lines. Configuration parameters \u00b6 The table below will list all configuration parameters available. Freqtrade can also load many options via command line (CLI) arguments (check out the commands --help output for details). The prevalence for all Options is as follows: CLI arguments override any other option Configuration files are used in sequence (the last file wins) and override Strategy configurations. Strategy configurations are only used if they are not set via configuration or command-line arguments. These options are marked with Strategy Override in the below table. Mandatory parameters are marked as Required , which means that they are required to be set in one of the possible ways. Parameter Description max_open_trades Required. Number of open trades your bot is allowed to have. Only one open trade per pair is possible, so the length of your pairlist is another limitation that can apply. If -1 then it is ignored (i.e. potentially unlimited open trades, limited by the pairlist). More information below . Datatype: Positive integer or -1. stake_currency Required. Crypto-currency used for trading. Datatype: String stake_amount Required. Amount of crypto-currency your bot will use for each trade. Set it to \"unlimited\" to allow the bot to use all available balance. More information below . Datatype: Positive float or \"unlimited\" . tradable_balance_ratio Ratio of the total account balance the bot is allowed to trade. More information below . Defaults to 0.99 99%). Datatype: Positive float between 0.1 and 1.0 . available_capital Available starting capital for the bot. Useful when running multiple bots on the same exchange account. More information below . Datatype: Positive float. amend_last_stake_amount Use reduced last stake amount if necessary. More information below . Defaults to false . Datatype: Boolean last_stake_amount_min_ratio Defines minimum stake amount that has to be left and executed. Applies only to the last stake amount when it's amended to a reduced value (i.e. if amend_last_stake_amount is set to true ). More information below . Defaults to 0.5 . Datatype: Float (as ratio) amount_reserve_percent Reserve some amount in min pair stake amount. The bot will reserve amount_reserve_percent + stoploss value when calculating min pair stake amount in order to avoid possible trade refusals. Defaults to 0.05 (5%). Datatype: Positive Float as ratio. timeframe The timeframe (former ticker interval) to use (e.g 1m , 5m , 15m , 30m , 1h ...). Strategy Override . Datatype: String fiat_display_currency Fiat currency used to show your profits. More information below . Datatype: String dry_run Required. Define if the bot must be in Dry Run or production mode. Defaults to true . Datatype: Boolean dry_run_wallet Define the starting amount in stake currency for the simulated wallet used by the bot running in Dry Run mode. Defaults to 1000 . Datatype: Float cancel_open_orders_on_exit Cancel open orders when the /stop RPC command is issued, Ctrl+C is pressed or the bot dies unexpectedly. When set to true , this allows you to use /stop to cancel unfilled and partially filled orders in the event of a market crash. It does not impact open positions. Defaults to false . Datatype: Boolean process_only_new_candles Enable processing of indicators only when new candles arrive. If false each loop populates the indicators, this will mean the same candle is processed many times creating system load but can be useful of your strategy depends on tick data not only candle. Strategy Override . Defaults to false . Datatype: Boolean minimal_roi Required. Set the threshold as ratio the bot will use to sell a trade. More information below . Strategy Override . Datatype: Dict stoploss Required. Value as ratio of the stoploss used by the bot. More details in the stoploss documentation . Strategy Override . Datatype: Float (as ratio) trailing_stop Enables trailing stoploss (based on stoploss in either configuration or strategy file). More details in the stoploss documentation . Strategy Override . Datatype: Boolean trailing_stop_positive Changes stoploss once profit has been reached. More details in the stoploss documentation . Strategy Override . Datatype: Float trailing_stop_positive_offset Offset on when to apply trailing_stop_positive . Percentage value which should be positive. More details in the stoploss documentation . Strategy Override . Defaults to 0.0 (no offset). Datatype: Float trailing_only_offset_is_reached Only apply trailing stoploss when the offset is reached. stoploss documentation . Strategy Override . Defaults to false . Datatype: Boolean fee Fee used during backtesting / dry-runs. Should normally not be configured, which has freqtrade fall back to the exchange default fee. Set as ratio (e.g. 0.001 = 0.1%). Fee is applied twice for each trade, once when buying, once when selling. Datatype: Float (as ratio) unfilledtimeout.buy Required. How long (in minutes or seconds) the bot will wait for an unfilled buy order to complete, after which the order will be cancelled and repeated at current (new) price, as long as there is a signal. Strategy Override . Datatype: Integer unfilledtimeout.sell Required. How long (in minutes or seconds) the bot will wait for an unfilled sell order to complete, after which the order will be cancelled and repeated at current (new) price, as long as there is a signal. Strategy Override . Datatype: Integer unfilledtimeout.unit Unit to use in unfilledtimeout setting. Note: If you set unfilledtimeout.unit to \"seconds\", \"internals.process_throttle_secs\" must be inferior or equal to timeout Strategy Override . Defaults to minutes . Datatype: String bid_strategy.price_side Select the side of the spread the bot should look at to get the buy rate. More information below . Defaults to bid . Datatype: String (either ask or bid ). bid_strategy.ask_last_balance Required. Interpolate the bidding price. More information below . bid_strategy.use_order_book Enable buying using the rates in Order Book Bids . Datatype: Boolean bid_strategy.order_book_top Bot will use the top N rate in Order Book \"price_side\" to buy. I.e. a value of 2 will allow the bot to pick the 2 nd bid rate in Order Book Bids . Defaults to 1 . Datatype: Positive Integer bid_strategy. check_depth_of_market.enabled Do not buy if the difference of buy orders and sell orders is met in Order Book. Check market depth . Defaults to false . Datatype: Boolean bid_strategy. check_depth_of_market.bids_to_ask_delta The difference ratio of buy orders and sell orders found in Order Book. A value below 1 means sell order size is greater, while value greater than 1 means buy order size is higher. Check market depth Defaults to 0 . Datatype: Float (as ratio) ask_strategy.price_side Select the side of the spread the bot should look at to get the sell rate. More information below . Defaults to ask . Datatype: String (either ask or bid ). ask_strategy.bid_last_balance Interpolate the selling price. More information below . ask_strategy.use_order_book Enable selling of open trades using Order Book Asks . Datatype: Boolean ask_strategy.order_book_top Bot will use the top N rate in Order Book \"price_side\" to sell. I.e. a value of 2 will allow the bot to pick the 2 nd ask rate in Order Book Asks Defaults to 1 . Datatype: Positive Integer use_sell_signal Use sell signals produced by the strategy in addition to the minimal_roi . Strategy Override . Defaults to true . Datatype: Boolean sell_profit_only Wait until the bot reaches sell_profit_offset before taking a sell decision. Strategy Override . Defaults to false . Datatype: Boolean sell_profit_offset Sell-signal is only active above this value. Strategy Override . Defaults to 0.0 . Datatype: Float (as ratio) ignore_roi_if_buy_signal Do not sell if the buy signal is still active. This setting takes preference over minimal_roi and use_sell_signal . Strategy Override . Defaults to false . Datatype: Boolean ignore_buying_expired_candle_after Specifies the number of seconds until a buy signal is no longer used. Datatype: Integer order_types Configure order-types depending on the action ( \"buy\" , \"sell\" , \"stoploss\" , \"stoploss_on_exchange\" ). More information below . Strategy Override . Datatype: Dict order_time_in_force Configure time in force for buy and sell orders. More information below . Strategy Override . Datatype: Dict exchange.name Required. Name of the exchange class to use. List below . Datatype: String exchange.sandbox Use the 'sandbox' version of the exchange, where the exchange provides a sandbox for risk-free integration. See here in more details. Datatype: Boolean exchange.key API key to use for the exchange. Only required when you are in production mode. Keep it in secret, do not disclose publicly. Datatype: String exchange.secret API secret to use for the exchange. Only required when you are in production mode. Keep it in secret, do not disclose publicly. Datatype: String exchange.password API password to use for the exchange. Only required when you are in production mode and for exchanges that use password for API requests. Keep it in secret, do not disclose publicly. Datatype: String exchange.pair_whitelist List of pairs to use by the bot for trading and to check for potential trades during backtesting. Supports regex pairs as .*/BTC . Not used by VolumePairList. More information . Datatype: List exchange.pair_blacklist List of pairs the bot must absolutely avoid for trading and backtesting. More information . Datatype: List exchange.ccxt_config Additional CCXT parameters passed to both ccxt instances (sync and async). This is usually the correct place for ccxt configurations. Parameters may differ from exchange to exchange and are documented in the ccxt documentation Datatype: Dict exchange.ccxt_sync_config Additional CCXT parameters passed to the regular (sync) ccxt instance. Parameters may differ from exchange to exchange and are documented in the ccxt documentation Datatype: Dict exchange.ccxt_async_config Additional CCXT parameters passed to the async ccxt instance. Parameters may differ from exchange to exchange and are documented in the ccxt documentation Datatype: Dict exchange.markets_refresh_interval The interval in minutes in which markets are reloaded. Defaults to 60 minutes. Datatype: Positive Integer exchange.skip_pair_validation Skip pairlist validation on startup. Defaults to false Datatype: * Boolean exchange.skip_open_order_update Skips open order updates on startup should the exchange cause problems. Only relevant in live conditions. Defaults to false Datatype: * Boolean exchange.log_responses Log relevant exchange responses. For debug mode only - use with care. Defaults to false Datatype: * Boolean edge.* Please refer to edge configuration document for detailed explanation. experimental.block_bad_exchanges Block exchanges known to not work with freqtrade. Leave on default unless you want to test if that exchange works now. Defaults to true . Datatype: Boolean pairlists Define one or more pairlists to be used. More information . Defaults to StaticPairList . Datatype: List of Dicts protections Define one or more protections to be used. More information . Datatype: List of Dicts telegram.enabled Enable the usage of Telegram. Datatype: Boolean telegram.token Your Telegram bot token. Only required if telegram.enabled is true . Keep it in secret, do not disclose publicly. Datatype: String telegram.chat_id Your personal Telegram account id. Only required if telegram.enabled is true . Keep it in secret, do not disclose publicly. Datatype: String telegram.balance_dust_level Dust-level (in stake currency) - currencies with a balance below this will not be shown by /balance . Datatype: float webhook.enabled Enable usage of Webhook notifications Datatype: Boolean webhook.url URL for the webhook. Only required if webhook.enabled is true . See the webhook documentation for more details. Datatype: String webhook.webhookbuy Payload to send on buy. Only required if webhook.enabled is true . See the webhook documentation for more details. Datatype: String webhook.webhookbuycancel Payload to send on buy order cancel. Only required if webhook.enabled is true . See the webhook documentation for more details. Datatype: String webhook.webhooksell Payload to send on sell. Only required if webhook.enabled is true . See the webhook documentation for more details. Datatype: String webhook.webhooksellcancel Payload to send on sell order cancel. Only required if webhook.enabled is true . See the webhook documentation for more details. Datatype: String webhook.webhookstatus Payload to send on status calls. Only required if webhook.enabled is true . See the webhook documentation for more details. Datatype: String api_server.enabled Enable usage of API Server. See the API Server documentation for more details. Datatype: Boolean api_server.listen_ip_address Bind IP address. See the API Server documentation for more details. Datatype: IPv4 api_server.listen_port Bind Port. See the API Server documentation for more details. Datatype: Integer between 1024 and 65535 api_server.verbosity Logging verbosity. info will print all RPC Calls, while \"error\" will only display errors. Datatype: Enum, either info or error . Defaults to info . api_server.username Username for API server. See the API Server documentation for more details. Keep it in secret, do not disclose publicly. Datatype: String api_server.password Password for API server. See the API Server documentation for more details. Keep it in secret, do not disclose publicly. Datatype: String bot_name Name of the bot. Passed via API to a client - can be shown to distinguish / name bots. Defaults to freqtrade Datatype: String db_url Declares database URL to use. NOTE: This defaults to sqlite:///tradesv3.dryrun.sqlite if dry_run is true , and to sqlite:///tradesv3.sqlite for production instances. Datatype: String, SQLAlchemy connect string initial_state Defines the initial application state. If set to stopped, then the bot has to be explicitly started via /start RPC command. Defaults to stopped . Datatype: Enum, either stopped or running forcebuy_enable Enables the RPC Commands to force a buy. More information below. Datatype: Boolean disable_dataframe_checks Disable checking the OHLCV dataframe returned from the strategy methods for correctness. Only use when intentionally changing the dataframe and understand what you are doing. Strategy Override . Defaults to False . Datatype: Boolean strategy Required Defines Strategy class to use. Recommended to be set via --strategy NAME . Datatype: ClassName strategy_path Adds an additional strategy lookup path (must be a directory). Datatype: String internals.process_throttle_secs Set the process throttle, or minimum loop duration for one bot iteration loop. Value in second. Defaults to 5 seconds. Datatype: Positive Integer internals.heartbeat_interval Print heartbeat message every N seconds. Set to 0 to disable heartbeat messages. Defaults to 60 seconds. Datatype: Positive Integer or 0 internals.sd_notify Enables use of the sd_notify protocol to tell systemd service manager about changes in the bot state and issue keep-alive pings. See here for more details. Datatype: Boolean logfile Specifies logfile name. Uses a rolling strategy for log file rotation for 10 files with the 1MB limit per file. Datatype: String user_data_dir Directory containing user data. Defaults to ./user_data/ . Datatype: String dataformat_ohlcv Data format to use to store historical candle (OHLCV) data. Defaults to json . Datatype: String dataformat_trades Data format to use to store historical trades data. Defaults to jsongz . Datatype: String Parameters in the strategy \u00b6 The following parameters can be set in the configuration file or strategy. Values set in the configuration file always overwrite values set in the strategy. minimal_roi timeframe stoploss trailing_stop trailing_stop_positive trailing_stop_positive_offset trailing_only_offset_is_reached use_custom_stoploss process_only_new_candles order_types order_time_in_force unfilledtimeout disable_dataframe_checks use_sell_signal sell_profit_only sell_profit_offset ignore_roi_if_buy_signal ignore_buying_expired_candle_after Configuring amount per trade \u00b6 There are several methods to configure how much of the stake currency the bot will use to enter a trade. All methods respect the available balance configuration as explained below. Minimum trade stake \u00b6 The minimum stake amount will depend on exchange and pair and is usually listed in the exchange support pages. Assuming the minimum tradable amount for XRP/USD is 20 XRP (given by the exchange), and the price is 0.6$. The minimum stake amount to buy this pair is, therefore, 20 * 0.6 ~= 12 . This exchange has also a limit on USD - where all orders must be > 10$ - which however does not apply in this case. To guarantee safe execution, freqtrade will not allow buying with a stake-amount of 10.1$, instead, it'll make sure that there's enough space to place a stoploss below the pair (+ an offset, defined by amount_reserve_percent , which defaults to 5%). With a reserve of 5%, the minimum stake amount would be ~12.6$ ( 12 * (1 + 0.05) ). If we take into account a stoploss of 10% on top of that - we'd end up with a value of ~14$ ( 12.6 / (1 - 0.1) ). To limit this calculation in case of large stoploss values, the calculated minimum stake-limit will never be more than 50% above the real limit. Warning Since the limits on exchanges are usually stable and are not updated often, some pairs can show pretty high minimum limits, simply because the price increased a lot since the last limit adjustment by the exchange. Tradable balance \u00b6 By default, the bot assumes that the complete amount - 1% is at it's disposal, and when using dynamic stake amount , it will split the complete balance into max_open_trades buckets per trade. Freqtrade will reserve 1% for eventual fees when entering a trade and will therefore not touch that by default. You can configure the \"untouched\" amount by using the tradable_balance_ratio setting. For example, if you have 10 ETH available in your wallet on the exchange and tradable_balance_ratio=0.5 (which is 50%), then the bot will use a maximum amount of 5 ETH for trading and considers this as an available balance. The rest of the wallet is untouched by the trades. Danger This setting should not be used when running multiple bots on the same account. Please look at Available Capital to the bot instead. Warning The tradable_balance_ratio setting applies to the current balance (free balance + tied up in trades). Therefore, assuming the starting balance of 1000, a configuration with tradable_balance_ratio=0.99 will not guarantee that 10 currency units will always remain available on the exchange. For example, the free amount may reduce to 5 units if the total balance is reduced to 500 (either by a losing streak or by withdrawing balance). Assign available Capital \u00b6 To fully utilize compounding profits when using multiple bots on the same exchange account, you'll want to limit each bot to a certain starting balance. This can be accomplished by setting available_capital to the desired starting balance. Assuming your account has 10.000 USDT and you want to run 2 different strategies on this exchange. You'd set available_capital=5000 - granting each bot an initial capital of 5000 USDT. The bot will then split this starting balance equally into max_open_trades buckets. Profitable trades will result in increased stake-sizes for this bot - without affecting the stake-sizes of the other bot. Incompatible with tradable_balance_ratio Setting this option will replace any configuration of tradable_balance_ratio . Amend last stake amount \u00b6 Assuming we have the tradable balance of 1000 USDT, stake_amount=400 , and max_open_trades=3 . The bot would open 2 trades and will be unable to fill the last trading slot, since the requested 400 USDT are no longer available since 800 USDT are already tied in other trades. To overcome this, the option amend_last_stake_amount can be set to True , which will enable the bot to reduce stake_amount to the available balance to fill the last trade slot. In the example above this would mean: Trade1: 400 USDT Trade2: 400 USDT Trade3: 200 USDT Note This option only applies with Static stake amount - since Dynamic stake amount divides the balances evenly. Note The minimum last stake amount can be configured using last_stake_amount_min_ratio - which defaults to 0.5 (50%). This means that the minimum stake amount that's ever used is stake_amount * 0.5 . This avoids very low stake amounts, that are close to the minimum tradable amount for the pair and can be refused by the exchange. Static stake amount \u00b6 The stake_amount configuration statically configures the amount of stake-currency your bot will use for each trade. The minimal configuration value is 0.0001, however, please check your exchange's trading minimums for the stake currency you're using to avoid problems. This setting works in combination with max_open_trades . The maximum capital engaged in trades is stake_amount * max_open_trades . For example, the bot will at most use (0.05 BTC x 3) = 0.15 BTC, assuming a configuration of max_open_trades=3 and stake_amount=0.05 . Note This setting respects the available balance configuration . Dynamic stake amount \u00b6 Alternatively, you can use a dynamic stake amount, which will use the available balance on the exchange, and divide that equally by the number of allowed trades ( max_open_trades ). To configure this, set stake_amount=\"unlimited\" . We also recommend to set tradable_balance_ratio=0.99 (99%) - to keep a minimum balance for eventual fees. In this case a trade amount is calculated as: python currency_balance / (max_open_trades - current_open_trades) To allow the bot to trade all the available stake_currency in your account (minus tradable_balance_ratio ) set json \"stake_amount\" : \"unlimited\", \"tradable_balance_ratio\": 0.99, Compounding profits This configuration will allow increasing/decreasing stakes depending on the performance of the bot (lower stake if the bot is losing, higher stakes if the bot has a winning record since higher balances are available), and will result in profit compounding. When using Dry-Run Mode When using \"stake_amount\" : \"unlimited\", in combination with Dry-Run, Backtesting or Hyperopt, the balance will be simulated starting with a stake of dry_run_wallet which will evolve. It is therefore important to set dry_run_wallet to a sensible value (like 0.05 or 0.01 for BTC and 1000 or 100 for USDT, for example), otherwise, it may simulate trades with 100 BTC (or more) or 0.05 USDT (or less) at once - which may not correspond to your real available balance or is less than the exchange minimal limit for the order amount for the stake currency. Prices used for orders \u00b6 Prices for regular orders can be controlled via the parameter structures bid_strategy for buying and ask_strategy for selling. Prices are always retrieved right before an order is placed, either by querying the exchange tickers or by using the orderbook data. Note Orderbook data used by Freqtrade are the data retrieved from exchange by the ccxt's function fetch_order_book() , i.e. are usually data from the L2-aggregated orderbook, while the ticker data are the structures returned by the ccxt's fetch_ticker() / fetch_tickers() functions. Refer to the ccxt library documentation for more details. Using market orders Please read the section Market order pricing section when using market orders. Buy price \u00b6 Check depth of market \u00b6 When check depth of market is enabled ( bid_strategy.check_depth_of_market.enabled=True ), the buy signals are filtered based on the orderbook depth (sum of all amounts) for each orderbook side. Orderbook bid (buy) side depth is then divided by the orderbook ask (sell) side depth and the resulting delta is compared to the value of the bid_strategy.check_depth_of_market.bids_to_ask_delta parameter. The buy order is only executed if the orderbook delta is greater than or equal to the configured delta value. Note A delta value below 1 means that ask (sell) orderbook side depth is greater than the depth of the bid (buy) orderbook side, while a value greater than 1 means opposite (depth of the buy side is higher than the depth of the sell side). Buy price side \u00b6 The configuration setting bid_strategy.price_side defines the side of the spread the bot looks for when buying. The following displays an orderbook. explanation ... 103 102 101 # ask -------------Current spread 99 # bid 98 97 ... If bid_strategy.price_side is set to \"bid\" , then the bot will use 99 as buying price. In line with that, if bid_strategy.price_side is set to \"ask\" , then the bot will use 101 as buying price. Using ask price often guarantees quicker filled orders, but the bot can also end up paying more than what would have been necessary. Taker fees instead of maker fees will most likely apply even when using limit buy orders. Also, prices at the \"ask\" side of the spread are higher than prices at the \"bid\" side in the orderbook, so the order behaves similar to a market order (however with a maximum price). Buy price with Orderbook enabled \u00b6 When buying with the orderbook enabled ( bid_strategy.use_order_book=True ), Freqtrade fetches the bid_strategy.order_book_top entries from the orderbook and uses the entry specified as bid_strategy.order_book_top on the configured side ( bid_strategy.price_side ) of the orderbook. 1 specifies the topmost entry in the orderbook, while 2 would use the 2 nd entry in the orderbook, and so on. Buy price without Orderbook enabled \u00b6 The following section uses side as the configured bid_strategy.price_side . When not using orderbook ( bid_strategy.use_order_book=False ), Freqtrade uses the best side price from the ticker if it's below the last traded price from the ticker. Otherwise (when the side price is above the last price), it calculates a rate between side and last price. The bid_strategy.ask_last_balance configuration parameter controls this. A value of 0.0 will use side price, while 1.0 will use the last price and values between those interpolate between ask and last price. Sell price \u00b6 Sell price side \u00b6 The configuration setting ask_strategy.price_side defines the side of the spread the bot looks for when selling. The following displays an orderbook: explanation ... 103 102 101 # ask -------------Current spread 99 # bid 98 97 ... If ask_strategy.price_side is set to \"ask\" , then the bot will use 101 as selling price. In line with that, if ask_strategy.price_side is set to \"bid\" , then the bot will use 99 as selling price. Sell price with Orderbook enabled \u00b6 When selling with the orderbook enabled ( ask_strategy.use_order_book=True ), Freqtrade fetches the ask_strategy.order_book_top entries in the orderbook and uses the entry specified as ask_strategy.order_book_top from the configured side ( ask_strategy.price_side ) as selling price. 1 specifies the topmost entry in the orderbook, while 2 would use the 2 nd entry in the orderbook, and so on. Sell price without Orderbook enabled \u00b6 When not using orderbook ( ask_strategy.use_order_book=False ), the price at the ask_strategy.price_side side (defaults to \"ask\" ) from the ticker will be used as the sell price. When not using orderbook ( ask_strategy.use_order_book=False ), Freqtrade uses the best side price from the ticker if it's below the last traded price from the ticker. Otherwise (when the side price is above the last price), it calculates a rate between side and last price. The ask_strategy.bid_last_balance configuration parameter controls this. A value of 0.0 will use side price, while 1.0 will use the last price and values between those interpolate between side and last price. Market order pricing \u00b6 When using market orders, prices should be configured to use the \"correct\" side of the orderbook to allow realistic pricing detection. Assuming both buy and sell are using market orders, a configuration similar to the following might be used jsonc \"order_types\": { \"buy\": \"market\", \"sell\": \"market\" // ... }, \"bid_strategy\": { \"price_side\": \"ask\", // ... }, \"ask_strategy\":{ \"price_side\": \"bid\", // ... }, Obviously, if only one side is using limit orders, different pricing combinations can be used. Understand minimal_roi \u00b6 The minimal_roi configuration parameter is a JSON object where the key is a duration in minutes and the value is the minimum ROI as a ratio. See the example below: json \"minimal_roi\": { \"40\": 0.0, # Sell after 40 minutes if the profit is not negative \"30\": 0.01, # Sell after 30 minutes if there is at least 1% profit \"20\": 0.02, # Sell after 20 minutes if there is at least 2% profit \"0\": 0.04 # Sell immediately if there is at least 4% profit }, Most of the strategy files already include the optimal minimal_roi value. This parameter can be set in either Strategy or Configuration file. If you use it in the configuration file, it will override the minimal_roi value from the strategy file. If it is not set in either Strategy or Configuration, a default of 1000% {\"0\": 10} is used, and minimal ROI is disabled unless your trade generates 1000% profit. Special case to forcesell after a specific time A special case presents using \"\": -1 as ROI. This forces the bot to sell a trade after N Minutes, no matter if it's positive or negative, so represents a time-limited force-sell. Understand forcebuy_enable \u00b6 The forcebuy_enable configuration parameter enables the usage of forcebuy commands via Telegram and REST API. For security reasons, it's disabled by default, and freqtrade will show a warning message on startup if enabled. For example, you can send /forcebuy ETH/BTC to the bot, which will result in freqtrade buying the pair and holds it until a regular sell-signal (ROI, stoploss, /forcesell) appears. This can be dangerous with some strategies, so use with care. See the telegram documentation for details on usage. Ignoring expired candles \u00b6 When working with larger timeframes (for example 1h or more) and using a low max_open_trades value, the last candle can be processed as soon as a trade slot becomes available. When processing the last candle, this can lead to a situation where it may not be desirable to use the buy signal on that candle. For example, when using a condition in your strategy where you use a cross-over, that point may have passed too long ago for you to start a trade on it. In these situations, you can enable the functionality to ignore candles that are beyond a specified period by setting ignore_buying_expired_candle_after to a positive number, indicating the number of seconds after which the buy signal becomes expired. For example, if your strategy is using a 1h timeframe, and you only want to buy within the first 5 minutes when a new candle comes in, you can add the following configuration to your strategy: json { //... \"ignore_buying_expired_candle_after\": 300, // ... } Note This setting resets with each new candle, so it will not prevent sticking-signals from executing on the 2 nd or 3 rd candle they're active. Best use a \"trigger\" selector for buy signals, which are only active for one candle. Understand order_types \u00b6 The order_types configuration parameter maps actions ( buy , sell , stoploss , emergencysell , forcesell , forcebuy ) to order-types ( market , limit , ...) as well as configures stoploss to be on the exchange and defines stoploss on exchange update interval in seconds. This allows to buy using limit orders, sell using limit-orders, and create stoplosses using market orders. It also allows to set the stoploss \"on exchange\" which means stoploss order would be placed immediately once the buy order is fulfilled. order_types set in the configuration file overwrites values set in the strategy as a whole, so you need to configure the whole order_types dictionary in one place. If this is configured, the following 4 values ( buy , sell , stoploss and stoploss_on_exchange ) need to be present, otherwise, the bot will fail to start. For information on ( emergencysell , forcesell , forcebuy , stoploss_on_exchange , stoploss_on_exchange_interval , stoploss_on_exchange_limit_ratio ) please see stop loss documentation stop loss on exchange Syntax for Strategy: python order_types = { \"buy\": \"limit\", \"sell\": \"limit\", \"emergencysell\": \"market\", \"forcebuy\": \"market\", \"forcesell\": \"market\", \"stoploss\": \"market\", \"stoploss_on_exchange\": False, \"stoploss_on_exchange_interval\": 60, \"stoploss_on_exchange_limit_ratio\": 0.99, } Configuration: json \"order_types\": { \"buy\": \"limit\", \"sell\": \"limit\", \"emergencysell\": \"market\", \"forcebuy\": \"market\", \"forcesell\": \"market\", \"stoploss\": \"market\", \"stoploss_on_exchange\": false, \"stoploss_on_exchange_interval\": 60 } Market order support Not all exchanges support \"market\" orders. The following message will be shown if your exchange does not support market orders: \"Exchange does not support market orders.\" and the bot will refuse to start. Using market orders Please carefully read the section Market order pricing section when using market orders. Stoploss on exchange stoploss_on_exchange_interval is not mandatory. Do not change its value if you are unsure of what you are doing. For more information about how stoploss works please refer to the stoploss documentation . If stoploss_on_exchange is enabled and the stoploss is cancelled manually on the exchange, then the bot will create a new stoploss order. Warning: stoploss_on_exchange failures If stoploss on exchange creation fails for some reason, then an \"emergency sell\" is initiated. By default, this will sell the asset using a market order. The order-type for the emergency-sell can be changed by setting the emergencysell value in the order_types dictionary - however, this is not advised. Understand order_time_in_force \u00b6 The order_time_in_force configuration parameter defines the policy by which the order is executed on the exchange. Three commonly used time in force are: GTC (Good Till Canceled): This is most of the time the default time in force. It means the order will remain on exchange till it is cancelled by the user. It can be fully or partially fulfilled. If partially fulfilled, the remaining will stay on the exchange till cancelled. FOK (Fill Or Kill): It means if the order is not executed immediately AND fully then it is cancelled by the exchange. IOC (Immediate Or Canceled): It is the same as FOK (above) except it can be partially fulfilled. The remaining part is automatically cancelled by the exchange. The order_time_in_force parameter contains a dict with buy and sell time in force policy values. This can be set in the configuration file or in the strategy. Values set in the configuration file overwrites values set in the strategy. The possible values are: gtc (default), fok or ioc . python \"order_time_in_force\": { \"buy\": \"gtc\", \"sell\": \"gtc\" }, Warning This is ongoing work. For now, it is supported only for binance. Please don't change the default value unless you know what you are doing and have researched the impact of using different values. Exchange configuration \u00b6 Freqtrade is based on CCXT library that supports over 100 cryptocurrency exchange markets and trading APIs. The complete up-to-date list can be found in the CCXT repo homepage . However, the bot was tested by the development team with only Bittrex, Binance and Kraken, so these are the only officially supported exchanges: Bittrex : \"bittrex\" Binance : \"binance\" Kraken : \"kraken\" Feel free to test other exchanges and submit your PR to improve the bot. Some exchanges require special configuration, which can be found on the Exchange-specific Notes documentation page. Sample exchange configuration \u00b6 A exchange configuration for \"binance\" would look as follows: json \"exchange\": { \"name\": \"binance\", \"key\": \"your_exchange_key\", \"secret\": \"your_exchange_secret\", \"ccxt_config\": {\"enableRateLimit\": true}, \"ccxt_async_config\": { \"enableRateLimit\": true, \"rateLimit\": 200 }, This configuration enables binance, as well as rate-limiting to avoid bans from the exchange. \"rateLimit\": 200 defines a wait-event of 0.2s between each call. This can also be completely disabled by setting \"enableRateLimit\" to false. Note Optimal settings for rate-limiting depend on the exchange and the size of the whitelist, so an ideal parameter will vary on many other settings. We try to provide sensible defaults per exchange where possible, if you encounter bans please make sure that \"enableRateLimit\" is enabled and increase the \"rateLimit\" parameter step by step. What values can be used for fiat_display_currency? \u00b6 The fiat_display_currency configuration parameter sets the base currency to use for the conversion from coin to fiat in the bot Telegram reports. The valid values are: json \"AUD\", \"BRL\", \"CAD\", \"CHF\", \"CLP\", \"CNY\", \"CZK\", \"DKK\", \"EUR\", \"GBP\", \"HKD\", \"HUF\", \"IDR\", \"ILS\", \"INR\", \"JPY\", \"KRW\", \"MXN\", \"MYR\", \"NOK\", \"NZD\", \"PHP\", \"PKR\", \"PLN\", \"RUB\", \"SEK\", \"SGD\", \"THB\", \"TRY\", \"TWD\", \"ZAR\", \"USD\" In addition to fiat currencies, a range of crypto currencies is supported. The valid values are: json \"BTC\", \"ETH\", \"XRP\", \"LTC\", \"BCH\", \"USDT\" Using Dry-run mode \u00b6 We recommend starting the bot in the Dry-run mode to see how your bot will behave and what is the performance of your strategy. In the Dry-run mode, the bot does not engage your money. It only runs a live simulation without creating trades on the exchange. Edit your config.json configuration file. Switch dry-run to true and specify db_url for a persistence database. json \"dry_run\": true, \"db_url\": \"sqlite:///tradesv3.dryrun.sqlite\", Remove your Exchange API key and secret (change them by empty values or fake credentials): json \"exchange\": { \"name\": \"bittrex\", \"key\": \"key\", \"secret\": \"secret\", ... } Once you will be happy with your bot performance running in the Dry-run mode, you can switch it to production mode. Note A simulated wallet is available during dry-run mode and will assume a starting capital of dry_run_wallet (defaults to 1000). Considerations for dry-run \u00b6 API-keys may or may not be provided. Only Read-Only operations (i.e. operations that do not alter account state) on the exchange are performed in dry-run mode. Wallets ( /balance ) are simulated based on dry_run_wallet . Orders are simulated, and will not be posted to the exchange. Market orders fill based on orderbook volume the moment the order is placed. Limit orders fill once the price reaches the defined level - or time out based on unfilledtimeout settings. In combination with stoploss_on_exchange , the stop_loss price is assumed to be filled. Open orders (not trades, which are stored in the database) are reset on bot restart. Switch to production mode \u00b6 In production mode, the bot will engage your money. Be careful, since a wrong strategy can lose all your money. Be aware of what you are doing when you run it in production mode. Setup your exchange account \u00b6 You will need to create API Keys (usually you get key and secret , some exchanges require an additional password ) from the Exchange website and you'll need to insert this into the appropriate fields in the configuration or when asked by the freqtrade new-config command. API Keys are usually only required for live trading (trading for real money, bot running in \"production mode\", executing real orders on the exchange) and are not required for the bot running in dry-run (trade simulation) mode. When you set up the bot in dry-run mode, you may fill these fields with empty values. To switch your bot in production mode \u00b6 Edit your config.json file. Switch dry-run to false and don't forget to adapt your database URL if set: json \"dry_run\": false, Insert your Exchange API key (change them by fake API keys): json { \"exchange\": { \"name\": \"bittrex\", \"key\": \"af8ddd35195e9dc500b9a6f799f6f5c93d89193b\", \"secret\": \"08a9dc6db3d7b53e1acebd9275677f4b0a04f1a5\", //\"password\": \"\", // Optional, not needed by all exchanges) // ... } //... } You should also make sure to read the Exchanges section of the documentation to be aware of potential configuration details specific to your exchange. Keep your secrets secret To keep your secrets secret, we recommend using a 2 nd configuration for your API keys. Simply use the above snippet in a new configuration file (e.g. config-private.json ) and keep your settings in this file. You can then start the bot with freqtrade trade --config user_data/config.json --config user_data/config-private.json <...> to have your keys loaded. NEVER share your private configuration file or your exchange keys with anyone! Using proxy with Freqtrade \u00b6 To use a proxy with freqtrade, add the kwarg \"aiohttp_trust_env\"=true to the \"ccxt_async_kwargs\" dict in the exchange section of the configuration. An example for this can be found in config_examples/config_full.example.json json \"ccxt_async_config\": { \"aiohttp_trust_env\": true } Then, export your proxy settings using the variables \"HTTP_PROXY\" and \"HTTPS_PROXY\" set to the appropriate values bash export HTTP_PROXY=\"http://addr:port\" export HTTPS_PROXY=\"http://addr:port\" freqtrade Next step \u00b6 Now you have configured your config.json, the next step is to start your bot .","title":"Configuration"},{"location":"configuration/#configure-the-bot","text":"Freqtrade has many configurable features and possibilities. By default, these settings are configured via the configuration file (see below).","title":"Configure the bot"},{"location":"configuration/#the-freqtrade-configuration-file","text":"The bot uses a set of configuration parameters during its operation that all together conform to the bot configuration. It normally reads its configuration from a file (Freqtrade configuration file). Per default, the bot loads the configuration from the config.json file, located in the current working directory. You can specify a different configuration file used by the bot with the -c/--config command-line option. Multiple configuration files can be specified and used by the bot or the bot can read its configuration parameters from the process standard input stream. Use multiple configuration files to keep secrets secret You can use a 2 nd configuration file containing your secrets. That way you can share your \"primary\" configuration file, while still keeping your API keys for yourself. bash freqtrade trade --config user_data/config.json --config user_data/config-private.json <...> The 2 nd file should only specify what you intend to override. If a key is in more than one of the configurations, then the \"last specified configuration\" wins (in the above example, config-private.json ). If you used the Quick start method for installing the bot, the installation script should have already created the default configuration file ( config.json ) for you. If the default configuration file is not created we recommend you to use freqtrade new-config --config config.json to generate a basic configuration file. The Freqtrade configuration file is to be written in JSON format. Additionally to the standard JSON syntax, you may use one-line // ... and multi-line /* ... */ comments in your configuration files and trailing commas in the lists of parameters. Do not worry if you are not familiar with JSON format -- simply open the configuration file with an editor of your choice, make some changes to the parameters you need, save your changes and, finally, restart the bot or, if it was previously stopped, run it again with the changes you made to the configuration. The bot validates the syntax of the configuration file at startup and will warn you if you made any errors editing it, pointing out problematic lines.","title":"The Freqtrade configuration file"},{"location":"configuration/#configuration-parameters","text":"The table below will list all configuration parameters available. Freqtrade can also load many options via command line (CLI) arguments (check out the commands --help output for details). The prevalence for all Options is as follows: CLI arguments override any other option Configuration files are used in sequence (the last file wins) and override Strategy configurations. Strategy configurations are only used if they are not set via configuration or command-line arguments. These options are marked with Strategy Override in the below table. Mandatory parameters are marked as Required , which means that they are required to be set in one of the possible ways. Parameter Description max_open_trades Required. Number of open trades your bot is allowed to have. Only one open trade per pair is possible, so the length of your pairlist is another limitation that can apply. If -1 then it is ignored (i.e. potentially unlimited open trades, limited by the pairlist). More information below . Datatype: Positive integer or -1. stake_currency Required. Crypto-currency used for trading. Datatype: String stake_amount Required. Amount of crypto-currency your bot will use for each trade. Set it to \"unlimited\" to allow the bot to use all available balance. More information below . Datatype: Positive float or \"unlimited\" . tradable_balance_ratio Ratio of the total account balance the bot is allowed to trade. More information below . Defaults to 0.99 99%). Datatype: Positive float between 0.1 and 1.0 . available_capital Available starting capital for the bot. Useful when running multiple bots on the same exchange account. More information below . Datatype: Positive float. amend_last_stake_amount Use reduced last stake amount if necessary. More information below . Defaults to false . Datatype: Boolean last_stake_amount_min_ratio Defines minimum stake amount that has to be left and executed. Applies only to the last stake amount when it's amended to a reduced value (i.e. if amend_last_stake_amount is set to true ). More information below . Defaults to 0.5 . Datatype: Float (as ratio) amount_reserve_percent Reserve some amount in min pair stake amount. The bot will reserve amount_reserve_percent + stoploss value when calculating min pair stake amount in order to avoid possible trade refusals. Defaults to 0.05 (5%). Datatype: Positive Float as ratio. timeframe The timeframe (former ticker interval) to use (e.g 1m , 5m , 15m , 30m , 1h ...). Strategy Override . Datatype: String fiat_display_currency Fiat currency used to show your profits. More information below . Datatype: String dry_run Required. Define if the bot must be in Dry Run or production mode. Defaults to true . Datatype: Boolean dry_run_wallet Define the starting amount in stake currency for the simulated wallet used by the bot running in Dry Run mode. Defaults to 1000 . Datatype: Float cancel_open_orders_on_exit Cancel open orders when the /stop RPC command is issued, Ctrl+C is pressed or the bot dies unexpectedly. When set to true , this allows you to use /stop to cancel unfilled and partially filled orders in the event of a market crash. It does not impact open positions. Defaults to false . Datatype: Boolean process_only_new_candles Enable processing of indicators only when new candles arrive. If false each loop populates the indicators, this will mean the same candle is processed many times creating system load but can be useful of your strategy depends on tick data not only candle. Strategy Override . Defaults to false . Datatype: Boolean minimal_roi Required. Set the threshold as ratio the bot will use to sell a trade. More information below . Strategy Override . Datatype: Dict stoploss Required. Value as ratio of the stoploss used by the bot. More details in the stoploss documentation . Strategy Override . Datatype: Float (as ratio) trailing_stop Enables trailing stoploss (based on stoploss in either configuration or strategy file). More details in the stoploss documentation . Strategy Override . Datatype: Boolean trailing_stop_positive Changes stoploss once profit has been reached. More details in the stoploss documentation . Strategy Override . Datatype: Float trailing_stop_positive_offset Offset on when to apply trailing_stop_positive . Percentage value which should be positive. More details in the stoploss documentation . Strategy Override . Defaults to 0.0 (no offset). Datatype: Float trailing_only_offset_is_reached Only apply trailing stoploss when the offset is reached. stoploss documentation . Strategy Override . Defaults to false . Datatype: Boolean fee Fee used during backtesting / dry-runs. Should normally not be configured, which has freqtrade fall back to the exchange default fee. Set as ratio (e.g. 0.001 = 0.1%). Fee is applied twice for each trade, once when buying, once when selling. Datatype: Float (as ratio) unfilledtimeout.buy Required. How long (in minutes or seconds) the bot will wait for an unfilled buy order to complete, after which the order will be cancelled and repeated at current (new) price, as long as there is a signal. Strategy Override . Datatype: Integer unfilledtimeout.sell Required. How long (in minutes or seconds) the bot will wait for an unfilled sell order to complete, after which the order will be cancelled and repeated at current (new) price, as long as there is a signal. Strategy Override . Datatype: Integer unfilledtimeout.unit Unit to use in unfilledtimeout setting. Note: If you set unfilledtimeout.unit to \"seconds\", \"internals.process_throttle_secs\" must be inferior or equal to timeout Strategy Override . Defaults to minutes . Datatype: String bid_strategy.price_side Select the side of the spread the bot should look at to get the buy rate. More information below . Defaults to bid . Datatype: String (either ask or bid ). bid_strategy.ask_last_balance Required. Interpolate the bidding price. More information below . bid_strategy.use_order_book Enable buying using the rates in Order Book Bids . Datatype: Boolean bid_strategy.order_book_top Bot will use the top N rate in Order Book \"price_side\" to buy. I.e. a value of 2 will allow the bot to pick the 2 nd bid rate in Order Book Bids . Defaults to 1 . Datatype: Positive Integer bid_strategy. check_depth_of_market.enabled Do not buy if the difference of buy orders and sell orders is met in Order Book. Check market depth . Defaults to false . Datatype: Boolean bid_strategy. check_depth_of_market.bids_to_ask_delta The difference ratio of buy orders and sell orders found in Order Book. A value below 1 means sell order size is greater, while value greater than 1 means buy order size is higher. Check market depth Defaults to 0 . Datatype: Float (as ratio) ask_strategy.price_side Select the side of the spread the bot should look at to get the sell rate. More information below . Defaults to ask . Datatype: String (either ask or bid ). ask_strategy.bid_last_balance Interpolate the selling price. More information below . ask_strategy.use_order_book Enable selling of open trades using Order Book Asks . Datatype: Boolean ask_strategy.order_book_top Bot will use the top N rate in Order Book \"price_side\" to sell. I.e. a value of 2 will allow the bot to pick the 2 nd ask rate in Order Book Asks Defaults to 1 . Datatype: Positive Integer use_sell_signal Use sell signals produced by the strategy in addition to the minimal_roi . Strategy Override . Defaults to true . Datatype: Boolean sell_profit_only Wait until the bot reaches sell_profit_offset before taking a sell decision. Strategy Override . Defaults to false . Datatype: Boolean sell_profit_offset Sell-signal is only active above this value. Strategy Override . Defaults to 0.0 . Datatype: Float (as ratio) ignore_roi_if_buy_signal Do not sell if the buy signal is still active. This setting takes preference over minimal_roi and use_sell_signal . Strategy Override . Defaults to false . Datatype: Boolean ignore_buying_expired_candle_after Specifies the number of seconds until a buy signal is no longer used. Datatype: Integer order_types Configure order-types depending on the action ( \"buy\" , \"sell\" , \"stoploss\" , \"stoploss_on_exchange\" ). More information below . Strategy Override . Datatype: Dict order_time_in_force Configure time in force for buy and sell orders. More information below . Strategy Override . Datatype: Dict exchange.name Required. Name of the exchange class to use. List below . Datatype: String exchange.sandbox Use the 'sandbox' version of the exchange, where the exchange provides a sandbox for risk-free integration. See here in more details. Datatype: Boolean exchange.key API key to use for the exchange. Only required when you are in production mode. Keep it in secret, do not disclose publicly. Datatype: String exchange.secret API secret to use for the exchange. Only required when you are in production mode. Keep it in secret, do not disclose publicly. Datatype: String exchange.password API password to use for the exchange. Only required when you are in production mode and for exchanges that use password for API requests. Keep it in secret, do not disclose publicly. Datatype: String exchange.pair_whitelist List of pairs to use by the bot for trading and to check for potential trades during backtesting. Supports regex pairs as .*/BTC . Not used by VolumePairList. More information . Datatype: List exchange.pair_blacklist List of pairs the bot must absolutely avoid for trading and backtesting. More information . Datatype: List exchange.ccxt_config Additional CCXT parameters passed to both ccxt instances (sync and async). This is usually the correct place for ccxt configurations. Parameters may differ from exchange to exchange and are documented in the ccxt documentation Datatype: Dict exchange.ccxt_sync_config Additional CCXT parameters passed to the regular (sync) ccxt instance. Parameters may differ from exchange to exchange and are documented in the ccxt documentation Datatype: Dict exchange.ccxt_async_config Additional CCXT parameters passed to the async ccxt instance. Parameters may differ from exchange to exchange and are documented in the ccxt documentation Datatype: Dict exchange.markets_refresh_interval The interval in minutes in which markets are reloaded. Defaults to 60 minutes. Datatype: Positive Integer exchange.skip_pair_validation Skip pairlist validation on startup. Defaults to false Datatype: * Boolean exchange.skip_open_order_update Skips open order updates on startup should the exchange cause problems. Only relevant in live conditions. Defaults to false Datatype: * Boolean exchange.log_responses Log relevant exchange responses. For debug mode only - use with care. Defaults to false Datatype: * Boolean edge.* Please refer to edge configuration document for detailed explanation. experimental.block_bad_exchanges Block exchanges known to not work with freqtrade. Leave on default unless you want to test if that exchange works now. Defaults to true . Datatype: Boolean pairlists Define one or more pairlists to be used. More information . Defaults to StaticPairList . Datatype: List of Dicts protections Define one or more protections to be used. More information . Datatype: List of Dicts telegram.enabled Enable the usage of Telegram. Datatype: Boolean telegram.token Your Telegram bot token. Only required if telegram.enabled is true . Keep it in secret, do not disclose publicly. Datatype: String telegram.chat_id Your personal Telegram account id. Only required if telegram.enabled is true . Keep it in secret, do not disclose publicly. Datatype: String telegram.balance_dust_level Dust-level (in stake currency) - currencies with a balance below this will not be shown by /balance . Datatype: float webhook.enabled Enable usage of Webhook notifications Datatype: Boolean webhook.url URL for the webhook. Only required if webhook.enabled is true . See the webhook documentation for more details. Datatype: String webhook.webhookbuy Payload to send on buy. Only required if webhook.enabled is true . See the webhook documentation for more details. Datatype: String webhook.webhookbuycancel Payload to send on buy order cancel. Only required if webhook.enabled is true . See the webhook documentation for more details. Datatype: String webhook.webhooksell Payload to send on sell. Only required if webhook.enabled is true . See the webhook documentation for more details. Datatype: String webhook.webhooksellcancel Payload to send on sell order cancel. Only required if webhook.enabled is true . See the webhook documentation for more details. Datatype: String webhook.webhookstatus Payload to send on status calls. Only required if webhook.enabled is true . See the webhook documentation for more details. Datatype: String api_server.enabled Enable usage of API Server. See the API Server documentation for more details. Datatype: Boolean api_server.listen_ip_address Bind IP address. See the API Server documentation for more details. Datatype: IPv4 api_server.listen_port Bind Port. See the API Server documentation for more details. Datatype: Integer between 1024 and 65535 api_server.verbosity Logging verbosity. info will print all RPC Calls, while \"error\" will only display errors. Datatype: Enum, either info or error . Defaults to info . api_server.username Username for API server. See the API Server documentation for more details. Keep it in secret, do not disclose publicly. Datatype: String api_server.password Password for API server. See the API Server documentation for more details. Keep it in secret, do not disclose publicly. Datatype: String bot_name Name of the bot. Passed via API to a client - can be shown to distinguish / name bots. Defaults to freqtrade Datatype: String db_url Declares database URL to use. NOTE: This defaults to sqlite:///tradesv3.dryrun.sqlite if dry_run is true , and to sqlite:///tradesv3.sqlite for production instances. Datatype: String, SQLAlchemy connect string initial_state Defines the initial application state. If set to stopped, then the bot has to be explicitly started via /start RPC command. Defaults to stopped . Datatype: Enum, either stopped or running forcebuy_enable Enables the RPC Commands to force a buy. More information below. Datatype: Boolean disable_dataframe_checks Disable checking the OHLCV dataframe returned from the strategy methods for correctness. Only use when intentionally changing the dataframe and understand what you are doing. Strategy Override . Defaults to False . Datatype: Boolean strategy Required Defines Strategy class to use. Recommended to be set via --strategy NAME . Datatype: ClassName strategy_path Adds an additional strategy lookup path (must be a directory). Datatype: String internals.process_throttle_secs Set the process throttle, or minimum loop duration for one bot iteration loop. Value in second. Defaults to 5 seconds. Datatype: Positive Integer internals.heartbeat_interval Print heartbeat message every N seconds. Set to 0 to disable heartbeat messages. Defaults to 60 seconds. Datatype: Positive Integer or 0 internals.sd_notify Enables use of the sd_notify protocol to tell systemd service manager about changes in the bot state and issue keep-alive pings. See here for more details. Datatype: Boolean logfile Specifies logfile name. Uses a rolling strategy for log file rotation for 10 files with the 1MB limit per file. Datatype: String user_data_dir Directory containing user data. Defaults to ./user_data/ . Datatype: String dataformat_ohlcv Data format to use to store historical candle (OHLCV) data. Defaults to json . Datatype: String dataformat_trades Data format to use to store historical trades data. Defaults to jsongz . Datatype: String","title":"Configuration parameters"},{"location":"configuration/#parameters-in-the-strategy","text":"The following parameters can be set in the configuration file or strategy. Values set in the configuration file always overwrite values set in the strategy. minimal_roi timeframe stoploss trailing_stop trailing_stop_positive trailing_stop_positive_offset trailing_only_offset_is_reached use_custom_stoploss process_only_new_candles order_types order_time_in_force unfilledtimeout disable_dataframe_checks use_sell_signal sell_profit_only sell_profit_offset ignore_roi_if_buy_signal ignore_buying_expired_candle_after","title":"Parameters in the strategy"},{"location":"configuration/#configuring-amount-per-trade","text":"There are several methods to configure how much of the stake currency the bot will use to enter a trade. All methods respect the available balance configuration as explained below.","title":"Configuring amount per trade"},{"location":"configuration/#minimum-trade-stake","text":"The minimum stake amount will depend on exchange and pair and is usually listed in the exchange support pages. Assuming the minimum tradable amount for XRP/USD is 20 XRP (given by the exchange), and the price is 0.6$. The minimum stake amount to buy this pair is, therefore, 20 * 0.6 ~= 12 . This exchange has also a limit on USD - where all orders must be > 10$ - which however does not apply in this case. To guarantee safe execution, freqtrade will not allow buying with a stake-amount of 10.1$, instead, it'll make sure that there's enough space to place a stoploss below the pair (+ an offset, defined by amount_reserve_percent , which defaults to 5%). With a reserve of 5%, the minimum stake amount would be ~12.6$ ( 12 * (1 + 0.05) ). If we take into account a stoploss of 10% on top of that - we'd end up with a value of ~14$ ( 12.6 / (1 - 0.1) ). To limit this calculation in case of large stoploss values, the calculated minimum stake-limit will never be more than 50% above the real limit. Warning Since the limits on exchanges are usually stable and are not updated often, some pairs can show pretty high minimum limits, simply because the price increased a lot since the last limit adjustment by the exchange.","title":"Minimum trade stake"},{"location":"configuration/#tradable-balance","text":"By default, the bot assumes that the complete amount - 1% is at it's disposal, and when using dynamic stake amount , it will split the complete balance into max_open_trades buckets per trade. Freqtrade will reserve 1% for eventual fees when entering a trade and will therefore not touch that by default. You can configure the \"untouched\" amount by using the tradable_balance_ratio setting. For example, if you have 10 ETH available in your wallet on the exchange and tradable_balance_ratio=0.5 (which is 50%), then the bot will use a maximum amount of 5 ETH for trading and considers this as an available balance. The rest of the wallet is untouched by the trades. Danger This setting should not be used when running multiple bots on the same account. Please look at Available Capital to the bot instead. Warning The tradable_balance_ratio setting applies to the current balance (free balance + tied up in trades). Therefore, assuming the starting balance of 1000, a configuration with tradable_balance_ratio=0.99 will not guarantee that 10 currency units will always remain available on the exchange. For example, the free amount may reduce to 5 units if the total balance is reduced to 500 (either by a losing streak or by withdrawing balance).","title":"Tradable balance"},{"location":"configuration/#assign-available-capital","text":"To fully utilize compounding profits when using multiple bots on the same exchange account, you'll want to limit each bot to a certain starting balance. This can be accomplished by setting available_capital to the desired starting balance. Assuming your account has 10.000 USDT and you want to run 2 different strategies on this exchange. You'd set available_capital=5000 - granting each bot an initial capital of 5000 USDT. The bot will then split this starting balance equally into max_open_trades buckets. Profitable trades will result in increased stake-sizes for this bot - without affecting the stake-sizes of the other bot. Incompatible with tradable_balance_ratio Setting this option will replace any configuration of tradable_balance_ratio .","title":"Assign available Capital"},{"location":"configuration/#amend-last-stake-amount","text":"Assuming we have the tradable balance of 1000 USDT, stake_amount=400 , and max_open_trades=3 . The bot would open 2 trades and will be unable to fill the last trading slot, since the requested 400 USDT are no longer available since 800 USDT are already tied in other trades. To overcome this, the option amend_last_stake_amount can be set to True , which will enable the bot to reduce stake_amount to the available balance to fill the last trade slot. In the example above this would mean: Trade1: 400 USDT Trade2: 400 USDT Trade3: 200 USDT Note This option only applies with Static stake amount - since Dynamic stake amount divides the balances evenly. Note The minimum last stake amount can be configured using last_stake_amount_min_ratio - which defaults to 0.5 (50%). This means that the minimum stake amount that's ever used is stake_amount * 0.5 . This avoids very low stake amounts, that are close to the minimum tradable amount for the pair and can be refused by the exchange.","title":"Amend last stake amount"},{"location":"configuration/#static-stake-amount","text":"The stake_amount configuration statically configures the amount of stake-currency your bot will use for each trade. The minimal configuration value is 0.0001, however, please check your exchange's trading minimums for the stake currency you're using to avoid problems. This setting works in combination with max_open_trades . The maximum capital engaged in trades is stake_amount * max_open_trades . For example, the bot will at most use (0.05 BTC x 3) = 0.15 BTC, assuming a configuration of max_open_trades=3 and stake_amount=0.05 . Note This setting respects the available balance configuration .","title":"Static stake amount"},{"location":"configuration/#dynamic-stake-amount","text":"Alternatively, you can use a dynamic stake amount, which will use the available balance on the exchange, and divide that equally by the number of allowed trades ( max_open_trades ). To configure this, set stake_amount=\"unlimited\" . We also recommend to set tradable_balance_ratio=0.99 (99%) - to keep a minimum balance for eventual fees. In this case a trade amount is calculated as: python currency_balance / (max_open_trades - current_open_trades) To allow the bot to trade all the available stake_currency in your account (minus tradable_balance_ratio ) set json \"stake_amount\" : \"unlimited\", \"tradable_balance_ratio\": 0.99, Compounding profits This configuration will allow increasing/decreasing stakes depending on the performance of the bot (lower stake if the bot is losing, higher stakes if the bot has a winning record since higher balances are available), and will result in profit compounding. When using Dry-Run Mode When using \"stake_amount\" : \"unlimited\", in combination with Dry-Run, Backtesting or Hyperopt, the balance will be simulated starting with a stake of dry_run_wallet which will evolve. It is therefore important to set dry_run_wallet to a sensible value (like 0.05 or 0.01 for BTC and 1000 or 100 for USDT, for example), otherwise, it may simulate trades with 100 BTC (or more) or 0.05 USDT (or less) at once - which may not correspond to your real available balance or is less than the exchange minimal limit for the order amount for the stake currency.","title":"Dynamic stake amount"},{"location":"configuration/#prices-used-for-orders","text":"Prices for regular orders can be controlled via the parameter structures bid_strategy for buying and ask_strategy for selling. Prices are always retrieved right before an order is placed, either by querying the exchange tickers or by using the orderbook data. Note Orderbook data used by Freqtrade are the data retrieved from exchange by the ccxt's function fetch_order_book() , i.e. are usually data from the L2-aggregated orderbook, while the ticker data are the structures returned by the ccxt's fetch_ticker() / fetch_tickers() functions. Refer to the ccxt library documentation for more details. Using market orders Please read the section Market order pricing section when using market orders.","title":"Prices used for orders"},{"location":"configuration/#buy-price","text":"","title":"Buy price"},{"location":"configuration/#check-depth-of-market","text":"When check depth of market is enabled ( bid_strategy.check_depth_of_market.enabled=True ), the buy signals are filtered based on the orderbook depth (sum of all amounts) for each orderbook side. Orderbook bid (buy) side depth is then divided by the orderbook ask (sell) side depth and the resulting delta is compared to the value of the bid_strategy.check_depth_of_market.bids_to_ask_delta parameter. The buy order is only executed if the orderbook delta is greater than or equal to the configured delta value. Note A delta value below 1 means that ask (sell) orderbook side depth is greater than the depth of the bid (buy) orderbook side, while a value greater than 1 means opposite (depth of the buy side is higher than the depth of the sell side).","title":"Check depth of market"},{"location":"configuration/#buy-price-side","text":"The configuration setting bid_strategy.price_side defines the side of the spread the bot looks for when buying. The following displays an orderbook. explanation ... 103 102 101 # ask -------------Current spread 99 # bid 98 97 ... If bid_strategy.price_side is set to \"bid\" , then the bot will use 99 as buying price. In line with that, if bid_strategy.price_side is set to \"ask\" , then the bot will use 101 as buying price. Using ask price often guarantees quicker filled orders, but the bot can also end up paying more than what would have been necessary. Taker fees instead of maker fees will most likely apply even when using limit buy orders. Also, prices at the \"ask\" side of the spread are higher than prices at the \"bid\" side in the orderbook, so the order behaves similar to a market order (however with a maximum price).","title":"Buy price side"},{"location":"configuration/#buy-price-with-orderbook-enabled","text":"When buying with the orderbook enabled ( bid_strategy.use_order_book=True ), Freqtrade fetches the bid_strategy.order_book_top entries from the orderbook and uses the entry specified as bid_strategy.order_book_top on the configured side ( bid_strategy.price_side ) of the orderbook. 1 specifies the topmost entry in the orderbook, while 2 would use the 2 nd entry in the orderbook, and so on.","title":"Buy price with Orderbook enabled"},{"location":"configuration/#buy-price-without-orderbook-enabled","text":"The following section uses side as the configured bid_strategy.price_side . When not using orderbook ( bid_strategy.use_order_book=False ), Freqtrade uses the best side price from the ticker if it's below the last traded price from the ticker. Otherwise (when the side price is above the last price), it calculates a rate between side and last price. The bid_strategy.ask_last_balance configuration parameter controls this. A value of 0.0 will use side price, while 1.0 will use the last price and values between those interpolate between ask and last price.","title":"Buy price without Orderbook enabled"},{"location":"configuration/#sell-price","text":"","title":"Sell price"},{"location":"configuration/#sell-price-side","text":"The configuration setting ask_strategy.price_side defines the side of the spread the bot looks for when selling. The following displays an orderbook: explanation ... 103 102 101 # ask -------------Current spread 99 # bid 98 97 ... If ask_strategy.price_side is set to \"ask\" , then the bot will use 101 as selling price. In line with that, if ask_strategy.price_side is set to \"bid\" , then the bot will use 99 as selling price.","title":"Sell price side"},{"location":"configuration/#sell-price-with-orderbook-enabled","text":"When selling with the orderbook enabled ( ask_strategy.use_order_book=True ), Freqtrade fetches the ask_strategy.order_book_top entries in the orderbook and uses the entry specified as ask_strategy.order_book_top from the configured side ( ask_strategy.price_side ) as selling price. 1 specifies the topmost entry in the orderbook, while 2 would use the 2 nd entry in the orderbook, and so on.","title":"Sell price with Orderbook enabled"},{"location":"configuration/#sell-price-without-orderbook-enabled","text":"When not using orderbook ( ask_strategy.use_order_book=False ), the price at the ask_strategy.price_side side (defaults to \"ask\" ) from the ticker will be used as the sell price. When not using orderbook ( ask_strategy.use_order_book=False ), Freqtrade uses the best side price from the ticker if it's below the last traded price from the ticker. Otherwise (when the side price is above the last price), it calculates a rate between side and last price. The ask_strategy.bid_last_balance configuration parameter controls this. A value of 0.0 will use side price, while 1.0 will use the last price and values between those interpolate between side and last price.","title":"Sell price without Orderbook enabled"},{"location":"configuration/#market-order-pricing","text":"When using market orders, prices should be configured to use the \"correct\" side of the orderbook to allow realistic pricing detection. Assuming both buy and sell are using market orders, a configuration similar to the following might be used jsonc \"order_types\": { \"buy\": \"market\", \"sell\": \"market\" // ... }, \"bid_strategy\": { \"price_side\": \"ask\", // ... }, \"ask_strategy\":{ \"price_side\": \"bid\", // ... }, Obviously, if only one side is using limit orders, different pricing combinations can be used.","title":"Market order pricing"},{"location":"configuration/#understand-minimal_roi","text":"The minimal_roi configuration parameter is a JSON object where the key is a duration in minutes and the value is the minimum ROI as a ratio. See the example below: json \"minimal_roi\": { \"40\": 0.0, # Sell after 40 minutes if the profit is not negative \"30\": 0.01, # Sell after 30 minutes if there is at least 1% profit \"20\": 0.02, # Sell after 20 minutes if there is at least 2% profit \"0\": 0.04 # Sell immediately if there is at least 4% profit }, Most of the strategy files already include the optimal minimal_roi value. This parameter can be set in either Strategy or Configuration file. If you use it in the configuration file, it will override the minimal_roi value from the strategy file. If it is not set in either Strategy or Configuration, a default of 1000% {\"0\": 10} is used, and minimal ROI is disabled unless your trade generates 1000% profit. Special case to forcesell after a specific time A special case presents using \"\": -1 as ROI. This forces the bot to sell a trade after N Minutes, no matter if it's positive or negative, so represents a time-limited force-sell.","title":"Understand minimal_roi"},{"location":"configuration/#understand-forcebuy_enable","text":"The forcebuy_enable configuration parameter enables the usage of forcebuy commands via Telegram and REST API. For security reasons, it's disabled by default, and freqtrade will show a warning message on startup if enabled. For example, you can send /forcebuy ETH/BTC to the bot, which will result in freqtrade buying the pair and holds it until a regular sell-signal (ROI, stoploss, /forcesell) appears. This can be dangerous with some strategies, so use with care. See the telegram documentation for details on usage.","title":"Understand forcebuy_enable"},{"location":"configuration/#ignoring-expired-candles","text":"When working with larger timeframes (for example 1h or more) and using a low max_open_trades value, the last candle can be processed as soon as a trade slot becomes available. When processing the last candle, this can lead to a situation where it may not be desirable to use the buy signal on that candle. For example, when using a condition in your strategy where you use a cross-over, that point may have passed too long ago for you to start a trade on it. In these situations, you can enable the functionality to ignore candles that are beyond a specified period by setting ignore_buying_expired_candle_after to a positive number, indicating the number of seconds after which the buy signal becomes expired. For example, if your strategy is using a 1h timeframe, and you only want to buy within the first 5 minutes when a new candle comes in, you can add the following configuration to your strategy: json { //... \"ignore_buying_expired_candle_after\": 300, // ... } Note This setting resets with each new candle, so it will not prevent sticking-signals from executing on the 2 nd or 3 rd candle they're active. Best use a \"trigger\" selector for buy signals, which are only active for one candle.","title":"Ignoring expired candles"},{"location":"configuration/#understand-order_types","text":"The order_types configuration parameter maps actions ( buy , sell , stoploss , emergencysell , forcesell , forcebuy ) to order-types ( market , limit , ...) as well as configures stoploss to be on the exchange and defines stoploss on exchange update interval in seconds. This allows to buy using limit orders, sell using limit-orders, and create stoplosses using market orders. It also allows to set the stoploss \"on exchange\" which means stoploss order would be placed immediately once the buy order is fulfilled. order_types set in the configuration file overwrites values set in the strategy as a whole, so you need to configure the whole order_types dictionary in one place. If this is configured, the following 4 values ( buy , sell , stoploss and stoploss_on_exchange ) need to be present, otherwise, the bot will fail to start. For information on ( emergencysell , forcesell , forcebuy , stoploss_on_exchange , stoploss_on_exchange_interval , stoploss_on_exchange_limit_ratio ) please see stop loss documentation stop loss on exchange Syntax for Strategy: python order_types = { \"buy\": \"limit\", \"sell\": \"limit\", \"emergencysell\": \"market\", \"forcebuy\": \"market\", \"forcesell\": \"market\", \"stoploss\": \"market\", \"stoploss_on_exchange\": False, \"stoploss_on_exchange_interval\": 60, \"stoploss_on_exchange_limit_ratio\": 0.99, } Configuration: json \"order_types\": { \"buy\": \"limit\", \"sell\": \"limit\", \"emergencysell\": \"market\", \"forcebuy\": \"market\", \"forcesell\": \"market\", \"stoploss\": \"market\", \"stoploss_on_exchange\": false, \"stoploss_on_exchange_interval\": 60 } Market order support Not all exchanges support \"market\" orders. The following message will be shown if your exchange does not support market orders: \"Exchange does not support market orders.\" and the bot will refuse to start. Using market orders Please carefully read the section Market order pricing section when using market orders. Stoploss on exchange stoploss_on_exchange_interval is not mandatory. Do not change its value if you are unsure of what you are doing. For more information about how stoploss works please refer to the stoploss documentation . If stoploss_on_exchange is enabled and the stoploss is cancelled manually on the exchange, then the bot will create a new stoploss order. Warning: stoploss_on_exchange failures If stoploss on exchange creation fails for some reason, then an \"emergency sell\" is initiated. By default, this will sell the asset using a market order. The order-type for the emergency-sell can be changed by setting the emergencysell value in the order_types dictionary - however, this is not advised.","title":"Understand order_types"},{"location":"configuration/#understand-order_time_in_force","text":"The order_time_in_force configuration parameter defines the policy by which the order is executed on the exchange. Three commonly used time in force are: GTC (Good Till Canceled): This is most of the time the default time in force. It means the order will remain on exchange till it is cancelled by the user. It can be fully or partially fulfilled. If partially fulfilled, the remaining will stay on the exchange till cancelled. FOK (Fill Or Kill): It means if the order is not executed immediately AND fully then it is cancelled by the exchange. IOC (Immediate Or Canceled): It is the same as FOK (above) except it can be partially fulfilled. The remaining part is automatically cancelled by the exchange. The order_time_in_force parameter contains a dict with buy and sell time in force policy values. This can be set in the configuration file or in the strategy. Values set in the configuration file overwrites values set in the strategy. The possible values are: gtc (default), fok or ioc . python \"order_time_in_force\": { \"buy\": \"gtc\", \"sell\": \"gtc\" }, Warning This is ongoing work. For now, it is supported only for binance. Please don't change the default value unless you know what you are doing and have researched the impact of using different values.","title":"Understand order_time_in_force"},{"location":"configuration/#exchange-configuration","text":"Freqtrade is based on CCXT library that supports over 100 cryptocurrency exchange markets and trading APIs. The complete up-to-date list can be found in the CCXT repo homepage . However, the bot was tested by the development team with only Bittrex, Binance and Kraken, so these are the only officially supported exchanges: Bittrex : \"bittrex\" Binance : \"binance\" Kraken : \"kraken\" Feel free to test other exchanges and submit your PR to improve the bot. Some exchanges require special configuration, which can be found on the Exchange-specific Notes documentation page.","title":"Exchange configuration"},{"location":"configuration/#sample-exchange-configuration","text":"A exchange configuration for \"binance\" would look as follows: json \"exchange\": { \"name\": \"binance\", \"key\": \"your_exchange_key\", \"secret\": \"your_exchange_secret\", \"ccxt_config\": {\"enableRateLimit\": true}, \"ccxt_async_config\": { \"enableRateLimit\": true, \"rateLimit\": 200 }, This configuration enables binance, as well as rate-limiting to avoid bans from the exchange. \"rateLimit\": 200 defines a wait-event of 0.2s between each call. This can also be completely disabled by setting \"enableRateLimit\" to false. Note Optimal settings for rate-limiting depend on the exchange and the size of the whitelist, so an ideal parameter will vary on many other settings. We try to provide sensible defaults per exchange where possible, if you encounter bans please make sure that \"enableRateLimit\" is enabled and increase the \"rateLimit\" parameter step by step.","title":"Sample exchange configuration"},{"location":"configuration/#what-values-can-be-used-for-fiat_display_currency","text":"The fiat_display_currency configuration parameter sets the base currency to use for the conversion from coin to fiat in the bot Telegram reports. The valid values are: json \"AUD\", \"BRL\", \"CAD\", \"CHF\", \"CLP\", \"CNY\", \"CZK\", \"DKK\", \"EUR\", \"GBP\", \"HKD\", \"HUF\", \"IDR\", \"ILS\", \"INR\", \"JPY\", \"KRW\", \"MXN\", \"MYR\", \"NOK\", \"NZD\", \"PHP\", \"PKR\", \"PLN\", \"RUB\", \"SEK\", \"SGD\", \"THB\", \"TRY\", \"TWD\", \"ZAR\", \"USD\" In addition to fiat currencies, a range of crypto currencies is supported. The valid values are: json \"BTC\", \"ETH\", \"XRP\", \"LTC\", \"BCH\", \"USDT\"","title":"What values can be used for fiat_display_currency?"},{"location":"configuration/#using-dry-run-mode","text":"We recommend starting the bot in the Dry-run mode to see how your bot will behave and what is the performance of your strategy. In the Dry-run mode, the bot does not engage your money. It only runs a live simulation without creating trades on the exchange. Edit your config.json configuration file. Switch dry-run to true and specify db_url for a persistence database. json \"dry_run\": true, \"db_url\": \"sqlite:///tradesv3.dryrun.sqlite\", Remove your Exchange API key and secret (change them by empty values or fake credentials): json \"exchange\": { \"name\": \"bittrex\", \"key\": \"key\", \"secret\": \"secret\", ... } Once you will be happy with your bot performance running in the Dry-run mode, you can switch it to production mode. Note A simulated wallet is available during dry-run mode and will assume a starting capital of dry_run_wallet (defaults to 1000).","title":"Using Dry-run mode"},{"location":"configuration/#considerations-for-dry-run","text":"API-keys may or may not be provided. Only Read-Only operations (i.e. operations that do not alter account state) on the exchange are performed in dry-run mode. Wallets ( /balance ) are simulated based on dry_run_wallet . Orders are simulated, and will not be posted to the exchange. Market orders fill based on orderbook volume the moment the order is placed. Limit orders fill once the price reaches the defined level - or time out based on unfilledtimeout settings. In combination with stoploss_on_exchange , the stop_loss price is assumed to be filled. Open orders (not trades, which are stored in the database) are reset on bot restart.","title":"Considerations for dry-run"},{"location":"configuration/#switch-to-production-mode","text":"In production mode, the bot will engage your money. Be careful, since a wrong strategy can lose all your money. Be aware of what you are doing when you run it in production mode.","title":"Switch to production mode"},{"location":"configuration/#setup-your-exchange-account","text":"You will need to create API Keys (usually you get key and secret , some exchanges require an additional password ) from the Exchange website and you'll need to insert this into the appropriate fields in the configuration or when asked by the freqtrade new-config command. API Keys are usually only required for live trading (trading for real money, bot running in \"production mode\", executing real orders on the exchange) and are not required for the bot running in dry-run (trade simulation) mode. When you set up the bot in dry-run mode, you may fill these fields with empty values.","title":"Setup your exchange account"},{"location":"configuration/#to-switch-your-bot-in-production-mode","text":"Edit your config.json file. Switch dry-run to false and don't forget to adapt your database URL if set: json \"dry_run\": false, Insert your Exchange API key (change them by fake API keys): json { \"exchange\": { \"name\": \"bittrex\", \"key\": \"af8ddd35195e9dc500b9a6f799f6f5c93d89193b\", \"secret\": \"08a9dc6db3d7b53e1acebd9275677f4b0a04f1a5\", //\"password\": \"\", // Optional, not needed by all exchanges) // ... } //... } You should also make sure to read the Exchanges section of the documentation to be aware of potential configuration details specific to your exchange. Keep your secrets secret To keep your secrets secret, we recommend using a 2 nd configuration for your API keys. Simply use the above snippet in a new configuration file (e.g. config-private.json ) and keep your settings in this file. You can then start the bot with freqtrade trade --config user_data/config.json --config user_data/config-private.json <...> to have your keys loaded. NEVER share your private configuration file or your exchange keys with anyone!","title":"To switch your bot in production mode"},{"location":"configuration/#using-proxy-with-freqtrade","text":"To use a proxy with freqtrade, add the kwarg \"aiohttp_trust_env\"=true to the \"ccxt_async_kwargs\" dict in the exchange section of the configuration. An example for this can be found in config_examples/config_full.example.json json \"ccxt_async_config\": { \"aiohttp_trust_env\": true } Then, export your proxy settings using the variables \"HTTP_PROXY\" and \"HTTPS_PROXY\" set to the appropriate values bash export HTTP_PROXY=\"http://addr:port\" export HTTPS_PROXY=\"http://addr:port\" freqtrade","title":"Using proxy with Freqtrade"},{"location":"configuration/#next-step","text":"Now you have configured your config.json, the next step is to start your bot .","title":"Next step"},{"location":"data-analysis/","text":"Analyzing bot data with Jupyter notebooks \u00b6 You can analyze the results of backtests and trading history easily using Jupyter notebooks. Sample notebooks are located at user_data/notebooks/ after initializing the user directory with freqtrade create-userdir --userdir user_data . Quick start with docker \u00b6 Freqtrade provides a docker-compose file which starts up a jupyter lab server. You can run this server using the following command: docker-compose -f docker/docker-compose-jupyter.yml up This will create a dockercontainer running jupyter lab, which will be accessible using https://127.0.0.1:8888/lab . Please use the link that's printed in the console after startup for simplified login. For more information, Please visit the Data analysis with Docker section. Pro tips \u00b6 See jupyter.org for usage instructions. Don't forget to start a Jupyter notebook server from within your conda or venv environment or use nb_conda_kernels * Copy the example notebook before use so your changes don't get overwritten with the next freqtrade update. Using virtual environment with system-wide Jupyter installation \u00b6 Sometimes it can be desired to use a system-wide installation of Jupyter notebook, and use a jupyter kernel from the virtual environment. This prevents you from installing the full jupyter suite multiple times per system, and provides an easy way to switch between tasks (freqtrade / other analytics tasks). For this to work, first activate your virtual environment and run the following commands: ``` bash Activate virtual environment \u00b6 source .env/bin/activate pip install ipykernel ipython kernel install --user --name=freqtrade Restart jupyter (lab / notebook) \u00b6 select kernel \"freqtrade\" in the notebook \u00b6 ``` Note This section is provided for completeness, the Freqtrade Team won't provide full support for problems with this setup and will recommend to install Jupyter in the virtual environment directly, as that is the easiest way to get jupyter notebooks up and running. For help with this setup please refer to the Project Jupyter documentation or help channels . Warning Some tasks don't work especially well in notebooks. For example, anything using asynchronous execution is a problem for Jupyter. Also, freqtrade's primary entry point is the shell cli, so using pure python in a notebook bypasses arguments that provide required objects and parameters to helper functions. You may need to set those values or create expected objects manually. Recommended workflow \u00b6 Task Tool Bot operations CLI Repetitive tasks Shell scripts Data analysis & visualization Notebook Use the CLI to * download historical data * run a backtest * run with real-time data * export results Collect these actions in shell scripts * save complicated commands with arguments * execute multi-step operations * automate testing strategies and preparing data for analysis Use a notebook to * visualize data * munge and plot to generate insights Example utility snippets \u00b6 Change directory to root \u00b6 Jupyter notebooks execute from the notebook directory. The following snippet searches for the project root, so relative paths remain consistent. ```python import os from pathlib import Path Change directory \u00b6 Modify this cell to insure that the output shows the correct path. \u00b6 Define all paths relative to the project root shown in the cell output \u00b6 project_root = \"somedir/freqtrade\" i=0 try: os.chdirdir(project_root) assert Path('LICENSE').is_file() except: while i<4 and (not Path('LICENSE').is_file()): os.chdir(Path(Path.cwd(), '../')) i+=1 project_root = Path.cwd() print(Path.cwd()) ``` Load multiple configuration files \u00b6 This option can be useful to inspect the results of passing in multiple configs. This will also run through the whole Configuration initialization, so the configuration is completely initialized to be passed to other methods. ``` python import json from freqtrade.configuration import Configuration Load config from multiple files \u00b6 config = Configuration.from_files([\"config1.json\", \"config2.json\"]) Show the config in memory \u00b6 print(json.dumps(config['original_config'], indent=2)) ``` For Interactive environments, have an additional configuration specifying user_data_dir and pass this in last, so you don't have to change directories while running the bot. Best avoid relative paths, since this starts at the storage location of the jupyter notebook, unless the directory is changed. json { \"user_data_dir\": \"~/.freqtrade/\" } Further Data analysis documentation \u00b6 Strategy debugging - also available as Jupyter notebook ( user_data/notebooks/strategy_analysis_example.ipynb ) Plotting Feel free to submit an issue or Pull Request enhancing this document if you would like to share ideas on how to best analyze the data.","title":"Jupyter Notebooks"},{"location":"data-analysis/#analyzing-bot-data-with-jupyter-notebooks","text":"You can analyze the results of backtests and trading history easily using Jupyter notebooks. Sample notebooks are located at user_data/notebooks/ after initializing the user directory with freqtrade create-userdir --userdir user_data .","title":"Analyzing bot data with Jupyter notebooks"},{"location":"data-analysis/#quick-start-with-docker","text":"Freqtrade provides a docker-compose file which starts up a jupyter lab server. You can run this server using the following command: docker-compose -f docker/docker-compose-jupyter.yml up This will create a dockercontainer running jupyter lab, which will be accessible using https://127.0.0.1:8888/lab . Please use the link that's printed in the console after startup for simplified login. For more information, Please visit the Data analysis with Docker section.","title":"Quick start with docker"},{"location":"data-analysis/#pro-tips","text":"See jupyter.org for usage instructions. Don't forget to start a Jupyter notebook server from within your conda or venv environment or use nb_conda_kernels * Copy the example notebook before use so your changes don't get overwritten with the next freqtrade update.","title":"Pro tips"},{"location":"data-analysis/#using-virtual-environment-with-system-wide-jupyter-installation","text":"Sometimes it can be desired to use a system-wide installation of Jupyter notebook, and use a jupyter kernel from the virtual environment. This prevents you from installing the full jupyter suite multiple times per system, and provides an easy way to switch between tasks (freqtrade / other analytics tasks). For this to work, first activate your virtual environment and run the following commands: ``` bash","title":"Using virtual environment with system-wide Jupyter installation"},{"location":"data-analysis/#activate-virtual-environment","text":"source .env/bin/activate pip install ipykernel ipython kernel install --user --name=freqtrade","title":"Activate virtual environment"},{"location":"data-analysis/#restart-jupyter-lab-notebook","text":"","title":"Restart jupyter (lab / notebook)"},{"location":"data-analysis/#select-kernel-freqtrade-in-the-notebook","text":"``` Note This section is provided for completeness, the Freqtrade Team won't provide full support for problems with this setup and will recommend to install Jupyter in the virtual environment directly, as that is the easiest way to get jupyter notebooks up and running. For help with this setup please refer to the Project Jupyter documentation or help channels . Warning Some tasks don't work especially well in notebooks. For example, anything using asynchronous execution is a problem for Jupyter. Also, freqtrade's primary entry point is the shell cli, so using pure python in a notebook bypasses arguments that provide required objects and parameters to helper functions. You may need to set those values or create expected objects manually.","title":"select kernel \"freqtrade\" in the notebook"},{"location":"data-analysis/#recommended-workflow","text":"Task Tool Bot operations CLI Repetitive tasks Shell scripts Data analysis & visualization Notebook Use the CLI to * download historical data * run a backtest * run with real-time data * export results Collect these actions in shell scripts * save complicated commands with arguments * execute multi-step operations * automate testing strategies and preparing data for analysis Use a notebook to * visualize data * munge and plot to generate insights","title":"Recommended workflow"},{"location":"data-analysis/#example-utility-snippets","text":"","title":"Example utility snippets"},{"location":"data-analysis/#change-directory-to-root","text":"Jupyter notebooks execute from the notebook directory. The following snippet searches for the project root, so relative paths remain consistent. ```python import os from pathlib import Path","title":"Change directory to root"},{"location":"data-analysis/#change-directory","text":"","title":"Change directory"},{"location":"data-analysis/#modify-this-cell-to-insure-that-the-output-shows-the-correct-path","text":"","title":"Modify this cell to insure that the output shows the correct path."},{"location":"data-analysis/#define-all-paths-relative-to-the-project-root-shown-in-the-cell-output","text":"project_root = \"somedir/freqtrade\" i=0 try: os.chdirdir(project_root) assert Path('LICENSE').is_file() except: while i<4 and (not Path('LICENSE').is_file()): os.chdir(Path(Path.cwd(), '../')) i+=1 project_root = Path.cwd() print(Path.cwd()) ```","title":"Define all paths relative to the project root shown in the cell output"},{"location":"data-analysis/#load-multiple-configuration-files","text":"This option can be useful to inspect the results of passing in multiple configs. This will also run through the whole Configuration initialization, so the configuration is completely initialized to be passed to other methods. ``` python import json from freqtrade.configuration import Configuration","title":"Load multiple configuration files"},{"location":"data-analysis/#load-config-from-multiple-files","text":"config = Configuration.from_files([\"config1.json\", \"config2.json\"])","title":"Load config from multiple files"},{"location":"data-analysis/#show-the-config-in-memory","text":"print(json.dumps(config['original_config'], indent=2)) ``` For Interactive environments, have an additional configuration specifying user_data_dir and pass this in last, so you don't have to change directories while running the bot. Best avoid relative paths, since this starts at the storage location of the jupyter notebook, unless the directory is changed. json { \"user_data_dir\": \"~/.freqtrade/\" }","title":"Show the config in memory"},{"location":"data-analysis/#further-data-analysis-documentation","text":"Strategy debugging - also available as Jupyter notebook ( user_data/notebooks/strategy_analysis_example.ipynb ) Plotting Feel free to submit an issue or Pull Request enhancing this document if you would like to share ideas on how to best analyze the data.","title":"Further Data analysis documentation"},{"location":"data-download/","text":"Data Downloading \u00b6 Getting data for backtesting and hyperopt \u00b6 To download data (candles / OHLCV) needed for backtesting and hyperoptimization use the freqtrade download-data command. If no additional parameter is specified, freqtrade will download data for \"1m\" and \"5m\" timeframes for the last 30 days. Exchange and pairs will come from config.json (if specified using -c/--config ). Otherwise --exchange becomes mandatory. You can use a relative timerange ( --days 20 ) or an absolute starting point ( --timerange 20200101- ). For incremental downloads, the relative approach should be used. Tip: Updating existing data If you already have backtesting data available in your data-directory and would like to refresh this data up to today, do not use --days or --timerange parameters. Freqtrade will keep the available data and only download the missing data. If you are updating existing data after inserting new pairs that you have no data for, use --new-pairs-days xx parameter. Specified number of days will be downloaded for new pairs while old pairs will be updated with missing data only. If you use --days xx parameter alone - data for specified number of days will be downloaded for all pairs. Be careful, if specified number of days is smaller than gap between now and last downloaded candle - freqtrade will delete all existing data to avoid gaps in candle data. Usage \u00b6 ``` usage: freqtrade download-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-p PAIRS [PAIRS ...]] [--pairs-file FILE] [--days INT] [--new-pairs-days INT] [--timerange TIMERANGE] [--dl-trades] [--exchange EXCHANGE] [-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...]] [--erase] [--data-format-ohlcv {json,jsongz,hdf5}] [--data-format-trades {json,jsongz,hdf5}] optional arguments: -h, --help show this help message and exit -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] Limit command to these pairs. Pairs are space- separated. --pairs-file FILE File containing a list of pairs to download. --days INT Download data for given number of days. --new-pairs-days INT Download data of new pairs for given number of days. Default: None . --timerange TIMERANGE Specify what timerange of data to use. --dl-trades Download trades instead of OHLCV data. The bot will resample trades to the desired timeframe as specified as --timeframes/-t. --exchange EXCHANGE Exchange name (default: bittrex ). Only valid if no config is provided. -t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...], --timeframes {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...] Specify which tickers to download. Space-separated list. Default: 1m 5m . --erase Clean all existing data for the selected exchange/pairs/timeframes. --data-format-ohlcv {json,jsongz,hdf5} Storage format for downloaded candle (OHLCV) data. (default: None ). --data-format-trades {json,jsongz,hdf5} Storage format for downloaded trades data. (default: None ). Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. ``` Startup period download-data is a strategy-independent command. The idea is to download a big chunk of data once, and then iteratively increase the amount of data stored. For that reason, download-data does not care about the \"startup-period\" defined in a strategy. It's up to the user to download additional days if the backtest should start at a specific point in time (while respecting startup period). Data format \u00b6 Freqtrade currently supports 3 data-formats for both OHLCV and trades data: json (plain \"text\" json files) jsongz (a gzip-zipped version of json files) hdf5 (a high performance datastore) By default, OHLCV data is stored as json data, while trades data is stored as jsongz data. This can be changed via the --data-format-ohlcv and --data-format-trades command line arguments respectively. To persist this change, you can should also add the following snippet to your configuration, so you don't have to insert the above arguments each time: jsonc // ... \"dataformat_ohlcv\": \"hdf5\", \"dataformat_trades\": \"hdf5\", // ... If the default data-format has been changed during download, then the keys dataformat_ohlcv and dataformat_trades in the configuration file need to be adjusted to the selected dataformat as well. Note You can convert between data-formats using the convert-data and convert-trade-data methods. Sub-command convert data \u00b6 ``` usage: freqtrade convert-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-p PAIRS [PAIRS ...]] --format-from {json,jsongz,hdf5} --format-to {json,jsongz,hdf5} [--erase] [-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...]] optional arguments: -h, --help show this help message and exit -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] Show profits for only these pairs. Pairs are space- separated. --format-from {json,jsongz,hdf5} Source format for data conversion. --format-to {json,jsongz,hdf5} Destination format for data conversion. --erase Clean all existing data for the selected exchange/pairs/timeframes. -t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...], --timeframes {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...] Specify which tickers to download. Space-separated list. Default: 1m 5m . Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. ``` Example converting data \u00b6 The following command will convert all candle (OHLCV) data available in ~/.freqtrade/data/binance from json to jsongz, saving diskspace in the process. It'll also remove original json data files ( --erase parameter). bash freqtrade convert-data --format-from json --format-to jsongz --datadir ~/.freqtrade/data/binance -t 5m 15m --erase Sub-command convert trade data \u00b6 ``` usage: freqtrade convert-trade-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-p PAIRS [PAIRS ...]] --format-from {json,jsongz,hdf5} --format-to {json,jsongz,hdf5} [--erase] optional arguments: -h, --help show this help message and exit -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] Show profits for only these pairs. Pairs are space- separated. --format-from {json,jsongz,hdf5} Source format for data conversion. --format-to {json,jsongz,hdf5} Destination format for data conversion. --erase Clean all existing data for the selected exchange/pairs/timeframes. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. ``` Example converting trades \u00b6 The following command will convert all available trade-data in ~/.freqtrade/data/kraken from jsongz to json. It'll also remove original jsongz data files ( --erase parameter). bash freqtrade convert-trade-data --format-from jsongz --format-to json --datadir ~/.freqtrade/data/kraken --erase Sub-command list-data \u00b6 You can get a list of downloaded data using the list-data sub-command. ``` usage: freqtrade list-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--exchange EXCHANGE] [--data-format-ohlcv {json,jsongz,hdf5}] [-p PAIRS [PAIRS ...]] optional arguments: -h, --help show this help message and exit --exchange EXCHANGE Exchange name (default: bittrex ). Only valid if no config is provided. --data-format-ohlcv {json,jsongz,hdf5} Storage format for downloaded candle (OHLCV) data. (default: json ). -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] Show profits for only these pairs. Pairs are space- separated. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. ``` Example list-data \u00b6 ```bash freqtrade list-data --userdir ~/.freqtrade/user_data/ Found 33 pair / timeframe combinations. pairs timeframe ADA/BTC 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d ADA/ETH 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d ETH/BTC 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d ETH/USDT 5m, 15m, 30m, 1h, 2h, 4h ``` Pairs file \u00b6 In alternative to the whitelist from config.json , a pairs.json file can be used. If you are using Binance for example: create a directory user_data/data/binance and copy or create the pairs.json file in that directory. update the pairs.json file to contain the currency pairs you are interested in. bash mkdir -p user_data/data/binance cp tests/testdata/pairs.json user_data/data/binance If your configuration directory user_data was made by docker, you may get the following error: cp: cannot create regular file 'user_data/data/binance/pairs.json': Permission denied You can fix the permissions of your user-data directory as follows: sudo chown -R $UID:$GID user_data The format of the pairs.json file is a simple json list. Mixing different stake-currencies is allowed for this file, since it's only used for downloading. json [ \"ETH/BTC\", \"ETH/USDT\", \"BTC/USDT\", \"XRP/ETH\" ] Start download \u00b6 Then run: bash freqtrade download-data --exchange binance This will download historical candle (OHLCV) data for all the currency pairs you defined in pairs.json . Other Notes \u00b6 To use a different directory than the exchange specific default, use --datadir user_data/data/some_directory . To change the exchange used to download the historical data from, please use a different configuration file (you'll probably need to adjust rate limits etc.) To use pairs.json from some other directory, use --pairs-file some_other_dir/pairs.json . To download historical candle (OHLCV) data for only 10 days, use --days 10 (defaults to 30 days). To download historical candle (OHLCV) data from a fixed starting point, use --timerange 20200101- - which will download all data from January 1 st , 2020. Eventually set end dates are ignored. Use --timeframes to specify what timeframe download the historical candle (OHLCV) data for. Default is --timeframes 1m 5m which will download 1-minute and 5-minute data. To use exchange, timeframe and list of pairs as defined in your configuration file, use the -c/--config option. With this, the script uses the whitelist defined in the config as the list of currency pairs to download data for and does not require the pairs.json file. You can combine -c/--config with most other options. Trades (tick) data \u00b6 By default, download-data sub-command downloads Candles (OHLCV) data. Some exchanges also provide historic trade-data via their API. This data can be useful if you need many different timeframes, since it is only downloaded once, and then resampled locally to the desired timeframes. Since this data is large by default, the files use gzip by default. They are stored in your data-directory with the naming convention of -trades.json.gz ( ETH_BTC-trades.json.gz ). Incremental mode is also supported, as for historic OHLCV data, so downloading the data once per week with --days 8 will create an incremental data-repository. To use this mode, simply add --dl-trades to your call. This will swap the download method to download trades, and resamples the data locally. do not use You should not use this unless you're a kraken user. Most other exchanges provide OHLCV data with sufficient history. Example call: bash freqtrade download-data --exchange kraken --pairs XRP/EUR ETH/EUR --days 20 --dl-trades Note While this method uses async calls, it will be slow, since it requires the result of the previous call to generate the next request to the exchange. Warning The historic trades are not available during Freqtrade dry-run and live trade modes because all exchanges tested provide this data with a delay of few 100 candles, so it's not suitable for real-time trading. Kraken user Kraken users should read this before starting to download data. Next step \u00b6 Great, you now have backtest data downloaded, so you can now start backtesting your strategy.","title":"Data Downloading"},{"location":"data-download/#data-downloading","text":"","title":"Data Downloading"},{"location":"data-download/#getting-data-for-backtesting-and-hyperopt","text":"To download data (candles / OHLCV) needed for backtesting and hyperoptimization use the freqtrade download-data command. If no additional parameter is specified, freqtrade will download data for \"1m\" and \"5m\" timeframes for the last 30 days. Exchange and pairs will come from config.json (if specified using -c/--config ). Otherwise --exchange becomes mandatory. You can use a relative timerange ( --days 20 ) or an absolute starting point ( --timerange 20200101- ). For incremental downloads, the relative approach should be used. Tip: Updating existing data If you already have backtesting data available in your data-directory and would like to refresh this data up to today, do not use --days or --timerange parameters. Freqtrade will keep the available data and only download the missing data. If you are updating existing data after inserting new pairs that you have no data for, use --new-pairs-days xx parameter. Specified number of days will be downloaded for new pairs while old pairs will be updated with missing data only. If you use --days xx parameter alone - data for specified number of days will be downloaded for all pairs. Be careful, if specified number of days is smaller than gap between now and last downloaded candle - freqtrade will delete all existing data to avoid gaps in candle data.","title":"Getting data for backtesting and hyperopt"},{"location":"data-download/#usage","text":"``` usage: freqtrade download-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-p PAIRS [PAIRS ...]] [--pairs-file FILE] [--days INT] [--new-pairs-days INT] [--timerange TIMERANGE] [--dl-trades] [--exchange EXCHANGE] [-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...]] [--erase] [--data-format-ohlcv {json,jsongz,hdf5}] [--data-format-trades {json,jsongz,hdf5}] optional arguments: -h, --help show this help message and exit -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] Limit command to these pairs. Pairs are space- separated. --pairs-file FILE File containing a list of pairs to download. --days INT Download data for given number of days. --new-pairs-days INT Download data of new pairs for given number of days. Default: None . --timerange TIMERANGE Specify what timerange of data to use. --dl-trades Download trades instead of OHLCV data. The bot will resample trades to the desired timeframe as specified as --timeframes/-t. --exchange EXCHANGE Exchange name (default: bittrex ). Only valid if no config is provided. -t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...], --timeframes {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...] Specify which tickers to download. Space-separated list. Default: 1m 5m . --erase Clean all existing data for the selected exchange/pairs/timeframes. --data-format-ohlcv {json,jsongz,hdf5} Storage format for downloaded candle (OHLCV) data. (default: None ). --data-format-trades {json,jsongz,hdf5} Storage format for downloaded trades data. (default: None ). Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. ``` Startup period download-data is a strategy-independent command. The idea is to download a big chunk of data once, and then iteratively increase the amount of data stored. For that reason, download-data does not care about the \"startup-period\" defined in a strategy. It's up to the user to download additional days if the backtest should start at a specific point in time (while respecting startup period).","title":"Usage"},{"location":"data-download/#data-format","text":"Freqtrade currently supports 3 data-formats for both OHLCV and trades data: json (plain \"text\" json files) jsongz (a gzip-zipped version of json files) hdf5 (a high performance datastore) By default, OHLCV data is stored as json data, while trades data is stored as jsongz data. This can be changed via the --data-format-ohlcv and --data-format-trades command line arguments respectively. To persist this change, you can should also add the following snippet to your configuration, so you don't have to insert the above arguments each time: jsonc // ... \"dataformat_ohlcv\": \"hdf5\", \"dataformat_trades\": \"hdf5\", // ... If the default data-format has been changed during download, then the keys dataformat_ohlcv and dataformat_trades in the configuration file need to be adjusted to the selected dataformat as well. Note You can convert between data-formats using the convert-data and convert-trade-data methods.","title":"Data format"},{"location":"data-download/#sub-command-convert-data","text":"``` usage: freqtrade convert-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-p PAIRS [PAIRS ...]] --format-from {json,jsongz,hdf5} --format-to {json,jsongz,hdf5} [--erase] [-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...]] optional arguments: -h, --help show this help message and exit -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] Show profits for only these pairs. Pairs are space- separated. --format-from {json,jsongz,hdf5} Source format for data conversion. --format-to {json,jsongz,hdf5} Destination format for data conversion. --erase Clean all existing data for the selected exchange/pairs/timeframes. -t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...], --timeframes {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,2w,1M,1y} ...] Specify which tickers to download. Space-separated list. Default: 1m 5m . Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. ```","title":"Sub-command convert data"},{"location":"data-download/#example-converting-data","text":"The following command will convert all candle (OHLCV) data available in ~/.freqtrade/data/binance from json to jsongz, saving diskspace in the process. It'll also remove original json data files ( --erase parameter). bash freqtrade convert-data --format-from json --format-to jsongz --datadir ~/.freqtrade/data/binance -t 5m 15m --erase","title":"Example converting data"},{"location":"data-download/#sub-command-convert-trade-data","text":"``` usage: freqtrade convert-trade-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-p PAIRS [PAIRS ...]] --format-from {json,jsongz,hdf5} --format-to {json,jsongz,hdf5} [--erase] optional arguments: -h, --help show this help message and exit -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] Show profits for only these pairs. Pairs are space- separated. --format-from {json,jsongz,hdf5} Source format for data conversion. --format-to {json,jsongz,hdf5} Destination format for data conversion. --erase Clean all existing data for the selected exchange/pairs/timeframes. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. ```","title":"Sub-command convert trade data"},{"location":"data-download/#example-converting-trades","text":"The following command will convert all available trade-data in ~/.freqtrade/data/kraken from jsongz to json. It'll also remove original jsongz data files ( --erase parameter). bash freqtrade convert-trade-data --format-from jsongz --format-to json --datadir ~/.freqtrade/data/kraken --erase","title":"Example converting trades"},{"location":"data-download/#sub-command-list-data","text":"You can get a list of downloaded data using the list-data sub-command. ``` usage: freqtrade list-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--exchange EXCHANGE] [--data-format-ohlcv {json,jsongz,hdf5}] [-p PAIRS [PAIRS ...]] optional arguments: -h, --help show this help message and exit --exchange EXCHANGE Exchange name (default: bittrex ). Only valid if no config is provided. --data-format-ohlcv {json,jsongz,hdf5} Storage format for downloaded candle (OHLCV) data. (default: json ). -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] Show profits for only these pairs. Pairs are space- separated. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. ```","title":"Sub-command list-data"},{"location":"data-download/#example-list-data","text":"```bash freqtrade list-data --userdir ~/.freqtrade/user_data/ Found 33 pair / timeframe combinations. pairs timeframe ADA/BTC 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d ADA/ETH 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d ETH/BTC 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d ETH/USDT 5m, 15m, 30m, 1h, 2h, 4h ```","title":"Example list-data"},{"location":"data-download/#pairs-file","text":"In alternative to the whitelist from config.json , a pairs.json file can be used. If you are using Binance for example: create a directory user_data/data/binance and copy or create the pairs.json file in that directory. update the pairs.json file to contain the currency pairs you are interested in. bash mkdir -p user_data/data/binance cp tests/testdata/pairs.json user_data/data/binance If your configuration directory user_data was made by docker, you may get the following error: cp: cannot create regular file 'user_data/data/binance/pairs.json': Permission denied You can fix the permissions of your user-data directory as follows: sudo chown -R $UID:$GID user_data The format of the pairs.json file is a simple json list. Mixing different stake-currencies is allowed for this file, since it's only used for downloading. json [ \"ETH/BTC\", \"ETH/USDT\", \"BTC/USDT\", \"XRP/ETH\" ]","title":"Pairs file"},{"location":"data-download/#start-download","text":"Then run: bash freqtrade download-data --exchange binance This will download historical candle (OHLCV) data for all the currency pairs you defined in pairs.json .","title":"Start download"},{"location":"data-download/#other-notes","text":"To use a different directory than the exchange specific default, use --datadir user_data/data/some_directory . To change the exchange used to download the historical data from, please use a different configuration file (you'll probably need to adjust rate limits etc.) To use pairs.json from some other directory, use --pairs-file some_other_dir/pairs.json . To download historical candle (OHLCV) data for only 10 days, use --days 10 (defaults to 30 days). To download historical candle (OHLCV) data from a fixed starting point, use --timerange 20200101- - which will download all data from January 1 st , 2020. Eventually set end dates are ignored. Use --timeframes to specify what timeframe download the historical candle (OHLCV) data for. Default is --timeframes 1m 5m which will download 1-minute and 5-minute data. To use exchange, timeframe and list of pairs as defined in your configuration file, use the -c/--config option. With this, the script uses the whitelist defined in the config as the list of currency pairs to download data for and does not require the pairs.json file. You can combine -c/--config with most other options.","title":"Other Notes"},{"location":"data-download/#trades-tick-data","text":"By default, download-data sub-command downloads Candles (OHLCV) data. Some exchanges also provide historic trade-data via their API. This data can be useful if you need many different timeframes, since it is only downloaded once, and then resampled locally to the desired timeframes. Since this data is large by default, the files use gzip by default. They are stored in your data-directory with the naming convention of -trades.json.gz ( ETH_BTC-trades.json.gz ). Incremental mode is also supported, as for historic OHLCV data, so downloading the data once per week with --days 8 will create an incremental data-repository. To use this mode, simply add --dl-trades to your call. This will swap the download method to download trades, and resamples the data locally. do not use You should not use this unless you're a kraken user. Most other exchanges provide OHLCV data with sufficient history. Example call: bash freqtrade download-data --exchange kraken --pairs XRP/EUR ETH/EUR --days 20 --dl-trades Note While this method uses async calls, it will be slow, since it requires the result of the previous call to generate the next request to the exchange. Warning The historic trades are not available during Freqtrade dry-run and live trade modes because all exchanges tested provide this data with a delay of few 100 candles, so it's not suitable for real-time trading. Kraken user Kraken users should read this before starting to download data.","title":"Trades (tick) data"},{"location":"data-download/#next-step","text":"Great, you now have backtest data downloaded, so you can now start backtesting your strategy.","title":"Next step"},{"location":"deprecated/","text":"Deprecated features \u00b6 This page contains description of the command line arguments, configuration parameters and the bot features that were declared as DEPRECATED by the bot development team and are no longer supported. Please avoid their usage in your configuration. Removed features \u00b6 the --refresh-pairs-cached command line option \u00b6 --refresh-pairs-cached in the context of backtesting, hyperopt and edge allows to refresh candle data for backtesting. Since this leads to much confusion, and slows down backtesting (while not being part of backtesting) this has been singled out as a separate freqtrade sub-command freqtrade download-data . This command line option was deprecated in 2019.7-dev (develop branch) and removed in 2019.9. The --dynamic-whitelist command line option \u00b6 This command line option was deprecated in 2018 and removed freqtrade 2019.6-dev (develop branch) and in freqtrade 2019.7. the --live command line option \u00b6 --live in the context of backtesting allowed to download the latest tick data for backtesting. Did only download the latest 500 candles, so was ineffective in getting good backtest data. Removed in 2019-7-dev (develop branch) and in freqtrade 2019.8. Allow running multiple pairlists in sequence \u00b6 The former \"pairlist\" section in the configuration has been removed, and is replaced by \"pairlists\" - being a list to specify a sequence of pairlists. The old section of configuration parameters ( \"pairlist\" ) has been deprecated in 2019.11 and has been removed in 2020.4. deprecation of bidVolume and askVolume from volume-pairlist \u00b6 Since only quoteVolume can be compared between assets, the other options (bidVolume, askVolume) have been deprecated in 2020.4, and have been removed in 2020.9. Using order book steps for sell price \u00b6 Using order_book_min and order_book_max used to allow stepping the orderbook and trying to find the next ROI slot - trying to place sell-orders early. As this does however increase risk and provides no benefit, it's been removed for maintainability purposes in 2021.7.","title":"Deprecated Features"},{"location":"deprecated/#deprecated-features","text":"This page contains description of the command line arguments, configuration parameters and the bot features that were declared as DEPRECATED by the bot development team and are no longer supported. Please avoid their usage in your configuration.","title":"Deprecated features"},{"location":"deprecated/#removed-features","text":"","title":"Removed features"},{"location":"deprecated/#the-refresh-pairs-cached-command-line-option","text":"--refresh-pairs-cached in the context of backtesting, hyperopt and edge allows to refresh candle data for backtesting. Since this leads to much confusion, and slows down backtesting (while not being part of backtesting) this has been singled out as a separate freqtrade sub-command freqtrade download-data . This command line option was deprecated in 2019.7-dev (develop branch) and removed in 2019.9.","title":"the --refresh-pairs-cached command line option"},{"location":"deprecated/#the-dynamic-whitelist-command-line-option","text":"This command line option was deprecated in 2018 and removed freqtrade 2019.6-dev (develop branch) and in freqtrade 2019.7.","title":"The --dynamic-whitelist command line option"},{"location":"deprecated/#the-live-command-line-option","text":"--live in the context of backtesting allowed to download the latest tick data for backtesting. Did only download the latest 500 candles, so was ineffective in getting good backtest data. Removed in 2019-7-dev (develop branch) and in freqtrade 2019.8.","title":"the --live command line option"},{"location":"deprecated/#allow-running-multiple-pairlists-in-sequence","text":"The former \"pairlist\" section in the configuration has been removed, and is replaced by \"pairlists\" - being a list to specify a sequence of pairlists. The old section of configuration parameters ( \"pairlist\" ) has been deprecated in 2019.11 and has been removed in 2020.4.","title":"Allow running multiple pairlists in sequence"},{"location":"deprecated/#deprecation-of-bidvolume-and-askvolume-from-volume-pairlist","text":"Since only quoteVolume can be compared between assets, the other options (bidVolume, askVolume) have been deprecated in 2020.4, and have been removed in 2020.9.","title":"deprecation of bidVolume and askVolume from volume-pairlist"},{"location":"deprecated/#using-order-book-steps-for-sell-price","text":"Using order_book_min and order_book_max used to allow stepping the orderbook and trying to find the next ROI slot - trying to place sell-orders early. As this does however increase risk and provides no benefit, it's been removed for maintainability purposes in 2021.7.","title":"Using order book steps for sell price"},{"location":"developer/","text":"Development Help \u00b6 This page is intended for developers of Freqtrade, people who want to contribute to the Freqtrade codebase or documentation, or people who want to understand the source code of the application they're running. All contributions, bug reports, bug fixes, documentation improvements, enhancements and ideas are welcome. We track issues on GitHub and also have a dev channel on discord where you can ask questions. Documentation \u00b6 Documentation is available at https://freqtrade.io and needs to be provided with every new feature PR. Special fields for the documentation (like Note boxes, ...) can be found here . To test the documentation locally use the following commands. bash pip install -r docs/requirements-docs.txt mkdocs serve This will spin up a local server (usually on port 8000) so you can see if everything looks as you'd like it to. Developer setup \u00b6 To configure a development environment, you can either use the provided DevContainer , or use the setup.sh script and answer \"y\" when asked \"Do you want to install dependencies for dev [y/N]? \". Alternatively (e.g. if your system is not supported by the setup.sh script), follow the manual installation process and run pip3 install -e .[all] . This will install all required tools for development, including pytest , flake8 , mypy , and coveralls . Devcontainer setup \u00b6 The fastest and easiest way to get started is to use VSCode with the Remote container extension. This gives developers the ability to start the bot with all required dependencies without needing to install any freqtrade specific dependencies on your local machine. Devcontainer dependencies \u00b6 VSCode docker Remote container extension documentation For more information about the Remote container extension , best consult the documentation. Tests \u00b6 New code should be covered by basic unittests. Depending on the complexity of the feature, Reviewers may request more in-depth unittests. If necessary, the Freqtrade team can assist and give guidance with writing good tests (however please don't expect anyone to write the tests for you). Checking log content in tests \u00b6 Freqtrade uses 2 main methods to check log content in tests, log_has() and log_has_re() (to check using regex, in case of dynamic log-messages). These are available from conftest.py and can be imported in any test module. A sample check looks as follows: ``` python from tests.conftest import log_has, log_has_re def test_method_to_test(caplog): method_to_test() assert log_has(\"This event happened\", caplog) # Check regex with trailing number ... assert log_has_re(r\"This dynamic event happened and produced \\d+\", caplog) ``` ErrorHandling \u00b6 Freqtrade Exceptions all inherit from FreqtradeException . This general class of error should however not be used directly. Instead, multiple specialized sub-Exceptions exist. Below is an outline of exception inheritance hierarchy: + FreqtradeException | +---+ OperationalException | +---+ DependencyException | | | +---+ PricingError | | | +---+ ExchangeError | | | +---+ TemporaryError | | | +---+ DDosProtection | | | +---+ InvalidOrderException | | | +---+ RetryableOrderError | | | +---+ InsufficientFundsError | +---+ StrategyError Plugins \u00b6 Pairlists \u00b6 You have a great idea for a new pair selection algorithm you would like to try out? Great. Hopefully you also want to contribute this back upstream. Whatever your motivations are - This should get you off the ground in trying to develop a new Pairlist Handler. First of all, have a look at the VolumePairList Handler, and best copy this file with a name of your new Pairlist Handler. This is a simple Handler, which however serves as a good example on how to start developing. Next, modify the class-name of the Handler (ideally align this with the module filename). The base-class provides an instance of the exchange ( self._exchange ) the pairlist manager ( self._pairlistmanager ), as well as the main configuration ( self._config ), the pairlist dedicated configuration ( self._pairlistconfig ) and the absolute position within the list of pairlists. python self._exchange = exchange self._pairlistmanager = pairlistmanager self._config = config self._pairlistconfig = pairlistconfig self._pairlist_pos = pairlist_pos Tip Don't forget to register your pairlist in constants.py under the variable AVAILABLE_PAIRLISTS - otherwise it will not be selectable. Now, let's step through the methods which require actions: Pairlist configuration \u00b6 Configuration for the chain of Pairlist Handlers is done in the bot configuration file in the element \"pairlists\" , an array of configuration parameters for each Pairlist Handlers in the chain. By convention, \"number_assets\" is used to specify the maximum number of pairs to keep in the pairlist. Please follow this to ensure a consistent user experience. Additional parameters can be configured as needed. For instance, VolumePairList uses \"sort_key\" to specify the sorting value - however feel free to specify whatever is necessary for your great algorithm to be successful and dynamic. short_desc \u00b6 Returns a description used for Telegram messages. This should contain the name of the Pairlist Handler, as well as a short description containing the number of assets. Please follow the format \"PairlistName - top/bottom X pairs\" . gen_pairlist \u00b6 Override this method if the Pairlist Handler can be used as the leading Pairlist Handler in the chain, defining the initial pairlist which is then handled by all Pairlist Handlers in the chain. Examples are StaticPairList and VolumePairList . This is called with each iteration of the bot (only if the Pairlist Handler is at the first location) - so consider implementing caching for compute/network heavy calculations. It must return the resulting pairlist (which may then be passed into the chain of Pairlist Handlers). Validations are optional, the parent class exposes a _verify_blacklist(pairlist) and _whitelist_for_active_markets(pairlist) to do default filtering. Use this if you limit your result to a certain number of pairs - so the end-result is not shorter than expected. filter_pairlist \u00b6 This method is called for each Pairlist Handler in the chain by the pairlist manager. This is called with each iteration of the bot - so consider implementing caching for compute/network heavy calculations. It gets passed a pairlist (which can be the result of previous pairlists) as well as tickers , a pre-fetched version of get_tickers() . The default implementation in the base class simply calls the _validate_pair() method for each pair in the pairlist, but you may override it. So you should either implement the _validate_pair() in your Pairlist Handler or override filter_pairlist() to do something else. If overridden, it must return the resulting pairlist (which may then be passed into the next Pairlist Handler in the chain). Validations are optional, the parent class exposes a _verify_blacklist(pairlist) and _whitelist_for_active_markets(pairlist) to do default filters. Use this if you limit your result to a certain number of pairs - so the end result is not shorter than expected. In VolumePairList , this implements different methods of sorting, does early validation so only the expected number of pairs is returned. sample \u00b6 python def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]: # Generate dynamic whitelist pairs = self._calculate_pairlist(pairlist, tickers) return pairs Protections \u00b6 Best read the Protection documentation to understand protections. This Guide is directed towards Developers who want to develop a new protection. No protection should use datetime directly, but use the provided date_now variable for date calculations. This preserves the ability to backtest protections. Writing a new Protection Best copy one of the existing Protections to have a good example. Don't forget to register your protection in constants.py under the variable AVAILABLE_PROTECTIONS - otherwise it will not be selectable. Implementation of a new protection \u00b6 All Protection implementations must have IProtection as parent class. For that reason, they must implement the following methods: short_desc() global_stop() stop_per_pair() . global_stop() and stop_per_pair() must return a ProtectionReturn tuple, which consists of: lock pair - boolean lock until - datetime - until when should the pair be locked (will be rounded up to the next new candle) reason - string, used for logging and storage in the database The until portion should be calculated using the provided calculate_lock_end() method. All Protections should use \"stop_duration\" / \"stop_duration_candles\" to define how long a a pair (or all pairs) should be locked. The content of this is made available as self._stop_duration to the each Protection. If your protection requires a look-back period, please use \"lookback_period\" / \"lockback_period_candles\" to keep all protections aligned. Global vs. local stops \u00b6 Protections can have 2 different ways to stop trading for a limited : Per pair (local) For all Pairs (globally) Protections - per pair \u00b6 Protections that implement the per pair approach must set has_local_stop=True . The method stop_per_pair() will be called whenever a trade closed (sell order completed). Protections - global protection \u00b6 These Protections should do their evaluation across all pairs, and consequently will also lock all pairs from trading (called a global PairLock). Global protection must set has_global_stop=True to be evaluated for global stops. The method global_stop() will be called whenever a trade closed (sell order completed). Protections - calculating lock end time \u00b6 Protections should calculate the lock end time based on the last trade it considers. This avoids re-locking should the lookback-period be longer than the actual lock period. The IProtection parent class provides a helper method for this in calculate_lock_end() . Implement a new Exchange (WIP) \u00b6 Note This section is a Work in Progress and is not a complete guide on how to test a new exchange with Freqtrade. Most exchanges supported by CCXT should work out of the box. To quickly test the public endpoints of an exchange, add a configuration for your exchange to test_ccxt_compat.py and run these tests with pytest --longrun tests/exchange/test_ccxt_compat.py . Completing these tests successfully a good basis point (it's a requirement, actually), however these won't guarantee correct exchange functioning, as this only tests public endpoints, but no private endpoint (like generate order or similar). Stoploss On Exchange \u00b6 Check if the new exchange supports Stoploss on Exchange orders through their API. Since CCXT does not provide unification for Stoploss On Exchange yet, we'll need to implement the exchange-specific parameters ourselves. Best look at binance.py for an example implementation of this. You'll need to dig through the documentation of the Exchange's API on how exactly this can be done. CCXT Issues may also provide great help, since others may have implemented something similar for their projects. Incomplete candles \u00b6 While fetching candle (OHLCV) data, we may end up getting incomplete candles (depending on the exchange). To demonstrate this, we'll use daily candles ( \"1d\" ) to keep things simple. We query the api ( ct.fetch_ohlcv() ) for the timeframe and look at the date of the last entry. If this entry changes or shows the date of a \"incomplete\" candle, then we should drop this since having incomplete candles is problematic because indicators assume that only complete candles are passed to them, and will generate a lot of false buy signals. By default, we're therefore removing the last candle assuming it's incomplete. To check how the new exchange behaves, you can use the following snippet: ``` python import ccxt from datetime import datetime from freqtrade.data.converter import ohlcv_to_dataframe ct = ccxt.binance() timeframe = \"1d\" pair = \"XLM/BTC\" # Make sure to use a pair that exists on that exchange! raw = ct.fetch_ohlcv(pair, timeframe=timeframe) convert to dataframe \u00b6 df1 = ohlcv_to_dataframe(raw, timeframe, pair=pair, drop_incomplete=False) print(df1.tail(1)) print(datetime.utcnow()) ``` output date open high low close volume 499 2019-06-08 00:00:00+00:00 0.000007 0.000007 0.000007 0.000007 26264344.0 2019-06-09 12:30:27.873327 The output will show the last entry from the Exchange as well as the current UTC date. If the day shows the same day, then the last candle can be assumed as incomplete and should be dropped (leave the setting \"ohlcv_partial_candle\" from the exchange-class untouched / True). Otherwise, set \"ohlcv_partial_candle\" to False to not drop Candles (shown in the example above). Another way is to run this command multiple times in a row and observe if the volume is changing (while the date remains the same). Updating example notebooks \u00b6 To keep the jupyter notebooks aligned with the documentation, the following should be ran after updating a example notebook. bash jupyter nbconvert --ClearOutputPreprocessor.enabled=True --inplace freqtrade/templates/strategy_analysis_example.ipynb jupyter nbconvert --ClearOutputPreprocessor.enabled=True --to markdown freqtrade/templates/strategy_analysis_example.ipynb --stdout > docs/strategy_analysis_example.md Continuous integration \u00b6 This documents some decisions taken for the CI Pipeline. CI runs on all OS variants, Linux (ubuntu), macOS and Windows. Docker images are build for the branches stable and develop . Docker images containing Plot dependencies are also available as stable_plot and develop_plot . Raspberry PI Docker images are postfixed with _pi - so tags will be :stable_pi and develop_pi . Docker images contain a file, /freqtrade/freqtrade_commit containing the commit this image is based of. Full docker image rebuilds are run once a week via schedule. Deployments run on ubuntu. ta-lib binaries are contained in the build_helpers directory to avoid fails related to external unavailability. All tests must pass for a PR to be merged to stable or develop . Creating a release \u00b6 This part of the documentation is aimed at maintainers, and shows how to create a release. Create release branch \u00b6 First, pick a commit that's about one week old (to not include latest additions to releases). ``` bash create new branch \u00b6 git checkout -b new_release ``` Determine if crucial bugfixes have been made between this commit and the current state, and eventually cherry-pick these. Merge the release branch (stable) into this branch. Edit freqtrade/__init__.py and add the version matching the current date (for example 2019.7 for July 2019). Minor versions can be 2019.7.1 should we need to do a second release that month. Version numbers must follow allowed versions from PEP0440 to avoid failures pushing to pypi. Commit this part push that branch to the remote and create a PR against the stable branch Create changelog from git commits \u00b6 Note Make sure that the stable branch is up-to-date! ``` bash Needs to be done before merging / pulling that branch. \u00b6 git log --oneline --no-decorate --no-merges stable..new_release ``` To keep the release-log short, best wrap the full git changelog into a collapsible details section. ```markdown Expand full changelog ... Full git changelog ``` Create github release / tag \u00b6 Once the PR against stable is merged (best right after merging): Use the button \"Draft a new release\" in the Github UI (subsection releases). Use the version-number specified as tag. Use \"stable\" as reference (this step comes after the above PR is merged). Use the above changelog as release comment (as codeblock) Releases \u00b6 pypi \u00b6 Note This process is now automated as part of Github Actions. To create a pypi release, please run the following commands: Additional requirement: wheel , twine (for uploading), account on pypi with proper permissions. ``` bash python setup.py sdist bdist_wheel For pypi test (to check if some change to the installation did work) \u00b6 twine upload --repository-url https://test.pypi.org/legacy/ dist/* For production: \u00b6 twine upload dist/* ``` Please don't push non-releases to the productive / real pypi instance.","title":"Contributors Guide"},{"location":"developer/#development-help","text":"This page is intended for developers of Freqtrade, people who want to contribute to the Freqtrade codebase or documentation, or people who want to understand the source code of the application they're running. All contributions, bug reports, bug fixes, documentation improvements, enhancements and ideas are welcome. We track issues on GitHub and also have a dev channel on discord where you can ask questions.","title":"Development Help"},{"location":"developer/#documentation","text":"Documentation is available at https://freqtrade.io and needs to be provided with every new feature PR. Special fields for the documentation (like Note boxes, ...) can be found here . To test the documentation locally use the following commands. bash pip install -r docs/requirements-docs.txt mkdocs serve This will spin up a local server (usually on port 8000) so you can see if everything looks as you'd like it to.","title":"Documentation"},{"location":"developer/#developer-setup","text":"To configure a development environment, you can either use the provided DevContainer , or use the setup.sh script and answer \"y\" when asked \"Do you want to install dependencies for dev [y/N]? \". Alternatively (e.g. if your system is not supported by the setup.sh script), follow the manual installation process and run pip3 install -e .[all] . This will install all required tools for development, including pytest , flake8 , mypy , and coveralls .","title":"Developer setup"},{"location":"developer/#devcontainer-setup","text":"The fastest and easiest way to get started is to use VSCode with the Remote container extension. This gives developers the ability to start the bot with all required dependencies without needing to install any freqtrade specific dependencies on your local machine.","title":"Devcontainer setup"},{"location":"developer/#devcontainer-dependencies","text":"VSCode docker Remote container extension documentation For more information about the Remote container extension , best consult the documentation.","title":"Devcontainer dependencies"},{"location":"developer/#tests","text":"New code should be covered by basic unittests. Depending on the complexity of the feature, Reviewers may request more in-depth unittests. If necessary, the Freqtrade team can assist and give guidance with writing good tests (however please don't expect anyone to write the tests for you).","title":"Tests"},{"location":"developer/#checking-log-content-in-tests","text":"Freqtrade uses 2 main methods to check log content in tests, log_has() and log_has_re() (to check using regex, in case of dynamic log-messages). These are available from conftest.py and can be imported in any test module. A sample check looks as follows: ``` python from tests.conftest import log_has, log_has_re def test_method_to_test(caplog): method_to_test() assert log_has(\"This event happened\", caplog) # Check regex with trailing number ... assert log_has_re(r\"This dynamic event happened and produced \\d+\", caplog) ```","title":"Checking log content in tests"},{"location":"developer/#errorhandling","text":"Freqtrade Exceptions all inherit from FreqtradeException . This general class of error should however not be used directly. Instead, multiple specialized sub-Exceptions exist. Below is an outline of exception inheritance hierarchy: + FreqtradeException | +---+ OperationalException | +---+ DependencyException | | | +---+ PricingError | | | +---+ ExchangeError | | | +---+ TemporaryError | | | +---+ DDosProtection | | | +---+ InvalidOrderException | | | +---+ RetryableOrderError | | | +---+ InsufficientFundsError | +---+ StrategyError","title":"ErrorHandling"},{"location":"developer/#plugins","text":"","title":"Plugins"},{"location":"developer/#pairlists","text":"You have a great idea for a new pair selection algorithm you would like to try out? Great. Hopefully you also want to contribute this back upstream. Whatever your motivations are - This should get you off the ground in trying to develop a new Pairlist Handler. First of all, have a look at the VolumePairList Handler, and best copy this file with a name of your new Pairlist Handler. This is a simple Handler, which however serves as a good example on how to start developing. Next, modify the class-name of the Handler (ideally align this with the module filename). The base-class provides an instance of the exchange ( self._exchange ) the pairlist manager ( self._pairlistmanager ), as well as the main configuration ( self._config ), the pairlist dedicated configuration ( self._pairlistconfig ) and the absolute position within the list of pairlists. python self._exchange = exchange self._pairlistmanager = pairlistmanager self._config = config self._pairlistconfig = pairlistconfig self._pairlist_pos = pairlist_pos Tip Don't forget to register your pairlist in constants.py under the variable AVAILABLE_PAIRLISTS - otherwise it will not be selectable. Now, let's step through the methods which require actions:","title":"Pairlists"},{"location":"developer/#pairlist-configuration","text":"Configuration for the chain of Pairlist Handlers is done in the bot configuration file in the element \"pairlists\" , an array of configuration parameters for each Pairlist Handlers in the chain. By convention, \"number_assets\" is used to specify the maximum number of pairs to keep in the pairlist. Please follow this to ensure a consistent user experience. Additional parameters can be configured as needed. For instance, VolumePairList uses \"sort_key\" to specify the sorting value - however feel free to specify whatever is necessary for your great algorithm to be successful and dynamic.","title":"Pairlist configuration"},{"location":"developer/#short_desc","text":"Returns a description used for Telegram messages. This should contain the name of the Pairlist Handler, as well as a short description containing the number of assets. Please follow the format \"PairlistName - top/bottom X pairs\" .","title":"short_desc"},{"location":"developer/#gen_pairlist","text":"Override this method if the Pairlist Handler can be used as the leading Pairlist Handler in the chain, defining the initial pairlist which is then handled by all Pairlist Handlers in the chain. Examples are StaticPairList and VolumePairList . This is called with each iteration of the bot (only if the Pairlist Handler is at the first location) - so consider implementing caching for compute/network heavy calculations. It must return the resulting pairlist (which may then be passed into the chain of Pairlist Handlers). Validations are optional, the parent class exposes a _verify_blacklist(pairlist) and _whitelist_for_active_markets(pairlist) to do default filtering. Use this if you limit your result to a certain number of pairs - so the end-result is not shorter than expected.","title":"gen_pairlist"},{"location":"developer/#filter_pairlist","text":"This method is called for each Pairlist Handler in the chain by the pairlist manager. This is called with each iteration of the bot - so consider implementing caching for compute/network heavy calculations. It gets passed a pairlist (which can be the result of previous pairlists) as well as tickers , a pre-fetched version of get_tickers() . The default implementation in the base class simply calls the _validate_pair() method for each pair in the pairlist, but you may override it. So you should either implement the _validate_pair() in your Pairlist Handler or override filter_pairlist() to do something else. If overridden, it must return the resulting pairlist (which may then be passed into the next Pairlist Handler in the chain). Validations are optional, the parent class exposes a _verify_blacklist(pairlist) and _whitelist_for_active_markets(pairlist) to do default filters. Use this if you limit your result to a certain number of pairs - so the end result is not shorter than expected. In VolumePairList , this implements different methods of sorting, does early validation so only the expected number of pairs is returned.","title":"filter_pairlist"},{"location":"developer/#sample","text":"python def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]: # Generate dynamic whitelist pairs = self._calculate_pairlist(pairlist, tickers) return pairs","title":"sample"},{"location":"developer/#protections","text":"Best read the Protection documentation to understand protections. This Guide is directed towards Developers who want to develop a new protection. No protection should use datetime directly, but use the provided date_now variable for date calculations. This preserves the ability to backtest protections. Writing a new Protection Best copy one of the existing Protections to have a good example. Don't forget to register your protection in constants.py under the variable AVAILABLE_PROTECTIONS - otherwise it will not be selectable.","title":"Protections"},{"location":"developer/#implementation-of-a-new-protection","text":"All Protection implementations must have IProtection as parent class. For that reason, they must implement the following methods: short_desc() global_stop() stop_per_pair() . global_stop() and stop_per_pair() must return a ProtectionReturn tuple, which consists of: lock pair - boolean lock until - datetime - until when should the pair be locked (will be rounded up to the next new candle) reason - string, used for logging and storage in the database The until portion should be calculated using the provided calculate_lock_end() method. All Protections should use \"stop_duration\" / \"stop_duration_candles\" to define how long a a pair (or all pairs) should be locked. The content of this is made available as self._stop_duration to the each Protection. If your protection requires a look-back period, please use \"lookback_period\" / \"lockback_period_candles\" to keep all protections aligned.","title":"Implementation of a new protection"},{"location":"developer/#global-vs-local-stops","text":"Protections can have 2 different ways to stop trading for a limited : Per pair (local) For all Pairs (globally)","title":"Global vs. local stops"},{"location":"developer/#protections-per-pair","text":"Protections that implement the per pair approach must set has_local_stop=True . The method stop_per_pair() will be called whenever a trade closed (sell order completed).","title":"Protections - per pair"},{"location":"developer/#protections-global-protection","text":"These Protections should do their evaluation across all pairs, and consequently will also lock all pairs from trading (called a global PairLock). Global protection must set has_global_stop=True to be evaluated for global stops. The method global_stop() will be called whenever a trade closed (sell order completed).","title":"Protections - global protection"},{"location":"developer/#protections-calculating-lock-end-time","text":"Protections should calculate the lock end time based on the last trade it considers. This avoids re-locking should the lookback-period be longer than the actual lock period. The IProtection parent class provides a helper method for this in calculate_lock_end() .","title":"Protections - calculating lock end time"},{"location":"developer/#implement-a-new-exchange-wip","text":"Note This section is a Work in Progress and is not a complete guide on how to test a new exchange with Freqtrade. Most exchanges supported by CCXT should work out of the box. To quickly test the public endpoints of an exchange, add a configuration for your exchange to test_ccxt_compat.py and run these tests with pytest --longrun tests/exchange/test_ccxt_compat.py . Completing these tests successfully a good basis point (it's a requirement, actually), however these won't guarantee correct exchange functioning, as this only tests public endpoints, but no private endpoint (like generate order or similar).","title":"Implement a new Exchange (WIP)"},{"location":"developer/#stoploss-on-exchange","text":"Check if the new exchange supports Stoploss on Exchange orders through their API. Since CCXT does not provide unification for Stoploss On Exchange yet, we'll need to implement the exchange-specific parameters ourselves. Best look at binance.py for an example implementation of this. You'll need to dig through the documentation of the Exchange's API on how exactly this can be done. CCXT Issues may also provide great help, since others may have implemented something similar for their projects.","title":"Stoploss On Exchange"},{"location":"developer/#incomplete-candles","text":"While fetching candle (OHLCV) data, we may end up getting incomplete candles (depending on the exchange). To demonstrate this, we'll use daily candles ( \"1d\" ) to keep things simple. We query the api ( ct.fetch_ohlcv() ) for the timeframe and look at the date of the last entry. If this entry changes or shows the date of a \"incomplete\" candle, then we should drop this since having incomplete candles is problematic because indicators assume that only complete candles are passed to them, and will generate a lot of false buy signals. By default, we're therefore removing the last candle assuming it's incomplete. To check how the new exchange behaves, you can use the following snippet: ``` python import ccxt from datetime import datetime from freqtrade.data.converter import ohlcv_to_dataframe ct = ccxt.binance() timeframe = \"1d\" pair = \"XLM/BTC\" # Make sure to use a pair that exists on that exchange! raw = ct.fetch_ohlcv(pair, timeframe=timeframe)","title":"Incomplete candles"},{"location":"developer/#convert-to-dataframe","text":"df1 = ohlcv_to_dataframe(raw, timeframe, pair=pair, drop_incomplete=False) print(df1.tail(1)) print(datetime.utcnow()) ``` output date open high low close volume 499 2019-06-08 00:00:00+00:00 0.000007 0.000007 0.000007 0.000007 26264344.0 2019-06-09 12:30:27.873327 The output will show the last entry from the Exchange as well as the current UTC date. If the day shows the same day, then the last candle can be assumed as incomplete and should be dropped (leave the setting \"ohlcv_partial_candle\" from the exchange-class untouched / True). Otherwise, set \"ohlcv_partial_candle\" to False to not drop Candles (shown in the example above). Another way is to run this command multiple times in a row and observe if the volume is changing (while the date remains the same).","title":"convert to dataframe"},{"location":"developer/#updating-example-notebooks","text":"To keep the jupyter notebooks aligned with the documentation, the following should be ran after updating a example notebook. bash jupyter nbconvert --ClearOutputPreprocessor.enabled=True --inplace freqtrade/templates/strategy_analysis_example.ipynb jupyter nbconvert --ClearOutputPreprocessor.enabled=True --to markdown freqtrade/templates/strategy_analysis_example.ipynb --stdout > docs/strategy_analysis_example.md","title":"Updating example notebooks"},{"location":"developer/#continuous-integration","text":"This documents some decisions taken for the CI Pipeline. CI runs on all OS variants, Linux (ubuntu), macOS and Windows. Docker images are build for the branches stable and develop . Docker images containing Plot dependencies are also available as stable_plot and develop_plot . Raspberry PI Docker images are postfixed with _pi - so tags will be :stable_pi and develop_pi . Docker images contain a file, /freqtrade/freqtrade_commit containing the commit this image is based of. Full docker image rebuilds are run once a week via schedule. Deployments run on ubuntu. ta-lib binaries are contained in the build_helpers directory to avoid fails related to external unavailability. All tests must pass for a PR to be merged to stable or develop .","title":"Continuous integration"},{"location":"developer/#creating-a-release","text":"This part of the documentation is aimed at maintainers, and shows how to create a release.","title":"Creating a release"},{"location":"developer/#create-release-branch","text":"First, pick a commit that's about one week old (to not include latest additions to releases). ``` bash","title":"Create release branch"},{"location":"developer/#create-new-branch","text":"git checkout -b new_release ``` Determine if crucial bugfixes have been made between this commit and the current state, and eventually cherry-pick these. Merge the release branch (stable) into this branch. Edit freqtrade/__init__.py and add the version matching the current date (for example 2019.7 for July 2019). Minor versions can be 2019.7.1 should we need to do a second release that month. Version numbers must follow allowed versions from PEP0440 to avoid failures pushing to pypi. Commit this part push that branch to the remote and create a PR against the stable branch","title":"create new branch"},{"location":"developer/#create-changelog-from-git-commits","text":"Note Make sure that the stable branch is up-to-date! ``` bash","title":"Create changelog from git commits"},{"location":"developer/#needs-to-be-done-before-merging-pulling-that-branch","text":"git log --oneline --no-decorate --no-merges stable..new_release ``` To keep the release-log short, best wrap the full git changelog into a collapsible details section. ```markdown Expand full changelog ... Full git changelog ```","title":"Needs to be done before merging / pulling that branch."},{"location":"developer/#create-github-release-tag","text":"Once the PR against stable is merged (best right after merging): Use the button \"Draft a new release\" in the Github UI (subsection releases). Use the version-number specified as tag. Use \"stable\" as reference (this step comes after the above PR is merged). Use the above changelog as release comment (as codeblock)","title":"Create github release / tag"},{"location":"developer/#releases","text":"","title":"Releases"},{"location":"developer/#pypi","text":"Note This process is now automated as part of Github Actions. To create a pypi release, please run the following commands: Additional requirement: wheel , twine (for uploading), account on pypi with proper permissions. ``` bash python setup.py sdist bdist_wheel","title":"pypi"},{"location":"developer/#for-pypi-test-to-check-if-some-change-to-the-installation-did-work","text":"twine upload --repository-url https://test.pypi.org/legacy/ dist/*","title":"For pypi test (to check if some change to the installation did work)"},{"location":"developer/#for-production","text":"twine upload dist/* ``` Please don't push non-releases to the productive / real pypi instance.","title":"For production:"},{"location":"docker_quickstart/","text":"Using Freqtrade with Docker \u00b6 This page explains how to run the bot with Docker. It is not meant to work out of the box. You'll still need to read through the documentation and understand how to properly configure it. Install Docker \u00b6 Start by downloading and installing Docker CE for your platform: Mac Windows Linux To simplify running freqtrade, docker-compose should be installed and available to follow the below docker quick start guide . Freqtrade with docker-compose \u00b6 Freqtrade provides an official Docker image on Dockerhub , as well as a docker-compose file ready for usage. Note The following section assumes that docker and docker-compose are installed and available to the logged in user. All below commands use relative directories and will have to be executed from the directory containing the docker-compose.yml file. Docker quick start \u00b6 Create a new directory and place the docker-compose file in this directory. ``` bash mkdir ft_userdata cd ft_userdata/ Download the docker-compose file from the repository \u00b6 curl https://raw.githubusercontent.com/freqtrade/freqtrade/stable/docker-compose.yml -o docker-compose.yml Pull the freqtrade image \u00b6 docker-compose pull Create user directory structure \u00b6 docker-compose run --rm freqtrade create-userdir --userdir user_data Create configuration - Requires answering interactive questions \u00b6 docker-compose run --rm freqtrade new-config --config user_data/config.json ``` The above snippet creates a new directory called ft_userdata , downloads the latest compose file and pulls the freqtrade image. The last 2 steps in the snippet create the directory with user_data , as well as (interactively) the default configuration based on your selections. How to edit the bot configuration? You can edit the configuration at any time, which is available as user_data/config.json (within the directory ft_userdata ) when using the above configuration. You can also change the both Strategy and commands by editing the command section of your docker-compose.yml file. Adding a custom strategy \u00b6 The configuration is now available as user_data/config.json Copy a custom strategy to the directory user_data/strategies/ Add the Strategy' class name to the docker-compose.yml file The SampleStrategy is run by default. SampleStrategy is just a demo! The SampleStrategy is there for your reference and give you ideas for your own strategy. Please always backtest your strategy and use dry-run for some time before risking real money! You will find more information about Strategy development in the Strategy documentation . Once this is done, you're ready to launch the bot in trading mode (Dry-run or Live-trading, depending on your answer to the corresponding question you made above). bash docker-compose up -d Default configuration While the configuration generated will be mostly functional, you will still need to verify that all options correspond to what you want (like Pricing, pairlist, ...) before starting the bot. Monitoring the bot \u00b6 You can check for running instances with docker-compose ps . This should list the service freqtrade as running . If that's not the case, best check the logs (see next point). Docker-compose logs \u00b6 Logs will be written to: user_data/logs/freqtrade.log . You can also check the latest log with the command docker-compose logs -f . Database \u00b6 The database will be located at: user_data/tradesv3.sqlite Updating freqtrade with docker-compose \u00b6 Updating freqtrade when using docker-compose is as simple as running the following 2 commands: ``` bash Download the latest image \u00b6 docker-compose pull Restart the image \u00b6 docker-compose up -d ``` This will first pull the latest image, and will then restart the container with the just pulled version. Check the Changelog You should always check the changelog for breaking changes / manual interventions required and make sure the bot starts correctly after the update. Editing the docker-compose file \u00b6 Advanced users may edit the docker-compose file further to include all possible options or arguments. All freqtrade arguments will be available by running docker-compose run --rm freqtrade . docker-compose for trade commands Trade commands ( freqtrade trade <...> ) should not be ran via docker-compose run - but should use docker-compose up -d instead. This makes sure that the container is properly started (including port forwardings) and will make sure that the container will restart after a system reboot. docker-compose run --rm Including --rm will remove the container after completion, and is highly recommended for all modes except trading mode (running with freqtrade trade command). Example: Download data with docker-compose \u00b6 Download backtesting data for 5 days for the pair ETH/BTC and 1h timeframe from Binance. The data will be stored in the directory user_data/data/ on the host. bash docker-compose run --rm freqtrade download-data --pairs ETH/BTC --exchange binance --days 5 -t 1h Head over to the Data Downloading Documentation for more details on downloading data. Example: Backtest with docker-compose \u00b6 Run backtesting in docker-containers for SampleStrategy and specified timerange of historical data, on 5m timeframe: bash docker-compose run --rm freqtrade backtesting --config user_data/config.json --strategy SampleStrategy --timerange 20190801-20191001 -i 5m Head over to the Backtesting Documentation to learn more. Additional dependencies with docker-compose \u00b6 If your strategy requires dependencies not included in the default image - it will be necessary to build the image on your host. For this, please create a Dockerfile containing installation steps for the additional dependencies (have a look at docker/Dockerfile.custom for an example). You'll then also need to modify the docker-compose.yml file and uncomment the build step, as well as rename the image to avoid naming collisions. yaml image: freqtrade_custom build: context: . dockerfile: \"./Dockerfile.\" You can then run docker-compose build to build the docker image, and run it using the commands described above. Plotting with docker-compose \u00b6 Commands freqtrade plot-profit and freqtrade plot-dataframe ( Documentation ) are available by changing the image to *_plot in your docker-compose.yml file. You can then use these commands as follows: bash docker-compose run --rm freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH --timerange=20180801-20180805 The output will be stored in the user_data/plot directory, and can be opened with any modern browser. Data analysis using docker compose \u00b6 Freqtrade provides a docker-compose file which starts up a jupyter lab server. You can run this server using the following command: bash docker-compose -f docker/docker-compose-jupyter.yml up This will create a docker-container running jupyter lab, which will be accessible using https://127.0.0.1:8888/lab . Please use the link that's printed in the console after startup for simplified login. Since part of this image is built on your machine, it is recommended to rebuild the image from time to time to keep freqtrade (and dependencies) up-to-date. bash docker-compose -f docker/docker-compose-jupyter.yml build --no-cache","title":"Quickstart with Docker"},{"location":"docker_quickstart/#using-freqtrade-with-docker","text":"This page explains how to run the bot with Docker. It is not meant to work out of the box. You'll still need to read through the documentation and understand how to properly configure it.","title":"Using Freqtrade with Docker"},{"location":"docker_quickstart/#install-docker","text":"Start by downloading and installing Docker CE for your platform: Mac Windows Linux To simplify running freqtrade, docker-compose should be installed and available to follow the below docker quick start guide .","title":"Install Docker"},{"location":"docker_quickstart/#freqtrade-with-docker-compose","text":"Freqtrade provides an official Docker image on Dockerhub , as well as a docker-compose file ready for usage. Note The following section assumes that docker and docker-compose are installed and available to the logged in user. All below commands use relative directories and will have to be executed from the directory containing the docker-compose.yml file.","title":"Freqtrade with docker-compose"},{"location":"docker_quickstart/#docker-quick-start","text":"Create a new directory and place the docker-compose file in this directory. ``` bash mkdir ft_userdata cd ft_userdata/","title":"Docker quick start"},{"location":"docker_quickstart/#download-the-docker-compose-file-from-the-repository","text":"curl https://raw.githubusercontent.com/freqtrade/freqtrade/stable/docker-compose.yml -o docker-compose.yml","title":"Download the docker-compose file from the repository"},{"location":"docker_quickstart/#pull-the-freqtrade-image","text":"docker-compose pull","title":"Pull the freqtrade image"},{"location":"docker_quickstart/#create-user-directory-structure","text":"docker-compose run --rm freqtrade create-userdir --userdir user_data","title":"Create user directory structure"},{"location":"docker_quickstart/#create-configuration-requires-answering-interactive-questions","text":"docker-compose run --rm freqtrade new-config --config user_data/config.json ``` The above snippet creates a new directory called ft_userdata , downloads the latest compose file and pulls the freqtrade image. The last 2 steps in the snippet create the directory with user_data , as well as (interactively) the default configuration based on your selections. How to edit the bot configuration? You can edit the configuration at any time, which is available as user_data/config.json (within the directory ft_userdata ) when using the above configuration. You can also change the both Strategy and commands by editing the command section of your docker-compose.yml file.","title":"Create configuration - Requires answering interactive questions"},{"location":"docker_quickstart/#adding-a-custom-strategy","text":"The configuration is now available as user_data/config.json Copy a custom strategy to the directory user_data/strategies/ Add the Strategy' class name to the docker-compose.yml file The SampleStrategy is run by default. SampleStrategy is just a demo! The SampleStrategy is there for your reference and give you ideas for your own strategy. Please always backtest your strategy and use dry-run for some time before risking real money! You will find more information about Strategy development in the Strategy documentation . Once this is done, you're ready to launch the bot in trading mode (Dry-run or Live-trading, depending on your answer to the corresponding question you made above). bash docker-compose up -d Default configuration While the configuration generated will be mostly functional, you will still need to verify that all options correspond to what you want (like Pricing, pairlist, ...) before starting the bot.","title":"Adding a custom strategy"},{"location":"docker_quickstart/#monitoring-the-bot","text":"You can check for running instances with docker-compose ps . This should list the service freqtrade as running . If that's not the case, best check the logs (see next point).","title":"Monitoring the bot"},{"location":"docker_quickstart/#docker-compose-logs","text":"Logs will be written to: user_data/logs/freqtrade.log . You can also check the latest log with the command docker-compose logs -f .","title":"Docker-compose logs"},{"location":"docker_quickstart/#database","text":"The database will be located at: user_data/tradesv3.sqlite","title":"Database"},{"location":"docker_quickstart/#updating-freqtrade-with-docker-compose","text":"Updating freqtrade when using docker-compose is as simple as running the following 2 commands: ``` bash","title":"Updating freqtrade with docker-compose"},{"location":"docker_quickstart/#download-the-latest-image","text":"docker-compose pull","title":"Download the latest image"},{"location":"docker_quickstart/#restart-the-image","text":"docker-compose up -d ``` This will first pull the latest image, and will then restart the container with the just pulled version. Check the Changelog You should always check the changelog for breaking changes / manual interventions required and make sure the bot starts correctly after the update.","title":"Restart the image"},{"location":"docker_quickstart/#editing-the-docker-compose-file","text":"Advanced users may edit the docker-compose file further to include all possible options or arguments. All freqtrade arguments will be available by running docker-compose run --rm freqtrade . docker-compose for trade commands Trade commands ( freqtrade trade <...> ) should not be ran via docker-compose run - but should use docker-compose up -d instead. This makes sure that the container is properly started (including port forwardings) and will make sure that the container will restart after a system reboot. docker-compose run --rm Including --rm will remove the container after completion, and is highly recommended for all modes except trading mode (running with freqtrade trade command).","title":"Editing the docker-compose file"},{"location":"docker_quickstart/#example-download-data-with-docker-compose","text":"Download backtesting data for 5 days for the pair ETH/BTC and 1h timeframe from Binance. The data will be stored in the directory user_data/data/ on the host. bash docker-compose run --rm freqtrade download-data --pairs ETH/BTC --exchange binance --days 5 -t 1h Head over to the Data Downloading Documentation for more details on downloading data.","title":"Example: Download data with docker-compose"},{"location":"docker_quickstart/#example-backtest-with-docker-compose","text":"Run backtesting in docker-containers for SampleStrategy and specified timerange of historical data, on 5m timeframe: bash docker-compose run --rm freqtrade backtesting --config user_data/config.json --strategy SampleStrategy --timerange 20190801-20191001 -i 5m Head over to the Backtesting Documentation to learn more.","title":"Example: Backtest with docker-compose"},{"location":"docker_quickstart/#additional-dependencies-with-docker-compose","text":"If your strategy requires dependencies not included in the default image - it will be necessary to build the image on your host. For this, please create a Dockerfile containing installation steps for the additional dependencies (have a look at docker/Dockerfile.custom for an example). You'll then also need to modify the docker-compose.yml file and uncomment the build step, as well as rename the image to avoid naming collisions. yaml image: freqtrade_custom build: context: . dockerfile: \"./Dockerfile.\" You can then run docker-compose build to build the docker image, and run it using the commands described above.","title":"Additional dependencies with docker-compose"},{"location":"docker_quickstart/#plotting-with-docker-compose","text":"Commands freqtrade plot-profit and freqtrade plot-dataframe ( Documentation ) are available by changing the image to *_plot in your docker-compose.yml file. You can then use these commands as follows: bash docker-compose run --rm freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH --timerange=20180801-20180805 The output will be stored in the user_data/plot directory, and can be opened with any modern browser.","title":"Plotting with docker-compose"},{"location":"docker_quickstart/#data-analysis-using-docker-compose","text":"Freqtrade provides a docker-compose file which starts up a jupyter lab server. You can run this server using the following command: bash docker-compose -f docker/docker-compose-jupyter.yml up This will create a docker-container running jupyter lab, which will be accessible using https://127.0.0.1:8888/lab . Please use the link that's printed in the console after startup for simplified login. Since part of this image is built on your machine, it is recommended to rebuild the image from time to time to keep freqtrade (and dependencies) up-to-date. bash docker-compose -f docker/docker-compose-jupyter.yml build --no-cache","title":"Data analysis using docker compose"},{"location":"edge/","text":"Edge positioning \u00b6 The Edge Positioning module uses probability to calculate your win rate and risk reward ratio. It will use these statistics to control your strategy trade entry points, position size and, stoploss. Warning WHen using Edge positioning with a dynamic whitelist (VolumePairList), make sure to also use AgeFilter and set it to at least calculate_since_number_of_days to avoid problems with missing data. Note Edge Positioning only considers its own buy/sell/stoploss signals. It ignores the stoploss, trailing stoploss, and ROI settings in the strategy configuration file. Edge Positioning improves the performance of some trading strategies and decreases the performance of others. Introduction \u00b6 Trading strategies are not perfect. They are frameworks that are susceptible to the market and its indicators. Because the market is not at all predictable, sometimes a strategy will win and sometimes the same strategy will lose. To obtain an edge in the market, a strategy has to make more money than it loses. Making money in trading is not only about how often the strategy makes or loses money. It doesn't matter how often, but how much! A bad strategy might make 1 penny in ten transactions but lose 1 dollar in one transaction. If one only checks the number of winning trades, it would be misleading to think that the strategy is actually making a profit. The Edge Positioning module seeks to improve a strategy's winning probability and the money that the strategy will make on the long run . We raise the following question 1 : Which trade is a better option? a) A trade with 80% of chance of losing 100$ and 20% chance of winning 200$ b) A trade with 100% of chance of losing 30$ Answer The expected value of a) is smaller than the expected value of b) . Hence, b ) represents a smaller loss in the long run. However, the answer is: it depends Another way to look at it is to ask a similar question: Which trade is a better option? a) A trade with 80% of chance of winning 100$ and 20% chance of losing 200$ b) A trade with 100% of chance of winning 30$ Edge positioning tries to answer the hard questions about risk/reward and position size automatically, seeking to minimizes the chances of losing of a given strategy. Trading, winning and losing \u00b6 Let's call \\(o\\) the return of a single transaction \\(o\\) where \\(o \\in \\mathbb{R}\\) . The collection \\(O = \\{o_1, o_2, ..., o_N\\}\\) is the set of all returns of transactions made during a trading session. We say that \\(N\\) is the cardinality of \\(O\\) , or, in lay terms, it is the number of transactions made in a trading session. Example In a session where a strategy made three transactions we can say that \\(O = \\{3.5, -1, 15\\}\\) . That means that \\(N = 3\\) and \\(o_1 = 3.5\\) , \\(o_2 = -1\\) , \\(o_3 = 15\\) . A winning trade is a trade where a strategy made money. Making money means that the strategy closed the position in a value that returned a profit, after all deducted fees. Formally, a winning trade will have a return \\(o_i > 0\\) . Similarly, a losing trade will have a return \\(o_j \\leq 0\\) . With that, we can discover the set of all winning trades, \\(T_{win}\\) , as follows: \\[ T_{win} = \\{ o \\in O | o > 0 \\} \\] Similarly, we can discover the set of losing trades \\(T_{lose}\\) as follows: \\[ T_{lose} = \\{o \\in O | o \\leq 0\\} \\] Example In a section where a strategy made four transactions \\(O = \\{3.5, -1, 15, 0\\}\\) : \\(T_{win} = \\{3.5, 15\\}\\) \\(T_{lose} = \\{-1, 0\\}\\) Win Rate and Lose Rate \u00b6 The win rate \\(W\\) is the proportion of winning trades with respect to all the trades made by a strategy. We use the following function to compute the win rate: \\[W = \\frac{|T_{win}|}{N}\\] Where \\(W\\) is the win rate, \\(N\\) is the number of trades and, \\(T_{win}\\) is the set of all trades where the strategy made money. Similarly, we can compute the rate of losing trades: \\[ L = \\frac{|T_{lose}|}{N} \\] Where \\(L\\) is the lose rate, \\(N\\) is the amount of trades made and, \\(T_{lose}\\) is the set of all trades where the strategy lost money. Note that the above formula is the same as calculating \\(L = 1 \u2013 W\\) or \\(W = 1 \u2013 L\\) Risk Reward Ratio \u00b6 Risk Reward Ratio ( \\(R\\) ) is a formula used to measure the expected gains of a given investment against the risk of loss. It is basically what you potentially win divided by what you potentially lose. Formally: \\[ R = \\frac{\\text{potential_profit}}{\\text{potential_loss}} \\] Worked example of \\(R\\) calculation Let's say that you think that the price of stonecoin today is 10.0$. You believe that, because they will start mining stonecoin, it will go up to 15.0$ tomorrow. There is the risk that the stone is too hard, and the GPUs can't mine it, so the price might go to 0$ tomorrow. You are planning to invest 100$, which will give you 10 shares (100 / 10). Your potential profit is calculated as: \\(\\begin{aligned} \\text{potential_profit} &= (\\text{potential_price} - \\text{entry_price}) * \\frac{\\text{investment}}{\\text{entry_price}} \\\\ &= (15 - 10) * (100 / 10) \\\\ &= 50 \\end{aligned}\\) Since the price might go to 0$, the 100$ dollars invested could turn into 0. We do however use a stoploss of 15% - so in the worst case, we'll sell 15% below entry price (or at 8.5$). \\(\\begin{aligned} \\text{potential_loss} &= (\\text{entry_price} - \\text{stoploss}) * \\frac{\\text{investment}}{\\text{entry_price}} \\\\ &= (10 - 8.5) * (100 / 10)\\\\ &= 15 \\end{aligned}\\) We can compute the Risk Reward Ratio as follows: \\(\\begin{aligned} R &= \\frac{\\text{potential_profit}}{\\text{potential_loss}}\\\\ &= \\frac{50}{15}\\\\ &= 3.33 \\end{aligned}\\) What it effectively means is that the strategy have the potential to make 3.33$ for each 1$ invested. On a long horizon, that is, on many trades, we can calculate the risk reward by dividing the strategy' average profit on winning trades by the strategy' average loss on losing trades. We can calculate the average profit, \\(\\mu_{win}\\) , as follows: \\[ \\text{average_profit} = \\mu_{win} = \\frac{\\text{sum_of_profits}}{\\text{count_winning_trades}} = \\frac{\\sum^{o \\in T_{win}} o}{|T_{win}|} \\] Similarly, we can calculate the average loss, \\(\\mu_{lose}\\) , as follows: \\[ \\text{average_loss} = \\mu_{lose} = \\frac{\\text{sum_of_losses}}{\\text{count_losing_trades}} = \\frac{\\sum^{o \\in T_{lose}} o}{|T_{lose}|} \\] Finally, we can calculate the Risk Reward ratio, \\(R\\) , as follows: \\[ R = \\frac{\\text{average_profit}}{\\text{average_loss}} = \\frac{\\mu_{win}}{\\mu_{lose}}\\\\ \\] Worked example of \\(R\\) calculation using mean profit/loss Let's say the strategy that we are using makes an average win \\(\\mu_{win} = 2.06\\) and an average loss \\(\\mu_{loss} = 4.11\\) . We calculate the risk reward ratio as follows: \\(R = \\frac{\\mu_{win}}{\\mu_{loss}} = \\frac{2.06}{4.11} = 0.5012...\\) Expectancy \u00b6 By combining the Win Rate \\(W\\) and and the Risk Reward ratio \\(R\\) to create an expectancy ratio \\(E\\) . A expectance ratio is the expected return of the investment made in a trade. We can compute the value of \\(E\\) as follows: \\[E = R * W - L\\] Calculating \\(E\\) Let's say that a strategy has a win rate \\(W = 0.28\\) and a risk reward ratio \\(R = 5\\) . What this means is that the strategy is expected to make 5 times the investment around on 28% of the trades it makes. Working out the example: \\(E = R * W - L = 5 * 0.28 - 0.72 = 0.68\\) The expectancy worked out in the example above means that, on average, this strategy' trades will return 1.68 times the size of its losses. Said another way, the strategy makes 1.68$ for every 1$ it loses, on average. This is important for two reasons: First, it may seem obvious, but you know right away that you have a positive return. Second, you now have a number you can compare to other candidate systems to make decisions about which ones you employ. It is important to remember that any system with an expectancy greater than 0 is profitable using past data. The key is finding one that will be profitable in the future. You can also use this value to evaluate the effectiveness of modifications to this system. Note It's important to keep in mind that Edge is testing your expectancy using historical data, there's no guarantee that you will have a similar edge in the future. It's still vital to do this testing in order to build confidence in your methodology but be wary of \"curve-fitting\" your approach to the historical data as things are unlikely to play out the exact same way for future trades. How does it work? \u00b6 Edge combines dynamic stoploss, dynamic positions, and whitelist generation into one isolated module which is then applied to the trading strategy. If enabled in config, Edge will go through historical data with a range of stoplosses in order to find buy and sell/stoploss signals. It then calculates win rate and expectancy over N trades for each stoploss. Here is an example: Pair Stoploss Win Rate Risk Reward Ratio Expectancy XZC/ETH -0.01 0.50 1.176384 0.088 XZC/ETH -0.02 0.51 1.115941 0.079 XZC/ETH -0.03 0.52 1.359670 0.228 XZC/ETH -0.04 0.51 1.234539 0.117 The goal here is to find the best stoploss for the strategy in order to have the maximum expectancy. In the above example stoploss at \\(3%\\) leads to the maximum expectancy according to historical data. Edge module then forces stoploss value it evaluated to your strategy dynamically. Position size \u00b6 Edge dictates the amount at stake for each trade to the bot according to the following factors: Allowed capital at risk Stoploss Allowed capital at risk is calculated as follows: Allowed capital at risk = (Capital available_percentage) X (Allowed risk per trade) Stoploss is calculated as described above with respect to historical data. The position size is calculated as follows: Position size = (Allowed capital at risk) / Stoploss Example: Let's say the stake currency is ETH and there is \\(10\\) ETH on the wallet. The capital available percentage is \\(50%\\) and the allowed risk per trade is \\(1\\%\\) . Thus, the available capital for trading is \\(10 * 0.5 = 5\\) ETH and the allowed capital at risk would be \\(5 * 0.01 = 0.05\\) ETH . Trade 1: The strategy detects a new buy signal in the XLM/ETH market. Edge Positioning calculates a stoploss of \\(2\\%\\) and a position of \\(0.05 / 0.02 = 2.5\\) ETH . The bot takes a position of \\(2.5\\) ETH in the XLM/ETH market. Trade 2: The strategy detects a buy signal on the BTC/ETH market while Trade 1 is still open. Edge Positioning calculates the stoploss of \\(4\\%\\) on this market. Thus, Trade 2 position size is \\(0.05 / 0.04 = 1.25\\) ETH . Available Capital \\(\\neq\\) Available in wallet The available capital for trading didn't change in Trade 2 even with Trade 1 still open. The available capital is not the free amount in the wallet. Trade 3: The strategy detects a buy signal in the ADA/ETH market. Edge Positioning calculates a stoploss of \\(1\\%\\) and a position of \\(0.05 / 0.01 = 5\\) ETH . Since Trade 1 has \\(2.5\\) ETH blocked and Trade 2 has \\(1.25\\) ETH blocked, there is only \\(5 - 1.25 - 2.5 = 1.25\\) ETH available. Hence, the position size of Trade 3 is \\(1.25\\) ETH . Available Capital Updates The available capital does not change before a position is sold. After a trade is closed the Available Capital goes up if the trade was profitable or goes down if the trade was a loss. The strategy detects a sell signal in the XLM/ETH market. The bot exits Trade 1 for a profit of \\(1\\) ETH . The total capital in the wallet becomes \\(11\\) ETH and the available capital for trading becomes \\(5.5\\) ETH . Trade 4 The strategy detects a new buy signal int the XLM/ETH market. Edge Positioning calculates the stoploss of \\(2\\%\\) , and the position size of \\(0.055 / 0.02 = 2.75\\) ETH . Edge command reference \u00b6 ``` usage: freqtrade edge [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-s NAME] [--strategy-path PATH] [-i TIMEFRAME] [--timerange TIMERANGE] [--data-format-ohlcv {json,jsongz,hdf5}] [--max-open-trades INT] [--stake-amount STAKE_AMOUNT] [--fee FLOAT] [-p PAIRS [PAIRS ...]] [--stoplosses STOPLOSS_RANGE] optional arguments: -h, --help show this help message and exit -i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME Specify timeframe ( 1m , 5m , 30m , 1h , 1d ). --timerange TIMERANGE Specify what timerange of data to use. --data-format-ohlcv {json,jsongz,hdf5} Storage format for downloaded candle (OHLCV) data. (default: None ). --max-open-trades INT Override the value of the max_open_trades configuration setting. --stake-amount STAKE_AMOUNT Override the value of the stake_amount configuration setting. --fee FLOAT Specify fee ratio. Will be applied twice (on trade entry and exit). -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] Limit command to these pairs. Pairs are space- separated. --stoplosses STOPLOSS_RANGE Defines a range of stoploss values against which edge will assess the strategy. The format is \"min,max,step\" (without any space). Example: --stoplosses=-0.01,-0.1,-0.001 Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. Strategy arguments: -s NAME, --strategy NAME Specify strategy class name which will be used by the bot. --strategy-path PATH Specify additional strategy lookup path. ``` Configurations \u00b6 Edge module has following configuration options: Parameter Description enabled If true, then Edge will run periodically. Defaults to false . Datatype: Boolean process_throttle_secs How often should Edge run in seconds. Defaults to 3600 (once per hour). Datatype: Integer calculate_since_number_of_days Number of days of data against which Edge calculates Win Rate, Risk Reward and Expectancy. Note that it downloads historical data so increasing this number would lead to slowing down the bot. Defaults to 7 . Datatype: Integer allowed_risk Ratio of allowed risk per trade. Defaults to 0.01 (1%)). Datatype: Float stoploss_range_min Minimum stoploss. Defaults to -0.01 . Datatype: Float stoploss_range_max Maximum stoploss. Defaults to -0.10 . Datatype: Float stoploss_range_step As an example if this is set to -0.01 then Edge will test the strategy for [-0.01, -0,02, -0,03 ..., -0.09, -0.10] ranges. Note than having a smaller step means having a bigger range which could lead to slow calculation. If you set this parameter to -0.001, you then slow down the Edge calculation by a factor of 10. Defaults to -0.001 . Datatype: Float minimum_winrate It filters out pairs which don't have at least minimum_winrate. This comes handy if you want to be conservative and don't comprise win rate in favour of risk reward ratio. Defaults to 0.60 . Datatype: Float minimum_expectancy It filters out pairs which have the expectancy lower than this number. Having an expectancy of 0.20 means if you put 10$ on a trade you expect a 12$ return. Defaults to 0.20 . Datatype: Float min_trade_number When calculating W , R and E (expectancy) against historical data, you always want to have a minimum number of trades. The more this number is the more Edge is reliable. Having a win rate of 100% on a single trade doesn't mean anything at all. But having a win rate of 70% over past 100 trades means clearly something. Defaults to 10 (it is highly recommended not to decrease this number). Datatype: Integer max_trade_duration_minute Edge will filter out trades with long duration. If a trade is profitable after 1 month, it is hard to evaluate the strategy based on it. But if most of trades are profitable and they have maximum duration of 30 minutes, then it is clearly a good sign. NOTICE: While configuring this value, you should take into consideration your timeframe. As an example filtering out trades having duration less than one day for a strategy which has 4h interval does not make sense. Default value is set assuming your strategy interval is relatively small (1m or 5m, etc.). Defaults to 1440 (one day). Datatype: Integer remove_pumps Edge will remove sudden pumps in a given market while going through historical data. However, given that pumps happen very often in crypto markets, we recommend you keep this off. Defaults to false . Datatype: Boolean Running Edge independently \u00b6 You can run Edge independently in order to see in details the result. Here is an example: bash freqtrade edge An example of its output: pair stoploss win rate risk reward ratio required risk reward expectancy total number of trades average duration (min) AGI/BTC -0.02 0.64 5.86 0.56 3.41 14 54 NXS/BTC -0.03 0.64 2.99 0.57 1.54 11 26 LEND/BTC -0.02 0.82 2.05 0.22 1.50 11 36 VIA/BTC -0.01 0.55 3.01 0.83 1.19 11 48 MTH/BTC -0.09 0.56 2.82 0.80 1.12 18 52 ARDR/BTC -0.04 0.42 3.14 1.40 0.73 12 42 BCPT/BTC -0.01 0.71 1.34 0.40 0.67 14 30 WINGS/BTC -0.02 0.56 1.97 0.80 0.65 27 42 VIBE/BTC -0.02 0.83 0.91 0.20 0.59 12 35 MCO/BTC -0.02 0.79 0.97 0.27 0.55 14 31 GNT/BTC -0.02 0.50 2.06 1.00 0.53 18 24 HOT/BTC -0.01 0.17 7.72 4.81 0.50 209 7 SNM/BTC -0.03 0.71 1.06 0.42 0.45 17 38 APPC/BTC -0.02 0.44 2.28 1.27 0.44 25 43 NEBL/BTC -0.03 0.63 1.29 0.58 0.44 19 59 Edge produced the above table by comparing calculate_since_number_of_days to minimum_expectancy to find min_trade_number historical information based on the config file. The timerange Edge uses for its comparisons can be further limited by using the --timerange switch. In live and dry-run modes, after the process_throttle_secs has passed, Edge will again process calculate_since_number_of_days against minimum_expectancy to find min_trade_number . If no min_trade_number is found, the bot will return \"whitelist empty\". Depending on the trade strategy being deployed, \"whitelist empty\" may be return much of the time - or all of the time. The use of Edge may also cause trading to occur in bursts, though this is rare. If you encounter \"whitelist empty\" a lot, condsider tuning calculate_since_number_of_days , minimum_expectancy and min_trade_number to align to the trading frequency of your strategy. Update cached pairs with the latest data \u00b6 Edge requires historic data the same way as backtesting does. Please refer to the Data Downloading section of the documentation for details. Precising stoploss range \u00b6 bash freqtrade edge --stoplosses=-0.01,-0.1,-0.001 #min,max,step Advanced use of timerange \u00b6 bash freqtrade edge --timerange=20181110-20181113 Doing --timerange=-20190901 will get all available data until September 1 st (excluding September 1 st 2019). The full timerange specification: Use tickframes till 2018/01/31: --timerange=-20180131 Use tickframes since 2018/01/31: --timerange=20180131- Use tickframes since 2018/01/31 till 2018/03/01 : --timerange=20180131-20180301 Use tickframes between POSIX timestamps 1527595200 1527618600: --timerange=1527595200-1527618600 Question extracted from MIT Opencourseware S096 - Mathematics with applications in Finance: https://ocw.mit.edu/courses/mathematics/18-s096-topics-in-mathematics-with-applications-in-finance-fall-2013/ \u21a9","title":"Edge Positioning"},{"location":"edge/#edge-positioning","text":"The Edge Positioning module uses probability to calculate your win rate and risk reward ratio. It will use these statistics to control your strategy trade entry points, position size and, stoploss. Warning WHen using Edge positioning with a dynamic whitelist (VolumePairList), make sure to also use AgeFilter and set it to at least calculate_since_number_of_days to avoid problems with missing data. Note Edge Positioning only considers its own buy/sell/stoploss signals. It ignores the stoploss, trailing stoploss, and ROI settings in the strategy configuration file. Edge Positioning improves the performance of some trading strategies and decreases the performance of others.","title":"Edge positioning"},{"location":"edge/#introduction","text":"Trading strategies are not perfect. They are frameworks that are susceptible to the market and its indicators. Because the market is not at all predictable, sometimes a strategy will win and sometimes the same strategy will lose. To obtain an edge in the market, a strategy has to make more money than it loses. Making money in trading is not only about how often the strategy makes or loses money. It doesn't matter how often, but how much! A bad strategy might make 1 penny in ten transactions but lose 1 dollar in one transaction. If one only checks the number of winning trades, it would be misleading to think that the strategy is actually making a profit. The Edge Positioning module seeks to improve a strategy's winning probability and the money that the strategy will make on the long run . We raise the following question 1 : Which trade is a better option? a) A trade with 80% of chance of losing 100$ and 20% chance of winning 200$ b) A trade with 100% of chance of losing 30$ Answer The expected value of a) is smaller than the expected value of b) . Hence, b ) represents a smaller loss in the long run. However, the answer is: it depends Another way to look at it is to ask a similar question: Which trade is a better option? a) A trade with 80% of chance of winning 100$ and 20% chance of losing 200$ b) A trade with 100% of chance of winning 30$ Edge positioning tries to answer the hard questions about risk/reward and position size automatically, seeking to minimizes the chances of losing of a given strategy.","title":"Introduction"},{"location":"edge/#trading-winning-and-losing","text":"Let's call \\(o\\) the return of a single transaction \\(o\\) where \\(o \\in \\mathbb{R}\\) . The collection \\(O = \\{o_1, o_2, ..., o_N\\}\\) is the set of all returns of transactions made during a trading session. We say that \\(N\\) is the cardinality of \\(O\\) , or, in lay terms, it is the number of transactions made in a trading session. Example In a session where a strategy made three transactions we can say that \\(O = \\{3.5, -1, 15\\}\\) . That means that \\(N = 3\\) and \\(o_1 = 3.5\\) , \\(o_2 = -1\\) , \\(o_3 = 15\\) . A winning trade is a trade where a strategy made money. Making money means that the strategy closed the position in a value that returned a profit, after all deducted fees. Formally, a winning trade will have a return \\(o_i > 0\\) . Similarly, a losing trade will have a return \\(o_j \\leq 0\\) . With that, we can discover the set of all winning trades, \\(T_{win}\\) , as follows: \\[ T_{win} = \\{ o \\in O | o > 0 \\} \\] Similarly, we can discover the set of losing trades \\(T_{lose}\\) as follows: \\[ T_{lose} = \\{o \\in O | o \\leq 0\\} \\] Example In a section where a strategy made four transactions \\(O = \\{3.5, -1, 15, 0\\}\\) : \\(T_{win} = \\{3.5, 15\\}\\) \\(T_{lose} = \\{-1, 0\\}\\)","title":"Trading, winning and losing"},{"location":"edge/#win-rate-and-lose-rate","text":"The win rate \\(W\\) is the proportion of winning trades with respect to all the trades made by a strategy. We use the following function to compute the win rate: \\[W = \\frac{|T_{win}|}{N}\\] Where \\(W\\) is the win rate, \\(N\\) is the number of trades and, \\(T_{win}\\) is the set of all trades where the strategy made money. Similarly, we can compute the rate of losing trades: \\[ L = \\frac{|T_{lose}|}{N} \\] Where \\(L\\) is the lose rate, \\(N\\) is the amount of trades made and, \\(T_{lose}\\) is the set of all trades where the strategy lost money. Note that the above formula is the same as calculating \\(L = 1 \u2013 W\\) or \\(W = 1 \u2013 L\\)","title":"Win Rate and Lose Rate"},{"location":"edge/#risk-reward-ratio","text":"Risk Reward Ratio ( \\(R\\) ) is a formula used to measure the expected gains of a given investment against the risk of loss. It is basically what you potentially win divided by what you potentially lose. Formally: \\[ R = \\frac{\\text{potential_profit}}{\\text{potential_loss}} \\] Worked example of \\(R\\) calculation Let's say that you think that the price of stonecoin today is 10.0$. You believe that, because they will start mining stonecoin, it will go up to 15.0$ tomorrow. There is the risk that the stone is too hard, and the GPUs can't mine it, so the price might go to 0$ tomorrow. You are planning to invest 100$, which will give you 10 shares (100 / 10). Your potential profit is calculated as: \\(\\begin{aligned} \\text{potential_profit} &= (\\text{potential_price} - \\text{entry_price}) * \\frac{\\text{investment}}{\\text{entry_price}} \\\\ &= (15 - 10) * (100 / 10) \\\\ &= 50 \\end{aligned}\\) Since the price might go to 0$, the 100$ dollars invested could turn into 0. We do however use a stoploss of 15% - so in the worst case, we'll sell 15% below entry price (or at 8.5$). \\(\\begin{aligned} \\text{potential_loss} &= (\\text{entry_price} - \\text{stoploss}) * \\frac{\\text{investment}}{\\text{entry_price}} \\\\ &= (10 - 8.5) * (100 / 10)\\\\ &= 15 \\end{aligned}\\) We can compute the Risk Reward Ratio as follows: \\(\\begin{aligned} R &= \\frac{\\text{potential_profit}}{\\text{potential_loss}}\\\\ &= \\frac{50}{15}\\\\ &= 3.33 \\end{aligned}\\) What it effectively means is that the strategy have the potential to make 3.33$ for each 1$ invested. On a long horizon, that is, on many trades, we can calculate the risk reward by dividing the strategy' average profit on winning trades by the strategy' average loss on losing trades. We can calculate the average profit, \\(\\mu_{win}\\) , as follows: \\[ \\text{average_profit} = \\mu_{win} = \\frac{\\text{sum_of_profits}}{\\text{count_winning_trades}} = \\frac{\\sum^{o \\in T_{win}} o}{|T_{win}|} \\] Similarly, we can calculate the average loss, \\(\\mu_{lose}\\) , as follows: \\[ \\text{average_loss} = \\mu_{lose} = \\frac{\\text{sum_of_losses}}{\\text{count_losing_trades}} = \\frac{\\sum^{o \\in T_{lose}} o}{|T_{lose}|} \\] Finally, we can calculate the Risk Reward ratio, \\(R\\) , as follows: \\[ R = \\frac{\\text{average_profit}}{\\text{average_loss}} = \\frac{\\mu_{win}}{\\mu_{lose}}\\\\ \\] Worked example of \\(R\\) calculation using mean profit/loss Let's say the strategy that we are using makes an average win \\(\\mu_{win} = 2.06\\) and an average loss \\(\\mu_{loss} = 4.11\\) . We calculate the risk reward ratio as follows: \\(R = \\frac{\\mu_{win}}{\\mu_{loss}} = \\frac{2.06}{4.11} = 0.5012...\\)","title":"Risk Reward Ratio"},{"location":"edge/#expectancy","text":"By combining the Win Rate \\(W\\) and and the Risk Reward ratio \\(R\\) to create an expectancy ratio \\(E\\) . A expectance ratio is the expected return of the investment made in a trade. We can compute the value of \\(E\\) as follows: \\[E = R * W - L\\] Calculating \\(E\\) Let's say that a strategy has a win rate \\(W = 0.28\\) and a risk reward ratio \\(R = 5\\) . What this means is that the strategy is expected to make 5 times the investment around on 28% of the trades it makes. Working out the example: \\(E = R * W - L = 5 * 0.28 - 0.72 = 0.68\\) The expectancy worked out in the example above means that, on average, this strategy' trades will return 1.68 times the size of its losses. Said another way, the strategy makes 1.68$ for every 1$ it loses, on average. This is important for two reasons: First, it may seem obvious, but you know right away that you have a positive return. Second, you now have a number you can compare to other candidate systems to make decisions about which ones you employ. It is important to remember that any system with an expectancy greater than 0 is profitable using past data. The key is finding one that will be profitable in the future. You can also use this value to evaluate the effectiveness of modifications to this system. Note It's important to keep in mind that Edge is testing your expectancy using historical data, there's no guarantee that you will have a similar edge in the future. It's still vital to do this testing in order to build confidence in your methodology but be wary of \"curve-fitting\" your approach to the historical data as things are unlikely to play out the exact same way for future trades.","title":"Expectancy"},{"location":"edge/#how-does-it-work","text":"Edge combines dynamic stoploss, dynamic positions, and whitelist generation into one isolated module which is then applied to the trading strategy. If enabled in config, Edge will go through historical data with a range of stoplosses in order to find buy and sell/stoploss signals. It then calculates win rate and expectancy over N trades for each stoploss. Here is an example: Pair Stoploss Win Rate Risk Reward Ratio Expectancy XZC/ETH -0.01 0.50 1.176384 0.088 XZC/ETH -0.02 0.51 1.115941 0.079 XZC/ETH -0.03 0.52 1.359670 0.228 XZC/ETH -0.04 0.51 1.234539 0.117 The goal here is to find the best stoploss for the strategy in order to have the maximum expectancy. In the above example stoploss at \\(3%\\) leads to the maximum expectancy according to historical data. Edge module then forces stoploss value it evaluated to your strategy dynamically.","title":"How does it work?"},{"location":"edge/#position-size","text":"Edge dictates the amount at stake for each trade to the bot according to the following factors: Allowed capital at risk Stoploss Allowed capital at risk is calculated as follows: Allowed capital at risk = (Capital available_percentage) X (Allowed risk per trade) Stoploss is calculated as described above with respect to historical data. The position size is calculated as follows: Position size = (Allowed capital at risk) / Stoploss Example: Let's say the stake currency is ETH and there is \\(10\\) ETH on the wallet. The capital available percentage is \\(50%\\) and the allowed risk per trade is \\(1\\%\\) . Thus, the available capital for trading is \\(10 * 0.5 = 5\\) ETH and the allowed capital at risk would be \\(5 * 0.01 = 0.05\\) ETH . Trade 1: The strategy detects a new buy signal in the XLM/ETH market. Edge Positioning calculates a stoploss of \\(2\\%\\) and a position of \\(0.05 / 0.02 = 2.5\\) ETH . The bot takes a position of \\(2.5\\) ETH in the XLM/ETH market. Trade 2: The strategy detects a buy signal on the BTC/ETH market while Trade 1 is still open. Edge Positioning calculates the stoploss of \\(4\\%\\) on this market. Thus, Trade 2 position size is \\(0.05 / 0.04 = 1.25\\) ETH . Available Capital \\(\\neq\\) Available in wallet The available capital for trading didn't change in Trade 2 even with Trade 1 still open. The available capital is not the free amount in the wallet. Trade 3: The strategy detects a buy signal in the ADA/ETH market. Edge Positioning calculates a stoploss of \\(1\\%\\) and a position of \\(0.05 / 0.01 = 5\\) ETH . Since Trade 1 has \\(2.5\\) ETH blocked and Trade 2 has \\(1.25\\) ETH blocked, there is only \\(5 - 1.25 - 2.5 = 1.25\\) ETH available. Hence, the position size of Trade 3 is \\(1.25\\) ETH . Available Capital Updates The available capital does not change before a position is sold. After a trade is closed the Available Capital goes up if the trade was profitable or goes down if the trade was a loss. The strategy detects a sell signal in the XLM/ETH market. The bot exits Trade 1 for a profit of \\(1\\) ETH . The total capital in the wallet becomes \\(11\\) ETH and the available capital for trading becomes \\(5.5\\) ETH . Trade 4 The strategy detects a new buy signal int the XLM/ETH market. Edge Positioning calculates the stoploss of \\(2\\%\\) , and the position size of \\(0.055 / 0.02 = 2.75\\) ETH .","title":"Position size"},{"location":"edge/#edge-command-reference","text":"``` usage: freqtrade edge [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-s NAME] [--strategy-path PATH] [-i TIMEFRAME] [--timerange TIMERANGE] [--data-format-ohlcv {json,jsongz,hdf5}] [--max-open-trades INT] [--stake-amount STAKE_AMOUNT] [--fee FLOAT] [-p PAIRS [PAIRS ...]] [--stoplosses STOPLOSS_RANGE] optional arguments: -h, --help show this help message and exit -i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME Specify timeframe ( 1m , 5m , 30m , 1h , 1d ). --timerange TIMERANGE Specify what timerange of data to use. --data-format-ohlcv {json,jsongz,hdf5} Storage format for downloaded candle (OHLCV) data. (default: None ). --max-open-trades INT Override the value of the max_open_trades configuration setting. --stake-amount STAKE_AMOUNT Override the value of the stake_amount configuration setting. --fee FLOAT Specify fee ratio. Will be applied twice (on trade entry and exit). -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] Limit command to these pairs. Pairs are space- separated. --stoplosses STOPLOSS_RANGE Defines a range of stoploss values against which edge will assess the strategy. The format is \"min,max,step\" (without any space). Example: --stoplosses=-0.01,-0.1,-0.001 Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. Strategy arguments: -s NAME, --strategy NAME Specify strategy class name which will be used by the bot. --strategy-path PATH Specify additional strategy lookup path. ```","title":"Edge command reference"},{"location":"edge/#configurations","text":"Edge module has following configuration options: Parameter Description enabled If true, then Edge will run periodically. Defaults to false . Datatype: Boolean process_throttle_secs How often should Edge run in seconds. Defaults to 3600 (once per hour). Datatype: Integer calculate_since_number_of_days Number of days of data against which Edge calculates Win Rate, Risk Reward and Expectancy. Note that it downloads historical data so increasing this number would lead to slowing down the bot. Defaults to 7 . Datatype: Integer allowed_risk Ratio of allowed risk per trade. Defaults to 0.01 (1%)). Datatype: Float stoploss_range_min Minimum stoploss. Defaults to -0.01 . Datatype: Float stoploss_range_max Maximum stoploss. Defaults to -0.10 . Datatype: Float stoploss_range_step As an example if this is set to -0.01 then Edge will test the strategy for [-0.01, -0,02, -0,03 ..., -0.09, -0.10] ranges. Note than having a smaller step means having a bigger range which could lead to slow calculation. If you set this parameter to -0.001, you then slow down the Edge calculation by a factor of 10. Defaults to -0.001 . Datatype: Float minimum_winrate It filters out pairs which don't have at least minimum_winrate. This comes handy if you want to be conservative and don't comprise win rate in favour of risk reward ratio. Defaults to 0.60 . Datatype: Float minimum_expectancy It filters out pairs which have the expectancy lower than this number. Having an expectancy of 0.20 means if you put 10$ on a trade you expect a 12$ return. Defaults to 0.20 . Datatype: Float min_trade_number When calculating W , R and E (expectancy) against historical data, you always want to have a minimum number of trades. The more this number is the more Edge is reliable. Having a win rate of 100% on a single trade doesn't mean anything at all. But having a win rate of 70% over past 100 trades means clearly something. Defaults to 10 (it is highly recommended not to decrease this number). Datatype: Integer max_trade_duration_minute Edge will filter out trades with long duration. If a trade is profitable after 1 month, it is hard to evaluate the strategy based on it. But if most of trades are profitable and they have maximum duration of 30 minutes, then it is clearly a good sign. NOTICE: While configuring this value, you should take into consideration your timeframe. As an example filtering out trades having duration less than one day for a strategy which has 4h interval does not make sense. Default value is set assuming your strategy interval is relatively small (1m or 5m, etc.). Defaults to 1440 (one day). Datatype: Integer remove_pumps Edge will remove sudden pumps in a given market while going through historical data. However, given that pumps happen very often in crypto markets, we recommend you keep this off. Defaults to false . Datatype: Boolean","title":"Configurations"},{"location":"edge/#running-edge-independently","text":"You can run Edge independently in order to see in details the result. Here is an example: bash freqtrade edge An example of its output: pair stoploss win rate risk reward ratio required risk reward expectancy total number of trades average duration (min) AGI/BTC -0.02 0.64 5.86 0.56 3.41 14 54 NXS/BTC -0.03 0.64 2.99 0.57 1.54 11 26 LEND/BTC -0.02 0.82 2.05 0.22 1.50 11 36 VIA/BTC -0.01 0.55 3.01 0.83 1.19 11 48 MTH/BTC -0.09 0.56 2.82 0.80 1.12 18 52 ARDR/BTC -0.04 0.42 3.14 1.40 0.73 12 42 BCPT/BTC -0.01 0.71 1.34 0.40 0.67 14 30 WINGS/BTC -0.02 0.56 1.97 0.80 0.65 27 42 VIBE/BTC -0.02 0.83 0.91 0.20 0.59 12 35 MCO/BTC -0.02 0.79 0.97 0.27 0.55 14 31 GNT/BTC -0.02 0.50 2.06 1.00 0.53 18 24 HOT/BTC -0.01 0.17 7.72 4.81 0.50 209 7 SNM/BTC -0.03 0.71 1.06 0.42 0.45 17 38 APPC/BTC -0.02 0.44 2.28 1.27 0.44 25 43 NEBL/BTC -0.03 0.63 1.29 0.58 0.44 19 59 Edge produced the above table by comparing calculate_since_number_of_days to minimum_expectancy to find min_trade_number historical information based on the config file. The timerange Edge uses for its comparisons can be further limited by using the --timerange switch. In live and dry-run modes, after the process_throttle_secs has passed, Edge will again process calculate_since_number_of_days against minimum_expectancy to find min_trade_number . If no min_trade_number is found, the bot will return \"whitelist empty\". Depending on the trade strategy being deployed, \"whitelist empty\" may be return much of the time - or all of the time. The use of Edge may also cause trading to occur in bursts, though this is rare. If you encounter \"whitelist empty\" a lot, condsider tuning calculate_since_number_of_days , minimum_expectancy and min_trade_number to align to the trading frequency of your strategy.","title":"Running Edge independently"},{"location":"edge/#update-cached-pairs-with-the-latest-data","text":"Edge requires historic data the same way as backtesting does. Please refer to the Data Downloading section of the documentation for details.","title":"Update cached pairs with the latest data"},{"location":"edge/#precising-stoploss-range","text":"bash freqtrade edge --stoplosses=-0.01,-0.1,-0.001 #min,max,step","title":"Precising stoploss range"},{"location":"edge/#advanced-use-of-timerange","text":"bash freqtrade edge --timerange=20181110-20181113 Doing --timerange=-20190901 will get all available data until September 1 st (excluding September 1 st 2019). The full timerange specification: Use tickframes till 2018/01/31: --timerange=-20180131 Use tickframes since 2018/01/31: --timerange=20180131- Use tickframes since 2018/01/31 till 2018/03/01 : --timerange=20180131-20180301 Use tickframes between POSIX timestamps 1527595200 1527618600: --timerange=1527595200-1527618600 Question extracted from MIT Opencourseware S096 - Mathematics with applications in Finance: https://ocw.mit.edu/courses/mathematics/18-s096-topics-in-mathematics-with-applications-in-finance-fall-2013/ \u21a9","title":"Advanced use of timerange"},{"location":"exchanges/","text":"Exchange-specific Notes \u00b6 This page combines common gotchas and informations which are exchange-specific and most likely don't apply to other exchanges. Binance \u00b6 Stoploss on Exchange Binance supports stoploss_on_exchange and uses stop-loss-limit orders. It provides great advantages, so we recommend to benefit from it. Binance Blacklist \u00b6 For Binance, please add \"BNB/\" to your blacklist to avoid issues. Accounts having BNB accounts use this to pay for fees - if your first trade happens to be on BNB , further trades will consume this position and make the initial BNB trade unsellable as the expected amount is not there anymore. Binance sites \u00b6 Binance has been split into 2, and users must use the correct ccxt exchange ID for their exchange, otherwise API keys are not recognized. binance.com - International users. Use exchange id: binance . binance.us - US based users. Use exchange id: binanceus . Kraken \u00b6 Stoploss on Exchange Kraken supports stoploss_on_exchange and can use both stop-loss-market and stop-loss-limit orders. It provides great advantages, so we recommend to benefit from it. You can use either \"limit\" or \"market\" in the order_types.stoploss configuration setting to decide which type to use. Historic Kraken data \u00b6 The Kraken API does only provide 720 historic candles, which is sufficient for Freqtrade dry-run and live trade modes, but is a problem for backtesting. To download data for the Kraken exchange, using --dl-trades is mandatory, otherwise the bot will download the same 720 candles over and over, and you'll not have enough backtest data. Due to the heavy rate-limiting applied by Kraken, the following configuration section should be used to download data: json \"ccxt_async_config\": { \"enableRateLimit\": true, \"rateLimit\": 3100 }, Downloading data from kraken Downloading kraken data will require significantly more memory (RAM) than any other exchange, as the trades-data needs to be converted into candles on your machine. It will also take a long time, as freqtrade will need to download every single trade that happened on the exchange for the pair / timerange combination, therefore please be patient. rateLimit tuning Please pay attention that rateLimit configuration entry holds delay in milliseconds between requests, NOT requests\\sec rate. So, in order to mitigate Kraken API \"Rate limit exceeded\" exception, this configuration should be increased, NOT decreased. Bittrex \u00b6 Order types \u00b6 Bittrex does not support market orders. If you have a message at the bot startup about this, you should change order type values set in your configuration and/or in the strategy from \"market\" to \"limit\" . See some more details on this here in the FAQ . Bittrex also does not support VolumePairlist due to limited / split API constellation at the moment. Please use StaticPairlist . Other pairlists (other than VolumePairlist ) should not be affected. Restricted markets \u00b6 Bittrex split its exchange into US and International versions. The International version has more pairs available, however the API always returns all pairs, so there is currently no automated way to detect if you're affected by the restriction. If you have restricted pairs in your whitelist, you'll get a warning message in the log on Freqtrade startup for each restricted pair. The warning message will look similar to the following: output [...] Message: bittrex {\"success\":false,\"message\":\"RESTRICTED_MARKET\",\"result\":null,\"explanation\":null}\" If you're an \"International\" customer on the Bittrex exchange, then this warning will probably not impact you. If you're a US customer, the bot will fail to create orders for these pairs, and you should remove them from your whitelist. You can get a list of restricted markets by using the following snippet: ``` python import ccxt ct = ccxt.bittrex() lm = ct.load_markets() res = [p for p, x in lm.items() if 'US' in x['info']['prohibitedIn']] print(res) ``` FTX \u00b6 Stoploss on Exchange FTX supports stoploss_on_exchange and can use both stop-loss-market and stop-loss-limit orders. It provides great advantages, so we recommend to benefit from it. You can use either \"limit\" or \"market\" in the order_types.stoploss configuration setting to decide which type of stoploss shall be used. Using subaccounts \u00b6 To use subaccounts with FTX, you need to edit the configuration and add the following: json \"exchange\": { \"ccxt_config\": { \"headers\": { \"FTX-SUBACCOUNT\": \"name\" } }, } Kucoin \u00b6 Kucoin requries a passphrase for each api key, you will therefore need to add this key into the configuration so your exchange section looks as follows: json \"exchange\": { \"name\": \"kucoin\", \"key\": \"your_exchange_key\", \"secret\": \"your_exchange_secret\", \"password\": \"your_exchange_api_key_password\", Kucoin Blacklists \u00b6 For Kucoin, please add \"KCS/\" to your blacklist to avoid issues. Accounts having KCS accounts use this to pay for fees - if your first trade happens to be on KCS , further trades will consume this position and make the initial KCS trade unsellable as the expected amount is not there anymore. All exchanges \u00b6 Should you experience constant errors with Nonce (like InvalidNonce ), it is best to regenerate the API keys. Resetting Nonce is difficult and it's usually easier to regenerate the API keys. Random notes for other exchanges \u00b6 The Ocean (exchange id: theocean ) exchange uses Web3 functionality and requires web3 python package to be installed: shell $ pip3 install web3 Getting latest price / Incomplete candles \u00b6 Most exchanges return current incomplete candle via their OHLCV/klines API interface. By default, Freqtrade assumes that incomplete candle is fetched from the exchange and removes the last candle assuming it's the incomplete candle. Whether your exchange returns incomplete candles or not can be checked using the helper script from the Contributor documentation. Due to the danger of repainting, Freqtrade does not allow you to use this incomplete candle. However, if it is based on the need for the latest price for your strategy - then this requirement can be acquired using the data provider from within the strategy. Advanced Freqtrade Exchange configuration \u00b6 Advanced options can be configured using the _ft_has_params setting, which will override Defaults and exchange-specific behavior. Available options are listed in the exchange-class as _ft_has_default . For example, to test the order type FOK with Kraken, and modify candle limit to 200 (so you only get 200 candles per API call): json \"exchange\": { \"name\": \"kraken\", \"_ft_has_params\": { \"order_time_in_force\": [\"gtc\", \"fok\"], \"ohlcv_candle_limit\": 200 } Warning Please make sure to fully understand the impacts of these settings before modifying them.","title":"Exchange-specific Notes"},{"location":"exchanges/#exchange-specific-notes","text":"This page combines common gotchas and informations which are exchange-specific and most likely don't apply to other exchanges.","title":"Exchange-specific Notes"},{"location":"exchanges/#binance","text":"Stoploss on Exchange Binance supports stoploss_on_exchange and uses stop-loss-limit orders. It provides great advantages, so we recommend to benefit from it.","title":"Binance"},{"location":"exchanges/#binance-blacklist","text":"For Binance, please add \"BNB/\" to your blacklist to avoid issues. Accounts having BNB accounts use this to pay for fees - if your first trade happens to be on BNB , further trades will consume this position and make the initial BNB trade unsellable as the expected amount is not there anymore.","title":"Binance Blacklist"},{"location":"exchanges/#binance-sites","text":"Binance has been split into 2, and users must use the correct ccxt exchange ID for their exchange, otherwise API keys are not recognized. binance.com - International users. Use exchange id: binance . binance.us - US based users. Use exchange id: binanceus .","title":"Binance sites"},{"location":"exchanges/#kraken","text":"Stoploss on Exchange Kraken supports stoploss_on_exchange and can use both stop-loss-market and stop-loss-limit orders. It provides great advantages, so we recommend to benefit from it. You can use either \"limit\" or \"market\" in the order_types.stoploss configuration setting to decide which type to use.","title":"Kraken"},{"location":"exchanges/#historic-kraken-data","text":"The Kraken API does only provide 720 historic candles, which is sufficient for Freqtrade dry-run and live trade modes, but is a problem for backtesting. To download data for the Kraken exchange, using --dl-trades is mandatory, otherwise the bot will download the same 720 candles over and over, and you'll not have enough backtest data. Due to the heavy rate-limiting applied by Kraken, the following configuration section should be used to download data: json \"ccxt_async_config\": { \"enableRateLimit\": true, \"rateLimit\": 3100 }, Downloading data from kraken Downloading kraken data will require significantly more memory (RAM) than any other exchange, as the trades-data needs to be converted into candles on your machine. It will also take a long time, as freqtrade will need to download every single trade that happened on the exchange for the pair / timerange combination, therefore please be patient. rateLimit tuning Please pay attention that rateLimit configuration entry holds delay in milliseconds between requests, NOT requests\\sec rate. So, in order to mitigate Kraken API \"Rate limit exceeded\" exception, this configuration should be increased, NOT decreased.","title":"Historic Kraken data"},{"location":"exchanges/#bittrex","text":"","title":"Bittrex"},{"location":"exchanges/#order-types","text":"Bittrex does not support market orders. If you have a message at the bot startup about this, you should change order type values set in your configuration and/or in the strategy from \"market\" to \"limit\" . See some more details on this here in the FAQ . Bittrex also does not support VolumePairlist due to limited / split API constellation at the moment. Please use StaticPairlist . Other pairlists (other than VolumePairlist ) should not be affected.","title":"Order types"},{"location":"exchanges/#restricted-markets","text":"Bittrex split its exchange into US and International versions. The International version has more pairs available, however the API always returns all pairs, so there is currently no automated way to detect if you're affected by the restriction. If you have restricted pairs in your whitelist, you'll get a warning message in the log on Freqtrade startup for each restricted pair. The warning message will look similar to the following: output [...] Message: bittrex {\"success\":false,\"message\":\"RESTRICTED_MARKET\",\"result\":null,\"explanation\":null}\" If you're an \"International\" customer on the Bittrex exchange, then this warning will probably not impact you. If you're a US customer, the bot will fail to create orders for these pairs, and you should remove them from your whitelist. You can get a list of restricted markets by using the following snippet: ``` python import ccxt ct = ccxt.bittrex() lm = ct.load_markets() res = [p for p, x in lm.items() if 'US' in x['info']['prohibitedIn']] print(res) ```","title":"Restricted markets"},{"location":"exchanges/#ftx","text":"Stoploss on Exchange FTX supports stoploss_on_exchange and can use both stop-loss-market and stop-loss-limit orders. It provides great advantages, so we recommend to benefit from it. You can use either \"limit\" or \"market\" in the order_types.stoploss configuration setting to decide which type of stoploss shall be used.","title":"FTX"},{"location":"exchanges/#using-subaccounts","text":"To use subaccounts with FTX, you need to edit the configuration and add the following: json \"exchange\": { \"ccxt_config\": { \"headers\": { \"FTX-SUBACCOUNT\": \"name\" } }, }","title":"Using subaccounts"},{"location":"exchanges/#kucoin","text":"Kucoin requries a passphrase for each api key, you will therefore need to add this key into the configuration so your exchange section looks as follows: json \"exchange\": { \"name\": \"kucoin\", \"key\": \"your_exchange_key\", \"secret\": \"your_exchange_secret\", \"password\": \"your_exchange_api_key_password\",","title":"Kucoin"},{"location":"exchanges/#kucoin-blacklists","text":"For Kucoin, please add \"KCS/\" to your blacklist to avoid issues. Accounts having KCS accounts use this to pay for fees - if your first trade happens to be on KCS , further trades will consume this position and make the initial KCS trade unsellable as the expected amount is not there anymore.","title":"Kucoin Blacklists"},{"location":"exchanges/#all-exchanges","text":"Should you experience constant errors with Nonce (like InvalidNonce ), it is best to regenerate the API keys. Resetting Nonce is difficult and it's usually easier to regenerate the API keys.","title":"All exchanges"},{"location":"exchanges/#random-notes-for-other-exchanges","text":"The Ocean (exchange id: theocean ) exchange uses Web3 functionality and requires web3 python package to be installed: shell $ pip3 install web3","title":"Random notes for other exchanges"},{"location":"exchanges/#getting-latest-price-incomplete-candles","text":"Most exchanges return current incomplete candle via their OHLCV/klines API interface. By default, Freqtrade assumes that incomplete candle is fetched from the exchange and removes the last candle assuming it's the incomplete candle. Whether your exchange returns incomplete candles or not can be checked using the helper script from the Contributor documentation. Due to the danger of repainting, Freqtrade does not allow you to use this incomplete candle. However, if it is based on the need for the latest price for your strategy - then this requirement can be acquired using the data provider from within the strategy.","title":"Getting latest price / Incomplete candles"},{"location":"exchanges/#advanced-freqtrade-exchange-configuration","text":"Advanced options can be configured using the _ft_has_params setting, which will override Defaults and exchange-specific behavior. Available options are listed in the exchange-class as _ft_has_default . For example, to test the order type FOK with Kraken, and modify candle limit to 200 (so you only get 200 candles per API call): json \"exchange\": { \"name\": \"kraken\", \"_ft_has_params\": { \"order_time_in_force\": [\"gtc\", \"fok\"], \"ohlcv_candle_limit\": 200 } Warning Please make sure to fully understand the impacts of these settings before modifying them.","title":"Advanced Freqtrade Exchange configuration"},{"location":"faq/","text":"Freqtrade FAQ \u00b6 Supported Markets \u00b6 Freqtrade supports spot trading only. Can I open short positions? \u00b6 No, Freqtrade does not support trading with margin / leverage, and cannot open short positions. In some cases, your exchange may provide leveraged spot tokens which can be traded with Freqtrade eg. BTCUP/USD, BTCDOWN/USD, ETHBULL/USD, ETHBEAR/USD, etc... Can I trade options or futures? \u00b6 No, options and futures trading are not supported. Beginner Tips & Tricks \u00b6 When you work with your strategy & hyperopt file you should use a proper code editor like VSCode or PyCharm. A good code editor will provide syntax highlighting as well as line numbers, making it easy to find syntax errors (most likely pointed out by Freqtrade during startup). Freqtrade common issues \u00b6 The bot does not start \u00b6 Running the bot with freqtrade trade --config config.json shows the output freqtrade: command not found . This could be caused by the following reasons: The virtual environment is not active. Run source .env/bin/activate to activate the virtual environment. The installation did not work correctly. Please check the Installation documentation . I have waited 5 minutes, why hasn't the bot made any trades yet? \u00b6 Depending on the buy strategy, the amount of whitelisted coins, the situation of the market etc, it can take up to hours to find a good entry position for a trade. Be patient! It may be because of a configuration error. It's best to check the logs, they usually tell you if the bot is simply not getting buy signals (only heartbeat messages), or if there is something wrong (errors / exceptions in the log). I have made 12 trades already, why is my total profit negative? \u00b6 I understand your disappointment but unfortunately 12 trades is just not enough to say anything. If you run backtesting, you can see that our current algorithm does leave you on the plus side, but that is after thousands of trades and even there, you will be left with losses on specific coins that you have traded tens if not hundreds of times. We of course constantly aim to improve the bot but it will always be a gamble, which should leave you with modest wins on monthly basis but you can't say much from few trades. I\u2019d like to make changes to the config. Can I do that without having to kill the bot? \u00b6 Yes. You can edit your config and use the /reload_config command to reload the configuration. The bot will stop, reload the configuration and strategy and will restart with the new configuration and strategy. I want to improve the bot with a new strategy \u00b6 That's great. We have a nice backtesting and hyperoptimization setup. See the tutorial here|Testing-new-strategies-with-Hyperopt . Is there a setting to only SELL the coins being held and not perform anymore BUYS? \u00b6 You can use the /stopbuy command in Telegram to prevent future buys, followed by /forcesell all (sell all open trades). I want to run multiple bots on the same machine \u00b6 Please look at the advanced setup documentation Page . I'm getting \"Missing data fillup\" messages in the log \u00b6 This message is just a warning that the latest candles had missing candles in them. Depending on the exchange, this can indicate that the pair didn't have a trade for the timeframe you are using - and the exchange does only return candles with volume. On low volume pairs, this is a rather common occurrence. If this happens for all pairs in the pairlist, this might indicate a recent exchange downtime. Please check your exchange's public channels for details. Irrespectively of the reason, Freqtrade will fill up these candles with \"empty\" candles, where open, high, low and close are set to the previous candle close - and volume is empty. In a chart, this will look like a _ - and is aligned with how exchanges usually represent 0 volume candles. I'm getting the \"RESTRICTED_MARKET\" message in the log \u00b6 Currently known to happen for US Bittrex users. Read the Bittrex section about restricted markets for more information. I'm getting the \"Exchange Bittrex does not support market orders.\" message and cannot run my strategy \u00b6 As the message says, Bittrex does not support market orders and you have one of the order types set to \"market\". Your strategy was probably written with other exchanges in mind and sets \"market\" orders for \"stoploss\" orders, which is correct and preferable for most of the exchanges supporting market orders (but not for Bittrex). To fix it for Bittrex, redefine order types in the strategy to use \"limit\" instead of \"market\": order_types = { ... 'stoploss': 'limit', ... } The same fix should be applied in the configuration file, if order types are defined in your custom config rather than in the strategy. How do I search the bot logs for something? \u00b6 By default, the bot writes its log into stderr stream. This is implemented this way so that you can easily separate the bot's diagnostics messages from Backtesting, Edge and Hyperopt results, output from other various Freqtrade utility sub-commands, as well as from the output of your custom print() 's you may have inserted into your strategy. So if you need to search the log messages with the grep utility, you need to redirect stderr to stdout and disregard stdout. In unix shells, this normally can be done as simple as: shell $ freqtrade --some-options 2>&1 >/dev/null | grep 'something' (note, 2>&1 and >/dev/null should be written in this order) Bash interpreter also supports so called process substitution syntax, you can grep the log for a string with it as: shell $ freqtrade --some-options 2> >(grep 'something') >/dev/null or shell $ freqtrade --some-options 2> >(grep -v 'something' 1>&2) You can also write the copy of Freqtrade log messages to a file with the --logfile option: shell $ freqtrade --logfile /path/to/mylogfile.log --some-options and then grep it as: shell $ cat /path/to/mylogfile.log | grep 'something' or even on the fly, as the bot works and the log file grows: shell $ tail -f /path/to/mylogfile.log | grep 'something' from a separate terminal window. On Windows, the --logfile option is also supported by Freqtrade and you can use the findstr command to search the log for the string of interest: ``` type \\path\\to\\mylogfile.log | findstr \"something\" ``` Why does freqtrade not have GPU support? \u00b6 First of all, most indicator libraries don't have GPU support - as such, there would be little benefit for indicator calculations. The GPU improvements would only apply to pandas-native calculations - or ones written by yourself. For hyperopt, freqtrade is using scikit-optimize, which is built on top of scikit-learn. Their statement about GPU support is pretty clear . GPU's also are only good at crunching numbers (floating point operations). For hyperopt, we need both number-crunching (find next parameters) and running python code (running backtesting). As such, GPU's are not too well suited for most parts of hyperopt. The benefit of using GPU would therefore be pretty slim - and will not justify the complexity introduced by trying to add GPU support. There is however nothing preventing you from using GPU-enabled indicators within your strategy if you think you must have this - you will however probably be disappointed by the slim gain that will give you (compared to the complexity). Hyperopt module \u00b6 How many epochs do I need to get a good Hyperopt result? \u00b6 Per default Hyperopt called without the -e / --epochs command line option will only run 100 epochs, means 100 evaluations of your triggers, guards, ... Too few to find a great result (unless if you are very lucky), so you probably have to run it for 10.000 or more. But it will take an eternity to compute. Since hyperopt uses Bayesian search, running for too many epochs may not produce greater results. It's therefore recommended to run between 500-1000 epochs over and over until you hit at least 10.000 epochs in total (or are satisfied with the result). You can best judge by looking at the results - if the bot keeps discovering better strategies, it's best to keep on going. bash freqtrade hyperopt --hyperopt SampleHyperopt --hyperopt-loss SharpeHyperOptLossDaily --strategy SampleStrategy -e 1000 Why does it take a long time to run hyperopt? \u00b6 Discovering a great strategy with Hyperopt takes time. Study www.freqtrade.io , the Freqtrade Documentation page, join the Freqtrade discord community . While you patiently wait for the most advanced, free crypto bot in the world, to hand you a possible golden strategy specially designed just for you. If you wonder why it can take from 20 minutes to days to do 1000 epochs here are some answers: This answer was written during the release 0.15.1, when we had: 8 triggers 9 guards: let's say we evaluate even 10 values from each 1 stoploss calculation: let's say we want 10 values from that too to be evaluated The following calculation is still very rough and not very precise but it will give the idea. With only these triggers and guards there is already 8*10^9*10 evaluations. A roughly total of 80 billion evaluations. Did you run 100 000 evaluations? Congrats, you've done roughly 1 / 100 000 th of the search space, assuming that the bot never tests the same parameters more than once. The time it takes to run 1000 hyperopt epochs depends on things like: The available cpu, hard-disk, ram, timeframe, timerange, indicator settings, indicator count, amount of coins that hyperopt test strategies on and the resulting trade count - which can be 650 trades in a year or 10.0000 trades depending if the strategy aims for big profits by trading rarely or for many low profit trades. Example: 4% profit 650 times vs 0,3% profit a trade 10.000 times in a year. If we assume you set the --timerange to 365 days. Example: freqtrade --config config.json --strategy SampleStrategy --hyperopt SampleHyperopt -e 1000 --timerange 20190601-20200601 Edge module \u00b6 Edge implements interesting approach for controlling position size, is there any theory behind it? \u00b6 The Edge module is mostly a result of brainstorming of @mishaker and @creslinux freqtrade team members. You can find further info on expectancy, win rate, risk management and position size in the following sources: https://www.tradeciety.com/ultimate-math-guide-for-traders/ http://www.vantharp.com/tharp-concepts/expectancy.asp https://samuraitradingacademy.com/trading-expectancy/ https://www.learningmarkets.com/determining-expectancy-in-your-trading/ http://www.lonestocktrader.com/make-money-trading-positive-expectancy/ https://www.babypips.com/trading/trade-expectancy-matter","title":"FAQ"},{"location":"faq/#freqtrade-faq","text":"","title":"Freqtrade FAQ"},{"location":"faq/#supported-markets","text":"Freqtrade supports spot trading only.","title":"Supported Markets"},{"location":"faq/#can-i-open-short-positions","text":"No, Freqtrade does not support trading with margin / leverage, and cannot open short positions. In some cases, your exchange may provide leveraged spot tokens which can be traded with Freqtrade eg. BTCUP/USD, BTCDOWN/USD, ETHBULL/USD, ETHBEAR/USD, etc...","title":"Can I open short positions?"},{"location":"faq/#can-i-trade-options-or-futures","text":"No, options and futures trading are not supported.","title":"Can I trade options or futures?"},{"location":"faq/#beginner-tips-tricks","text":"When you work with your strategy & hyperopt file you should use a proper code editor like VSCode or PyCharm. A good code editor will provide syntax highlighting as well as line numbers, making it easy to find syntax errors (most likely pointed out by Freqtrade during startup).","title":"Beginner Tips & Tricks"},{"location":"faq/#freqtrade-common-issues","text":"","title":"Freqtrade common issues"},{"location":"faq/#the-bot-does-not-start","text":"Running the bot with freqtrade trade --config config.json shows the output freqtrade: command not found . This could be caused by the following reasons: The virtual environment is not active. Run source .env/bin/activate to activate the virtual environment. The installation did not work correctly. Please check the Installation documentation .","title":"The bot does not start"},{"location":"faq/#i-have-waited-5-minutes-why-hasnt-the-bot-made-any-trades-yet","text":"Depending on the buy strategy, the amount of whitelisted coins, the situation of the market etc, it can take up to hours to find a good entry position for a trade. Be patient! It may be because of a configuration error. It's best to check the logs, they usually tell you if the bot is simply not getting buy signals (only heartbeat messages), or if there is something wrong (errors / exceptions in the log).","title":"I have waited 5 minutes, why hasn't the bot made any trades yet?"},{"location":"faq/#i-have-made-12-trades-already-why-is-my-total-profit-negative","text":"I understand your disappointment but unfortunately 12 trades is just not enough to say anything. If you run backtesting, you can see that our current algorithm does leave you on the plus side, but that is after thousands of trades and even there, you will be left with losses on specific coins that you have traded tens if not hundreds of times. We of course constantly aim to improve the bot but it will always be a gamble, which should leave you with modest wins on monthly basis but you can't say much from few trades.","title":"I have made 12 trades already, why is my total profit negative?"},{"location":"faq/#id-like-to-make-changes-to-the-config-can-i-do-that-without-having-to-kill-the-bot","text":"Yes. You can edit your config and use the /reload_config command to reload the configuration. The bot will stop, reload the configuration and strategy and will restart with the new configuration and strategy.","title":"I\u2019d like to make changes to the config. Can I do that without having to kill the bot?"},{"location":"faq/#i-want-to-improve-the-bot-with-a-new-strategy","text":"That's great. We have a nice backtesting and hyperoptimization setup. See the tutorial here|Testing-new-strategies-with-Hyperopt .","title":"I want to improve the bot with a new strategy"},{"location":"faq/#is-there-a-setting-to-only-sell-the-coins-being-held-and-not-perform-anymore-buys","text":"You can use the /stopbuy command in Telegram to prevent future buys, followed by /forcesell all (sell all open trades).","title":"Is there a setting to only SELL the coins being held and not perform anymore BUYS?"},{"location":"faq/#i-want-to-run-multiple-bots-on-the-same-machine","text":"Please look at the advanced setup documentation Page .","title":"I want to run multiple bots on the same machine"},{"location":"faq/#im-getting-missing-data-fillup-messages-in-the-log","text":"This message is just a warning that the latest candles had missing candles in them. Depending on the exchange, this can indicate that the pair didn't have a trade for the timeframe you are using - and the exchange does only return candles with volume. On low volume pairs, this is a rather common occurrence. If this happens for all pairs in the pairlist, this might indicate a recent exchange downtime. Please check your exchange's public channels for details. Irrespectively of the reason, Freqtrade will fill up these candles with \"empty\" candles, where open, high, low and close are set to the previous candle close - and volume is empty. In a chart, this will look like a _ - and is aligned with how exchanges usually represent 0 volume candles.","title":"I'm getting \"Missing data fillup\" messages in the log"},{"location":"faq/#im-getting-the-restricted_market-message-in-the-log","text":"Currently known to happen for US Bittrex users. Read the Bittrex section about restricted markets for more information.","title":"I'm getting the \"RESTRICTED_MARKET\" message in the log"},{"location":"faq/#im-getting-the-exchange-bittrex-does-not-support-market-orders-message-and-cannot-run-my-strategy","text":"As the message says, Bittrex does not support market orders and you have one of the order types set to \"market\". Your strategy was probably written with other exchanges in mind and sets \"market\" orders for \"stoploss\" orders, which is correct and preferable for most of the exchanges supporting market orders (but not for Bittrex). To fix it for Bittrex, redefine order types in the strategy to use \"limit\" instead of \"market\": order_types = { ... 'stoploss': 'limit', ... } The same fix should be applied in the configuration file, if order types are defined in your custom config rather than in the strategy.","title":"I'm getting the \"Exchange Bittrex does not support market orders.\" message and cannot run my strategy"},{"location":"faq/#how-do-i-search-the-bot-logs-for-something","text":"By default, the bot writes its log into stderr stream. This is implemented this way so that you can easily separate the bot's diagnostics messages from Backtesting, Edge and Hyperopt results, output from other various Freqtrade utility sub-commands, as well as from the output of your custom print() 's you may have inserted into your strategy. So if you need to search the log messages with the grep utility, you need to redirect stderr to stdout and disregard stdout. In unix shells, this normally can be done as simple as: shell $ freqtrade --some-options 2>&1 >/dev/null | grep 'something' (note, 2>&1 and >/dev/null should be written in this order) Bash interpreter also supports so called process substitution syntax, you can grep the log for a string with it as: shell $ freqtrade --some-options 2> >(grep 'something') >/dev/null or shell $ freqtrade --some-options 2> >(grep -v 'something' 1>&2) You can also write the copy of Freqtrade log messages to a file with the --logfile option: shell $ freqtrade --logfile /path/to/mylogfile.log --some-options and then grep it as: shell $ cat /path/to/mylogfile.log | grep 'something' or even on the fly, as the bot works and the log file grows: shell $ tail -f /path/to/mylogfile.log | grep 'something' from a separate terminal window. On Windows, the --logfile option is also supported by Freqtrade and you can use the findstr command to search the log for the string of interest: ``` type \\path\\to\\mylogfile.log | findstr \"something\" ```","title":"How do I search the bot logs for something?"},{"location":"faq/#why-does-freqtrade-not-have-gpu-support","text":"First of all, most indicator libraries don't have GPU support - as such, there would be little benefit for indicator calculations. The GPU improvements would only apply to pandas-native calculations - or ones written by yourself. For hyperopt, freqtrade is using scikit-optimize, which is built on top of scikit-learn. Their statement about GPU support is pretty clear . GPU's also are only good at crunching numbers (floating point operations). For hyperopt, we need both number-crunching (find next parameters) and running python code (running backtesting). As such, GPU's are not too well suited for most parts of hyperopt. The benefit of using GPU would therefore be pretty slim - and will not justify the complexity introduced by trying to add GPU support. There is however nothing preventing you from using GPU-enabled indicators within your strategy if you think you must have this - you will however probably be disappointed by the slim gain that will give you (compared to the complexity).","title":"Why does freqtrade not have GPU support?"},{"location":"faq/#hyperopt-module","text":"","title":"Hyperopt module"},{"location":"faq/#how-many-epochs-do-i-need-to-get-a-good-hyperopt-result","text":"Per default Hyperopt called without the -e / --epochs command line option will only run 100 epochs, means 100 evaluations of your triggers, guards, ... Too few to find a great result (unless if you are very lucky), so you probably have to run it for 10.000 or more. But it will take an eternity to compute. Since hyperopt uses Bayesian search, running for too many epochs may not produce greater results. It's therefore recommended to run between 500-1000 epochs over and over until you hit at least 10.000 epochs in total (or are satisfied with the result). You can best judge by looking at the results - if the bot keeps discovering better strategies, it's best to keep on going. bash freqtrade hyperopt --hyperopt SampleHyperopt --hyperopt-loss SharpeHyperOptLossDaily --strategy SampleStrategy -e 1000","title":"How many epochs do I need to get a good Hyperopt result?"},{"location":"faq/#why-does-it-take-a-long-time-to-run-hyperopt","text":"Discovering a great strategy with Hyperopt takes time. Study www.freqtrade.io , the Freqtrade Documentation page, join the Freqtrade discord community . While you patiently wait for the most advanced, free crypto bot in the world, to hand you a possible golden strategy specially designed just for you. If you wonder why it can take from 20 minutes to days to do 1000 epochs here are some answers: This answer was written during the release 0.15.1, when we had: 8 triggers 9 guards: let's say we evaluate even 10 values from each 1 stoploss calculation: let's say we want 10 values from that too to be evaluated The following calculation is still very rough and not very precise but it will give the idea. With only these triggers and guards there is already 8*10^9*10 evaluations. A roughly total of 80 billion evaluations. Did you run 100 000 evaluations? Congrats, you've done roughly 1 / 100 000 th of the search space, assuming that the bot never tests the same parameters more than once. The time it takes to run 1000 hyperopt epochs depends on things like: The available cpu, hard-disk, ram, timeframe, timerange, indicator settings, indicator count, amount of coins that hyperopt test strategies on and the resulting trade count - which can be 650 trades in a year or 10.0000 trades depending if the strategy aims for big profits by trading rarely or for many low profit trades. Example: 4% profit 650 times vs 0,3% profit a trade 10.000 times in a year. If we assume you set the --timerange to 365 days. Example: freqtrade --config config.json --strategy SampleStrategy --hyperopt SampleHyperopt -e 1000 --timerange 20190601-20200601","title":"Why does it take a long time to run hyperopt?"},{"location":"faq/#edge-module","text":"","title":"Edge module"},{"location":"faq/#edge-implements-interesting-approach-for-controlling-position-size-is-there-any-theory-behind-it","text":"The Edge module is mostly a result of brainstorming of @mishaker and @creslinux freqtrade team members. You can find further info on expectancy, win rate, risk management and position size in the following sources: https://www.tradeciety.com/ultimate-math-guide-for-traders/ http://www.vantharp.com/tharp-concepts/expectancy.asp https://samuraitradingacademy.com/trading-expectancy/ https://www.learningmarkets.com/determining-expectancy-in-your-trading/ http://www.lonestocktrader.com/make-money-trading-positive-expectancy/ https://www.babypips.com/trading/trade-expectancy-matter","title":"Edge implements interesting approach for controlling position size, is there any theory behind it?"},{"location":"hyperopt/","text":"Hyperopt \u00b6 This page explains how to tune your strategy by finding the optimal parameters, a process called hyperparameter optimization. The bot uses algorithms included in the scikit-optimize package to accomplish this. The search will burn all your CPU cores, make your laptop sound like a fighter jet and still take a long time. In general, the search for best parameters starts with a few random combinations (see below for more details) and then uses Bayesian search with a ML regressor algorithm (currently ExtraTreesRegressor) to quickly find a combination of parameters in the search hyperspace that minimizes the value of the loss function . Hyperopt requires historic data to be available, just as backtesting does (hyperopt runs backtesting many times with different parameters). To learn how to get data for the pairs and exchange you're interested in, head over to the Data Downloading section of the documentation. Bug Hyperopt can crash when used with only 1 CPU Core as found out in Issue #1133 Note Since 2021.4 release you no longer have to write a separate hyperopt class, but can configure the parameters directly in the strategy. The legacy method is still supported, but it is no longer the recommended way of setting up hyperopt. The legacy documentation is available at Legacy Hyperopt . Install hyperopt dependencies \u00b6 Since Hyperopt dependencies are not needed to run the bot itself, are heavy, can not be easily built on some platforms (like Raspberry PI), they are not installed by default. Before you run Hyperopt, you need to install the corresponding dependencies, as described in this section below. Note Since Hyperopt is a resource intensive process, running it on a Raspberry Pi is not recommended nor supported. Docker \u00b6 The docker-image includes hyperopt dependencies, no further action needed. Easy installation script (setup.sh) / Manual installation \u00b6 bash source .env/bin/activate pip install -r requirements-hyperopt.txt Hyperopt command reference \u00b6 ``` usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-s NAME] [--strategy-path PATH] [-i TIMEFRAME] [--timerange TIMERANGE] [--data-format-ohlcv {json,jsongz,hdf5}] [--max-open-trades INT] [--stake-amount STAKE_AMOUNT] [--fee FLOAT] [-p PAIRS [PAIRS ...]] [--hyperopt NAME] [--hyperopt-path PATH] [--eps] [--dmmp] [--enable-protections] [--dry-run-wallet DRY_RUN_WALLET] [-e INT] [--spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...]] [--print-all] [--no-color] [--print-json] [-j JOBS] [--random-state INT] [--min-trades INT] [--hyperopt-loss NAME] [--disable-param-export] optional arguments: -h, --help show this help message and exit -i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME Specify timeframe ( 1m , 5m , 30m , 1h , 1d ). --timerange TIMERANGE Specify what timerange of data to use. --data-format-ohlcv {json,jsongz,hdf5} Storage format for downloaded candle (OHLCV) data. (default: None ). --max-open-trades INT Override the value of the max_open_trades configuration setting. --stake-amount STAKE_AMOUNT Override the value of the stake_amount configuration setting. --fee FLOAT Specify fee ratio. Will be applied twice (on trade entry and exit). -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] Limit command to these pairs. Pairs are space- separated. --hyperopt NAME Specify hyperopt class name which will be used by the bot. --hyperopt-path PATH Specify additional lookup path for Hyperopt and Hyperopt Loss functions. --eps, --enable-position-stacking Allow buying the same pair multiple times (position stacking). --dmmp, --disable-max-market-positions Disable applying max_open_trades during backtest (same as setting max_open_trades to a very high number). --enable-protections, --enableprotections Enable protections for backtesting.Will slow backtesting down by a considerable amount, but will include configured protections --dry-run-wallet DRY_RUN_WALLET, --starting-balance DRY_RUN_WALLET Starting balance, used for backtesting / hyperopt and dry-runs. -e INT, --epochs INT Specify number of epochs (default: 100). --spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...] Specify which parameters to hyperopt. Space-separated list. --print-all Print all results, not only the best ones. --no-color Disable colorization of hyperopt results. May be useful if you are redirecting output to a file. --print-json Print output in JSON format. -j JOBS, --job-workers JOBS The number of concurrently running jobs for hyperoptimization (hyperopt worker processes). If -1 (default), all CPUs are used, for -2, all CPUs but one are used, etc. If 1 is given, no parallel computing code is used at all. --random-state INT Set random state to some positive integer for reproducible hyperopt results. --min-trades INT Set minimal desired number of trades for evaluations in the hyperopt optimization path (default: 1). --hyperopt-loss NAME, --hyperoptloss NAME Specify the class name of the hyperopt loss function class (IHyperOptLoss). Different functions can generate completely different results, since the target for optimization is different. Built-in Hyperopt-loss-functions are: ShortTradeDurHyperOptLoss, OnlyProfitHyperOptLoss, SharpeHyperOptLoss, SharpeHyperOptLossDaily, SortinoHyperOptLoss, SortinoHyperOptLossDaily --disable-param-export Disable automatic hyperopt parameter export. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. Strategy arguments: -s NAME, --strategy NAME Specify strategy class name which will be used by the bot. --strategy-path PATH Specify additional strategy lookup path. ``` Hyperopt checklist \u00b6 Checklist on all tasks / possibilities in hyperopt Depending on the space you want to optimize, only some of the below are required: define parameters with space='buy' - for buy signal optimization define parameters with space='sell' - for sell signal optimization Note populate_indicators needs to create all indicators any of the spaces may use, otherwise hyperopt will not work. Rarely you may also need to create a nested class named HyperOpt and implement roi_space - for custom ROI optimization (if you need the ranges for the ROI parameters in the optimization hyperspace that differ from default) generate_roi_table - for custom ROI optimization (if you need the ranges for the values in the ROI table that differ from default or the number of entries (steps) in the ROI table which differs from the default 4 steps) stoploss_space - for custom stoploss optimization (if you need the range for the stoploss parameter in the optimization hyperspace that differs from default) trailing_space - for custom trailing stop optimization (if you need the ranges for the trailing stop parameters in the optimization hyperspace that differ from default) Quickly optimize ROI, stoploss and trailing stoploss You can quickly optimize the spaces roi , stoploss and trailing without changing anything in your strategy. ``` bash Have a working strategy at hand. \u00b6 freqtrade hyperopt --hyperopt-loss SharpeHyperOptLossDaily --spaces roi stoploss trailing --strategy MyWorkingStrategy --config config.json -e 100 ``` Hyperopt execution logic \u00b6 Hyperopt will first load your data into memory and will then run populate_indicators() once per Pair to generate all indicators. Hyperopt will then spawn into different processes (number of processors, or -j ), and run backtesting over and over again, changing the parameters that are part of the --spaces defined. For every new set of parameters, freqtrade will run first populate_buy_trend() followed by populate_sell_trend() , and then run the regular backtesting process to simulate trades. After backtesting, the results are passed into the loss function , which will evaluate if this result was better or worse than previous results. Based on the loss function result, hyperopt will determine the next set of parameters to try in the next round of backtesting. Configure your Guards and Triggers \u00b6 There are two places you need to change in your strategy file to add a new buy hyperopt for testing: Define the parameters at the class level hyperopt shall be optimizing. Within populate_buy_trend() - use defined parameter values instead of raw constants. There you have two different types of indicators: 1. guards and 2. triggers . Guards are conditions like \"never buy if ADX < 10\", or never buy if current price is over EMA10. Triggers are ones that actually trigger buy in specific moment, like \"buy when EMA5 crosses over EMA10\" or \"buy when close price touches lower Bollinger band\". Guards and Triggers Technically, there is no difference between Guards and Triggers. However, this guide will make this distinction to make it clear that signals should not be \"sticking\". Sticking signals are signals that are active for multiple candles. This can lead into buying a signal late (right before the signal disappears - which means that the chance of success is a lot lower than right at the beginning). Hyper-optimization will, for each epoch round, pick one trigger and possibly multiple guards. Sell optimization \u00b6 Similar to the buy-signal above, sell-signals can also be optimized. Place the corresponding settings into the following methods Define the parameters at the class level hyperopt shall be optimizing, either naming them sell_* , or by explicitly defining space='sell' . Within populate_sell_trend() - use defined parameter values instead of raw constants. The configuration and rules are the same than for buy signals. Solving a Mystery \u00b6 Let's say you are curious: should you use MACD crossings or lower Bollinger Bands to trigger your buys. And you also wonder should you use RSI or ADX to help with those buy decisions. If you decide to use RSI or ADX, which values should I use for them? So let's use hyperparameter optimization to solve this mystery. Defining indicators to be used \u00b6 We start by calculating the indicators our strategy is going to use. ``` python class MyAwesomeStrategy(IStrategy): def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: \"\"\" Generate all indicators used by the strategy \"\"\" dataframe['adx'] = ta.ADX(dataframe) dataframe['rsi'] = ta.RSI(dataframe) macd = ta.MACD(dataframe) dataframe['macd'] = macd['macd'] dataframe['macdsignal'] = macd['macdsignal'] dataframe['macdhist'] = macd['macdhist'] bollinger = ta.BBANDS(dataframe, timeperiod=20, nbdevup=2.0, nbdevdn=2.0) dataframe['bb_lowerband'] = bollinger['lowerband'] dataframe['bb_middleband'] = bollinger['middleband'] dataframe['bb_upperband'] = bollinger['upperband'] return dataframe ``` Hyperoptable parameters \u00b6 We continue to define hyperoptable parameters: python class MyAwesomeStrategy(IStrategy): buy_adx = DecimalParameter(20, 40, decimals=1, default=30.1, space=\"buy\") buy_rsi = IntParameter(20, 40, default=30, space=\"buy\") buy_adx_enabled = CategoricalParameter([True, False], default=True, space=\"buy\") buy_rsi_enabled = CategoricalParameter([True, False], default=False, space=\"buy\") buy_trigger = CategoricalParameter([\"bb_lower\", \"macd_cross_signal\"], default=\"bb_lower\", space=\"buy\") The above definition says: I have five parameters I want to randomly combine to find the best combination. buy_rsi is an integer parameter, which will be tested between 20 and 40. This space has a size of 20. buy_adx is a decimal parameter, which will be evaluated between 20 and 40 with 1 decimal place (so values are 20.1, 20.2, ...). This space has a size of 200. Then we have three category variables. First two are either True or False . We use these to either enable or disable the ADX and RSI guards. The last one we call trigger and use it to decide which buy trigger we want to use. Parameter space assignment Parameters must either be assigned to a variable named buy_* or sell_* - or contain space='buy' | space='sell' to be assigned to a space correctly. If no parameter is available for a space, you'll receive the error that no space was found when running hyperopt. So let's write the buy strategy using these values: ```python def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: conditions = [] # GUARDS AND TRENDS if self.buy_adx_enabled.value: conditions.append(dataframe['adx'] > self.buy_adx.value) if self.buy_rsi_enabled.value: conditions.append(dataframe['rsi'] < self.buy_rsi.value) # TRIGGERS if self.buy_trigger.value == 'bb_lower': conditions.append(dataframe['close'] < dataframe['bb_lowerband']) if self.buy_trigger.value == 'macd_cross_signal': conditions.append(qtpylib.crossed_above( dataframe['macd'], dataframe['macdsignal'] )) # Check that volume is not 0 conditions.append(dataframe['volume'] > 0) if conditions: dataframe.loc[ reduce(lambda x, y: x & y, conditions), 'buy'] = 1 return dataframe ``` Hyperopt will now call populate_buy_trend() many times ( epochs ) with different value combinations. It will use the given historical data and simulate buys based on the buy signals generated with the above function. Based on the results, hyperopt will tell you which parameter combination produced the best results (based on the configured loss function ). Note The above setup expects to find ADX, RSI and Bollinger Bands in the populated indicators. When you want to test an indicator that isn't used by the bot currently, remember to add it to the populate_indicators() method in your strategy or hyperopt file. Parameter types \u00b6 There are four parameter types each suited for different purposes. IntParameter - defines an integral parameter with upper and lower boundaries of search space. DecimalParameter - defines a floating point parameter with a limited number of decimals (default 3). Should be preferred instead of RealParameter in most cases. RealParameter - defines a floating point parameter with upper and lower boundaries and no precision limit. Rarely used as it creates a space with a near infinite number of possibilities. CategoricalParameter - defines a parameter with a predetermined number of choices. Disabling parameter optimization Each parameter takes two boolean parameters: * load - when set to False it will not load values configured in buy_params and sell_params . * optimize - when set to False parameter will not be included in optimization process. Use these parameters to quickly prototype various ideas. Warning Hyperoptable parameters cannot be used in populate_indicators - as hyperopt does not recalculate indicators for each epoch, so the starting value would be used in this case. Optimizing an indicator parameter \u00b6 Assuming you have a simple strategy in mind - a EMA cross strategy (2 Moving averages crossing) - and you'd like to find the ideal parameters for this strategy. ``` python from pandas import DataFrame from functools import reduce import talib.abstract as ta from freqtrade.strategy import IStrategy from freqtrade.strategy import CategoricalParameter, DecimalParameter, IntParameter import freqtrade.vendor.qtpylib.indicators as qtpylib class MyAwesomeStrategy(IStrategy): stoploss = -0.05 timeframe = '15m' # Define the parameter spaces buy_ema_short = IntParameter(3, 50, default=5) buy_ema_long = IntParameter(15, 200, default=50) def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: \"\"\"Generate all indicators used by the strategy\"\"\" # Calculate all ema_short values for val in self.buy_ema_short.range: dataframe[f'ema_short_{val}'] = ta.EMA(dataframe, timeperiod=val) # Calculate all ema_long values for val in self.buy_ema_long.range: dataframe[f'ema_long_{val}'] = ta.EMA(dataframe, timeperiod=val) return dataframe def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: conditions = [] conditions.append(qtpylib.crossed_above( dataframe[f'ema_short_{self.buy_ema_short.value}'], dataframe[f'ema_long_{self.buy_ema_long.value}'] )) # Check that volume is not 0 conditions.append(dataframe['volume'] > 0) if conditions: dataframe.loc[ reduce(lambda x, y: x & y, conditions), 'buy'] = 1 return dataframe def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: conditions = [] conditions.append(qtpylib.crossed_above( dataframe[f'ema_long_{self.buy_ema_long.value}'], dataframe[f'ema_short_{self.buy_ema_short.value}'] )) # Check that volume is not 0 conditions.append(dataframe['volume'] > 0) if conditions: dataframe.loc[ reduce(lambda x, y: x & y, conditions), 'sell'] = 1 return dataframe ``` Breaking it down: Using self.buy_ema_short.range will return a range object containing all entries between the Parameters low and high value. In this case ( IntParameter(3, 50, default=5) ), the loop would run for all numbers between 3 and 50 ( [3, 4, 5, ... 49, 50] ). By using this in a loop, hyperopt will generate 48 new columns ( ['buy_ema_3', 'buy_ema_4', ... , 'buy_ema_50'] ). Hyperopt itself will then use the selected value to create the buy and sell signals While this strategy is most likely too simple to provide consistent profit, it should serve as an example how optimize indicator parameters. Note self.buy_ema_short.range will act differently between hyperopt and other modes. For hyperopt, the above example may generate 48 new columns, however for all other modes (backtesting, dry/live), it will only generate the column for the selected value. You should therefore avoid using the resulting column with explicit values (values other than self.buy_ema_short.value ). Note range property may also be used with DecimalParameter and CategoricalParameter . RealParameter does not provide this property due to infinite search space. Performance tip By doing the calculation of all possible indicators in populate_indicators() , the calculation of the indicator happens only once for every parameter. While this may slow down the hyperopt startup speed, the overall performance will increase as the Hyperopt execution itself may pick the same value for multiple epochs (changing other values). You should however try to use space ranges as small as possible. Every new column will require more memory, and every possibility hyperopt can try will increase the search space. Loss-functions \u00b6 Each hyperparameter tuning requires a target. This is usually defined as a loss function (sometimes also called objective function), which should decrease for more desirable results, and increase for bad results. A loss function must be specified via the --hyperopt-loss argument (or optionally via the configuration under the \"hyperopt_loss\" key). This class should be in its own file within the user_data/hyperopts/ directory. Currently, the following loss functions are builtin: ShortTradeDurHyperOptLoss (default legacy Freqtrade hyperoptimization loss function) - Mostly for short trade duration and avoiding losses. OnlyProfitHyperOptLoss (which takes only amount of profit into consideration) SharpeHyperOptLoss (optimizes Sharpe Ratio calculated on trade returns relative to standard deviation) SharpeHyperOptLossDaily (optimizes Sharpe Ratio calculated on daily trade returns relative to standard deviation) SortinoHyperOptLoss (optimizes Sortino Ratio calculated on trade returns relative to downside standard deviation) SortinoHyperOptLossDaily (optimizes Sortino Ratio calculated on daily trade returns relative to downside standard deviation) Creation of a custom loss function is covered in the Advanced Hyperopt part of the documentation. Execute Hyperopt \u00b6 Once you have updated your hyperopt configuration you can run it. Because hyperopt tries a lot of combinations to find the best parameters it will take time to get a good result. We strongly recommend to use screen or tmux to prevent any connection loss. bash freqtrade hyperopt --config config.json --hyperopt-loss --strategy -e 500 --spaces all The -e option will set how many evaluations hyperopt will do. Since hyperopt uses Bayesian search, running too many epochs at once may not produce greater results. Experience has shown that best results are usually not improving much after 500-1000 epochs. Doing multiple runs (executions) with a few 1000 epochs and different random state will most likely produce different results. The --spaces all option determines that all possible parameters should be optimized. Possibilities are listed below. Note Hyperopt will store hyperopt results with the timestamp of the hyperopt start time. Reading commands ( hyperopt-list , hyperopt-show ) can use --hyperopt-filename to read and display older hyperopt results. You can find a list of filenames with ls -l user_data/hyperopt_results/ . Execute Hyperopt with different historical data source \u00b6 If you would like to hyperopt parameters using an alternate historical data set that you have on-disk, use the --datadir PATH option. By default, hyperopt uses data from directory user_data/data . Running Hyperopt with a smaller test-set \u00b6 Use the --timerange argument to change how much of the test-set you want to use. For example, to use one month of data, pass --timerange 20210101-20210201 (from january 2021 - february 2021) to the hyperopt call. Full command: bash freqtrade hyperopt --hyperopt --strategy --timerange 20210101-20210201 Running Hyperopt with Smaller Search Space \u00b6 Use the --spaces option to limit the search space used by hyperopt. Letting Hyperopt optimize everything is a huuuuge search space. Often it might make more sense to start by just searching for initial buy algorithm. Or maybe you just want to optimize your stoploss or roi table for that awesome new buy strategy you have. Legal values are: all : optimize everything buy : just search for a new buy strategy sell : just search for a new sell strategy roi : just optimize the minimal profit table for your strategy stoploss : search for the best stoploss value trailing : search for the best trailing stop values default : all except trailing space-separated list of any of the above values for example --spaces roi stoploss The default Hyperopt Search Space, used when no --space command line option is specified, does not include the trailing hyperspace. We recommend you to run optimization for the trailing hyperspace separately, when the best parameters for other hyperspaces were found, validated and pasted into your custom strategy. Understand the Hyperopt Result \u00b6 Once Hyperopt is completed you can use the result to update your strategy. Given the following result from hyperopt: ``` Best result: 44/100: 135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722%). Avg duration 180.4 mins. Objective: 1.94367 # Buy hyperspace params: buy_params = { 'buy_adx': 44, 'buy_rsi': 29, 'buy_adx_enabled': False, 'buy_rsi_enabled': True, 'buy_trigger': 'bb_lower' } ``` You should understand this result like: The buy trigger that worked best was bb_lower . You should not use ADX because 'buy_adx_enabled': False . You should consider using the RSI indicator ( 'buy_rsi_enabled': True ) and the best value is 29.0 ( 'buy_rsi': 29.0 ) Automatic parameter application to the strategy \u00b6 When using Hyperoptable parameters, the result of your hyperopt-run will be written to a json file next to your strategy (so for MyAwesomeStrategy.py , the file would be MyAwesomeStrategy.json ). This file is also updated when using the hyperopt-show sub-command, unless --disable-param-export is provided to either of the 2 commands. Your strategy class can also contain these results explicitly. Simply copy hyperopt results block and paste them at class level, replacing old parameters (if any). New parameters will automatically be loaded next time strategy is executed. Transferring your whole hyperopt result to your strategy would then look like: python class MyAwesomeStrategy(IStrategy): # Buy hyperspace params: buy_params = { 'buy_adx': 44, 'buy_rsi': 29, 'buy_adx_enabled': False, 'buy_rsi_enabled': True, 'buy_trigger': 'bb_lower' } Note Values in the configuration file will overwrite Parameter-file level parameters - and both will overwrite parameters within the strategy. The prevalence is therefore: config > parameter file > strategy Understand Hyperopt ROI results \u00b6 If you are optimizing ROI (i.e. if optimization search-space contains 'all', 'default' or 'roi'), your result will look as follows and include a ROI table: ``` Best result: 44/100: 135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722%). Avg duration 180.4 mins. Objective: 1.94367 # ROI table: minimal_roi = { 0: 0.10674, 21: 0.09158, 78: 0.03634, 118: 0 } ``` In order to use this best ROI table found by Hyperopt in backtesting and for live trades/dry-run, copy-paste it as the value of the minimal_roi attribute of your custom strategy: # Minimal ROI designed for the strategy. # This attribute will be overridden if the config file contains \"minimal_roi\" minimal_roi = { 0: 0.10674, 21: 0.09158, 78: 0.03634, 118: 0 } As stated in the comment, you can also use it as the value of the minimal_roi setting in the configuration file. Default ROI Search Space \u00b6 If you are optimizing ROI, Freqtrade creates the 'roi' optimization hyperspace for you -- it's the hyperspace of components for the ROI tables. By default, each ROI table generated by the Freqtrade consists of 4 rows (steps). Hyperopt implements adaptive ranges for ROI tables with ranges for values in the ROI steps that depend on the timeframe used. By default the values vary in the following ranges (for some of the most used timeframes, values are rounded to 3 digits after the decimal point): # step 1m 5m 1h 1d 1 0 0.011...0.119 0 0.03...0.31 0 0.068...0.711 0 0.121...1.258 2 2...8 0.007...0.042 10...40 0.02...0.11 120...480 0.045...0.252 2880...11520 0.081...0.446 3 4...20 0.003...0.015 20...100 0.01...0.04 240...1200 0.022...0.091 5760...28800 0.040...0.162 4 6...44 0.0 30...220 0.0 360...2640 0.0 8640...63360 0.0 These ranges should be sufficient in most cases. The minutes in the steps (ROI dict keys) are scaled linearly depending on the timeframe used. The ROI values in the steps (ROI dict values) are scaled logarithmically depending on the timeframe used. If you have the generate_roi_table() and roi_space() methods in your custom hyperopt file, remove them in order to utilize these adaptive ROI tables and the ROI hyperoptimization space generated by Freqtrade by default. Override the roi_space() method if you need components of the ROI tables to vary in other ranges. Override the generate_roi_table() and roi_space() methods and implement your own custom approach for generation of the ROI tables during hyperoptimization if you need a different structure of the ROI tables or other amount of rows (steps). A sample for these methods can be found in sample_hyperopt_advanced.py . Reduced search space To limit the search space further, Decimals are limited to 3 decimal places (a precision of 0.001). This is usually sufficient, every value more precise than this will usually result in overfitted results. You can however overriding pre-defined spaces to change this to your needs. Understand Hyperopt Stoploss results \u00b6 If you are optimizing stoploss values (i.e. if optimization search-space contains 'all', 'default' or 'stoploss'), your result will look as follows and include stoploss: ``` Best result: 44/100: 135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722%). Avg duration 180.4 mins. Objective: 1.94367 # Buy hyperspace params: buy_params = { 'buy_adx': 44, 'buy_rsi': 29, 'buy_adx_enabled': False, 'buy_rsi_enabled': True, 'buy_trigger': 'bb_lower' } stoploss: -0.27996 ``` In order to use this best stoploss value found by Hyperopt in backtesting and for live trades/dry-run, copy-paste it as the value of the stoploss attribute of your custom strategy: python # Optimal stoploss designed for the strategy # This attribute will be overridden if the config file contains \"stoploss\" stoploss = -0.27996 As stated in the comment, you can also use it as the value of the stoploss setting in the configuration file. Default Stoploss Search Space \u00b6 If you are optimizing stoploss values, Freqtrade creates the 'stoploss' optimization hyperspace for you. By default, the stoploss values in that hyperspace vary in the range -0.35...-0.02, which is sufficient in most cases. If you have the stoploss_space() method in your custom hyperopt file, remove it in order to utilize Stoploss hyperoptimization space generated by Freqtrade by default. Override the stoploss_space() method and define the desired range in it if you need stoploss values to vary in other range during hyperoptimization. A sample for this method can be found in user_data/hyperopts/sample_hyperopt_advanced.py . Reduced search space To limit the search space further, Decimals are limited to 3 decimal places (a precision of 0.001). This is usually sufficient, every value more precise than this will usually result in overfitted results. You can however overriding pre-defined spaces to change this to your needs. Understand Hyperopt Trailing Stop results \u00b6 If you are optimizing trailing stop values (i.e. if optimization search-space contains 'all' or 'trailing'), your result will look as follows and include trailing stop parameters: ``` Best result: 45/100: 606 trades. Avg profit 1.04%. Total profit 0.31555614 BTC ( 630.48%). Avg duration 150.3 mins. Objective: -1.10161 # Trailing stop: trailing_stop = True trailing_stop_positive = 0.02001 trailing_stop_positive_offset = 0.06038 trailing_only_offset_is_reached = True ``` In order to use these best trailing stop parameters found by Hyperopt in backtesting and for live trades/dry-run, copy-paste them as the values of the corresponding attributes of your custom strategy: python # Trailing stop # These attributes will be overridden if the config file contains corresponding values. trailing_stop = True trailing_stop_positive = 0.02001 trailing_stop_positive_offset = 0.06038 trailing_only_offset_is_reached = True As stated in the comment, you can also use it as the values of the corresponding settings in the configuration file. Default Trailing Stop Search Space \u00b6 If you are optimizing trailing stop values, Freqtrade creates the 'trailing' optimization hyperspace for you. By default, the trailing_stop parameter is always set to True in that hyperspace, the value of the trailing_only_offset_is_reached vary between True and False, the values of the trailing_stop_positive and trailing_stop_positive_offset parameters vary in the ranges 0.02...0.35 and 0.01...0.1 correspondingly, which is sufficient in most cases. Override the trailing_space() method and define the desired range in it if you need values of the trailing stop parameters to vary in other ranges during hyperoptimization. A sample for this method can be found in user_data/hyperopts/sample_hyperopt_advanced.py . Reduced search space To limit the search space further, Decimals are limited to 3 decimal places (a precision of 0.001). This is usually sufficient, every value more precise than this will usually result in overfitted results. You can however overriding pre-defined spaces to change this to your needs. Reproducible results \u00b6 The search for optimal parameters starts with a few (currently 30) random combinations in the hyperspace of parameters, random Hyperopt epochs. These random epochs are marked with an asterisk character ( * ) in the first column in the Hyperopt output. The initial state for generation of these random values (random state) is controlled by the value of the --random-state command line option. You can set it to some arbitrary value of your choice to obtain reproducible results. If you have not set this value explicitly in the command line options, Hyperopt seeds the random state with some random value for you. The random state value for each Hyperopt run is shown in the log, so you can copy and paste it into the --random-state command line option to repeat the set of the initial random epochs used. If you have not changed anything in the command line options, configuration, timerange, Strategy and Hyperopt classes, historical data and the Loss Function -- you should obtain same hyper-optimization results with same random state value used. Output formatting \u00b6 By default, hyperopt prints colorized results -- epochs with positive profit are printed in the green color. This highlighting helps you find epochs that can be interesting for later analysis. Epochs with zero total profit or with negative profits (losses) are printed in the normal color. If you do not need colorization of results (for instance, when you are redirecting hyperopt output to a file) you can switch colorization off by specifying the --no-color option in the command line. You can use the --print-all command line option if you would like to see all results in the hyperopt output, not only the best ones. When --print-all is used, current best results are also colorized by default -- they are printed in bold (bright) style. This can also be switched off with the --no-color command line option. Windows and color output Windows does not support color-output natively, therefore it is automatically disabled. To have color-output for hyperopt running under windows, please consider using WSL. Position stacking and disabling max market positions \u00b6 In some situations, you may need to run Hyperopt (and Backtesting) with the --eps / --enable-position-staking and --dmmp / --disable-max-market-positions arguments. By default, hyperopt emulates the behavior of the Freqtrade Live Run/Dry Run, where only one open trade is allowed for every traded pair. The total number of trades open for all pairs is also limited by the max_open_trades setting. During Hyperopt/Backtesting this may lead to some potential trades to be hidden (or masked) by previously open trades. The --eps / --enable-position-stacking argument allows emulation of buying the same pair multiple times, while --dmmp / --disable-max-market-positions disables applying max_open_trades during Hyperopt/Backtesting (which is equal to setting max_open_trades to a very high number). Note Dry/live runs will NOT use position stacking - therefore it does make sense to also validate the strategy without this as it's closer to reality. You can also enable position stacking in the configuration file by explicitly setting \"position_stacking\"=true . Out of Memory errors \u00b6 As hyperopt consumes a lot of memory (the complete data needs to be in memory once per parallel backtesting process), it's likely that you run into \"out of memory\" errors. To combat these, you have multiple options: reduce the amount of pairs reduce the timerange used ( --timerange ) reduce the number of parallel processes ( -j ) Increase the memory of your machine Show details of Hyperopt results \u00b6 After you run Hyperopt for the desired amount of epochs, you can later list all results for analysis, select only best or profitable once, and show the details for any of the epochs previously evaluated. This can be done with the hyperopt-list and hyperopt-show sub-commands. The usage of these sub-commands is described in the Utils chapter. Validate backtesting results \u00b6 Once the optimized strategy has been implemented into your strategy, you should backtest this strategy to make sure everything is working as expected. To achieve same results (number of trades, their durations, profit, etc.) than during Hyperopt, please use same configuration and parameters (timerange, timeframe, ...) used for hyperopt --dmmp / --disable-max-market-positions and --eps / --enable-position-stacking for Backtesting. Should results don't match, please double-check to make sure you transferred all conditions correctly. Pay special care to the stoploss (and trailing stoploss) parameters, as these are often set in configuration files, which override changes to the strategy. You should also carefully review the log of your backtest to ensure that there were no parameters inadvertently set by the configuration (like stoploss or trailing_stop ).","title":"Hyperopt"},{"location":"hyperopt/#hyperopt","text":"This page explains how to tune your strategy by finding the optimal parameters, a process called hyperparameter optimization. The bot uses algorithms included in the scikit-optimize package to accomplish this. The search will burn all your CPU cores, make your laptop sound like a fighter jet and still take a long time. In general, the search for best parameters starts with a few random combinations (see below for more details) and then uses Bayesian search with a ML regressor algorithm (currently ExtraTreesRegressor) to quickly find a combination of parameters in the search hyperspace that minimizes the value of the loss function . Hyperopt requires historic data to be available, just as backtesting does (hyperopt runs backtesting many times with different parameters). To learn how to get data for the pairs and exchange you're interested in, head over to the Data Downloading section of the documentation. Bug Hyperopt can crash when used with only 1 CPU Core as found out in Issue #1133 Note Since 2021.4 release you no longer have to write a separate hyperopt class, but can configure the parameters directly in the strategy. The legacy method is still supported, but it is no longer the recommended way of setting up hyperopt. The legacy documentation is available at Legacy Hyperopt .","title":"Hyperopt"},{"location":"hyperopt/#install-hyperopt-dependencies","text":"Since Hyperopt dependencies are not needed to run the bot itself, are heavy, can not be easily built on some platforms (like Raspberry PI), they are not installed by default. Before you run Hyperopt, you need to install the corresponding dependencies, as described in this section below. Note Since Hyperopt is a resource intensive process, running it on a Raspberry Pi is not recommended nor supported.","title":"Install hyperopt dependencies"},{"location":"hyperopt/#docker","text":"The docker-image includes hyperopt dependencies, no further action needed.","title":"Docker"},{"location":"hyperopt/#easy-installation-script-setupsh-manual-installation","text":"bash source .env/bin/activate pip install -r requirements-hyperopt.txt","title":"Easy installation script (setup.sh) / Manual installation"},{"location":"hyperopt/#hyperopt-command-reference","text":"``` usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-s NAME] [--strategy-path PATH] [-i TIMEFRAME] [--timerange TIMERANGE] [--data-format-ohlcv {json,jsongz,hdf5}] [--max-open-trades INT] [--stake-amount STAKE_AMOUNT] [--fee FLOAT] [-p PAIRS [PAIRS ...]] [--hyperopt NAME] [--hyperopt-path PATH] [--eps] [--dmmp] [--enable-protections] [--dry-run-wallet DRY_RUN_WALLET] [-e INT] [--spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...]] [--print-all] [--no-color] [--print-json] [-j JOBS] [--random-state INT] [--min-trades INT] [--hyperopt-loss NAME] [--disable-param-export] optional arguments: -h, --help show this help message and exit -i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME Specify timeframe ( 1m , 5m , 30m , 1h , 1d ). --timerange TIMERANGE Specify what timerange of data to use. --data-format-ohlcv {json,jsongz,hdf5} Storage format for downloaded candle (OHLCV) data. (default: None ). --max-open-trades INT Override the value of the max_open_trades configuration setting. --stake-amount STAKE_AMOUNT Override the value of the stake_amount configuration setting. --fee FLOAT Specify fee ratio. Will be applied twice (on trade entry and exit). -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] Limit command to these pairs. Pairs are space- separated. --hyperopt NAME Specify hyperopt class name which will be used by the bot. --hyperopt-path PATH Specify additional lookup path for Hyperopt and Hyperopt Loss functions. --eps, --enable-position-stacking Allow buying the same pair multiple times (position stacking). --dmmp, --disable-max-market-positions Disable applying max_open_trades during backtest (same as setting max_open_trades to a very high number). --enable-protections, --enableprotections Enable protections for backtesting.Will slow backtesting down by a considerable amount, but will include configured protections --dry-run-wallet DRY_RUN_WALLET, --starting-balance DRY_RUN_WALLET Starting balance, used for backtesting / hyperopt and dry-runs. -e INT, --epochs INT Specify number of epochs (default: 100). --spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...] Specify which parameters to hyperopt. Space-separated list. --print-all Print all results, not only the best ones. --no-color Disable colorization of hyperopt results. May be useful if you are redirecting output to a file. --print-json Print output in JSON format. -j JOBS, --job-workers JOBS The number of concurrently running jobs for hyperoptimization (hyperopt worker processes). If -1 (default), all CPUs are used, for -2, all CPUs but one are used, etc. If 1 is given, no parallel computing code is used at all. --random-state INT Set random state to some positive integer for reproducible hyperopt results. --min-trades INT Set minimal desired number of trades for evaluations in the hyperopt optimization path (default: 1). --hyperopt-loss NAME, --hyperoptloss NAME Specify the class name of the hyperopt loss function class (IHyperOptLoss). Different functions can generate completely different results, since the target for optimization is different. Built-in Hyperopt-loss-functions are: ShortTradeDurHyperOptLoss, OnlyProfitHyperOptLoss, SharpeHyperOptLoss, SharpeHyperOptLossDaily, SortinoHyperOptLoss, SortinoHyperOptLossDaily --disable-param-export Disable automatic hyperopt parameter export. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. Strategy arguments: -s NAME, --strategy NAME Specify strategy class name which will be used by the bot. --strategy-path PATH Specify additional strategy lookup path. ```","title":"Hyperopt command reference"},{"location":"hyperopt/#hyperopt-checklist","text":"Checklist on all tasks / possibilities in hyperopt Depending on the space you want to optimize, only some of the below are required: define parameters with space='buy' - for buy signal optimization define parameters with space='sell' - for sell signal optimization Note populate_indicators needs to create all indicators any of the spaces may use, otherwise hyperopt will not work. Rarely you may also need to create a nested class named HyperOpt and implement roi_space - for custom ROI optimization (if you need the ranges for the ROI parameters in the optimization hyperspace that differ from default) generate_roi_table - for custom ROI optimization (if you need the ranges for the values in the ROI table that differ from default or the number of entries (steps) in the ROI table which differs from the default 4 steps) stoploss_space - for custom stoploss optimization (if you need the range for the stoploss parameter in the optimization hyperspace that differs from default) trailing_space - for custom trailing stop optimization (if you need the ranges for the trailing stop parameters in the optimization hyperspace that differ from default) Quickly optimize ROI, stoploss and trailing stoploss You can quickly optimize the spaces roi , stoploss and trailing without changing anything in your strategy. ``` bash","title":"Hyperopt checklist"},{"location":"hyperopt/#have-a-working-strategy-at-hand","text":"freqtrade hyperopt --hyperopt-loss SharpeHyperOptLossDaily --spaces roi stoploss trailing --strategy MyWorkingStrategy --config config.json -e 100 ```","title":"Have a working strategy at hand."},{"location":"hyperopt/#hyperopt-execution-logic","text":"Hyperopt will first load your data into memory and will then run populate_indicators() once per Pair to generate all indicators. Hyperopt will then spawn into different processes (number of processors, or -j ), and run backtesting over and over again, changing the parameters that are part of the --spaces defined. For every new set of parameters, freqtrade will run first populate_buy_trend() followed by populate_sell_trend() , and then run the regular backtesting process to simulate trades. After backtesting, the results are passed into the loss function , which will evaluate if this result was better or worse than previous results. Based on the loss function result, hyperopt will determine the next set of parameters to try in the next round of backtesting.","title":"Hyperopt execution logic"},{"location":"hyperopt/#configure-your-guards-and-triggers","text":"There are two places you need to change in your strategy file to add a new buy hyperopt for testing: Define the parameters at the class level hyperopt shall be optimizing. Within populate_buy_trend() - use defined parameter values instead of raw constants. There you have two different types of indicators: 1. guards and 2. triggers . Guards are conditions like \"never buy if ADX < 10\", or never buy if current price is over EMA10. Triggers are ones that actually trigger buy in specific moment, like \"buy when EMA5 crosses over EMA10\" or \"buy when close price touches lower Bollinger band\". Guards and Triggers Technically, there is no difference between Guards and Triggers. However, this guide will make this distinction to make it clear that signals should not be \"sticking\". Sticking signals are signals that are active for multiple candles. This can lead into buying a signal late (right before the signal disappears - which means that the chance of success is a lot lower than right at the beginning). Hyper-optimization will, for each epoch round, pick one trigger and possibly multiple guards.","title":"Configure your Guards and Triggers"},{"location":"hyperopt/#sell-optimization","text":"Similar to the buy-signal above, sell-signals can also be optimized. Place the corresponding settings into the following methods Define the parameters at the class level hyperopt shall be optimizing, either naming them sell_* , or by explicitly defining space='sell' . Within populate_sell_trend() - use defined parameter values instead of raw constants. The configuration and rules are the same than for buy signals.","title":"Sell optimization"},{"location":"hyperopt/#solving-a-mystery","text":"Let's say you are curious: should you use MACD crossings or lower Bollinger Bands to trigger your buys. And you also wonder should you use RSI or ADX to help with those buy decisions. If you decide to use RSI or ADX, which values should I use for them? So let's use hyperparameter optimization to solve this mystery.","title":"Solving a Mystery"},{"location":"hyperopt/#defining-indicators-to-be-used","text":"We start by calculating the indicators our strategy is going to use. ``` python class MyAwesomeStrategy(IStrategy): def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: \"\"\" Generate all indicators used by the strategy \"\"\" dataframe['adx'] = ta.ADX(dataframe) dataframe['rsi'] = ta.RSI(dataframe) macd = ta.MACD(dataframe) dataframe['macd'] = macd['macd'] dataframe['macdsignal'] = macd['macdsignal'] dataframe['macdhist'] = macd['macdhist'] bollinger = ta.BBANDS(dataframe, timeperiod=20, nbdevup=2.0, nbdevdn=2.0) dataframe['bb_lowerband'] = bollinger['lowerband'] dataframe['bb_middleband'] = bollinger['middleband'] dataframe['bb_upperband'] = bollinger['upperband'] return dataframe ```","title":"Defining indicators to be used"},{"location":"hyperopt/#hyperoptable-parameters","text":"We continue to define hyperoptable parameters: python class MyAwesomeStrategy(IStrategy): buy_adx = DecimalParameter(20, 40, decimals=1, default=30.1, space=\"buy\") buy_rsi = IntParameter(20, 40, default=30, space=\"buy\") buy_adx_enabled = CategoricalParameter([True, False], default=True, space=\"buy\") buy_rsi_enabled = CategoricalParameter([True, False], default=False, space=\"buy\") buy_trigger = CategoricalParameter([\"bb_lower\", \"macd_cross_signal\"], default=\"bb_lower\", space=\"buy\") The above definition says: I have five parameters I want to randomly combine to find the best combination. buy_rsi is an integer parameter, which will be tested between 20 and 40. This space has a size of 20. buy_adx is a decimal parameter, which will be evaluated between 20 and 40 with 1 decimal place (so values are 20.1, 20.2, ...). This space has a size of 200. Then we have three category variables. First two are either True or False . We use these to either enable or disable the ADX and RSI guards. The last one we call trigger and use it to decide which buy trigger we want to use. Parameter space assignment Parameters must either be assigned to a variable named buy_* or sell_* - or contain space='buy' | space='sell' to be assigned to a space correctly. If no parameter is available for a space, you'll receive the error that no space was found when running hyperopt. So let's write the buy strategy using these values: ```python def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: conditions = [] # GUARDS AND TRENDS if self.buy_adx_enabled.value: conditions.append(dataframe['adx'] > self.buy_adx.value) if self.buy_rsi_enabled.value: conditions.append(dataframe['rsi'] < self.buy_rsi.value) # TRIGGERS if self.buy_trigger.value == 'bb_lower': conditions.append(dataframe['close'] < dataframe['bb_lowerband']) if self.buy_trigger.value == 'macd_cross_signal': conditions.append(qtpylib.crossed_above( dataframe['macd'], dataframe['macdsignal'] )) # Check that volume is not 0 conditions.append(dataframe['volume'] > 0) if conditions: dataframe.loc[ reduce(lambda x, y: x & y, conditions), 'buy'] = 1 return dataframe ``` Hyperopt will now call populate_buy_trend() many times ( epochs ) with different value combinations. It will use the given historical data and simulate buys based on the buy signals generated with the above function. Based on the results, hyperopt will tell you which parameter combination produced the best results (based on the configured loss function ). Note The above setup expects to find ADX, RSI and Bollinger Bands in the populated indicators. When you want to test an indicator that isn't used by the bot currently, remember to add it to the populate_indicators() method in your strategy or hyperopt file.","title":"Hyperoptable parameters"},{"location":"hyperopt/#parameter-types","text":"There are four parameter types each suited for different purposes. IntParameter - defines an integral parameter with upper and lower boundaries of search space. DecimalParameter - defines a floating point parameter with a limited number of decimals (default 3). Should be preferred instead of RealParameter in most cases. RealParameter - defines a floating point parameter with upper and lower boundaries and no precision limit. Rarely used as it creates a space with a near infinite number of possibilities. CategoricalParameter - defines a parameter with a predetermined number of choices. Disabling parameter optimization Each parameter takes two boolean parameters: * load - when set to False it will not load values configured in buy_params and sell_params . * optimize - when set to False parameter will not be included in optimization process. Use these parameters to quickly prototype various ideas. Warning Hyperoptable parameters cannot be used in populate_indicators - as hyperopt does not recalculate indicators for each epoch, so the starting value would be used in this case.","title":"Parameter types"},{"location":"hyperopt/#optimizing-an-indicator-parameter","text":"Assuming you have a simple strategy in mind - a EMA cross strategy (2 Moving averages crossing) - and you'd like to find the ideal parameters for this strategy. ``` python from pandas import DataFrame from functools import reduce import talib.abstract as ta from freqtrade.strategy import IStrategy from freqtrade.strategy import CategoricalParameter, DecimalParameter, IntParameter import freqtrade.vendor.qtpylib.indicators as qtpylib class MyAwesomeStrategy(IStrategy): stoploss = -0.05 timeframe = '15m' # Define the parameter spaces buy_ema_short = IntParameter(3, 50, default=5) buy_ema_long = IntParameter(15, 200, default=50) def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: \"\"\"Generate all indicators used by the strategy\"\"\" # Calculate all ema_short values for val in self.buy_ema_short.range: dataframe[f'ema_short_{val}'] = ta.EMA(dataframe, timeperiod=val) # Calculate all ema_long values for val in self.buy_ema_long.range: dataframe[f'ema_long_{val}'] = ta.EMA(dataframe, timeperiod=val) return dataframe def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: conditions = [] conditions.append(qtpylib.crossed_above( dataframe[f'ema_short_{self.buy_ema_short.value}'], dataframe[f'ema_long_{self.buy_ema_long.value}'] )) # Check that volume is not 0 conditions.append(dataframe['volume'] > 0) if conditions: dataframe.loc[ reduce(lambda x, y: x & y, conditions), 'buy'] = 1 return dataframe def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: conditions = [] conditions.append(qtpylib.crossed_above( dataframe[f'ema_long_{self.buy_ema_long.value}'], dataframe[f'ema_short_{self.buy_ema_short.value}'] )) # Check that volume is not 0 conditions.append(dataframe['volume'] > 0) if conditions: dataframe.loc[ reduce(lambda x, y: x & y, conditions), 'sell'] = 1 return dataframe ``` Breaking it down: Using self.buy_ema_short.range will return a range object containing all entries between the Parameters low and high value. In this case ( IntParameter(3, 50, default=5) ), the loop would run for all numbers between 3 and 50 ( [3, 4, 5, ... 49, 50] ). By using this in a loop, hyperopt will generate 48 new columns ( ['buy_ema_3', 'buy_ema_4', ... , 'buy_ema_50'] ). Hyperopt itself will then use the selected value to create the buy and sell signals While this strategy is most likely too simple to provide consistent profit, it should serve as an example how optimize indicator parameters. Note self.buy_ema_short.range will act differently between hyperopt and other modes. For hyperopt, the above example may generate 48 new columns, however for all other modes (backtesting, dry/live), it will only generate the column for the selected value. You should therefore avoid using the resulting column with explicit values (values other than self.buy_ema_short.value ). Note range property may also be used with DecimalParameter and CategoricalParameter . RealParameter does not provide this property due to infinite search space. Performance tip By doing the calculation of all possible indicators in populate_indicators() , the calculation of the indicator happens only once for every parameter. While this may slow down the hyperopt startup speed, the overall performance will increase as the Hyperopt execution itself may pick the same value for multiple epochs (changing other values). You should however try to use space ranges as small as possible. Every new column will require more memory, and every possibility hyperopt can try will increase the search space.","title":"Optimizing an indicator parameter"},{"location":"hyperopt/#loss-functions","text":"Each hyperparameter tuning requires a target. This is usually defined as a loss function (sometimes also called objective function), which should decrease for more desirable results, and increase for bad results. A loss function must be specified via the --hyperopt-loss argument (or optionally via the configuration under the \"hyperopt_loss\" key). This class should be in its own file within the user_data/hyperopts/ directory. Currently, the following loss functions are builtin: ShortTradeDurHyperOptLoss (default legacy Freqtrade hyperoptimization loss function) - Mostly for short trade duration and avoiding losses. OnlyProfitHyperOptLoss (which takes only amount of profit into consideration) SharpeHyperOptLoss (optimizes Sharpe Ratio calculated on trade returns relative to standard deviation) SharpeHyperOptLossDaily (optimizes Sharpe Ratio calculated on daily trade returns relative to standard deviation) SortinoHyperOptLoss (optimizes Sortino Ratio calculated on trade returns relative to downside standard deviation) SortinoHyperOptLossDaily (optimizes Sortino Ratio calculated on daily trade returns relative to downside standard deviation) Creation of a custom loss function is covered in the Advanced Hyperopt part of the documentation.","title":"Loss-functions"},{"location":"hyperopt/#execute-hyperopt","text":"Once you have updated your hyperopt configuration you can run it. Because hyperopt tries a lot of combinations to find the best parameters it will take time to get a good result. We strongly recommend to use screen or tmux to prevent any connection loss. bash freqtrade hyperopt --config config.json --hyperopt-loss --strategy -e 500 --spaces all The -e option will set how many evaluations hyperopt will do. Since hyperopt uses Bayesian search, running too many epochs at once may not produce greater results. Experience has shown that best results are usually not improving much after 500-1000 epochs. Doing multiple runs (executions) with a few 1000 epochs and different random state will most likely produce different results. The --spaces all option determines that all possible parameters should be optimized. Possibilities are listed below. Note Hyperopt will store hyperopt results with the timestamp of the hyperopt start time. Reading commands ( hyperopt-list , hyperopt-show ) can use --hyperopt-filename to read and display older hyperopt results. You can find a list of filenames with ls -l user_data/hyperopt_results/ .","title":"Execute Hyperopt"},{"location":"hyperopt/#execute-hyperopt-with-different-historical-data-source","text":"If you would like to hyperopt parameters using an alternate historical data set that you have on-disk, use the --datadir PATH option. By default, hyperopt uses data from directory user_data/data .","title":"Execute Hyperopt with different historical data source"},{"location":"hyperopt/#running-hyperopt-with-a-smaller-test-set","text":"Use the --timerange argument to change how much of the test-set you want to use. For example, to use one month of data, pass --timerange 20210101-20210201 (from january 2021 - february 2021) to the hyperopt call. Full command: bash freqtrade hyperopt --hyperopt --strategy --timerange 20210101-20210201","title":"Running Hyperopt with a smaller test-set"},{"location":"hyperopt/#running-hyperopt-with-smaller-search-space","text":"Use the --spaces option to limit the search space used by hyperopt. Letting Hyperopt optimize everything is a huuuuge search space. Often it might make more sense to start by just searching for initial buy algorithm. Or maybe you just want to optimize your stoploss or roi table for that awesome new buy strategy you have. Legal values are: all : optimize everything buy : just search for a new buy strategy sell : just search for a new sell strategy roi : just optimize the minimal profit table for your strategy stoploss : search for the best stoploss value trailing : search for the best trailing stop values default : all except trailing space-separated list of any of the above values for example --spaces roi stoploss The default Hyperopt Search Space, used when no --space command line option is specified, does not include the trailing hyperspace. We recommend you to run optimization for the trailing hyperspace separately, when the best parameters for other hyperspaces were found, validated and pasted into your custom strategy.","title":"Running Hyperopt with Smaller Search Space"},{"location":"hyperopt/#understand-the-hyperopt-result","text":"Once Hyperopt is completed you can use the result to update your strategy. Given the following result from hyperopt: ``` Best result: 44/100: 135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722%). Avg duration 180.4 mins. Objective: 1.94367 # Buy hyperspace params: buy_params = { 'buy_adx': 44, 'buy_rsi': 29, 'buy_adx_enabled': False, 'buy_rsi_enabled': True, 'buy_trigger': 'bb_lower' } ``` You should understand this result like: The buy trigger that worked best was bb_lower . You should not use ADX because 'buy_adx_enabled': False . You should consider using the RSI indicator ( 'buy_rsi_enabled': True ) and the best value is 29.0 ( 'buy_rsi': 29.0 )","title":"Understand the Hyperopt Result"},{"location":"hyperopt/#automatic-parameter-application-to-the-strategy","text":"When using Hyperoptable parameters, the result of your hyperopt-run will be written to a json file next to your strategy (so for MyAwesomeStrategy.py , the file would be MyAwesomeStrategy.json ). This file is also updated when using the hyperopt-show sub-command, unless --disable-param-export is provided to either of the 2 commands. Your strategy class can also contain these results explicitly. Simply copy hyperopt results block and paste them at class level, replacing old parameters (if any). New parameters will automatically be loaded next time strategy is executed. Transferring your whole hyperopt result to your strategy would then look like: python class MyAwesomeStrategy(IStrategy): # Buy hyperspace params: buy_params = { 'buy_adx': 44, 'buy_rsi': 29, 'buy_adx_enabled': False, 'buy_rsi_enabled': True, 'buy_trigger': 'bb_lower' } Note Values in the configuration file will overwrite Parameter-file level parameters - and both will overwrite parameters within the strategy. The prevalence is therefore: config > parameter file > strategy","title":"Automatic parameter application to the strategy"},{"location":"hyperopt/#understand-hyperopt-roi-results","text":"If you are optimizing ROI (i.e. if optimization search-space contains 'all', 'default' or 'roi'), your result will look as follows and include a ROI table: ``` Best result: 44/100: 135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722%). Avg duration 180.4 mins. Objective: 1.94367 # ROI table: minimal_roi = { 0: 0.10674, 21: 0.09158, 78: 0.03634, 118: 0 } ``` In order to use this best ROI table found by Hyperopt in backtesting and for live trades/dry-run, copy-paste it as the value of the minimal_roi attribute of your custom strategy: # Minimal ROI designed for the strategy. # This attribute will be overridden if the config file contains \"minimal_roi\" minimal_roi = { 0: 0.10674, 21: 0.09158, 78: 0.03634, 118: 0 } As stated in the comment, you can also use it as the value of the minimal_roi setting in the configuration file.","title":"Understand Hyperopt ROI results"},{"location":"hyperopt/#default-roi-search-space","text":"If you are optimizing ROI, Freqtrade creates the 'roi' optimization hyperspace for you -- it's the hyperspace of components for the ROI tables. By default, each ROI table generated by the Freqtrade consists of 4 rows (steps). Hyperopt implements adaptive ranges for ROI tables with ranges for values in the ROI steps that depend on the timeframe used. By default the values vary in the following ranges (for some of the most used timeframes, values are rounded to 3 digits after the decimal point): # step 1m 5m 1h 1d 1 0 0.011...0.119 0 0.03...0.31 0 0.068...0.711 0 0.121...1.258 2 2...8 0.007...0.042 10...40 0.02...0.11 120...480 0.045...0.252 2880...11520 0.081...0.446 3 4...20 0.003...0.015 20...100 0.01...0.04 240...1200 0.022...0.091 5760...28800 0.040...0.162 4 6...44 0.0 30...220 0.0 360...2640 0.0 8640...63360 0.0 These ranges should be sufficient in most cases. The minutes in the steps (ROI dict keys) are scaled linearly depending on the timeframe used. The ROI values in the steps (ROI dict values) are scaled logarithmically depending on the timeframe used. If you have the generate_roi_table() and roi_space() methods in your custom hyperopt file, remove them in order to utilize these adaptive ROI tables and the ROI hyperoptimization space generated by Freqtrade by default. Override the roi_space() method if you need components of the ROI tables to vary in other ranges. Override the generate_roi_table() and roi_space() methods and implement your own custom approach for generation of the ROI tables during hyperoptimization if you need a different structure of the ROI tables or other amount of rows (steps). A sample for these methods can be found in sample_hyperopt_advanced.py . Reduced search space To limit the search space further, Decimals are limited to 3 decimal places (a precision of 0.001). This is usually sufficient, every value more precise than this will usually result in overfitted results. You can however overriding pre-defined spaces to change this to your needs.","title":"Default ROI Search Space"},{"location":"hyperopt/#understand-hyperopt-stoploss-results","text":"If you are optimizing stoploss values (i.e. if optimization search-space contains 'all', 'default' or 'stoploss'), your result will look as follows and include stoploss: ``` Best result: 44/100: 135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722%). Avg duration 180.4 mins. Objective: 1.94367 # Buy hyperspace params: buy_params = { 'buy_adx': 44, 'buy_rsi': 29, 'buy_adx_enabled': False, 'buy_rsi_enabled': True, 'buy_trigger': 'bb_lower' } stoploss: -0.27996 ``` In order to use this best stoploss value found by Hyperopt in backtesting and for live trades/dry-run, copy-paste it as the value of the stoploss attribute of your custom strategy: python # Optimal stoploss designed for the strategy # This attribute will be overridden if the config file contains \"stoploss\" stoploss = -0.27996 As stated in the comment, you can also use it as the value of the stoploss setting in the configuration file.","title":"Understand Hyperopt Stoploss results"},{"location":"hyperopt/#default-stoploss-search-space","text":"If you are optimizing stoploss values, Freqtrade creates the 'stoploss' optimization hyperspace for you. By default, the stoploss values in that hyperspace vary in the range -0.35...-0.02, which is sufficient in most cases. If you have the stoploss_space() method in your custom hyperopt file, remove it in order to utilize Stoploss hyperoptimization space generated by Freqtrade by default. Override the stoploss_space() method and define the desired range in it if you need stoploss values to vary in other range during hyperoptimization. A sample for this method can be found in user_data/hyperopts/sample_hyperopt_advanced.py . Reduced search space To limit the search space further, Decimals are limited to 3 decimal places (a precision of 0.001). This is usually sufficient, every value more precise than this will usually result in overfitted results. You can however overriding pre-defined spaces to change this to your needs.","title":"Default Stoploss Search Space"},{"location":"hyperopt/#understand-hyperopt-trailing-stop-results","text":"If you are optimizing trailing stop values (i.e. if optimization search-space contains 'all' or 'trailing'), your result will look as follows and include trailing stop parameters: ``` Best result: 45/100: 606 trades. Avg profit 1.04%. Total profit 0.31555614 BTC ( 630.48%). Avg duration 150.3 mins. Objective: -1.10161 # Trailing stop: trailing_stop = True trailing_stop_positive = 0.02001 trailing_stop_positive_offset = 0.06038 trailing_only_offset_is_reached = True ``` In order to use these best trailing stop parameters found by Hyperopt in backtesting and for live trades/dry-run, copy-paste them as the values of the corresponding attributes of your custom strategy: python # Trailing stop # These attributes will be overridden if the config file contains corresponding values. trailing_stop = True trailing_stop_positive = 0.02001 trailing_stop_positive_offset = 0.06038 trailing_only_offset_is_reached = True As stated in the comment, you can also use it as the values of the corresponding settings in the configuration file.","title":"Understand Hyperopt Trailing Stop results"},{"location":"hyperopt/#default-trailing-stop-search-space","text":"If you are optimizing trailing stop values, Freqtrade creates the 'trailing' optimization hyperspace for you. By default, the trailing_stop parameter is always set to True in that hyperspace, the value of the trailing_only_offset_is_reached vary between True and False, the values of the trailing_stop_positive and trailing_stop_positive_offset parameters vary in the ranges 0.02...0.35 and 0.01...0.1 correspondingly, which is sufficient in most cases. Override the trailing_space() method and define the desired range in it if you need values of the trailing stop parameters to vary in other ranges during hyperoptimization. A sample for this method can be found in user_data/hyperopts/sample_hyperopt_advanced.py . Reduced search space To limit the search space further, Decimals are limited to 3 decimal places (a precision of 0.001). This is usually sufficient, every value more precise than this will usually result in overfitted results. You can however overriding pre-defined spaces to change this to your needs.","title":"Default Trailing Stop Search Space"},{"location":"hyperopt/#reproducible-results","text":"The search for optimal parameters starts with a few (currently 30) random combinations in the hyperspace of parameters, random Hyperopt epochs. These random epochs are marked with an asterisk character ( * ) in the first column in the Hyperopt output. The initial state for generation of these random values (random state) is controlled by the value of the --random-state command line option. You can set it to some arbitrary value of your choice to obtain reproducible results. If you have not set this value explicitly in the command line options, Hyperopt seeds the random state with some random value for you. The random state value for each Hyperopt run is shown in the log, so you can copy and paste it into the --random-state command line option to repeat the set of the initial random epochs used. If you have not changed anything in the command line options, configuration, timerange, Strategy and Hyperopt classes, historical data and the Loss Function -- you should obtain same hyper-optimization results with same random state value used.","title":"Reproducible results"},{"location":"hyperopt/#output-formatting","text":"By default, hyperopt prints colorized results -- epochs with positive profit are printed in the green color. This highlighting helps you find epochs that can be interesting for later analysis. Epochs with zero total profit or with negative profits (losses) are printed in the normal color. If you do not need colorization of results (for instance, when you are redirecting hyperopt output to a file) you can switch colorization off by specifying the --no-color option in the command line. You can use the --print-all command line option if you would like to see all results in the hyperopt output, not only the best ones. When --print-all is used, current best results are also colorized by default -- they are printed in bold (bright) style. This can also be switched off with the --no-color command line option. Windows and color output Windows does not support color-output natively, therefore it is automatically disabled. To have color-output for hyperopt running under windows, please consider using WSL.","title":"Output formatting"},{"location":"hyperopt/#position-stacking-and-disabling-max-market-positions","text":"In some situations, you may need to run Hyperopt (and Backtesting) with the --eps / --enable-position-staking and --dmmp / --disable-max-market-positions arguments. By default, hyperopt emulates the behavior of the Freqtrade Live Run/Dry Run, where only one open trade is allowed for every traded pair. The total number of trades open for all pairs is also limited by the max_open_trades setting. During Hyperopt/Backtesting this may lead to some potential trades to be hidden (or masked) by previously open trades. The --eps / --enable-position-stacking argument allows emulation of buying the same pair multiple times, while --dmmp / --disable-max-market-positions disables applying max_open_trades during Hyperopt/Backtesting (which is equal to setting max_open_trades to a very high number). Note Dry/live runs will NOT use position stacking - therefore it does make sense to also validate the strategy without this as it's closer to reality. You can also enable position stacking in the configuration file by explicitly setting \"position_stacking\"=true .","title":"Position stacking and disabling max market positions"},{"location":"hyperopt/#out-of-memory-errors","text":"As hyperopt consumes a lot of memory (the complete data needs to be in memory once per parallel backtesting process), it's likely that you run into \"out of memory\" errors. To combat these, you have multiple options: reduce the amount of pairs reduce the timerange used ( --timerange ) reduce the number of parallel processes ( -j ) Increase the memory of your machine","title":"Out of Memory errors"},{"location":"hyperopt/#show-details-of-hyperopt-results","text":"After you run Hyperopt for the desired amount of epochs, you can later list all results for analysis, select only best or profitable once, and show the details for any of the epochs previously evaluated. This can be done with the hyperopt-list and hyperopt-show sub-commands. The usage of these sub-commands is described in the Utils chapter.","title":"Show details of Hyperopt results"},{"location":"hyperopt/#validate-backtesting-results","text":"Once the optimized strategy has been implemented into your strategy, you should backtest this strategy to make sure everything is working as expected. To achieve same results (number of trades, their durations, profit, etc.) than during Hyperopt, please use same configuration and parameters (timerange, timeframe, ...) used for hyperopt --dmmp / --disable-max-market-positions and --eps / --enable-position-stacking for Backtesting. Should results don't match, please double-check to make sure you transferred all conditions correctly. Pay special care to the stoploss (and trailing stoploss) parameters, as these are often set in configuration files, which override changes to the strategy. You should also carefully review the log of your backtest to ensure that there were no parameters inadvertently set by the configuration (like stoploss or trailing_stop ).","title":"Validate backtesting results"},{"location":"installation/","text":"Installation \u00b6 This page explains how to prepare your environment for running the bot. The freqtrade documentation describes various ways to install freqtrade Docker images (separate page) Script Installation Manual Installation Installation with Conda Please consider using the prebuilt docker images to get started quickly while evaluating how freqtrade works. Information \u00b6 For Windows installation, please use the windows installation guide . The easiest way to install and run Freqtrade is to clone the bot Github repository and then run the ./setup.sh script, if it's available for your platform. Version considerations When cloning the repository the default working branch has the name develop . This branch contains all last features (can be considered as relatively stable, thanks to automated tests). The stable branch contains the code of the last release (done usually once per month on an approximately one week old snapshot of the develop branch to prevent packaging bugs, so potentially it's more stable). Note Python3.7 or higher and the corresponding pip are assumed to be available. The install-script will warn you and stop if that's not the case. git is also needed to clone the Freqtrade repository. Also, python headers ( python-dev / python-devel ) must be available for the installation to complete successfully. Up-to-date clock The clock on the system running the bot must be accurate, synchronized to a NTP server frequently enough to avoid problems with communication to the exchanges. Requirements \u00b6 These requirements apply to both Script Installation and Manual Installation . Install guide \u00b6 Python >= 3.7.x pip git virtualenv (Recommended) TA-Lib (install instructions below ) Install code \u00b6 We've included/collected install instructions for Ubuntu, MacOS, and Windows. These are guidelines and your success may vary with other distros. OS Specific steps are listed first, the Common section below is necessary for all systems. Note Python3.7 or higher and the corresponding pip are assumed to be available. Debian/Ubuntu Install necessary dependencies \u00b6 ```bash update repository \u00b6 sudo apt-get update install packages \u00b6 sudo apt install -y python3-pip python3-venv python3-dev python3-pandas git ``` RaspberryPi/Raspbian The following assumes the latest Raspbian Buster lite image . This image comes with python3.7 preinstalled, making it easy to get freqtrade up and running. Tested using a Raspberry Pi 3 with the Raspbian Buster lite image, all updates applied. ```bash sudo apt-get install python3-venv libatlas-base-dev cmake Use pywheels.org to speed up installation \u00b6 sudo echo \"[global]\\nextra-index-url= https://www.piwheels.org/simple \" > tee /etc/pip.conf git clone https://github.com/freqtrade/freqtrade.git cd freqtrade bash setup.sh -i ``` Installation duration Depending on your internet speed and the Raspberry Pi version, installation can take multiple hours to complete. Due to this, we recommend to use the pre-build docker-image for Raspberry, by following the Docker quickstart documentation Note The above does not install hyperopt dependencies. To install these, please use python3 -m pip install -e .[hyperopt] . We do not advise to run hyperopt on a Raspberry Pi, since this is a very resource-heavy operation, which should be done on powerful machine. Freqtrade repository \u00b6 Freqtrade is an open source crypto-currency trading bot, whose code is hosted on github.com ```bash Download develop branch of freqtrade repository \u00b6 git clone https://github.com/freqtrade/freqtrade.git Enter downloaded directory \u00b6 cd freqtrade your choice (1): novice user \u00b6 git checkout stable your choice (2): advanced user \u00b6 git checkout develop ``` (1) This command switches the cloned repository to the use of the stable branch. It's not needed, if you wish to stay on the (2) develop branch. You may later switch between branches at any time with the git checkout stable / git checkout develop commands. Script Installation \u00b6 First of the ways to install Freqtrade, is to use provided the Linux/MacOS ./setup.sh script, which install all dependencies and help you configure the bot. Make sure you fulfill the Requirements and have downloaded the Freqtrade repository . Use /setup.sh -install (Linux/MacOS) \u00b6 If you are on Debian, Ubuntu or MacOS, freqtrade provides the script to install freqtrade. ```bash --install, Install freqtrade from scratch \u00b6 ./setup.sh -i ``` Activate your virtual environment \u00b6 Each time you open a new terminal, you must run source .env/bin/activate to activate your virtual environment. ```bash then activate your .env \u00b6 source ./.env/bin/activate ``` Congratulations \u00b6 You are ready , and run the bot Other options of /setup.sh script \u00b6 You can as well update, configure and reset the codebase of your bot with ./script.sh ```bash --update, Command git pull to update. \u00b6 ./setup.sh -u --reset, Hard reset your develop/stable branch. \u00b6 ./setup.sh -r ``` ``` --install With this option, the script will install the bot and most dependencies: You will need to have git and python3.7+ installed beforehand for this to work. Mandatory software as: ta-lib Setup your virtualenv under .env/ This option is a combination of installation tasks and --reset --update This option will pull the last version of your current branch and update your virtualenv. Run the script with this option periodically to update your bot. --reset This option will hard reset your branch (only if you are on either stable or develop ) and recreate your virtualenv. ``` Manual Installation \u00b6 Make sure you fulfill the Requirements and have downloaded the Freqtrade repository . Install TA-Lib \u00b6 TA-Lib script installation \u00b6 bash sudo ./build_helpers/install_ta-lib.sh Note This will use the ta-lib tar.gz included in this repository. TA-Lib manual installation \u00b6 Official webpage: https://mrjbq7.github.io/ta-lib/install.html ```bash wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz tar xvzf ta-lib-0.4.0-src.tar.gz cd ta-lib sed -i.bak \"s|0.00000001|0.000000000000000001 |g\" src/ta_func/ta_utility.h ./configure --prefix=/usr/local make sudo make install On debian based systems (debian, ubuntu, ...) - updating ldconfig might be necessary. \u00b6 sudo ldconfig cd .. rm -rf ./ta-lib* ``` Setup Python virtual environment (virtualenv) \u00b6 You will run freqtrade in separated virtual environment ```bash create virtualenv in directory /freqtrade/.env \u00b6 python3 -m venv .env run virtualenv \u00b6 source .env/bin/activate ``` Install python dependencies \u00b6 bash python3 -m pip install --upgrade pip python3 -m pip install -e . Congratulations \u00b6 You are ready , and run the bot (Optional) Post-installation Tasks \u00b6 Note If you run the bot on a server, you should consider using Docker or a terminal multiplexer like screen or tmux to avoid that the bot is stopped on logout. On Linux with software suite systemd , as an optional post-installation task, you may wish to setup the bot to run as a systemd service or configure it to send the log messages to the syslog / rsyslog or journald daemons. See Advanced Logging for details. Installation with Conda \u00b6 Freqtrade can also be installed with Miniconda or Anaconda. We recommend using Miniconda as it's installation footprint is smaller. Conda will automatically prepare and manage the extensive library-dependencies of the Freqtrade program. What is Conda? \u00b6 Conda is a package, dependency and environment manager for multiple programming languages: conda docs Installation with conda \u00b6 Install Conda \u00b6 Installing on linux Installing on windows Answer all questions. After installation, it is mandatory to turn your terminal OFF and ON again. Freqtrade download \u00b6 Download and install freqtrade. ```bash download freqtrade \u00b6 git clone https://github.com/freqtrade/freqtrade.git enter downloaded directory 'freqtrade' \u00b6 cd freqtrade ``` Freqtrade install: Conda Environment \u00b6 Prepare conda-freqtrade environment, using file environment.yml , which exist in main freqtrade directory bash conda env create -n freqtrade-conda -f environment.yml Creating Conda Environment The conda command create -n automatically installs all nested dependencies for the selected libraries, general structure of installation command is: ```bash choose your own packages \u00b6 conda env create -n [name of the environment] [python version] [packages] point to file with packages \u00b6 conda env create -n [name of the environment] -f [file] ``` Enter/exit freqtrade-conda environment \u00b6 To check available environments, type bash conda env list Enter installed environment ```bash enter conda environment \u00b6 conda activate freqtrade-conda exit conda environment - don't do it now \u00b6 conda deactivate ``` Install last python dependencies with pip bash python3 -m pip install --upgrade pip python3 -m pip install -e . Congratulations \u00b6 You are ready , and run the bot Important shortcuts \u00b6 ```bash list installed conda environments \u00b6 conda env list activate base environment \u00b6 conda activate activate freqtrade-conda environment \u00b6 conda activate freqtrade-conda deactivate any conda environments \u00b6 conda deactivate ``` Further info on anaconda \u00b6 New heavy packages It may happen that creating a new Conda environment, populated with selected packages at the moment of creation takes less time than installing a large, heavy library or application, into previously set environment. pip install within conda The documentation of conda says that pip should NOT be used within conda, because internal problems can occur. However, they are rare. Anaconda Blogpost Nevertheless, that is why, the conda-forge channel is preferred: more libraries are available (less need for pip ) conda-forge works better with pip the libraries are newer Happy trading! You are ready \u00b6 You've made it this far, so you have successfully installed freqtrade. Initialize the configuration \u00b6 ```bash Step 1 - Initialize user folder \u00b6 freqtrade create-userdir --userdir user_data Step 2 - Create a new configuration file \u00b6 freqtrade new-config --config config.json ``` You are ready to run, read Bot Configuration , remember to start with dry_run: True and verify that everything is working. To learn how to setup your configuration, please refer to the Bot Configuration documentation page. Start the Bot \u00b6 bash freqtrade trade --config config.json --strategy SampleStrategy Warning You should read through the rest of the documentation, backtest the strategy you're going to use, and use dry-run before enabling trading with real money. Troubleshooting \u00b6 Common problem: \"command not found\" \u00b6 If you used (1) Script or (2) Manual installation, you need to run the bot in virtual environment. If you get error as below, make sure venv is active. ```bash if: \u00b6 bash: freqtrade: command not found then activate your .env \u00b6 source ./.env/bin/activate ``` MacOS installation error \u00b6 Newer versions of MacOS may have installation failed with errors like error: command 'g++' failed with exit status 1 . This error will require explicit installation of the SDK Headers, which are not installed by default in this version of MacOS. For MacOS 10.14, this can be accomplished with the below command. bash open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg If this file is inexistent, then you're probably on a different version of MacOS, so you may need to consult the internet for specific resolution details. MacOS installation error with python 3.9 \u00b6 When using python 3.9 on macOS, it's currently necessary to install some os-level modules to allow dependencies to compile. The errors you'll see happen during installation and are related to the installation of tables or blosc . You can install the necessary libraries with the following command: bash brew install hdf5 c-blosc After this, please run the installation (script) again.","title":"Linux/MacOS/Raspberry"},{"location":"installation/#installation","text":"This page explains how to prepare your environment for running the bot. The freqtrade documentation describes various ways to install freqtrade Docker images (separate page) Script Installation Manual Installation Installation with Conda Please consider using the prebuilt docker images to get started quickly while evaluating how freqtrade works.","title":"Installation"},{"location":"installation/#information","text":"For Windows installation, please use the windows installation guide . The easiest way to install and run Freqtrade is to clone the bot Github repository and then run the ./setup.sh script, if it's available for your platform. Version considerations When cloning the repository the default working branch has the name develop . This branch contains all last features (can be considered as relatively stable, thanks to automated tests). The stable branch contains the code of the last release (done usually once per month on an approximately one week old snapshot of the develop branch to prevent packaging bugs, so potentially it's more stable). Note Python3.7 or higher and the corresponding pip are assumed to be available. The install-script will warn you and stop if that's not the case. git is also needed to clone the Freqtrade repository. Also, python headers ( python-dev / python-devel ) must be available for the installation to complete successfully. Up-to-date clock The clock on the system running the bot must be accurate, synchronized to a NTP server frequently enough to avoid problems with communication to the exchanges.","title":"Information"},{"location":"installation/#requirements","text":"These requirements apply to both Script Installation and Manual Installation .","title":"Requirements"},{"location":"installation/#install-guide","text":"Python >= 3.7.x pip git virtualenv (Recommended) TA-Lib (install instructions below )","title":"Install guide"},{"location":"installation/#install-code","text":"We've included/collected install instructions for Ubuntu, MacOS, and Windows. These are guidelines and your success may vary with other distros. OS Specific steps are listed first, the Common section below is necessary for all systems. Note Python3.7 or higher and the corresponding pip are assumed to be available. Debian/Ubuntu","title":"Install code"},{"location":"installation/#install-necessary-dependencies","text":"```bash","title":"Install necessary dependencies"},{"location":"installation/#update-repository","text":"sudo apt-get update","title":"update repository"},{"location":"installation/#install-packages","text":"sudo apt install -y python3-pip python3-venv python3-dev python3-pandas git ``` RaspberryPi/Raspbian The following assumes the latest Raspbian Buster lite image . This image comes with python3.7 preinstalled, making it easy to get freqtrade up and running. Tested using a Raspberry Pi 3 with the Raspbian Buster lite image, all updates applied. ```bash sudo apt-get install python3-venv libatlas-base-dev cmake","title":"install packages"},{"location":"installation/#use-pywheelsorg-to-speed-up-installation","text":"sudo echo \"[global]\\nextra-index-url= https://www.piwheels.org/simple \" > tee /etc/pip.conf git clone https://github.com/freqtrade/freqtrade.git cd freqtrade bash setup.sh -i ``` Installation duration Depending on your internet speed and the Raspberry Pi version, installation can take multiple hours to complete. Due to this, we recommend to use the pre-build docker-image for Raspberry, by following the Docker quickstart documentation Note The above does not install hyperopt dependencies. To install these, please use python3 -m pip install -e .[hyperopt] . We do not advise to run hyperopt on a Raspberry Pi, since this is a very resource-heavy operation, which should be done on powerful machine.","title":"Use pywheels.org to speed up installation"},{"location":"installation/#freqtrade-repository","text":"Freqtrade is an open source crypto-currency trading bot, whose code is hosted on github.com ```bash","title":"Freqtrade repository"},{"location":"installation/#download-develop-branch-of-freqtrade-repository","text":"git clone https://github.com/freqtrade/freqtrade.git","title":"Download develop branch of freqtrade repository"},{"location":"installation/#enter-downloaded-directory","text":"cd freqtrade","title":"Enter downloaded directory"},{"location":"installation/#your-choice-1-novice-user","text":"git checkout stable","title":"your choice (1): novice user"},{"location":"installation/#your-choice-2-advanced-user","text":"git checkout develop ``` (1) This command switches the cloned repository to the use of the stable branch. It's not needed, if you wish to stay on the (2) develop branch. You may later switch between branches at any time with the git checkout stable / git checkout develop commands.","title":"your choice (2): advanced user"},{"location":"installation/#script-installation","text":"First of the ways to install Freqtrade, is to use provided the Linux/MacOS ./setup.sh script, which install all dependencies and help you configure the bot. Make sure you fulfill the Requirements and have downloaded the Freqtrade repository .","title":"Script Installation"},{"location":"installation/#use-setupsh-install-linuxmacos","text":"If you are on Debian, Ubuntu or MacOS, freqtrade provides the script to install freqtrade. ```bash","title":"Use /setup.sh -install (Linux/MacOS)"},{"location":"installation/#-install-install-freqtrade-from-scratch","text":"./setup.sh -i ```","title":"--install, Install freqtrade from scratch"},{"location":"installation/#activate-your-virtual-environment","text":"Each time you open a new terminal, you must run source .env/bin/activate to activate your virtual environment. ```bash","title":"Activate your virtual environment"},{"location":"installation/#then-activate-your-env","text":"source ./.env/bin/activate ```","title":"then activate your .env"},{"location":"installation/#congratulations","text":"You are ready , and run the bot","title":"Congratulations"},{"location":"installation/#other-options-of-setupsh-script","text":"You can as well update, configure and reset the codebase of your bot with ./script.sh ```bash","title":"Other options of /setup.sh script"},{"location":"installation/#-update-command-git-pull-to-update","text":"./setup.sh -u","title":"--update, Command git pull to update."},{"location":"installation/#-reset-hard-reset-your-developstable-branch","text":"./setup.sh -r ``` ``` --install With this option, the script will install the bot and most dependencies: You will need to have git and python3.7+ installed beforehand for this to work. Mandatory software as: ta-lib Setup your virtualenv under .env/ This option is a combination of installation tasks and --reset --update This option will pull the last version of your current branch and update your virtualenv. Run the script with this option periodically to update your bot. --reset This option will hard reset your branch (only if you are on either stable or develop ) and recreate your virtualenv. ```","title":"--reset, Hard reset your develop/stable branch."},{"location":"installation/#manual-installation","text":"Make sure you fulfill the Requirements and have downloaded the Freqtrade repository .","title":"Manual Installation"},{"location":"installation/#install-ta-lib","text":"","title":"Install TA-Lib"},{"location":"installation/#ta-lib-script-installation","text":"bash sudo ./build_helpers/install_ta-lib.sh Note This will use the ta-lib tar.gz included in this repository.","title":"TA-Lib script installation"},{"location":"installation/#ta-lib-manual-installation","text":"Official webpage: https://mrjbq7.github.io/ta-lib/install.html ```bash wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz tar xvzf ta-lib-0.4.0-src.tar.gz cd ta-lib sed -i.bak \"s|0.00000001|0.000000000000000001 |g\" src/ta_func/ta_utility.h ./configure --prefix=/usr/local make sudo make install","title":"TA-Lib manual installation"},{"location":"installation/#on-debian-based-systems-debian-ubuntu-updating-ldconfig-might-be-necessary","text":"sudo ldconfig cd .. rm -rf ./ta-lib* ```","title":"On debian based systems (debian, ubuntu, ...) - updating ldconfig might be necessary."},{"location":"installation/#setup-python-virtual-environment-virtualenv","text":"You will run freqtrade in separated virtual environment ```bash","title":"Setup Python virtual environment (virtualenv)"},{"location":"installation/#create-virtualenv-in-directory-freqtradeenv","text":"python3 -m venv .env","title":"create virtualenv in directory /freqtrade/.env"},{"location":"installation/#run-virtualenv","text":"source .env/bin/activate ```","title":"run virtualenv"},{"location":"installation/#install-python-dependencies","text":"bash python3 -m pip install --upgrade pip python3 -m pip install -e .","title":"Install python dependencies"},{"location":"installation/#congratulations_1","text":"You are ready , and run the bot","title":"Congratulations"},{"location":"installation/#optional-post-installation-tasks","text":"Note If you run the bot on a server, you should consider using Docker or a terminal multiplexer like screen or tmux to avoid that the bot is stopped on logout. On Linux with software suite systemd , as an optional post-installation task, you may wish to setup the bot to run as a systemd service or configure it to send the log messages to the syslog / rsyslog or journald daemons. See Advanced Logging for details.","title":"(Optional) Post-installation Tasks"},{"location":"installation/#installation-with-conda","text":"Freqtrade can also be installed with Miniconda or Anaconda. We recommend using Miniconda as it's installation footprint is smaller. Conda will automatically prepare and manage the extensive library-dependencies of the Freqtrade program.","title":"Installation with Conda"},{"location":"installation/#what-is-conda","text":"Conda is a package, dependency and environment manager for multiple programming languages: conda docs","title":"What is Conda?"},{"location":"installation/#installation-with-conda_1","text":"","title":"Installation with conda"},{"location":"installation/#install-conda","text":"Installing on linux Installing on windows Answer all questions. After installation, it is mandatory to turn your terminal OFF and ON again.","title":"Install Conda"},{"location":"installation/#freqtrade-download","text":"Download and install freqtrade. ```bash","title":"Freqtrade download"},{"location":"installation/#download-freqtrade","text":"git clone https://github.com/freqtrade/freqtrade.git","title":"download freqtrade"},{"location":"installation/#enter-downloaded-directory-freqtrade","text":"cd freqtrade ```","title":"enter downloaded directory 'freqtrade'"},{"location":"installation/#freqtrade-install-conda-environment","text":"Prepare conda-freqtrade environment, using file environment.yml , which exist in main freqtrade directory bash conda env create -n freqtrade-conda -f environment.yml Creating Conda Environment The conda command create -n automatically installs all nested dependencies for the selected libraries, general structure of installation command is: ```bash","title":"Freqtrade install: Conda Environment"},{"location":"installation/#choose-your-own-packages","text":"conda env create -n [name of the environment] [python version] [packages]","title":"choose your own packages"},{"location":"installation/#point-to-file-with-packages","text":"conda env create -n [name of the environment] -f [file] ```","title":"point to file with packages"},{"location":"installation/#enterexit-freqtrade-conda-environment","text":"To check available environments, type bash conda env list Enter installed environment ```bash","title":"Enter/exit freqtrade-conda environment"},{"location":"installation/#enter-conda-environment","text":"conda activate freqtrade-conda","title":"enter conda environment"},{"location":"installation/#exit-conda-environment-dont-do-it-now","text":"conda deactivate ``` Install last python dependencies with pip bash python3 -m pip install --upgrade pip python3 -m pip install -e .","title":"exit conda environment - don't do it now"},{"location":"installation/#congratulations_2","text":"You are ready , and run the bot","title":"Congratulations"},{"location":"installation/#important-shortcuts","text":"```bash","title":"Important shortcuts"},{"location":"installation/#list-installed-conda-environments","text":"conda env list","title":"list installed conda environments"},{"location":"installation/#activate-base-environment","text":"conda activate","title":"activate base environment"},{"location":"installation/#activate-freqtrade-conda-environment","text":"conda activate freqtrade-conda","title":"activate freqtrade-conda environment"},{"location":"installation/#deactivate-any-conda-environments","text":"conda deactivate ```","title":"deactivate any conda environments"},{"location":"installation/#further-info-on-anaconda","text":"New heavy packages It may happen that creating a new Conda environment, populated with selected packages at the moment of creation takes less time than installing a large, heavy library or application, into previously set environment. pip install within conda The documentation of conda says that pip should NOT be used within conda, because internal problems can occur. However, they are rare. Anaconda Blogpost Nevertheless, that is why, the conda-forge channel is preferred: more libraries are available (less need for pip ) conda-forge works better with pip the libraries are newer Happy trading!","title":"Further info on anaconda"},{"location":"installation/#you-are-ready","text":"You've made it this far, so you have successfully installed freqtrade.","title":"You are ready"},{"location":"installation/#initialize-the-configuration","text":"```bash","title":"Initialize the configuration"},{"location":"installation/#step-1-initialize-user-folder","text":"freqtrade create-userdir --userdir user_data","title":"Step 1 - Initialize user folder"},{"location":"installation/#step-2-create-a-new-configuration-file","text":"freqtrade new-config --config config.json ``` You are ready to run, read Bot Configuration , remember to start with dry_run: True and verify that everything is working. To learn how to setup your configuration, please refer to the Bot Configuration documentation page.","title":"Step 2 - Create a new configuration file"},{"location":"installation/#start-the-bot","text":"bash freqtrade trade --config config.json --strategy SampleStrategy Warning You should read through the rest of the documentation, backtest the strategy you're going to use, and use dry-run before enabling trading with real money.","title":"Start the Bot"},{"location":"installation/#troubleshooting","text":"","title":"Troubleshooting"},{"location":"installation/#common-problem-command-not-found","text":"If you used (1) Script or (2) Manual installation, you need to run the bot in virtual environment. If you get error as below, make sure venv is active. ```bash","title":"Common problem: \"command not found\""},{"location":"installation/#if","text":"bash: freqtrade: command not found","title":"if:"},{"location":"installation/#then-activate-your-env_1","text":"source ./.env/bin/activate ```","title":"then activate your .env"},{"location":"installation/#macos-installation-error","text":"Newer versions of MacOS may have installation failed with errors like error: command 'g++' failed with exit status 1 . This error will require explicit installation of the SDK Headers, which are not installed by default in this version of MacOS. For MacOS 10.14, this can be accomplished with the below command. bash open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg If this file is inexistent, then you're probably on a different version of MacOS, so you may need to consult the internet for specific resolution details.","title":"MacOS installation error"},{"location":"installation/#macos-installation-error-with-python-39","text":"When using python 3.9 on macOS, it's currently necessary to install some os-level modules to allow dependencies to compile. The errors you'll see happen during installation and are related to the installation of tables or blosc . You can install the necessary libraries with the following command: bash brew install hdf5 c-blosc After this, please run the installation (script) again.","title":"MacOS installation error with python 3.9"},{"location":"plotting/","text":"Plotting \u00b6 This page explains how to plot prices, indicators and profits. Installation / Setup \u00b6 Plotting modules use the Plotly library. You can install / upgrade this by running the following command: bash pip install -U -r requirements-plot.txt Plot price and indicators \u00b6 The freqtrade plot-dataframe subcommand shows an interactive graph with three subplots: Main plot with candlestics and indicators following price (sma/ema) Volume bars Additional indicators as specified by --indicators2 Possible arguments: ``` usage: freqtrade plot-dataframe [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-s NAME] [--strategy-path PATH] [-p PAIRS [PAIRS ...]] [--indicators1 INDICATORS1 [INDICATORS1 ...]] [--indicators2 INDICATORS2 [INDICATORS2 ...]] [--plot-limit INT] [--db-url PATH] [--trade-source {DB,file}] [--export EXPORT] [--export-filename PATH] [--timerange TIMERANGE] [-i TIMEFRAME] [--no-trades] optional arguments: -h, --help show this help message and exit -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] Limit command to these pairs. Pairs are space- separated. --indicators1 INDICATORS1 [INDICATORS1 ...] Set indicators from your strategy you want in the first row of the graph. Space-separated list. Example: ema3 ema5 . Default: ['sma', 'ema3', 'ema5'] . --indicators2 INDICATORS2 [INDICATORS2 ...] Set indicators from your strategy you want in the third row of the graph. Space-separated list. Example: fastd fastk . Default: ['macd', 'macdsignal'] . --plot-limit INT Specify tick limit for plotting. Notice: too high values cause huge files. Default: 750. --db-url PATH Override trades database URL, this is useful in custom deployments (default: sqlite:///tradesv3.sqlite for Live Run mode, sqlite:///tradesv3.dryrun.sqlite for Dry Run). --trade-source {DB,file} Specify the source for trades (Can be DB or file (backtest file)) Default: file --export EXPORT Export backtest results, argument are: trades. Example: --export=trades --export-filename PATH Save backtest results to the file with this filename. Requires --export to be set as well. Example: --export-filename=user_data/backtest_results/backtest _today.json --timerange TIMERANGE Specify what timerange of data to use. -i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME Specify timeframe ( 1m , 5m , 30m , 1h , 1d ). --no-trades Skip using trades from backtesting file and DB. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. Strategy arguments: -s NAME, --strategy NAME Specify strategy class name which will be used by the bot. --strategy-path PATH Specify additional strategy lookup path. ``` Example: bash freqtrade plot-dataframe -p BTC/ETH The -p/--pairs argument can be used to specify pairs you would like to plot. Note The freqtrade plot-dataframe subcommand generates one plot-file per pair. Specify custom indicators. Use --indicators1 for the main plot and --indicators2 for the subplot below (if values are in a different range than prices). Tip You will almost certainly want to specify a custom strategy! This can be done by adding -s Classname / --strategy ClassName to the command. bash freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH --indicators1 sma ema --indicators2 macd Further usage examples \u00b6 To plot multiple pairs, separate them with a space: bash freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH XRP/ETH To plot a timerange (to zoom in) bash freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH --timerange=20180801-20180805 To plot trades stored in a database use --db-url in combination with --trade-source DB : bash freqtrade plot-dataframe --strategy AwesomeStrategy --db-url sqlite:///tradesv3.dry_run.sqlite -p BTC/ETH --trade-source DB To plot trades from a backtesting result, use --export-filename bash freqtrade plot-dataframe --strategy AwesomeStrategy --export-filename user_data/backtest_results/backtest-result.json -p BTC/ETH Plot dataframe basics \u00b6 The plot-dataframe subcommand requires backtesting data, a strategy and either a backtesting-results file or a database, containing trades corresponding to the strategy. The resulting plot will have the following elements: Green triangles: Buy signals from the strategy. (Note: not every buy signal generates a trade, compare to cyan circles.) Red triangles: Sell signals from the strategy. (Also, not every sell signal terminates a trade, compare to red and green squares.) Cyan circles: Trade entry points. Red squares: Trade exit points for trades with loss or 0% profit. Green squares: Trade exit points for profitable trades. Indicators with values corresponding to the candle scale (e.g. SMA/EMA), as specified with --indicators1 . Volume (bar chart at the bottom of the main chart). Indicators with values in different scales (e.g. MACD, RSI) below the volume bars, as specified with --indicators2 . Bollinger Bands Bollinger bands are automatically added to the plot if the columns bb_lowerband and bb_upperband exist, and are painted as a light blue area spanning from the lower band to the upper band. Advanced plot configuration \u00b6 An advanced plot configuration can be specified in the strategy in the plot_config parameter. Additional features when using plot_config include: Specify colors per indicator Specify additional subplots Specify indicator pairs to fill area in between The sample plot configuration below specifies fixed colors for the indicators. Otherwise, consecutive plots may produce different color schemes each time, making comparisons difficult. It also allows multiple subplots to display both MACD and RSI at the same time. Plot type can be configured using type key. Possible types are: * scatter corresponding to plotly.graph_objects.Scatter class (default). * bar corresponding to plotly.graph_objects.Bar class. Extra parameters to plotly.graph_objects.* constructor can be specified in plotly dict. Sample configuration with inline comments explaining the process: `` python plot_config = { 'main_plot': { # Configuration for main plot indicators. # Specifies ema10 to be red, and ema50` to be a shade of gray 'ema10': {'color': 'red'}, 'ema50': {'color': '#CCCCCC'}, # By omitting color, a random color is selected. 'sar': {}, # fill area between senkou_a and senkou_b 'senkou_a': { 'color': 'green', #optional 'fill_to': 'senkou_b', 'fill_label': 'Ichimoku Cloud', #optional 'fill_color': 'rgba(255,76,46,0.2)', #optional }, # plot senkou_b, too. Not only the area to it. 'senkou_b': {} }, 'subplots': { # Create subplot MACD \"MACD\": { 'macd': {'color': 'blue', 'fill_to': 'macdhist'}, 'macdsignal': {'color': 'orange'}, 'macdhist': {'type': 'bar', 'plotly': {'opacity': 0.9}} }, # Additional subplot RSI \"RSI\": { 'rsi': {'color': 'red'} } } } ``` Note The above configuration assumes that ema10 , ema50 , senkou_a , senkou_b , macd , macdsignal , macdhist and rsi are columns in the DataFrame created by the strategy. Warning plotly arguments are only supported with plotly library and will not work with freq-ui. Plot profit \u00b6 The plot-profit subcommand shows an interactive graph with three plots: Average closing price for all pairs. The summarized profit made by backtesting. Note that this is not the real-world profit, but more of an estimate. Profit for each individual pair. The first graph is good to get a grip of how the overall market progresses. The second graph will show if your algorithm works or doesn't. Perhaps you want an algorithm that steadily makes small profits, or one that acts less often, but makes big swings. This graph will also highlight the start (and end) of the Max drawdown period. The third graph can be useful to spot outliers, events in pairs that cause profit spikes. Possible options for the freqtrade plot-profit subcommand: ``` usage: freqtrade plot-profit [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-s NAME] [--strategy-path PATH] [-p PAIRS [PAIRS ...]] [--timerange TIMERANGE] [--export EXPORT] [--export-filename PATH] [--db-url PATH] [--trade-source {DB,file}] [-i TIMEFRAME] optional arguments: -h, --help show this help message and exit -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] Limit command to these pairs. Pairs are space- separated. --timerange TIMERANGE Specify what timerange of data to use. --export EXPORT Export backtest results, argument are: trades. Example: --export=trades --export-filename PATH Save backtest results to the file with this filename. Requires --export to be set as well. Example: --export-filename=user_data/backtest_results/backtest _today.json --db-url PATH Override trades database URL, this is useful in custom deployments (default: sqlite:///tradesv3.sqlite for Live Run mode, sqlite:///tradesv3.dryrun.sqlite for Dry Run). --trade-source {DB,file} Specify the source for trades (Can be DB or file (backtest file)) Default: file -i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME Specify timeframe ( 1m , 5m , 30m , 1h , 1d ). --auto-open Automatically open generated plot. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. Strategy arguments: -s NAME, --strategy NAME Specify strategy class name which will be used by the bot. --strategy-path PATH Specify additional strategy lookup path. ``` The -p/--pairs argument, can be used to limit the pairs that are considered for this calculation. Examples: Use custom backtest-export file bash freqtrade plot-profit -p LTC/BTC --export-filename user_data/backtest_results/backtest-result.json Use custom database bash freqtrade plot-profit -p LTC/BTC --db-url sqlite:///tradesv3.sqlite --trade-source DB bash freqtrade --datadir user_data/data/binance_save/ plot-profit -p LTC/BTC","title":"Plotting"},{"location":"plotting/#plotting","text":"This page explains how to plot prices, indicators and profits.","title":"Plotting"},{"location":"plotting/#installation-setup","text":"Plotting modules use the Plotly library. You can install / upgrade this by running the following command: bash pip install -U -r requirements-plot.txt","title":"Installation / Setup"},{"location":"plotting/#plot-price-and-indicators","text":"The freqtrade plot-dataframe subcommand shows an interactive graph with three subplots: Main plot with candlestics and indicators following price (sma/ema) Volume bars Additional indicators as specified by --indicators2 Possible arguments: ``` usage: freqtrade plot-dataframe [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-s NAME] [--strategy-path PATH] [-p PAIRS [PAIRS ...]] [--indicators1 INDICATORS1 [INDICATORS1 ...]] [--indicators2 INDICATORS2 [INDICATORS2 ...]] [--plot-limit INT] [--db-url PATH] [--trade-source {DB,file}] [--export EXPORT] [--export-filename PATH] [--timerange TIMERANGE] [-i TIMEFRAME] [--no-trades] optional arguments: -h, --help show this help message and exit -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] Limit command to these pairs. Pairs are space- separated. --indicators1 INDICATORS1 [INDICATORS1 ...] Set indicators from your strategy you want in the first row of the graph. Space-separated list. Example: ema3 ema5 . Default: ['sma', 'ema3', 'ema5'] . --indicators2 INDICATORS2 [INDICATORS2 ...] Set indicators from your strategy you want in the third row of the graph. Space-separated list. Example: fastd fastk . Default: ['macd', 'macdsignal'] . --plot-limit INT Specify tick limit for plotting. Notice: too high values cause huge files. Default: 750. --db-url PATH Override trades database URL, this is useful in custom deployments (default: sqlite:///tradesv3.sqlite for Live Run mode, sqlite:///tradesv3.dryrun.sqlite for Dry Run). --trade-source {DB,file} Specify the source for trades (Can be DB or file (backtest file)) Default: file --export EXPORT Export backtest results, argument are: trades. Example: --export=trades --export-filename PATH Save backtest results to the file with this filename. Requires --export to be set as well. Example: --export-filename=user_data/backtest_results/backtest _today.json --timerange TIMERANGE Specify what timerange of data to use. -i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME Specify timeframe ( 1m , 5m , 30m , 1h , 1d ). --no-trades Skip using trades from backtesting file and DB. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. Strategy arguments: -s NAME, --strategy NAME Specify strategy class name which will be used by the bot. --strategy-path PATH Specify additional strategy lookup path. ``` Example: bash freqtrade plot-dataframe -p BTC/ETH The -p/--pairs argument can be used to specify pairs you would like to plot. Note The freqtrade plot-dataframe subcommand generates one plot-file per pair. Specify custom indicators. Use --indicators1 for the main plot and --indicators2 for the subplot below (if values are in a different range than prices). Tip You will almost certainly want to specify a custom strategy! This can be done by adding -s Classname / --strategy ClassName to the command. bash freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH --indicators1 sma ema --indicators2 macd","title":"Plot price and indicators"},{"location":"plotting/#further-usage-examples","text":"To plot multiple pairs, separate them with a space: bash freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH XRP/ETH To plot a timerange (to zoom in) bash freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH --timerange=20180801-20180805 To plot trades stored in a database use --db-url in combination with --trade-source DB : bash freqtrade plot-dataframe --strategy AwesomeStrategy --db-url sqlite:///tradesv3.dry_run.sqlite -p BTC/ETH --trade-source DB To plot trades from a backtesting result, use --export-filename bash freqtrade plot-dataframe --strategy AwesomeStrategy --export-filename user_data/backtest_results/backtest-result.json -p BTC/ETH","title":"Further usage examples"},{"location":"plotting/#plot-dataframe-basics","text":"The plot-dataframe subcommand requires backtesting data, a strategy and either a backtesting-results file or a database, containing trades corresponding to the strategy. The resulting plot will have the following elements: Green triangles: Buy signals from the strategy. (Note: not every buy signal generates a trade, compare to cyan circles.) Red triangles: Sell signals from the strategy. (Also, not every sell signal terminates a trade, compare to red and green squares.) Cyan circles: Trade entry points. Red squares: Trade exit points for trades with loss or 0% profit. Green squares: Trade exit points for profitable trades. Indicators with values corresponding to the candle scale (e.g. SMA/EMA), as specified with --indicators1 . Volume (bar chart at the bottom of the main chart). Indicators with values in different scales (e.g. MACD, RSI) below the volume bars, as specified with --indicators2 . Bollinger Bands Bollinger bands are automatically added to the plot if the columns bb_lowerband and bb_upperband exist, and are painted as a light blue area spanning from the lower band to the upper band.","title":"Plot dataframe basics"},{"location":"plotting/#advanced-plot-configuration","text":"An advanced plot configuration can be specified in the strategy in the plot_config parameter. Additional features when using plot_config include: Specify colors per indicator Specify additional subplots Specify indicator pairs to fill area in between The sample plot configuration below specifies fixed colors for the indicators. Otherwise, consecutive plots may produce different color schemes each time, making comparisons difficult. It also allows multiple subplots to display both MACD and RSI at the same time. Plot type can be configured using type key. Possible types are: * scatter corresponding to plotly.graph_objects.Scatter class (default). * bar corresponding to plotly.graph_objects.Bar class. Extra parameters to plotly.graph_objects.* constructor can be specified in plotly dict. Sample configuration with inline comments explaining the process: `` python plot_config = { 'main_plot': { # Configuration for main plot indicators. # Specifies ema10 to be red, and ema50` to be a shade of gray 'ema10': {'color': 'red'}, 'ema50': {'color': '#CCCCCC'}, # By omitting color, a random color is selected. 'sar': {}, # fill area between senkou_a and senkou_b 'senkou_a': { 'color': 'green', #optional 'fill_to': 'senkou_b', 'fill_label': 'Ichimoku Cloud', #optional 'fill_color': 'rgba(255,76,46,0.2)', #optional }, # plot senkou_b, too. Not only the area to it. 'senkou_b': {} }, 'subplots': { # Create subplot MACD \"MACD\": { 'macd': {'color': 'blue', 'fill_to': 'macdhist'}, 'macdsignal': {'color': 'orange'}, 'macdhist': {'type': 'bar', 'plotly': {'opacity': 0.9}} }, # Additional subplot RSI \"RSI\": { 'rsi': {'color': 'red'} } } } ``` Note The above configuration assumes that ema10 , ema50 , senkou_a , senkou_b , macd , macdsignal , macdhist and rsi are columns in the DataFrame created by the strategy. Warning plotly arguments are only supported with plotly library and will not work with freq-ui.","title":"Advanced plot configuration"},{"location":"plotting/#plot-profit","text":"The plot-profit subcommand shows an interactive graph with three plots: Average closing price for all pairs. The summarized profit made by backtesting. Note that this is not the real-world profit, but more of an estimate. Profit for each individual pair. The first graph is good to get a grip of how the overall market progresses. The second graph will show if your algorithm works or doesn't. Perhaps you want an algorithm that steadily makes small profits, or one that acts less often, but makes big swings. This graph will also highlight the start (and end) of the Max drawdown period. The third graph can be useful to spot outliers, events in pairs that cause profit spikes. Possible options for the freqtrade plot-profit subcommand: ``` usage: freqtrade plot-profit [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-s NAME] [--strategy-path PATH] [-p PAIRS [PAIRS ...]] [--timerange TIMERANGE] [--export EXPORT] [--export-filename PATH] [--db-url PATH] [--trade-source {DB,file}] [-i TIMEFRAME] optional arguments: -h, --help show this help message and exit -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...] Limit command to these pairs. Pairs are space- separated. --timerange TIMERANGE Specify what timerange of data to use. --export EXPORT Export backtest results, argument are: trades. Example: --export=trades --export-filename PATH Save backtest results to the file with this filename. Requires --export to be set as well. Example: --export-filename=user_data/backtest_results/backtest _today.json --db-url PATH Override trades database URL, this is useful in custom deployments (default: sqlite:///tradesv3.sqlite for Live Run mode, sqlite:///tradesv3.dryrun.sqlite for Dry Run). --trade-source {DB,file} Specify the source for trades (Can be DB or file (backtest file)) Default: file -i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME Specify timeframe ( 1m , 5m , 30m , 1h , 1d ). --auto-open Automatically open generated plot. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. Strategy arguments: -s NAME, --strategy NAME Specify strategy class name which will be used by the bot. --strategy-path PATH Specify additional strategy lookup path. ``` The -p/--pairs argument, can be used to limit the pairs that are considered for this calculation. Examples: Use custom backtest-export file bash freqtrade plot-profit -p LTC/BTC --export-filename user_data/backtest_results/backtest-result.json Use custom database bash freqtrade plot-profit -p LTC/BTC --db-url sqlite:///tradesv3.sqlite --trade-source DB bash freqtrade --datadir user_data/data/binance_save/ plot-profit -p LTC/BTC","title":"Plot profit"},{"location":"plugins/","text":"Plugins \u00b6 Pairlists and Pairlist Handlers \u00b6 Pairlist Handlers define the list of pairs (pairlist) that the bot should trade. They are configured in the pairlists section of the configuration settings. In your configuration, you can use Static Pairlist (defined by the StaticPairList Pairlist Handler) and Dynamic Pairlist (defined by the VolumePairList Pairlist Handler). Additionally, AgeFilter , PrecisionFilter , PriceFilter , ShuffleFilter , SpreadFilter and VolatilityFilter act as Pairlist Filters, removing certain pairs and/or moving their positions in the pairlist. If multiple Pairlist Handlers are used, they are chained and a combination of all Pairlist Handlers forms the resulting pairlist the bot uses for trading and backtesting. Pairlist Handlers are executed in the sequence they are configured. You should always configure either StaticPairList or VolumePairList as the starting Pairlist Handler. Inactive markets are always removed from the resulting pairlist. Explicitly blacklisted pairs (those in the pair_blacklist configuration setting) are also always removed from the resulting pairlist. Pair blacklist \u00b6 The pair blacklist (configured via exchange.pair_blacklist in the configuration) disallows certain pairs from trading. This can be as simple as excluding DOGE/BTC - which will remove exactly this pair. The pair-blacklist does also support wildcards (in regex-style) - so BNB/.* will exclude ALL pairs that start with BNB. You may also use something like .*DOWN/BTC or .*UP/BTC to exclude leveraged tokens (check Pair naming conventions for your exchange!) Available Pairlist Handlers \u00b6 StaticPairList (default, if not configured differently) VolumePairList AgeFilter OffsetFilter PerformanceFilter PrecisionFilter PriceFilter ShuffleFilter SpreadFilter RangeStabilityFilter VolatilityFilter Testing pairlists Pairlist configurations can be quite tricky to get right. Best use the test-pairlist utility sub-command to test your configuration quickly. Static Pair List \u00b6 By default, the StaticPairList method is used, which uses a statically defined pair whitelist from the configuration. The pairlist also supports wildcards (in regex-style) - so .*/BTC will include all pairs with BTC as a stake. It uses configuration from exchange.pair_whitelist and exchange.pair_blacklist . json \"pairlists\": [ {\"method\": \"StaticPairList\"} ], By default, only currently enabled pairs are allowed. To skip pair validation against active markets, set \"allow_inactive\": true within the StaticPairList configuration. This can be useful for backtesting expired pairs (like quarterly spot-markets). This option must be configured along with exchange.skip_pair_validation in the exchange configuration. Volume Pair List \u00b6 VolumePairList employs sorting/filtering of pairs by their trading volume. It selects number_assets top pairs with sorting based on the sort_key (which can only be quoteVolume ). When used in the chain of Pairlist Handlers in a non-leading position (after StaticPairList and other Pairlist Filters), VolumePairList considers outputs of previous Pairlist Handlers, adding its sorting/selection of the pairs by the trading volume. When used on the leading position of the chain of Pairlist Handlers, it does not consider pair_whitelist configuration setting, but selects the top assets from all available markets (with matching stake-currency) on the exchange. The refresh_period setting allows to define the period (in seconds), at which the pairlist will be refreshed. Defaults to 1800s (30 minutes). The pairlist cache ( refresh_period ) on VolumePairList is only applicable to generating pairlists. Filtering instances (not the first position in the list) will not apply any cache and will always use up-to-date data. VolumePairList is per default based on the ticker data from exchange, as reported by the ccxt library: The quoteVolume is the amount of quote (stake) currency traded (bought or sold) in last 24 hours. json \"pairlists\": [ { \"method\": \"VolumePairList\", \"number_assets\": 20, \"sort_key\": \"quoteVolume\", \"refresh_period\": 1800 } ], VolumePairList can also operate in an advanced mode to build volume over a given timerange of specified candle size. It utilizes exchange historical candle data, builds a typical price (calculated by (open+high+low)/3) and multiplies the typical price with every candle's volume. The sum is the quoteVolume over the given range. This allows different scenarios, for a more smoothened volume, when using longer ranges with larger candle sizes, or the opposite when using a short range with small candles. For convenience lookback_days can be specified, which will imply that 1d candles will be used for the lookback. In the example below the pairlist would be created based on the last 7 days: json \"pairlists\": [ { \"method\": \"VolumePairList\", \"number_assets\": 20, \"sort_key\": \"quoteVolume\", \"refresh_period\": 86400, \"lookback_days\": 7 } ], Range look back and refresh period When used in conjunction with lookback_days and lookback_timeframe the refresh_period can not be smaller than the candle size in seconds. As this will result in unnecessary requests to the exchanges API. Performance implications when using lookback range If used in first position in combination with lookback, the computation of the range based volume can be time and resource consuming, as it downloads candles for all tradable pairs. Hence it's highly advised to use the standard approach with VolumeFilter to narrow the pairlist down for further range volume calculation. More sophisticated approach can be used, by using lookback_timeframe for candle size and lookback_period which specifies the amount of candles. This example will build the volume pairs based on a rolling period of 3 days of 1h candles: json \"pairlists\": [ { \"method\": \"VolumePairList\", \"number_assets\": 20, \"sort_key\": \"quoteVolume\", \"refresh_period\": 3600, \"lookback_timeframe\": \"1h\", \"lookback_period\": 72 } ], Note VolumePairList does not support backtesting mode. AgeFilter \u00b6 Removes pairs that have been listed on the exchange for less than min_days_listed days (defaults to 10 ) or more than max_days_listed days (defaults None mean infinity). When pairs are first listed on an exchange they can suffer huge price drops and volatility in the first few days while the pair goes through its price-discovery period. Bots can often be caught out buying before the pair has finished dropping in price. This filter allows freqtrade to ignore pairs until they have been listed for at least min_days_listed days and listed before max_days_listed . OffsetFilter \u00b6 Offsets an incoming pairlist by a given offset value. As an example it can be used in conjunction with VolumeFilter to remove the top X volume pairs. Or to split a larger pairlist on two bot instances. Example to remove the first 10 pairs from the pairlist: json \"pairlists\": [ { \"method\": \"OffsetFilter\", \"offset\": 10 } ], Warning When OffsetFilter is used to split a larger pairlist among multiple bots in combination with VolumeFilter it can not be guaranteed that pairs won't overlap due to slightly different refresh intervals for the VolumeFilter . Note An offset larger then the total length of the incoming pairlist will result in an empty pairlist. PerformanceFilter \u00b6 Sorts pairs by past trade performance, as follows: Positive performance. No closed trades yet. Negative performance. Trade count is used as a tie breaker. Note PerformanceFilter does not support backtesting mode. PrecisionFilter \u00b6 Filters low-value coins which would not allow setting stoplosses. PriceFilter \u00b6 The PriceFilter allows filtering of pairs by price. Currently the following price filters are supported: min_price max_price max_value low_price_ratio The min_price setting removes pairs where the price is below the specified price. This is useful if you wish to avoid trading very low-priced pairs. This option is disabled by default, and will only apply if set to > 0. The max_price setting removes pairs where the price is above the specified price. This is useful if you wish to trade only low-priced pairs. This option is disabled by default, and will only apply if set to > 0. The max_value setting removes pairs where the minimum value change is above a specified value. This is useful when an exchange has unbalanced limits. For example, if step-size = 1 (so you can only buy 1, or 2, or 3, but not 1.1 Coins) - and the price is pretty high (like 20$) as the coin has risen sharply since the last limit adaption. As a result of the above, you can only buy for 20$, or 40$ - but not for 25$. On exchanges that deduct fees from the receiving currency (e.g. FTX) - this can result in high value coins / amounts that are unsellable as the amount is slightly below the limit. The low_price_ratio setting removes pairs where a raise of 1 price unit (pip) is above the low_price_ratio ratio. This option is disabled by default, and will only apply if set to > 0. For PriceFiler at least one of its min_price , max_price or low_price_ratio settings must be applied. Calculation example: Min price precision for SHITCOIN/BTC is 8 decimals. If its price is 0.00000011 - one price step above would be 0.00000012, which is ~9% higher than the previous price value. You may filter out this pair by using PriceFilter with low_price_ratio set to 0.09 (9%) or with min_price set to 0.00000011, correspondingly. Low priced pairs Low priced pairs with high \"1 pip movements\" are dangerous since they are often illiquid and it may also be impossible to place the desired stoploss, which can often result in high losses since price needs to be rounded to the next tradable price - so instead of having a stoploss of -5%, you could end up with a stoploss of -9% simply due to price rounding. ShuffleFilter \u00b6 Shuffles (randomizes) pairs in the pairlist. It can be used for preventing the bot from trading some of the pairs more frequently then others when you want all pairs be treated with the same priority. Tip You may set the seed value for this Pairlist to obtain reproducible results, which can be useful for repeated backtesting sessions. If seed is not set, the pairs are shuffled in the non-repeatable random order. SpreadFilter \u00b6 Removes pairs that have a difference between asks and bids above the specified ratio, max_spread_ratio (defaults to 0.005 ). Example: If DOGE/BTC maximum bid is 0.00000026 and minimum ask is 0.00000027, the ratio is calculated as: 1 - bid/ask ~= 0.037 which is > 0.005 and this pair will be filtered out. RangeStabilityFilter \u00b6 Removes pairs where the difference between lowest low and highest high over lookback_days days is below min_rate_of_change . Since this is a filter that requires additional data, the results are cached for refresh_period . In the below example: If the trading range over the last 10 days is <1%, remove the pair from the whitelist. json \"pairlists\": [ { \"method\": \"RangeStabilityFilter\", \"lookback_days\": 10, \"min_rate_of_change\": 0.01, \"refresh_period\": 1440 } ] Tip This Filter can be used to automatically remove stable coin pairs, which have a very low trading range, and are therefore extremely difficult to trade with profit. VolatilityFilter \u00b6 Volatility is the degree of historical variation of a pairs over time, is is measured by the standard deviation of logarithmic daily returns. Returns are assumed to be normally distributed, although actual distribution might be different. In a normal distribution, 68% of observations fall within one standard deviation and 95% of observations fall within two standard deviations. Assuming a volatility of 0.05 means that the expected returns for 20 out of 30 days is expected to be less than 5% (one standard deviation). Volatility is a positive ratio of the expected deviation of return and can be greater than 1.00. Please refer to the wikipedia definition of volatility . This filter removes pairs if the average volatility over a lookback_days days is below min_volatility or above max_volatility . Since this is a filter that requires additional data, the results are cached for refresh_period . This filter can be used to narrow down your pairs to a certain volatility or avoid very volatile pairs. In the below example: If the volatility over the last 10 days is not in the range of 0.05-0.50, remove the pair from the whitelist. The filter is applied every 24h. json \"pairlists\": [ { \"method\": \"VolatilityFilter\", \"lookback_days\": 10, \"min_volatility\": 0.05, \"max_volatility\": 0.50, \"refresh_period\": 86400 } ] Full example of Pairlist Handlers \u00b6 The below example blacklists BNB/BTC , uses VolumePairList with 20 assets, sorting pairs by quoteVolume and applies PrecisionFilter and PriceFilter , filtering all assets where 1 price unit is > 1%. Then the SpreadFilter and VolatilityFilter is applied and pairs are finally shuffled with the random seed set to some predefined value. json \"exchange\": { \"pair_whitelist\": [], \"pair_blacklist\": [\"BNB/BTC\"] }, \"pairlists\": [ { \"method\": \"VolumePairList\", \"number_assets\": 20, \"sort_key\": \"quoteVolume\" }, {\"method\": \"AgeFilter\", \"min_days_listed\": 10}, {\"method\": \"PrecisionFilter\"}, {\"method\": \"PriceFilter\", \"low_price_ratio\": 0.01}, {\"method\": \"SpreadFilter\", \"max_spread_ratio\": 0.005}, { \"method\": \"RangeStabilityFilter\", \"lookback_days\": 10, \"min_rate_of_change\": 0.01, \"refresh_period\": 1440 }, { \"method\": \"VolatilityFilter\", \"lookback_days\": 10, \"min_volatility\": 0.05, \"max_volatility\": 0.50, \"refresh_period\": 86400 }, {\"method\": \"ShuffleFilter\", \"seed\": 42} ], Protections \u00b6 Beta feature This feature is still in it's testing phase. Should you notice something you think is wrong please let us know via Discord or via Github Issue. Protections will protect your strategy from unexpected events and market conditions by temporarily stop trading for either one pair, or for all pairs. All protection end times are rounded up to the next candle to avoid sudden, unexpected intra-candle buys. Note Not all Protections will work for all strategies, and parameters will need to be tuned for your strategy to improve performance. Tip Each Protection can be configured multiple times with different parameters, to allow different levels of protection (short-term / long-term). Backtesting Protections are supported by backtesting and hyperopt, but must be explicitly enabled by using the --enable-protections flag. Available Protections \u00b6 StoplossGuard Stop trading if a certain amount of stoploss occurred within a certain time window. MaxDrawdown Stop trading if max-drawdown is reached. LowProfitPairs Lock pairs with low profits CooldownPeriod Don't enter a trade right after selling a trade. Common settings to all Protections \u00b6 Parameter Description method Protection name to use. Datatype: String, selected from available Protections stop_duration_candles For how many candles should the lock be set? Datatype: Positive integer (in candles) stop_duration how many minutes should protections be locked. Cannot be used together with stop_duration_candles . Datatype: Float (in minutes) lookback_period_candles Only trades that completed within the last lookback_period_candles candles will be considered. This setting may be ignored by some Protections. Datatype: Positive integer (in candles). lookback_period Only trades that completed after current_time - lookback_period will be considered. Cannot be used together with lookback_period_candles . This setting may be ignored by some Protections. Datatype: Float (in minutes) trade_limit Number of trades required at minimum (not used by all Protections). Datatype: Positive integer Durations Durations ( stop_duration* and lookback_period* can be defined in either minutes or candles). For more flexibility when testing different timeframes, all below examples will use the \"candle\" definition. Stoploss Guard \u00b6 StoplossGuard selects all trades within lookback_period in minutes (or in candles when using lookback_period_candles ). If trade_limit or more trades resulted in stoploss, trading will stop for stop_duration in minutes (or in candles when using stop_duration_candles ). This applies across all pairs, unless only_per_pair is set to true, which will then only look at one pair at a time. The below example stops trading for all pairs for 4 candles after the last trade if the bot hit stoploss 4 times within the last 24 candles. python protections = [ { \"method\": \"StoplossGuard\", \"lookback_period_candles\": 24, \"trade_limit\": 4, \"stop_duration_candles\": 4, \"only_per_pair\": False } ] Note StoplossGuard considers all trades with the results \"stop_loss\" , \"stoploss_on_exchange\" and \"trailing_stop_loss\" if the resulting profit was negative. trade_limit and lookback_period will need to be tuned for your strategy. MaxDrawdown \u00b6 MaxDrawdown uses all trades within lookback_period in minutes (or in candles when using lookback_period_candles ) to determine the maximum drawdown. If the drawdown is below max_allowed_drawdown , trading will stop for stop_duration in minutes (or in candles when using stop_duration_candles ) after the last trade - assuming that the bot needs some time to let markets recover. The below sample stops trading for 12 candles if max-drawdown is > 20% considering all pairs - with a minimum of trade_limit trades - within the last 48 candles. If desired, lookback_period and/or stop_duration can be used. python protections = [ { \"method\": \"MaxDrawdown\", \"lookback_period_candles\": 48, \"trade_limit\": 20, \"stop_duration_candles\": 12, \"max_allowed_drawdown\": 0.2 }, ] Low Profit Pairs \u00b6 LowProfitPairs uses all trades for a pair within lookback_period in minutes (or in candles when using lookback_period_candles ) to determine the overall profit ratio. If that ratio is below required_profit , that pair will be locked for stop_duration in minutes (or in candles when using stop_duration_candles ). The below example will stop trading a pair for 60 minutes if the pair does not have a required profit of 2% (and a minimum of 2 trades) within the last 6 candles. python protections = [ { \"method\": \"LowProfitPairs\", \"lookback_period_candles\": 6, \"trade_limit\": 2, \"stop_duration\": 60, \"required_profit\": 0.02 } ] Cooldown Period \u00b6 CooldownPeriod locks a pair for stop_duration in minutes (or in candles when using stop_duration_candles ) after selling, avoiding a re-entry for this pair for stop_duration minutes. The below example will stop trading a pair for 2 candles after closing a trade, allowing this pair to \"cool down\". python protections = [ { \"method\": \"CooldownPeriod\", \"stop_duration_candles\": 2 } ] Note This Protection applies only at pair-level, and will never lock all pairs globally. This Protection does not consider lookback_period as it only looks at the latest trade. Full example of Protections \u00b6 All protections can be combined at will, also with different parameters, creating a increasing wall for under-performing pairs. All protections are evaluated in the sequence they are defined. The below example assumes a timeframe of 1 hour: Locks each pair after selling for an additional 5 candles ( CooldownPeriod ), giving other pairs a chance to get filled. Stops trading for 4 hours ( 4 * 1h candles ) if the last 2 days ( 48 * 1h candles ) had 20 trades, which caused a max-drawdown of more than 20%. ( MaxDrawdown ). Stops trading if more than 4 stoploss occur for all pairs within a 1 day ( 24 * 1h candles ) limit ( StoplossGuard ). Locks all pairs that had 4 Trades within the last 6 hours ( 6 * 1h candles ) with a combined profit ratio of below 0.02 (<2%) ( LowProfitPairs ). Locks all pairs for 2 candles that had a profit of below 0.01 (<1%) within the last 24h ( 24 * 1h candles ), a minimum of 4 trades. ``` python from freqtrade.strategy import IStrategy class AwesomeStrategy(IStrategy) timeframe = '1h' protections = [ { \"method\": \"CooldownPeriod\", \"stop_duration_candles\": 5 }, { \"method\": \"MaxDrawdown\", \"lookback_period_candles\": 48, \"trade_limit\": 20, \"stop_duration_candles\": 4, \"max_allowed_drawdown\": 0.2 }, { \"method\": \"StoplossGuard\", \"lookback_period_candles\": 24, \"trade_limit\": 4, \"stop_duration_candles\": 2, \"only_per_pair\": False }, { \"method\": \"LowProfitPairs\", \"lookback_period_candles\": 6, \"trade_limit\": 2, \"stop_duration_candles\": 60, \"required_profit\": 0.02 }, { \"method\": \"LowProfitPairs\", \"lookback_period_candles\": 24, \"trade_limit\": 4, \"stop_duration_candles\": 2, \"required_profit\": 0.01 } ] # ... ```","title":"Plugins"},{"location":"plugins/#plugins","text":"","title":"Plugins"},{"location":"plugins/#pairlists-and-pairlist-handlers","text":"Pairlist Handlers define the list of pairs (pairlist) that the bot should trade. They are configured in the pairlists section of the configuration settings. In your configuration, you can use Static Pairlist (defined by the StaticPairList Pairlist Handler) and Dynamic Pairlist (defined by the VolumePairList Pairlist Handler). Additionally, AgeFilter , PrecisionFilter , PriceFilter , ShuffleFilter , SpreadFilter and VolatilityFilter act as Pairlist Filters, removing certain pairs and/or moving their positions in the pairlist. If multiple Pairlist Handlers are used, they are chained and a combination of all Pairlist Handlers forms the resulting pairlist the bot uses for trading and backtesting. Pairlist Handlers are executed in the sequence they are configured. You should always configure either StaticPairList or VolumePairList as the starting Pairlist Handler. Inactive markets are always removed from the resulting pairlist. Explicitly blacklisted pairs (those in the pair_blacklist configuration setting) are also always removed from the resulting pairlist.","title":"Pairlists and Pairlist Handlers"},{"location":"plugins/#pair-blacklist","text":"The pair blacklist (configured via exchange.pair_blacklist in the configuration) disallows certain pairs from trading. This can be as simple as excluding DOGE/BTC - which will remove exactly this pair. The pair-blacklist does also support wildcards (in regex-style) - so BNB/.* will exclude ALL pairs that start with BNB. You may also use something like .*DOWN/BTC or .*UP/BTC to exclude leveraged tokens (check Pair naming conventions for your exchange!)","title":"Pair blacklist"},{"location":"plugins/#available-pairlist-handlers","text":"StaticPairList (default, if not configured differently) VolumePairList AgeFilter OffsetFilter PerformanceFilter PrecisionFilter PriceFilter ShuffleFilter SpreadFilter RangeStabilityFilter VolatilityFilter Testing pairlists Pairlist configurations can be quite tricky to get right. Best use the test-pairlist utility sub-command to test your configuration quickly.","title":"Available Pairlist Handlers"},{"location":"plugins/#static-pair-list","text":"By default, the StaticPairList method is used, which uses a statically defined pair whitelist from the configuration. The pairlist also supports wildcards (in regex-style) - so .*/BTC will include all pairs with BTC as a stake. It uses configuration from exchange.pair_whitelist and exchange.pair_blacklist . json \"pairlists\": [ {\"method\": \"StaticPairList\"} ], By default, only currently enabled pairs are allowed. To skip pair validation against active markets, set \"allow_inactive\": true within the StaticPairList configuration. This can be useful for backtesting expired pairs (like quarterly spot-markets). This option must be configured along with exchange.skip_pair_validation in the exchange configuration.","title":"Static Pair List"},{"location":"plugins/#volume-pair-list","text":"VolumePairList employs sorting/filtering of pairs by their trading volume. It selects number_assets top pairs with sorting based on the sort_key (which can only be quoteVolume ). When used in the chain of Pairlist Handlers in a non-leading position (after StaticPairList and other Pairlist Filters), VolumePairList considers outputs of previous Pairlist Handlers, adding its sorting/selection of the pairs by the trading volume. When used on the leading position of the chain of Pairlist Handlers, it does not consider pair_whitelist configuration setting, but selects the top assets from all available markets (with matching stake-currency) on the exchange. The refresh_period setting allows to define the period (in seconds), at which the pairlist will be refreshed. Defaults to 1800s (30 minutes). The pairlist cache ( refresh_period ) on VolumePairList is only applicable to generating pairlists. Filtering instances (not the first position in the list) will not apply any cache and will always use up-to-date data. VolumePairList is per default based on the ticker data from exchange, as reported by the ccxt library: The quoteVolume is the amount of quote (stake) currency traded (bought or sold) in last 24 hours. json \"pairlists\": [ { \"method\": \"VolumePairList\", \"number_assets\": 20, \"sort_key\": \"quoteVolume\", \"refresh_period\": 1800 } ], VolumePairList can also operate in an advanced mode to build volume over a given timerange of specified candle size. It utilizes exchange historical candle data, builds a typical price (calculated by (open+high+low)/3) and multiplies the typical price with every candle's volume. The sum is the quoteVolume over the given range. This allows different scenarios, for a more smoothened volume, when using longer ranges with larger candle sizes, or the opposite when using a short range with small candles. For convenience lookback_days can be specified, which will imply that 1d candles will be used for the lookback. In the example below the pairlist would be created based on the last 7 days: json \"pairlists\": [ { \"method\": \"VolumePairList\", \"number_assets\": 20, \"sort_key\": \"quoteVolume\", \"refresh_period\": 86400, \"lookback_days\": 7 } ], Range look back and refresh period When used in conjunction with lookback_days and lookback_timeframe the refresh_period can not be smaller than the candle size in seconds. As this will result in unnecessary requests to the exchanges API. Performance implications when using lookback range If used in first position in combination with lookback, the computation of the range based volume can be time and resource consuming, as it downloads candles for all tradable pairs. Hence it's highly advised to use the standard approach with VolumeFilter to narrow the pairlist down for further range volume calculation. More sophisticated approach can be used, by using lookback_timeframe for candle size and lookback_period which specifies the amount of candles. This example will build the volume pairs based on a rolling period of 3 days of 1h candles: json \"pairlists\": [ { \"method\": \"VolumePairList\", \"number_assets\": 20, \"sort_key\": \"quoteVolume\", \"refresh_period\": 3600, \"lookback_timeframe\": \"1h\", \"lookback_period\": 72 } ], Note VolumePairList does not support backtesting mode.","title":"Volume Pair List"},{"location":"plugins/#agefilter","text":"Removes pairs that have been listed on the exchange for less than min_days_listed days (defaults to 10 ) or more than max_days_listed days (defaults None mean infinity). When pairs are first listed on an exchange they can suffer huge price drops and volatility in the first few days while the pair goes through its price-discovery period. Bots can often be caught out buying before the pair has finished dropping in price. This filter allows freqtrade to ignore pairs until they have been listed for at least min_days_listed days and listed before max_days_listed .","title":"AgeFilter"},{"location":"plugins/#offsetfilter","text":"Offsets an incoming pairlist by a given offset value. As an example it can be used in conjunction with VolumeFilter to remove the top X volume pairs. Or to split a larger pairlist on two bot instances. Example to remove the first 10 pairs from the pairlist: json \"pairlists\": [ { \"method\": \"OffsetFilter\", \"offset\": 10 } ], Warning When OffsetFilter is used to split a larger pairlist among multiple bots in combination with VolumeFilter it can not be guaranteed that pairs won't overlap due to slightly different refresh intervals for the VolumeFilter . Note An offset larger then the total length of the incoming pairlist will result in an empty pairlist.","title":"OffsetFilter"},{"location":"plugins/#performancefilter","text":"Sorts pairs by past trade performance, as follows: Positive performance. No closed trades yet. Negative performance. Trade count is used as a tie breaker. Note PerformanceFilter does not support backtesting mode.","title":"PerformanceFilter"},{"location":"plugins/#precisionfilter","text":"Filters low-value coins which would not allow setting stoplosses.","title":"PrecisionFilter"},{"location":"plugins/#pricefilter","text":"The PriceFilter allows filtering of pairs by price. Currently the following price filters are supported: min_price max_price max_value low_price_ratio The min_price setting removes pairs where the price is below the specified price. This is useful if you wish to avoid trading very low-priced pairs. This option is disabled by default, and will only apply if set to > 0. The max_price setting removes pairs where the price is above the specified price. This is useful if you wish to trade only low-priced pairs. This option is disabled by default, and will only apply if set to > 0. The max_value setting removes pairs where the minimum value change is above a specified value. This is useful when an exchange has unbalanced limits. For example, if step-size = 1 (so you can only buy 1, or 2, or 3, but not 1.1 Coins) - and the price is pretty high (like 20$) as the coin has risen sharply since the last limit adaption. As a result of the above, you can only buy for 20$, or 40$ - but not for 25$. On exchanges that deduct fees from the receiving currency (e.g. FTX) - this can result in high value coins / amounts that are unsellable as the amount is slightly below the limit. The low_price_ratio setting removes pairs where a raise of 1 price unit (pip) is above the low_price_ratio ratio. This option is disabled by default, and will only apply if set to > 0. For PriceFiler at least one of its min_price , max_price or low_price_ratio settings must be applied. Calculation example: Min price precision for SHITCOIN/BTC is 8 decimals. If its price is 0.00000011 - one price step above would be 0.00000012, which is ~9% higher than the previous price value. You may filter out this pair by using PriceFilter with low_price_ratio set to 0.09 (9%) or with min_price set to 0.00000011, correspondingly. Low priced pairs Low priced pairs with high \"1 pip movements\" are dangerous since they are often illiquid and it may also be impossible to place the desired stoploss, which can often result in high losses since price needs to be rounded to the next tradable price - so instead of having a stoploss of -5%, you could end up with a stoploss of -9% simply due to price rounding.","title":"PriceFilter"},{"location":"plugins/#shufflefilter","text":"Shuffles (randomizes) pairs in the pairlist. It can be used for preventing the bot from trading some of the pairs more frequently then others when you want all pairs be treated with the same priority. Tip You may set the seed value for this Pairlist to obtain reproducible results, which can be useful for repeated backtesting sessions. If seed is not set, the pairs are shuffled in the non-repeatable random order.","title":"ShuffleFilter"},{"location":"plugins/#spreadfilter","text":"Removes pairs that have a difference between asks and bids above the specified ratio, max_spread_ratio (defaults to 0.005 ). Example: If DOGE/BTC maximum bid is 0.00000026 and minimum ask is 0.00000027, the ratio is calculated as: 1 - bid/ask ~= 0.037 which is > 0.005 and this pair will be filtered out.","title":"SpreadFilter"},{"location":"plugins/#rangestabilityfilter","text":"Removes pairs where the difference between lowest low and highest high over lookback_days days is below min_rate_of_change . Since this is a filter that requires additional data, the results are cached for refresh_period . In the below example: If the trading range over the last 10 days is <1%, remove the pair from the whitelist. json \"pairlists\": [ { \"method\": \"RangeStabilityFilter\", \"lookback_days\": 10, \"min_rate_of_change\": 0.01, \"refresh_period\": 1440 } ] Tip This Filter can be used to automatically remove stable coin pairs, which have a very low trading range, and are therefore extremely difficult to trade with profit.","title":"RangeStabilityFilter"},{"location":"plugins/#volatilityfilter","text":"Volatility is the degree of historical variation of a pairs over time, is is measured by the standard deviation of logarithmic daily returns. Returns are assumed to be normally distributed, although actual distribution might be different. In a normal distribution, 68% of observations fall within one standard deviation and 95% of observations fall within two standard deviations. Assuming a volatility of 0.05 means that the expected returns for 20 out of 30 days is expected to be less than 5% (one standard deviation). Volatility is a positive ratio of the expected deviation of return and can be greater than 1.00. Please refer to the wikipedia definition of volatility . This filter removes pairs if the average volatility over a lookback_days days is below min_volatility or above max_volatility . Since this is a filter that requires additional data, the results are cached for refresh_period . This filter can be used to narrow down your pairs to a certain volatility or avoid very volatile pairs. In the below example: If the volatility over the last 10 days is not in the range of 0.05-0.50, remove the pair from the whitelist. The filter is applied every 24h. json \"pairlists\": [ { \"method\": \"VolatilityFilter\", \"lookback_days\": 10, \"min_volatility\": 0.05, \"max_volatility\": 0.50, \"refresh_period\": 86400 } ]","title":"VolatilityFilter"},{"location":"plugins/#full-example-of-pairlist-handlers","text":"The below example blacklists BNB/BTC , uses VolumePairList with 20 assets, sorting pairs by quoteVolume and applies PrecisionFilter and PriceFilter , filtering all assets where 1 price unit is > 1%. Then the SpreadFilter and VolatilityFilter is applied and pairs are finally shuffled with the random seed set to some predefined value. json \"exchange\": { \"pair_whitelist\": [], \"pair_blacklist\": [\"BNB/BTC\"] }, \"pairlists\": [ { \"method\": \"VolumePairList\", \"number_assets\": 20, \"sort_key\": \"quoteVolume\" }, {\"method\": \"AgeFilter\", \"min_days_listed\": 10}, {\"method\": \"PrecisionFilter\"}, {\"method\": \"PriceFilter\", \"low_price_ratio\": 0.01}, {\"method\": \"SpreadFilter\", \"max_spread_ratio\": 0.005}, { \"method\": \"RangeStabilityFilter\", \"lookback_days\": 10, \"min_rate_of_change\": 0.01, \"refresh_period\": 1440 }, { \"method\": \"VolatilityFilter\", \"lookback_days\": 10, \"min_volatility\": 0.05, \"max_volatility\": 0.50, \"refresh_period\": 86400 }, {\"method\": \"ShuffleFilter\", \"seed\": 42} ],","title":"Full example of Pairlist Handlers"},{"location":"plugins/#protections","text":"Beta feature This feature is still in it's testing phase. Should you notice something you think is wrong please let us know via Discord or via Github Issue. Protections will protect your strategy from unexpected events and market conditions by temporarily stop trading for either one pair, or for all pairs. All protection end times are rounded up to the next candle to avoid sudden, unexpected intra-candle buys. Note Not all Protections will work for all strategies, and parameters will need to be tuned for your strategy to improve performance. Tip Each Protection can be configured multiple times with different parameters, to allow different levels of protection (short-term / long-term). Backtesting Protections are supported by backtesting and hyperopt, but must be explicitly enabled by using the --enable-protections flag.","title":"Protections"},{"location":"plugins/#available-protections","text":"StoplossGuard Stop trading if a certain amount of stoploss occurred within a certain time window. MaxDrawdown Stop trading if max-drawdown is reached. LowProfitPairs Lock pairs with low profits CooldownPeriod Don't enter a trade right after selling a trade.","title":"Available Protections"},{"location":"plugins/#common-settings-to-all-protections","text":"Parameter Description method Protection name to use. Datatype: String, selected from available Protections stop_duration_candles For how many candles should the lock be set? Datatype: Positive integer (in candles) stop_duration how many minutes should protections be locked. Cannot be used together with stop_duration_candles . Datatype: Float (in minutes) lookback_period_candles Only trades that completed within the last lookback_period_candles candles will be considered. This setting may be ignored by some Protections. Datatype: Positive integer (in candles). lookback_period Only trades that completed after current_time - lookback_period will be considered. Cannot be used together with lookback_period_candles . This setting may be ignored by some Protections. Datatype: Float (in minutes) trade_limit Number of trades required at minimum (not used by all Protections). Datatype: Positive integer Durations Durations ( stop_duration* and lookback_period* can be defined in either minutes or candles). For more flexibility when testing different timeframes, all below examples will use the \"candle\" definition.","title":"Common settings to all Protections"},{"location":"plugins/#stoploss-guard","text":"StoplossGuard selects all trades within lookback_period in minutes (or in candles when using lookback_period_candles ). If trade_limit or more trades resulted in stoploss, trading will stop for stop_duration in minutes (or in candles when using stop_duration_candles ). This applies across all pairs, unless only_per_pair is set to true, which will then only look at one pair at a time. The below example stops trading for all pairs for 4 candles after the last trade if the bot hit stoploss 4 times within the last 24 candles. python protections = [ { \"method\": \"StoplossGuard\", \"lookback_period_candles\": 24, \"trade_limit\": 4, \"stop_duration_candles\": 4, \"only_per_pair\": False } ] Note StoplossGuard considers all trades with the results \"stop_loss\" , \"stoploss_on_exchange\" and \"trailing_stop_loss\" if the resulting profit was negative. trade_limit and lookback_period will need to be tuned for your strategy.","title":"Stoploss Guard"},{"location":"plugins/#maxdrawdown","text":"MaxDrawdown uses all trades within lookback_period in minutes (or in candles when using lookback_period_candles ) to determine the maximum drawdown. If the drawdown is below max_allowed_drawdown , trading will stop for stop_duration in minutes (or in candles when using stop_duration_candles ) after the last trade - assuming that the bot needs some time to let markets recover. The below sample stops trading for 12 candles if max-drawdown is > 20% considering all pairs - with a minimum of trade_limit trades - within the last 48 candles. If desired, lookback_period and/or stop_duration can be used. python protections = [ { \"method\": \"MaxDrawdown\", \"lookback_period_candles\": 48, \"trade_limit\": 20, \"stop_duration_candles\": 12, \"max_allowed_drawdown\": 0.2 }, ]","title":"MaxDrawdown"},{"location":"plugins/#low-profit-pairs","text":"LowProfitPairs uses all trades for a pair within lookback_period in minutes (or in candles when using lookback_period_candles ) to determine the overall profit ratio. If that ratio is below required_profit , that pair will be locked for stop_duration in minutes (or in candles when using stop_duration_candles ). The below example will stop trading a pair for 60 minutes if the pair does not have a required profit of 2% (and a minimum of 2 trades) within the last 6 candles. python protections = [ { \"method\": \"LowProfitPairs\", \"lookback_period_candles\": 6, \"trade_limit\": 2, \"stop_duration\": 60, \"required_profit\": 0.02 } ]","title":"Low Profit Pairs"},{"location":"plugins/#cooldown-period","text":"CooldownPeriod locks a pair for stop_duration in minutes (or in candles when using stop_duration_candles ) after selling, avoiding a re-entry for this pair for stop_duration minutes. The below example will stop trading a pair for 2 candles after closing a trade, allowing this pair to \"cool down\". python protections = [ { \"method\": \"CooldownPeriod\", \"stop_duration_candles\": 2 } ] Note This Protection applies only at pair-level, and will never lock all pairs globally. This Protection does not consider lookback_period as it only looks at the latest trade.","title":"Cooldown Period"},{"location":"plugins/#full-example-of-protections","text":"All protections can be combined at will, also with different parameters, creating a increasing wall for under-performing pairs. All protections are evaluated in the sequence they are defined. The below example assumes a timeframe of 1 hour: Locks each pair after selling for an additional 5 candles ( CooldownPeriod ), giving other pairs a chance to get filled. Stops trading for 4 hours ( 4 * 1h candles ) if the last 2 days ( 48 * 1h candles ) had 20 trades, which caused a max-drawdown of more than 20%. ( MaxDrawdown ). Stops trading if more than 4 stoploss occur for all pairs within a 1 day ( 24 * 1h candles ) limit ( StoplossGuard ). Locks all pairs that had 4 Trades within the last 6 hours ( 6 * 1h candles ) with a combined profit ratio of below 0.02 (<2%) ( LowProfitPairs ). Locks all pairs for 2 candles that had a profit of below 0.01 (<1%) within the last 24h ( 24 * 1h candles ), a minimum of 4 trades. ``` python from freqtrade.strategy import IStrategy class AwesomeStrategy(IStrategy) timeframe = '1h' protections = [ { \"method\": \"CooldownPeriod\", \"stop_duration_candles\": 5 }, { \"method\": \"MaxDrawdown\", \"lookback_period_candles\": 48, \"trade_limit\": 20, \"stop_duration_candles\": 4, \"max_allowed_drawdown\": 0.2 }, { \"method\": \"StoplossGuard\", \"lookback_period_candles\": 24, \"trade_limit\": 4, \"stop_duration_candles\": 2, \"only_per_pair\": False }, { \"method\": \"LowProfitPairs\", \"lookback_period_candles\": 6, \"trade_limit\": 2, \"stop_duration_candles\": 60, \"required_profit\": 0.02 }, { \"method\": \"LowProfitPairs\", \"lookback_period_candles\": 24, \"trade_limit\": 4, \"stop_duration_candles\": 2, \"required_profit\": 0.01 } ] # ... ```","title":"Full example of Protections"},{"location":"rest-api/","text":"REST API & FreqUI \u00b6 FreqUI \u00b6 Freqtrade provides a builtin webserver, which can serve FreqUI , the freqtrade UI. By default, the UI is not included in the installation (except for docker images), and must be installed explicitly with freqtrade install-ui . This same command can also be used to update freqUI, should there be a new release. Once the bot is started in trade / dry-run mode (with freqtrade trade ) - the UI will be available under the configured port below (usually http://127.0.0.1:8080 ). Alpha release FreqUI is still considered an alpha release - if you encounter bugs or inconsistencies please open a FreqUI issue . developers Developers should not use this method, but instead use the method described in the freqUI repository to get the source-code of freqUI. Configuration \u00b6 Enable the rest API by adding the api_server section to your configuration and setting api_server.enabled to true . Sample configuration: json \"api_server\": { \"enabled\": true, \"listen_ip_address\": \"127.0.0.1\", \"listen_port\": 8080, \"verbosity\": \"error\", \"enable_openapi\": false, \"jwt_secret_key\": \"somethingrandom\", \"CORS_origins\": [], \"username\": \"Freqtrader\", \"password\": \"SuperSecret1!\" }, Security warning By default, the configuration listens on localhost only (so it's not reachable from other systems). We strongly recommend to not expose this API to the internet and choose a strong, unique password, since others will potentially be able to control your bot. You can then access the API by going to http://127.0.0.1:8080/api/v1/ping in a browser to check if the API is running correctly. This should return the response: output {\"status\":\"pong\"} All other endpoints return sensitive info and require authentication and are therefore not available through a web browser. Security \u00b6 To generate a secure password, best use a password manager, or use the below code. python import secrets secrets.token_hex() JWT token Use the same method to also generate a JWT secret key ( jwt_secret_key ). Password selection Please make sure to select a very strong, unique password to protect your bot from unauthorized access. Also change jwt_secret_key to something random (no need to remember this, but it'll be used to encrypt your session, so it better be something unique!). Configuration with docker \u00b6 If you run your bot using docker, you'll need to have the bot listen to incoming connections. The security is then handled by docker. json \"api_server\": { \"enabled\": true, \"listen_ip_address\": \"0.0.0.0\", \"listen_port\": 8080, \"username\": \"Freqtrader\", \"password\": \"SuperSecret1!\", //... }, Uncomment the following from your docker-compose file: yml ports: - \"127.0.0.1:8080:8080\" Security warning By using 8080:8080 in the docker port mapping, the API will be available to everyone connecting to the server under the correct port, so others may be able to control your bot. Rest API \u00b6 Consuming the API \u00b6 You can consume the API by using the script scripts/rest_client.py . The client script only requires the requests module, so Freqtrade does not need to be installed on the system. bash python3 scripts/rest_client.py [optional parameters] By default, the script assumes 127.0.0.1 (localhost) and port 8080 to be used, however you can specify a configuration file to override this behaviour. Minimalistic client config \u00b6 json { \"api_server\": { \"enabled\": true, \"listen_ip_address\": \"0.0.0.0\", \"listen_port\": 8080, \"username\": \"Freqtrader\", \"password\": \"SuperSecret1!\", //... } } bash python3 scripts/rest_client.py --config rest_config.json [optional parameters] Available endpoints \u00b6 Command Description ping Simple command testing the API Readiness - requires no authentication. start Starts the trader. stop Stops the trader. stopbuy Stops the trader from opening new trades. Gracefully closes open trades according to their rules. reload_config Reloads the configuration file. trades List last trades. Limited to 500 trades per call. trade/ Get specific trade. delete_trade Remove trade from the database. Tries to close open orders. Requires manual handling of this trade on the exchange. show_config Shows part of the current configuration with relevant settings to operation. logs Shows last log messages. status Lists all open trades. count Displays number of trades used and available. locks Displays currently locked pairs. delete_lock Deletes (disables) the lock by id. profit Display a summary of your profit/loss from close trades and some stats about your performance. forcesell Instantly sells the given trade (Ignoring minimum_roi ). forcesell all Instantly sells all open trades (Ignoring minimum_roi ). forcebuy [rate] Instantly buys the given pair. Rate is optional. ( forcebuy_enable must be set to True) performance Show performance of each finished trade grouped by pair. balance Show account balance per currency. daily Shows profit or loss per day, over the last n days (n defaults to 7). stats Display a summary of profit / loss reasons as well as average holding times. whitelist Show the current whitelist. blacklist [pair] Show the current blacklist, or adds a pair to the blacklist. edge Show validated pairs by Edge if it is enabled. pair_candles Returns dataframe for a pair / timeframe combination while the bot is running. Alpha pair_history Returns an analyzed dataframe for a given timerange, analyzed by a given strategy. Alpha plot_config Get plot config from the strategy (or nothing if not configured). Alpha strategies List strategies in strategy directory. Alpha strategy Get specific Strategy content. Alpha available_pairs List available backtest data. Alpha version Show version. Alpha status Endpoints labeled with Alpha status above may change at any time without notice. Possible commands can be listed from the rest-client script using the help command. bash python3 scripts/rest_client.py help ``` output Possible commands: available_pairs Return available pair (backtest data) based on timeframe / stake_currency selection :param timeframe: Only pairs with this timeframe available. :param stake_currency: Only pairs that include this timeframe balance Get the account balance. blacklist Show the current blacklist. :param add: List of coins to add (example: \"BNB/BTC\") count Return the amount of open trades. daily Return the profits for each day, and amount of trades. delete_lock Delete (disable) lock from the database. :param lock_id: ID for the lock to delete delete_trade Delete trade from the database. Tries to close open orders. Requires manual handling of this asset on the exchange. :param trade_id: Deletes the trade with this ID from the database. edge Return information about edge. forcebuy Buy an asset. :param pair: Pair to buy (ETH/BTC) :param price: Optional - price to buy forcesell Force-sell a trade. :param tradeid: Id of the trade (can be received via status command) locks Return current locks logs Show latest logs. :param limit: Limits log messages to the last logs. No limit to get the entire log. pair_candles Return live dataframe for . :param pair: Pair to get data for :param timeframe: Only pairs with this timeframe available. :param limit: Limit result to the last n candles. pair_history Return historic, analyzed dataframe :param pair: Pair to get data for :param timeframe: Only pairs with this timeframe available. :param strategy: Strategy to analyze and get values for :param timerange: Timerange to get data for (same format than --timerange endpoints) performance Return the performance of the different coins. ping simple ping plot_config Return plot configuration if the strategy defines one. profit Return the profit summary. reload_config Reload configuration. show_config Returns part of the configuration, relevant for trading operations. start Start the bot if it's in the stopped state. stats Return the stats report (durations, sell-reasons). status Get the status of open trades. stop Stop the bot. Use start to restart. stopbuy Stop buying (but handle sells gracefully). Use reload_config to reset. strategies Lists available strategies strategy Get strategy details :param strategy: Strategy class name trade Return specific trade :param trade_id: Specify which trade to get. trades Return trades history, sorted by id :param limit: Limits trades to the X last trades. Max 500 trades. :param offset: Offset by this amount of trades. version Return the version of the bot. whitelist Show the current whitelist. ``` OpenAPI interface \u00b6 To enable the builtin openAPI interface (Swagger UI), specify \"enable_openapi\": true in the api_server configuration. This will enable the Swagger UI at the /docs endpoint. By default, that's running at http://localhost:8080/docs/ - but it'll depend on your settings. Advanced API usage using JWT tokens \u00b6 Note The below should be done in an application (a Freqtrade REST API client, which fetches info via API), and is not intended to be used on a regular basis. Freqtrade's REST API also offers JWT (JSON Web Tokens). You can login using the following command, and subsequently use the resulting access_token. ``` bash curl -X POST --user Freqtrader http://localhost:8080/api/v1/token/login access_token=\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1ODkxMTk2ODEsIm5iZiI6MTU4OTExOTY4MSwianRpIjoiMmEwYmY0NWUtMjhmOS00YTUzLTlmNzItMmM5ZWVlYThkNzc2IiwiZXhwIjoxNTg5MTIwNTgxLCJpZGVudGl0eSI6eyJ1IjoiRnJlcXRyYWRlciJ9LCJmcmVzaCI6ZmFsc2UsInR5cGUiOiJhY2Nlc3MifQ.qt6MAXYIa-l556OM7arBvYJ0SDI9J8bIk3_glDujF5g\" Use access_token for authentication \u00b6 curl -X GET --header \"Authorization: Bearer ${access_token}\" http://localhost:8080/api/v1/count ``` Since the access token has a short timeout (15 min) - the token/refresh request should be used periodically to get a fresh access token: ``` bash curl -X POST --header \"Authorization: Bearer ${refresh_token}\" http://localhost:8080/api/v1/token/refresh {\"access_token\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1ODkxMTk5NzQsIm5iZiI6MTU4OTExOTk3NCwianRpIjoiMDBjNTlhMWUtMjBmYS00ZTk0LTliZjAtNWQwNTg2MTdiZDIyIiwiZXhwIjoxNTg5MTIwODc0LCJpZGVudGl0eSI6eyJ1IjoiRnJlcXRyYWRlciJ9LCJmcmVzaCI6ZmFsc2UsInR5cGUiOiJhY2Nlc3MifQ.1seHlII3WprjjclY6DpRhen0rqdF4j6jbvxIhUFaSbs\"} ``` CORS \u00b6 All web-based front-ends are subject to CORS - Cross-Origin Resource Sharing. Since most of the requests to the Freqtrade API must be authenticated, a proper CORS policy is key to avoid security problems. Also, the standard disallows * CORS policies for requests with credentials, so this setting must be set appropriately. Users can configure this themselves via the CORS_origins configuration setting. It consists of a list of allowed sites that are allowed to consume resources from the bot's API. Assuming your application is deployed as https://frequi.freqtrade.io/home/ - this would mean that the following configuration becomes necessary: jsonc { //... \"jwt_secret_key\": \"somethingrandom\", \"CORS_origins\": [\"https://frequi.freqtrade.io\"], //... } Note We strongly recommend to also set jwt_secret_key to something random and known only to yourself to avoid unauthorized access to your bot.","title":"REST API & FreqUI"},{"location":"rest-api/#rest-api-frequi","text":"","title":"REST API & FreqUI"},{"location":"rest-api/#frequi","text":"Freqtrade provides a builtin webserver, which can serve FreqUI , the freqtrade UI. By default, the UI is not included in the installation (except for docker images), and must be installed explicitly with freqtrade install-ui . This same command can also be used to update freqUI, should there be a new release. Once the bot is started in trade / dry-run mode (with freqtrade trade ) - the UI will be available under the configured port below (usually http://127.0.0.1:8080 ). Alpha release FreqUI is still considered an alpha release - if you encounter bugs or inconsistencies please open a FreqUI issue . developers Developers should not use this method, but instead use the method described in the freqUI repository to get the source-code of freqUI.","title":"FreqUI"},{"location":"rest-api/#configuration","text":"Enable the rest API by adding the api_server section to your configuration and setting api_server.enabled to true . Sample configuration: json \"api_server\": { \"enabled\": true, \"listen_ip_address\": \"127.0.0.1\", \"listen_port\": 8080, \"verbosity\": \"error\", \"enable_openapi\": false, \"jwt_secret_key\": \"somethingrandom\", \"CORS_origins\": [], \"username\": \"Freqtrader\", \"password\": \"SuperSecret1!\" }, Security warning By default, the configuration listens on localhost only (so it's not reachable from other systems). We strongly recommend to not expose this API to the internet and choose a strong, unique password, since others will potentially be able to control your bot. You can then access the API by going to http://127.0.0.1:8080/api/v1/ping in a browser to check if the API is running correctly. This should return the response: output {\"status\":\"pong\"} All other endpoints return sensitive info and require authentication and are therefore not available through a web browser.","title":"Configuration"},{"location":"rest-api/#security","text":"To generate a secure password, best use a password manager, or use the below code. python import secrets secrets.token_hex() JWT token Use the same method to also generate a JWT secret key ( jwt_secret_key ). Password selection Please make sure to select a very strong, unique password to protect your bot from unauthorized access. Also change jwt_secret_key to something random (no need to remember this, but it'll be used to encrypt your session, so it better be something unique!).","title":"Security"},{"location":"rest-api/#configuration-with-docker","text":"If you run your bot using docker, you'll need to have the bot listen to incoming connections. The security is then handled by docker. json \"api_server\": { \"enabled\": true, \"listen_ip_address\": \"0.0.0.0\", \"listen_port\": 8080, \"username\": \"Freqtrader\", \"password\": \"SuperSecret1!\", //... }, Uncomment the following from your docker-compose file: yml ports: - \"127.0.0.1:8080:8080\" Security warning By using 8080:8080 in the docker port mapping, the API will be available to everyone connecting to the server under the correct port, so others may be able to control your bot.","title":"Configuration with docker"},{"location":"rest-api/#rest-api","text":"","title":"Rest API"},{"location":"rest-api/#consuming-the-api","text":"You can consume the API by using the script scripts/rest_client.py . The client script only requires the requests module, so Freqtrade does not need to be installed on the system. bash python3 scripts/rest_client.py [optional parameters] By default, the script assumes 127.0.0.1 (localhost) and port 8080 to be used, however you can specify a configuration file to override this behaviour.","title":"Consuming the API"},{"location":"rest-api/#minimalistic-client-config","text":"json { \"api_server\": { \"enabled\": true, \"listen_ip_address\": \"0.0.0.0\", \"listen_port\": 8080, \"username\": \"Freqtrader\", \"password\": \"SuperSecret1!\", //... } } bash python3 scripts/rest_client.py --config rest_config.json [optional parameters]","title":"Minimalistic client config"},{"location":"rest-api/#available-endpoints","text":"Command Description ping Simple command testing the API Readiness - requires no authentication. start Starts the trader. stop Stops the trader. stopbuy Stops the trader from opening new trades. Gracefully closes open trades according to their rules. reload_config Reloads the configuration file. trades List last trades. Limited to 500 trades per call. trade/ Get specific trade. delete_trade Remove trade from the database. Tries to close open orders. Requires manual handling of this trade on the exchange. show_config Shows part of the current configuration with relevant settings to operation. logs Shows last log messages. status Lists all open trades. count Displays number of trades used and available. locks Displays currently locked pairs. delete_lock Deletes (disables) the lock by id. profit Display a summary of your profit/loss from close trades and some stats about your performance. forcesell Instantly sells the given trade (Ignoring minimum_roi ). forcesell all Instantly sells all open trades (Ignoring minimum_roi ). forcebuy [rate] Instantly buys the given pair. Rate is optional. ( forcebuy_enable must be set to True) performance Show performance of each finished trade grouped by pair. balance Show account balance per currency. daily Shows profit or loss per day, over the last n days (n defaults to 7). stats Display a summary of profit / loss reasons as well as average holding times. whitelist Show the current whitelist. blacklist [pair] Show the current blacklist, or adds a pair to the blacklist. edge Show validated pairs by Edge if it is enabled. pair_candles Returns dataframe for a pair / timeframe combination while the bot is running. Alpha pair_history Returns an analyzed dataframe for a given timerange, analyzed by a given strategy. Alpha plot_config Get plot config from the strategy (or nothing if not configured). Alpha strategies List strategies in strategy directory. Alpha strategy Get specific Strategy content. Alpha available_pairs List available backtest data. Alpha version Show version. Alpha status Endpoints labeled with Alpha status above may change at any time without notice. Possible commands can be listed from the rest-client script using the help command. bash python3 scripts/rest_client.py help ``` output Possible commands: available_pairs Return available pair (backtest data) based on timeframe / stake_currency selection :param timeframe: Only pairs with this timeframe available. :param stake_currency: Only pairs that include this timeframe balance Get the account balance. blacklist Show the current blacklist. :param add: List of coins to add (example: \"BNB/BTC\") count Return the amount of open trades. daily Return the profits for each day, and amount of trades. delete_lock Delete (disable) lock from the database. :param lock_id: ID for the lock to delete delete_trade Delete trade from the database. Tries to close open orders. Requires manual handling of this asset on the exchange. :param trade_id: Deletes the trade with this ID from the database. edge Return information about edge. forcebuy Buy an asset. :param pair: Pair to buy (ETH/BTC) :param price: Optional - price to buy forcesell Force-sell a trade. :param tradeid: Id of the trade (can be received via status command) locks Return current locks logs Show latest logs. :param limit: Limits log messages to the last logs. No limit to get the entire log. pair_candles Return live dataframe for . :param pair: Pair to get data for :param timeframe: Only pairs with this timeframe available. :param limit: Limit result to the last n candles. pair_history Return historic, analyzed dataframe :param pair: Pair to get data for :param timeframe: Only pairs with this timeframe available. :param strategy: Strategy to analyze and get values for :param timerange: Timerange to get data for (same format than --timerange endpoints) performance Return the performance of the different coins. ping simple ping plot_config Return plot configuration if the strategy defines one. profit Return the profit summary. reload_config Reload configuration. show_config Returns part of the configuration, relevant for trading operations. start Start the bot if it's in the stopped state. stats Return the stats report (durations, sell-reasons). status Get the status of open trades. stop Stop the bot. Use start to restart. stopbuy Stop buying (but handle sells gracefully). Use reload_config to reset. strategies Lists available strategies strategy Get strategy details :param strategy: Strategy class name trade Return specific trade :param trade_id: Specify which trade to get. trades Return trades history, sorted by id :param limit: Limits trades to the X last trades. Max 500 trades. :param offset: Offset by this amount of trades. version Return the version of the bot. whitelist Show the current whitelist. ```","title":"Available endpoints"},{"location":"rest-api/#openapi-interface","text":"To enable the builtin openAPI interface (Swagger UI), specify \"enable_openapi\": true in the api_server configuration. This will enable the Swagger UI at the /docs endpoint. By default, that's running at http://localhost:8080/docs/ - but it'll depend on your settings.","title":"OpenAPI interface"},{"location":"rest-api/#advanced-api-usage-using-jwt-tokens","text":"Note The below should be done in an application (a Freqtrade REST API client, which fetches info via API), and is not intended to be used on a regular basis. Freqtrade's REST API also offers JWT (JSON Web Tokens). You can login using the following command, and subsequently use the resulting access_token. ``` bash curl -X POST --user Freqtrader http://localhost:8080/api/v1/token/login access_token=\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1ODkxMTk2ODEsIm5iZiI6MTU4OTExOTY4MSwianRpIjoiMmEwYmY0NWUtMjhmOS00YTUzLTlmNzItMmM5ZWVlYThkNzc2IiwiZXhwIjoxNTg5MTIwNTgxLCJpZGVudGl0eSI6eyJ1IjoiRnJlcXRyYWRlciJ9LCJmcmVzaCI6ZmFsc2UsInR5cGUiOiJhY2Nlc3MifQ.qt6MAXYIa-l556OM7arBvYJ0SDI9J8bIk3_glDujF5g\"","title":"Advanced API usage using JWT tokens"},{"location":"rest-api/#use-access_token-for-authentication","text":"curl -X GET --header \"Authorization: Bearer ${access_token}\" http://localhost:8080/api/v1/count ``` Since the access token has a short timeout (15 min) - the token/refresh request should be used periodically to get a fresh access token: ``` bash curl -X POST --header \"Authorization: Bearer ${refresh_token}\" http://localhost:8080/api/v1/token/refresh {\"access_token\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1ODkxMTk5NzQsIm5iZiI6MTU4OTExOTk3NCwianRpIjoiMDBjNTlhMWUtMjBmYS00ZTk0LTliZjAtNWQwNTg2MTdiZDIyIiwiZXhwIjoxNTg5MTIwODc0LCJpZGVudGl0eSI6eyJ1IjoiRnJlcXRyYWRlciJ9LCJmcmVzaCI6ZmFsc2UsInR5cGUiOiJhY2Nlc3MifQ.1seHlII3WprjjclY6DpRhen0rqdF4j6jbvxIhUFaSbs\"} ```","title":"Use access_token for authentication"},{"location":"rest-api/#cors","text":"All web-based front-ends are subject to CORS - Cross-Origin Resource Sharing. Since most of the requests to the Freqtrade API must be authenticated, a proper CORS policy is key to avoid security problems. Also, the standard disallows * CORS policies for requests with credentials, so this setting must be set appropriately. Users can configure this themselves via the CORS_origins configuration setting. It consists of a list of allowed sites that are allowed to consume resources from the bot's API. Assuming your application is deployed as https://frequi.freqtrade.io/home/ - this would mean that the following configuration becomes necessary: jsonc { //... \"jwt_secret_key\": \"somethingrandom\", \"CORS_origins\": [\"https://frequi.freqtrade.io\"], //... } Note We strongly recommend to also set jwt_secret_key to something random and known only to yourself to avoid unauthorized access to your bot.","title":"CORS"},{"location":"sandbox-testing/","text":"Sandbox API testing \u00b6 Some exchanges provide sandboxes or testbeds for risk-free testing, while running the bot against a real exchange. With some configuration, freqtrade (in combination with ccxt) provides access to these. This document is an overview to configure Freqtrade to be used with sandboxes. This can be useful to developers and trader alike. Warning Sandboxes usually have very low volume, and either a very wide spread, or no orders available at all. Therefore, sandboxes will usually not do a good job of showing you how a strategy would work in real trading. Exchanges known to have a sandbox / testnet \u00b6 binance coinbasepro gemini huobipro kucoin phemex Note We did not test correct functioning of all of the above testnets. Please report your experiences with each sandbox. Configure a Sandbox account \u00b6 When testing your API connectivity, make sure to use the appropriate sandbox / testnet URL. In general, you should follow these steps to enable an exchange's sandbox: Figure out if an exchange has a sandbox (most likely by using google or the exchange's support documents) Create a sandbox account (often the sandbox-account requires separate registration) Add some test assets to account Create API keys Add test funds \u00b6 Usually, sandbox exchanges allow depositing funds directly via web-interface. You should make sure to have a realistic amount of funds available to your test-account, so results are representable of your real account funds. Warning Test exchanges will NEVER require your real credit card or banking details! Configure freqtrade to use a exchange's sandbox \u00b6 Sandbox URLs \u00b6 Freqtrade makes use of CCXT which in turn provides a list of URLs to Freqtrade. These include ['test'] and ['api'] . [Test] if available will point to an Exchanges sandbox. [Api] normally used, and resolves to live API target on the exchange. To make use of sandbox / test add \"sandbox\": true, to your config.json json \"exchange\": { \"name\": \"coinbasepro\", \"sandbox\": true, \"key\": \"5wowfxemogxeowo;heiohgmd\", \"secret\": \"/ZMH1P62rCVmwefewrgcewX8nh4gob+lywxfwfxwwfxwfNsH1ySgvWCUR/w==\", \"password\": \"1bkjfkhfhfu6sr\", \"outdated_offset\": 5 \"pair_whitelist\": [ \"BTC/USD\" ] }, \"datadir\": \"user_data/data/coinbasepro_sandbox\" Also the following information: api-key (created for the sandbox webpage) api-secret (noted earlier) password (the passphrase - noted earlier) Different data directory We also recommend to set datadir to something identifying downloaded data as sandbox data, to avoid having sandbox data mixed with data from the real exchange. This can be done by adding the \"datadir\" key to the configuration. Now, whenever you use this configuration, your data directory will be set to this directory. You should now be ready to test your sandbox \u00b6 Ensure Freqtrade logs show the sandbox URL, and trades made are shown in sandbox. Also make sure to select a pair which shows at least some decent value (which very often is BTC/ ). Common problems with sandbox exchanges \u00b6 Sandbox exchange instances often have very low volume, which can cause some problems which usually are not seen on a real exchange instance. Old Candles problem \u00b6 Since Sandboxes often have low volume, candles can be quite old and show no volume. To disable the error \"Outdated history for pair ...\", best increase the parameter \"outdated_offset\" to a number that seems realistic for the sandbox you're using. Unfilled orders \u00b6 Sandboxes often have very low volumes - which means that many trades can go unfilled, or can go unfilled for a very long time. To mitigate this, you can try to match the first order on the opposite orderbook side using the following configuration: jsonc \"order_types\": { \"buy\": \"limit\", \"sell\": \"limit\" // ... }, \"bid_strategy\": { \"price_side\": \"ask\", // ... }, \"ask_strategy\":{ \"price_side\": \"bid\", // ... }, The configuration is similar to the suggested configuration for market orders - however by using limit-orders you can avoid moving the price too much, and you can set the worst price you might get.","title":"Sandbox Testing"},{"location":"sandbox-testing/#sandbox-api-testing","text":"Some exchanges provide sandboxes or testbeds for risk-free testing, while running the bot against a real exchange. With some configuration, freqtrade (in combination with ccxt) provides access to these. This document is an overview to configure Freqtrade to be used with sandboxes. This can be useful to developers and trader alike. Warning Sandboxes usually have very low volume, and either a very wide spread, or no orders available at all. Therefore, sandboxes will usually not do a good job of showing you how a strategy would work in real trading.","title":"Sandbox API testing"},{"location":"sandbox-testing/#exchanges-known-to-have-a-sandbox-testnet","text":"binance coinbasepro gemini huobipro kucoin phemex Note We did not test correct functioning of all of the above testnets. Please report your experiences with each sandbox.","title":"Exchanges known to have a sandbox / testnet"},{"location":"sandbox-testing/#configure-a-sandbox-account","text":"When testing your API connectivity, make sure to use the appropriate sandbox / testnet URL. In general, you should follow these steps to enable an exchange's sandbox: Figure out if an exchange has a sandbox (most likely by using google or the exchange's support documents) Create a sandbox account (often the sandbox-account requires separate registration) Add some test assets to account Create API keys","title":"Configure a Sandbox account"},{"location":"sandbox-testing/#add-test-funds","text":"Usually, sandbox exchanges allow depositing funds directly via web-interface. You should make sure to have a realistic amount of funds available to your test-account, so results are representable of your real account funds. Warning Test exchanges will NEVER require your real credit card or banking details!","title":"Add test funds"},{"location":"sandbox-testing/#configure-freqtrade-to-use-a-exchanges-sandbox","text":"","title":"Configure freqtrade to use a exchange's sandbox"},{"location":"sandbox-testing/#sandbox-urls","text":"Freqtrade makes use of CCXT which in turn provides a list of URLs to Freqtrade. These include ['test'] and ['api'] . [Test] if available will point to an Exchanges sandbox. [Api] normally used, and resolves to live API target on the exchange. To make use of sandbox / test add \"sandbox\": true, to your config.json json \"exchange\": { \"name\": \"coinbasepro\", \"sandbox\": true, \"key\": \"5wowfxemogxeowo;heiohgmd\", \"secret\": \"/ZMH1P62rCVmwefewrgcewX8nh4gob+lywxfwfxwwfxwfNsH1ySgvWCUR/w==\", \"password\": \"1bkjfkhfhfu6sr\", \"outdated_offset\": 5 \"pair_whitelist\": [ \"BTC/USD\" ] }, \"datadir\": \"user_data/data/coinbasepro_sandbox\" Also the following information: api-key (created for the sandbox webpage) api-secret (noted earlier) password (the passphrase - noted earlier) Different data directory We also recommend to set datadir to something identifying downloaded data as sandbox data, to avoid having sandbox data mixed with data from the real exchange. This can be done by adding the \"datadir\" key to the configuration. Now, whenever you use this configuration, your data directory will be set to this directory.","title":"Sandbox URLs"},{"location":"sandbox-testing/#you-should-now-be-ready-to-test-your-sandbox","text":"Ensure Freqtrade logs show the sandbox URL, and trades made are shown in sandbox. Also make sure to select a pair which shows at least some decent value (which very often is BTC/ ).","title":"You should now be ready to test your sandbox"},{"location":"sandbox-testing/#common-problems-with-sandbox-exchanges","text":"Sandbox exchange instances often have very low volume, which can cause some problems which usually are not seen on a real exchange instance.","title":"Common problems with sandbox exchanges"},{"location":"sandbox-testing/#old-candles-problem","text":"Since Sandboxes often have low volume, candles can be quite old and show no volume. To disable the error \"Outdated history for pair ...\", best increase the parameter \"outdated_offset\" to a number that seems realistic for the sandbox you're using.","title":"Old Candles problem"},{"location":"sandbox-testing/#unfilled-orders","text":"Sandboxes often have very low volumes - which means that many trades can go unfilled, or can go unfilled for a very long time. To mitigate this, you can try to match the first order on the opposite orderbook side using the following configuration: jsonc \"order_types\": { \"buy\": \"limit\", \"sell\": \"limit\" // ... }, \"bid_strategy\": { \"price_side\": \"ask\", // ... }, \"ask_strategy\":{ \"price_side\": \"bid\", // ... }, The configuration is similar to the suggested configuration for market orders - however by using limit-orders you can avoid moving the price too much, and you can set the worst price you might get.","title":"Unfilled orders"},{"location":"sql_cheatsheet/","text":"SQL Helper \u00b6 This page contains some help if you want to edit your sqlite db. Install sqlite3 \u00b6 Sqlite3 is a terminal based sqlite application. Feel free to use a visual Database editor like SqliteBrowser if you feel more comfortable with that. Ubuntu/Debian installation \u00b6 bash sudo apt-get install sqlite3 Using sqlite3 via docker-compose \u00b6 The freqtrade docker image does contain sqlite3, so you can edit the database without having to install anything on the host system. bash docker-compose exec freqtrade /bin/bash sqlite3 .sqlite Open the DB \u00b6 bash sqlite3 .open Table structure \u00b6 List tables \u00b6 bash .tables Display table structure \u00b6 bash .schema Get all trades in the table \u00b6 sql SELECT * FROM trades; Fix trade still open after a manual sell on the exchange \u00b6 Warning Manually selling a pair on the exchange will not be detected by the bot and it will try to sell anyway. Whenever possible, forcesell should be used to accomplish the same thing. It is strongly advised to backup your database file before making any manual changes. Note This should not be necessary after /forcesell, as forcesell orders are closed automatically by the bot on the next iteration. sql UPDATE trades SET is_open=0, close_date=, close_rate=, close_profit = close_rate / open_rate - 1, close_profit_abs = (amount * * (1 - fee_close) - (amount * (open_rate * (1 - fee_open)))), sell_reason= WHERE id=; Example \u00b6 sql UPDATE trades SET is_open=0, close_date='2020-06-20 03:08:45.103418', close_rate=0.19638016, close_profit=0.0496, close_profit_abs = (amount * 0.19638016 * (1 - fee_close) - (amount * (open_rate * (1 - fee_open)))), sell_reason='force_sell' WHERE id=31; Remove trade from the database \u00b6 Use RPC Methods to delete trades Consider using /delete via telegram or rest API. That's the recommended way to deleting trades. If you'd still like to remove a trade from the database directly, you can use the below query. sql DELETE FROM trades WHERE id = ; sql DELETE FROM trades WHERE id = 31; Warning This will remove this trade from the database. Please make sure you got the correct id and NEVER run this query without the where clause. Use a different database system \u00b6 Warning By using one of the below database systems, you acknowledge that you know how to manage such a system. Freqtrade will not provide any support with setup or maintenance (or backups) of the below database systems. PostgreSQL \u00b6 Freqtrade supports PostgreSQL by using SQLAlchemy, which supports multiple different database systems. Installation: pip install psycopg2 Usage: ... --db-url postgresql+psycopg2://:@localhost:5432/ Freqtrade will automatically create the tables necessary upon startup. If you're running different instances of Freqtrade, you must either setup one database per Instance or use different users / schemas for your connections. MariaDB / MySQL \u00b6 Freqtrade supports MariaDB by using SQLAlchemy, which supports multiple different database systems. Installation: pip install pymysql Usage: ... --db-url mysql+pymysql://:@localhost:3306/","title":"SQL Cheat-sheet"},{"location":"sql_cheatsheet/#sql-helper","text":"This page contains some help if you want to edit your sqlite db.","title":"SQL Helper"},{"location":"sql_cheatsheet/#install-sqlite3","text":"Sqlite3 is a terminal based sqlite application. Feel free to use a visual Database editor like SqliteBrowser if you feel more comfortable with that.","title":"Install sqlite3"},{"location":"sql_cheatsheet/#ubuntudebian-installation","text":"bash sudo apt-get install sqlite3","title":"Ubuntu/Debian installation"},{"location":"sql_cheatsheet/#using-sqlite3-via-docker-compose","text":"The freqtrade docker image does contain sqlite3, so you can edit the database without having to install anything on the host system. bash docker-compose exec freqtrade /bin/bash sqlite3 .sqlite","title":"Using sqlite3 via docker-compose"},{"location":"sql_cheatsheet/#open-the-db","text":"bash sqlite3 .open ","title":"Open the DB"},{"location":"sql_cheatsheet/#table-structure","text":"","title":"Table structure"},{"location":"sql_cheatsheet/#list-tables","text":"bash .tables","title":"List tables"},{"location":"sql_cheatsheet/#display-table-structure","text":"bash .schema ","title":"Display table structure"},{"location":"sql_cheatsheet/#get-all-trades-in-the-table","text":"sql SELECT * FROM trades;","title":"Get all trades in the table"},{"location":"sql_cheatsheet/#fix-trade-still-open-after-a-manual-sell-on-the-exchange","text":"Warning Manually selling a pair on the exchange will not be detected by the bot and it will try to sell anyway. Whenever possible, forcesell should be used to accomplish the same thing. It is strongly advised to backup your database file before making any manual changes. Note This should not be necessary after /forcesell, as forcesell orders are closed automatically by the bot on the next iteration. sql UPDATE trades SET is_open=0, close_date=, close_rate=, close_profit = close_rate / open_rate - 1, close_profit_abs = (amount * * (1 - fee_close) - (amount * (open_rate * (1 - fee_open)))), sell_reason= WHERE id=;","title":"Fix trade still open after a manual sell on the exchange"},{"location":"sql_cheatsheet/#example","text":"sql UPDATE trades SET is_open=0, close_date='2020-06-20 03:08:45.103418', close_rate=0.19638016, close_profit=0.0496, close_profit_abs = (amount * 0.19638016 * (1 - fee_close) - (amount * (open_rate * (1 - fee_open)))), sell_reason='force_sell' WHERE id=31;","title":"Example"},{"location":"sql_cheatsheet/#remove-trade-from-the-database","text":"Use RPC Methods to delete trades Consider using /delete via telegram or rest API. That's the recommended way to deleting trades. If you'd still like to remove a trade from the database directly, you can use the below query. sql DELETE FROM trades WHERE id = ; sql DELETE FROM trades WHERE id = 31; Warning This will remove this trade from the database. Please make sure you got the correct id and NEVER run this query without the where clause.","title":"Remove trade from the database"},{"location":"sql_cheatsheet/#use-a-different-database-system","text":"Warning By using one of the below database systems, you acknowledge that you know how to manage such a system. Freqtrade will not provide any support with setup or maintenance (or backups) of the below database systems.","title":"Use a different database system"},{"location":"sql_cheatsheet/#postgresql","text":"Freqtrade supports PostgreSQL by using SQLAlchemy, which supports multiple different database systems. Installation: pip install psycopg2 Usage: ... --db-url postgresql+psycopg2://:@localhost:5432/ Freqtrade will automatically create the tables necessary upon startup. If you're running different instances of Freqtrade, you must either setup one database per Instance or use different users / schemas for your connections.","title":"PostgreSQL"},{"location":"sql_cheatsheet/#mariadb-mysql","text":"Freqtrade supports MariaDB by using SQLAlchemy, which supports multiple different database systems. Installation: pip install pymysql Usage: ... --db-url mysql+pymysql://:@localhost:3306/","title":"MariaDB / MySQL"},{"location":"stoploss/","text":"Stop Loss \u00b6 The stoploss configuration parameter is loss as ratio that should trigger a sale. For example, value -0.10 will cause immediate sell if the profit dips below -10% for a given trade. This parameter is optional. Most of the strategy files already include the optimal stoploss value. Info All stoploss properties mentioned in this file can be set in the Strategy, or in the configuration. Configuration values will override the strategy values. Stop Loss On-Exchange/Freqtrade \u00b6 Those stoploss modes can be on exchange or off exchange . These modes can be configured with these values: python 'emergencysell': 'market', 'stoploss_on_exchange': False 'stoploss_on_exchange_interval': 60, 'stoploss_on_exchange_limit_ratio': 0.99 Note Stoploss on exchange is only supported for Binance (stop-loss-limit), Kraken (stop-loss-market, stop-loss-limit) and FTX (stop limit and stop-market) as of now. Do not set too low/tight stoploss value if using stop loss on exchange! If set to low/tight then you have greater risk of missing fill on the order and stoploss will not work. stoploss_on_exchange and stoploss_on_exchange_limit_ratio \u00b6 Enable or Disable stop loss on exchange. If the stoploss is on exchange it means a stoploss limit order is placed on the exchange immediately after buy order happens successfully. This will protect you against sudden crashes in market as the order will be in the queue immediately and if market goes down then the order has more chance of being fulfilled. If stoploss_on_exchange uses limit orders, the exchange needs 2 prices, the stoploss_price and the Limit price. stoploss defines the stop-price where the limit order is placed - and limit should be slightly below this. If an exchange supports both limit and market stoploss orders, then the value of stoploss will be used to determine the stoploss type. Calculation example: we bought the asset at 100$. Stop-price is 95$, then limit would be 95 * 0.99 = 94.05$ - so the limit order fill can happen between 95$ and 94.05$. For example, assuming the stoploss is on exchange, and trailing stoploss is enabled, and the market is going up, then the bot automatically cancels the previous stoploss order and puts a new one with a stop value higher than the previous stoploss order. Note If stoploss_on_exchange is enabled and the stoploss is cancelled manually on the exchange, then the bot will create a new stoploss order. stoploss_on_exchange_interval \u00b6 In case of stoploss on exchange there is another parameter called stoploss_on_exchange_interval . This configures the interval in seconds at which the bot will check the stoploss and update it if necessary. The bot cannot do these every 5 seconds (at each iteration), otherwise it would get banned by the exchange. So this parameter will tell the bot how often it should update the stoploss order. The default value is 60 (1 minute). This same logic will reapply a stoploss order on the exchange should you cancel it accidentally. forcesell \u00b6 forcesell is an optional value, which defaults to the same value as sell and is used when sending a /forcesell command from Telegram or from the Rest API. forcebuy \u00b6 forcebuy is an optional value, which defaults to the same value as buy and is used when sending a /forcebuy command from Telegram or from the Rest API. emergencysell \u00b6 emergencysell is an optional value, which defaults to market and is used when creating stop loss on exchange orders fails. The below is the default which is used if not changed in strategy or configuration file. Example from strategy file: python order_types = { 'buy': 'limit', 'sell': 'limit', 'emergencysell': 'market', 'stoploss': 'market', 'stoploss_on_exchange': True, 'stoploss_on_exchange_interval': 60, 'stoploss_on_exchange_limit_ratio': 0.99 } Stop Loss Types \u00b6 At this stage the bot contains the following stoploss support modes: Static stop loss. Trailing stop loss. Trailing stop loss, custom positive loss. Trailing stop loss only once the trade has reached a certain offset. Custom stoploss function Static Stop Loss \u00b6 This is very simple, you define a stop loss of x (as a ratio of price, i.e. x * 100% of price). This will try to sell the asset once the loss exceeds the defined loss. Example of stop loss: python stoploss = -0.10 For example, simplified math: the bot buys an asset at a price of 100$ the stop loss is defined at -10% the stop loss would get triggered once the asset drops below 90$ Trailing Stop Loss \u00b6 The initial value for this is stoploss , just as you would define your static Stop loss. To enable trailing stoploss: python stoploss = -0.10 trailing_stop = True This will now activate an algorithm, which automatically moves the stop loss up every time the price of your asset increases. For example, simplified math: the bot buys an asset at a price of 100$ the stop loss is defined at -10% the stop loss would get triggered once the asset drops below 90$ assuming the asset now increases to 102$ the stop loss will now be -10% of 102$ = 91.8$ now the asset drops in value to 101$, the stop loss will still be 91.8$ and would trigger at 91.8$. In summary: The stoploss will be adjusted to be always be -10% of the highest observed price. Trailing stop loss, custom positive loss \u00b6 It is also possible to have a default stop loss, when you are in the red with your buy (buy - fee), but once you hit positive result the system will utilize a new stop loss, which can have a different value. For example, your default stop loss is -10%, but once you have more than 0% profit (example 0.1%) a different trailing stoploss will be used. Note If you want the stoploss to only be changed when you break even of making a profit (what most users want) please refer to next section with offset enabled . Both values require trailing_stop to be set to true and trailing_stop_positive with a value. python stoploss = -0.10 trailing_stop = True trailing_stop_positive = 0.02 For example, simplified math: the bot buys an asset at a price of 100$ the stop loss is defined at -10% the stop loss would get triggered once the asset drops below 90$ assuming the asset now increases to 102$ the stop loss will now be -2% of 102$ = 99.96$ (99.96$ stop loss will be locked in and will follow asset price increments with -2%) now the asset drops in value to 101$, the stop loss will still be 99.96$ and would trigger at 99.96$ The 0.02 would translate to a -2% stop loss. Before this, stoploss is used for the trailing stoploss. Trailing stop loss only once the trade has reached a certain offset \u00b6 It is also possible to use a static stoploss until the offset is reached, and then trail the trade to take profits once the market turns. If \"trailing_only_offset_is_reached\": true then the trailing stoploss is only activated once the offset is reached. Until then, the stoploss remains at the configured stoploss . This option can be used with or without trailing_stop_positive , but uses trailing_stop_positive_offset as offset. python trailing_stop_positive_offset = 0.011 trailing_only_offset_is_reached = True Configuration (offset is buy-price + 3%): python stoploss = -0.10 trailing_stop = True trailing_stop_positive = 0.02 trailing_stop_positive_offset = 0.03 trailing_only_offset_is_reached = True For example, simplified math: the bot buys an asset at a price of 100$ the stop loss is defined at -10% the stop loss would get triggered once the asset drops below 90$ stoploss will remain at 90$ unless asset increases to or above our configured offset assuming the asset now increases to 103$ (where we have the offset configured) the stop loss will now be -2% of 103$ = 100.94$ now the asset drops in value to 101$, the stop loss will still be 100.94$ and would trigger at 100.94$ Tip Make sure to have this value ( trailing_stop_positive_offset ) lower than minimal ROI, otherwise minimal ROI will apply first and sell the trade. Changing stoploss on open trades \u00b6 A stoploss on an open trade can be changed by changing the value in the configuration or strategy and use the /reload_config command (alternatively, completely stopping and restarting the bot also works). The new stoploss value will be applied to open trades (and corresponding log-messages will be generated). Limitations \u00b6 Stoploss values cannot be changed if trailing_stop is enabled and the stoploss has already been adjusted, or if Edge is enabled (since Edge would recalculate stoploss based on the current market situation).","title":"Stoploss"},{"location":"stoploss/#stop-loss","text":"The stoploss configuration parameter is loss as ratio that should trigger a sale. For example, value -0.10 will cause immediate sell if the profit dips below -10% for a given trade. This parameter is optional. Most of the strategy files already include the optimal stoploss value. Info All stoploss properties mentioned in this file can be set in the Strategy, or in the configuration. Configuration values will override the strategy values.","title":"Stop Loss"},{"location":"stoploss/#stop-loss-on-exchangefreqtrade","text":"Those stoploss modes can be on exchange or off exchange . These modes can be configured with these values: python 'emergencysell': 'market', 'stoploss_on_exchange': False 'stoploss_on_exchange_interval': 60, 'stoploss_on_exchange_limit_ratio': 0.99 Note Stoploss on exchange is only supported for Binance (stop-loss-limit), Kraken (stop-loss-market, stop-loss-limit) and FTX (stop limit and stop-market) as of now. Do not set too low/tight stoploss value if using stop loss on exchange! If set to low/tight then you have greater risk of missing fill on the order and stoploss will not work.","title":"Stop Loss On-Exchange/Freqtrade"},{"location":"stoploss/#stoploss_on_exchange-and-stoploss_on_exchange_limit_ratio","text":"Enable or Disable stop loss on exchange. If the stoploss is on exchange it means a stoploss limit order is placed on the exchange immediately after buy order happens successfully. This will protect you against sudden crashes in market as the order will be in the queue immediately and if market goes down then the order has more chance of being fulfilled. If stoploss_on_exchange uses limit orders, the exchange needs 2 prices, the stoploss_price and the Limit price. stoploss defines the stop-price where the limit order is placed - and limit should be slightly below this. If an exchange supports both limit and market stoploss orders, then the value of stoploss will be used to determine the stoploss type. Calculation example: we bought the asset at 100$. Stop-price is 95$, then limit would be 95 * 0.99 = 94.05$ - so the limit order fill can happen between 95$ and 94.05$. For example, assuming the stoploss is on exchange, and trailing stoploss is enabled, and the market is going up, then the bot automatically cancels the previous stoploss order and puts a new one with a stop value higher than the previous stoploss order. Note If stoploss_on_exchange is enabled and the stoploss is cancelled manually on the exchange, then the bot will create a new stoploss order.","title":"stoploss_on_exchange and stoploss_on_exchange_limit_ratio"},{"location":"stoploss/#stoploss_on_exchange_interval","text":"In case of stoploss on exchange there is another parameter called stoploss_on_exchange_interval . This configures the interval in seconds at which the bot will check the stoploss and update it if necessary. The bot cannot do these every 5 seconds (at each iteration), otherwise it would get banned by the exchange. So this parameter will tell the bot how often it should update the stoploss order. The default value is 60 (1 minute). This same logic will reapply a stoploss order on the exchange should you cancel it accidentally.","title":"stoploss_on_exchange_interval"},{"location":"stoploss/#forcesell","text":"forcesell is an optional value, which defaults to the same value as sell and is used when sending a /forcesell command from Telegram or from the Rest API.","title":"forcesell"},{"location":"stoploss/#forcebuy","text":"forcebuy is an optional value, which defaults to the same value as buy and is used when sending a /forcebuy command from Telegram or from the Rest API.","title":"forcebuy"},{"location":"stoploss/#emergencysell","text":"emergencysell is an optional value, which defaults to market and is used when creating stop loss on exchange orders fails. The below is the default which is used if not changed in strategy or configuration file. Example from strategy file: python order_types = { 'buy': 'limit', 'sell': 'limit', 'emergencysell': 'market', 'stoploss': 'market', 'stoploss_on_exchange': True, 'stoploss_on_exchange_interval': 60, 'stoploss_on_exchange_limit_ratio': 0.99 }","title":"emergencysell"},{"location":"stoploss/#stop-loss-types","text":"At this stage the bot contains the following stoploss support modes: Static stop loss. Trailing stop loss. Trailing stop loss, custom positive loss. Trailing stop loss only once the trade has reached a certain offset. Custom stoploss function","title":"Stop Loss Types"},{"location":"stoploss/#static-stop-loss","text":"This is very simple, you define a stop loss of x (as a ratio of price, i.e. x * 100% of price). This will try to sell the asset once the loss exceeds the defined loss. Example of stop loss: python stoploss = -0.10 For example, simplified math: the bot buys an asset at a price of 100$ the stop loss is defined at -10% the stop loss would get triggered once the asset drops below 90$","title":"Static Stop Loss"},{"location":"stoploss/#trailing-stop-loss","text":"The initial value for this is stoploss , just as you would define your static Stop loss. To enable trailing stoploss: python stoploss = -0.10 trailing_stop = True This will now activate an algorithm, which automatically moves the stop loss up every time the price of your asset increases. For example, simplified math: the bot buys an asset at a price of 100$ the stop loss is defined at -10% the stop loss would get triggered once the asset drops below 90$ assuming the asset now increases to 102$ the stop loss will now be -10% of 102$ = 91.8$ now the asset drops in value to 101$, the stop loss will still be 91.8$ and would trigger at 91.8$. In summary: The stoploss will be adjusted to be always be -10% of the highest observed price.","title":"Trailing Stop Loss"},{"location":"stoploss/#trailing-stop-loss-custom-positive-loss","text":"It is also possible to have a default stop loss, when you are in the red with your buy (buy - fee), but once you hit positive result the system will utilize a new stop loss, which can have a different value. For example, your default stop loss is -10%, but once you have more than 0% profit (example 0.1%) a different trailing stoploss will be used. Note If you want the stoploss to only be changed when you break even of making a profit (what most users want) please refer to next section with offset enabled . Both values require trailing_stop to be set to true and trailing_stop_positive with a value. python stoploss = -0.10 trailing_stop = True trailing_stop_positive = 0.02 For example, simplified math: the bot buys an asset at a price of 100$ the stop loss is defined at -10% the stop loss would get triggered once the asset drops below 90$ assuming the asset now increases to 102$ the stop loss will now be -2% of 102$ = 99.96$ (99.96$ stop loss will be locked in and will follow asset price increments with -2%) now the asset drops in value to 101$, the stop loss will still be 99.96$ and would trigger at 99.96$ The 0.02 would translate to a -2% stop loss. Before this, stoploss is used for the trailing stoploss.","title":"Trailing stop loss, custom positive loss"},{"location":"stoploss/#trailing-stop-loss-only-once-the-trade-has-reached-a-certain-offset","text":"It is also possible to use a static stoploss until the offset is reached, and then trail the trade to take profits once the market turns. If \"trailing_only_offset_is_reached\": true then the trailing stoploss is only activated once the offset is reached. Until then, the stoploss remains at the configured stoploss . This option can be used with or without trailing_stop_positive , but uses trailing_stop_positive_offset as offset. python trailing_stop_positive_offset = 0.011 trailing_only_offset_is_reached = True Configuration (offset is buy-price + 3%): python stoploss = -0.10 trailing_stop = True trailing_stop_positive = 0.02 trailing_stop_positive_offset = 0.03 trailing_only_offset_is_reached = True For example, simplified math: the bot buys an asset at a price of 100$ the stop loss is defined at -10% the stop loss would get triggered once the asset drops below 90$ stoploss will remain at 90$ unless asset increases to or above our configured offset assuming the asset now increases to 103$ (where we have the offset configured) the stop loss will now be -2% of 103$ = 100.94$ now the asset drops in value to 101$, the stop loss will still be 100.94$ and would trigger at 100.94$ Tip Make sure to have this value ( trailing_stop_positive_offset ) lower than minimal ROI, otherwise minimal ROI will apply first and sell the trade.","title":"Trailing stop loss only once the trade has reached a certain offset"},{"location":"stoploss/#changing-stoploss-on-open-trades","text":"A stoploss on an open trade can be changed by changing the value in the configuration or strategy and use the /reload_config command (alternatively, completely stopping and restarting the bot also works). The new stoploss value will be applied to open trades (and corresponding log-messages will be generated).","title":"Changing stoploss on open trades"},{"location":"stoploss/#limitations","text":"Stoploss values cannot be changed if trailing_stop is enabled and the stoploss has already been adjusted, or if Edge is enabled (since Edge would recalculate stoploss based on the current market situation).","title":"Limitations"},{"location":"strategy-advanced/","text":"Advanced Strategies \u00b6 This page explains some advanced concepts available for strategies. If you're just getting started, please be familiar with the methods described in the Strategy Customization documentation and with the Freqtrade basics first. Freqtrade basics describes in which sequence each method described below is called, which can be helpful to understand which method to use for your custom needs. Note All callback methods described below should only be implemented in a strategy if they are actually used. Tip You can get a strategy template containing all below methods by running freqtrade new-strategy --strategy MyAwesomeStrategy --template advanced Storing information \u00b6 Storing information can be accomplished by creating a new dictionary within the strategy class. The name of the variable can be chosen at will, but should be prefixed with cust_ to avoid naming collisions with predefined strategy variables. ```python class AwesomeStrategy(IStrategy): # Create custom dictionary custom_info = {} def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: # Check if the entry already exists if not metadata[\"pair\"] in self.custom_info: # Create empty entry for this pair self.custom_info[metadata[\"pair\"]] = {} if \"crosstime\" in self.custom_info[metadata[\"pair\"]]: self.custom_info[metadata[\"pair\"]][\"crosstime\"] += 1 else: self.custom_info[metadata[\"pair\"]][\"crosstime\"] = 1 ``` Warning The data is not persisted after a bot-restart (or config-reload). Also, the amount of data should be kept smallish (no DataFrames and such), otherwise the bot will start to consume a lot of memory and eventually run out of memory and crash. Note If the data is pair-specific, make sure to use pair as one of the keys in the dictionary. Dataframe access \u00b6 You may access dataframe in various strategy functions by querying it from dataprovider. ``` python from freqtrade.exchange import timeframe_to_prev_date class AwesomeStrategy(IStrategy): def confirm_trade_exit(self, pair: str, trade: 'Trade', order_type: str, amount: float, rate: float, time_in_force: str, sell_reason: str, current_time: 'datetime', **kwargs) -> bool: # Obtain pair dataframe. dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe) # Obtain last available candle. Do not use current_time to look up latest candle, because # current_time points to current incomplete candle whose data is not available. last_candle = dataframe.iloc[-1].squeeze() # <...> # In dry/live runs trade open date will not match candle open date therefore it must be # rounded. trade_date = timeframe_to_prev_date(self.timeframe, trade.open_date_utc) # Look up trade candle. trade_candle = dataframe.loc[dataframe['date'] == trade_date] # trade_candle may be empty for trades that just opened as it is still incomplete. if not trade_candle.empty: trade_candle = trade_candle.squeeze() # <...> ``` Using .iloc[-1] You can use .iloc[-1] here because get_analyzed_dataframe() only returns candles that backtesting is allowed to see. This will not work in populate_* methods, so make sure to not use .iloc[] in that area. Also, this will only work starting with version 2021.5. Custom sell signal \u00b6 It is possible to define custom sell signals, indicating that specified position should be sold. This is very useful when we need to customize sell conditions for each individual trade, or if you need the trade profit to take the sell decision. For example you could implement a 1:2 risk-reward ROI with custom_sell() . Using custom_sell() signals in place of stoploss though is not recommended . It is a inferior method to using custom_stoploss() in this regard - which also allows you to keep the stoploss on exchange. Note Returning a string or True from this method is equal to setting sell signal on a candle at specified time. This method is not called when sell signal is set already, or if sell signals are disabled ( use_sell_signal=False or sell_profit_only=True while profit is below sell_profit_offset ). string max length is 64 characters. Exceeding this limit will cause the message to be truncated to 64 characters. An example of how we can use different indicators depending on the current profit and also sell trades that were open longer than one day: ``` python class AwesomeStrategy(IStrategy): def custom_sell(self, pair: str, trade: 'Trade', current_time: 'datetime', current_rate: float, current_profit: float, **kwargs): dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe) last_candle = dataframe.iloc[-1].squeeze() # Above 20% profit, sell when rsi < 80 if current_profit > 0.2: if last_candle['rsi'] < 80: return 'rsi_below_80' # Between 2% and 10%, sell if EMA-long above EMA-short if 0.02 < current_profit < 0.1: if last_candle['emalong'] > last_candle['emashort']: return 'ema_long_below_80' # Sell any positions at a loss if they are held for more than one day. if current_profit < 0.0 and (current_time - trade.open_date_utc).days >= 1: return 'unclog' ``` See Dataframe access for more information about dataframe use in strategy callbacks. Custom stoploss \u00b6 The stoploss price can only ever move upwards - if the stoploss value returned from custom_stoploss would result in a lower stoploss price than was previously set, it will be ignored. The traditional stoploss value serves as an absolute lower level and will be instated as the initial stoploss. The usage of the custom stoploss method must be enabled by setting use_custom_stoploss=True on the strategy object. The method must return a stoploss value (float / number) as a percentage of the current price. E.g. If the current_rate is 200 USD, then returning 0.02 will set the stoploss price 2% lower, at 196 USD. The absolute value of the return value is used (the sign is ignored), so returning 0.05 or -0.05 have the same result, a stoploss 5% below the current price. To simulate a regular trailing stoploss of 4% (trailing 4% behind the maximum reached price) you would use the following very simple method: ``` python additional imports required \u00b6 from datetime import datetime from freqtrade.persistence import Trade class AwesomeStrategy(IStrategy): # ... populate_* methods use_custom_stoploss = True def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: \"\"\" Custom stoploss logic, returning the new distance relative to current_rate (as ratio). e.g. returning -0.05 would create a stoploss 5% below current_rate. The custom stoploss can never be below self.stoploss, which serves as a hard maximum loss. For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/ When not implemented by a strategy, returns the initial stoploss value Only called when use_custom_stoploss is set to True. :param pair: Pair that's currently analyzed :param trade: trade object. :param current_time: datetime object, containing the current datetime :param current_rate: Rate, calculated based on pricing settings in ask_strategy. :param current_profit: Current profit (as ratio), calculated based on current_rate. :param **kwargs: Ensure to keep this here so updates to this won't break your strategy. :return float: New stoploss value, relative to the current rate \"\"\" return -0.04 ``` Stoploss on exchange works similar to trailing_stop , and the stoploss on exchange is updated as configured in stoploss_on_exchange_interval ( More details about stoploss on exchange ). Use of dates All time-based calculations should be done based on current_time - using datetime.now() or datetime.utcnow() is discouraged, as this will break backtesting support. Trailing stoploss It's recommended to disable trailing_stop when using custom stoploss values. Both can work in tandem, but you might encounter the trailing stop to move the price higher while your custom function would not want this, causing conflicting behavior. Custom stoploss examples \u00b6 The next section will show some examples on what's possible with the custom stoploss function. Of course, many more things are possible, and all examples can be combined at will. Time based trailing stop \u00b6 Use the initial stoploss for the first 60 minutes, after this change to 10% trailing stoploss, and after 2 hours (120 minutes) we use a 5% trailing stoploss. ``` python from datetime import datetime, timedelta from freqtrade.persistence import Trade class AwesomeStrategy(IStrategy): # ... populate_* methods use_custom_stoploss = True def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: # Make sure you have the longest interval first - these conditions are evaluated from top to bottom. if current_time - timedelta(minutes=120) > trade.open_date_utc: return -0.05 elif current_time - timedelta(minutes=60) > trade.open_date_utc: return -0.10 return 1 ``` Different stoploss per pair \u00b6 Use a different stoploss depending on the pair. In this example, we'll trail the highest price with 10% trailing stoploss for ETH/BTC and XRP/BTC , with 5% trailing stoploss for LTC/BTC and with 15% for all other pairs. ``` python from datetime import datetime from freqtrade.persistence import Trade class AwesomeStrategy(IStrategy): # ... populate_* methods use_custom_stoploss = True def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: if pair in ('ETH/BTC', 'XRP/BTC'): return -0.10 elif pair in ('LTC/BTC'): return -0.05 return -0.15 ``` Trailing stoploss with positive offset \u00b6 Use the initial stoploss until the profit is above 4%, then use a trailing stoploss of 50% of the current profit with a minimum of 2.5% and a maximum of 5%. Please note that the stoploss can only increase, values lower than the current stoploss are ignored. ``` python from datetime import datetime, timedelta from freqtrade.persistence import Trade class AwesomeStrategy(IStrategy): # ... populate_* methods use_custom_stoploss = True def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: if current_profit < 0.04: return -1 # return a value bigger than the initial stoploss to keep using the initial stoploss # After reaching the desired offset, allow the stoploss to trail by half the profit desired_stoploss = current_profit / 2 # Use a minimum of 2.5% and a maximum of 5% return max(min(desired_stoploss, 0.05), 0.025) ``` Calculating stoploss relative to open price \u00b6 Stoploss values returned from custom_stoploss() always specify a percentage relative to current_rate . In order to set a stoploss relative to the open price, we need to use current_profit to calculate what percentage relative to the current_rate will give you the same result as if the percentage was specified from the open price. The helper function stoploss_from_open() can be used to convert from an open price relative stop, to a current price relative stop which can be returned from custom_stoploss() . Stepped stoploss \u00b6 Instead of continuously trailing behind the current price, this example sets fixed stoploss price levels based on the current profit. Use the regular stoploss until 20% profit is reached Once profit is > 20% - set stoploss to 7% above open price. Once profit is > 25% - set stoploss to 15% above open price. Once profit is > 40% - set stoploss to 25% above open price. ``` python from datetime import datetime from freqtrade.persistence import Trade from freqtrade.strategy import stoploss_from_open class AwesomeStrategy(IStrategy): # ... populate_* methods use_custom_stoploss = True def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: # evaluate highest to lowest, so that highest possible stop is used if current_profit > 0.40: return stoploss_from_open(0.25, current_profit) elif current_profit > 0.25: return stoploss_from_open(0.15, current_profit) elif current_profit > 0.20: return stoploss_from_open(0.07, current_profit) # return maximum stoploss value, keeping current stoploss price unchanged return 1 ``` Custom stoploss using an indicator from dataframe example \u00b6 Absolute stoploss value may be derived from indicators stored in dataframe. Example uses parabolic SAR below the price as stoploss. ``` python class AwesomeStrategy(IStrategy): def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: # <...> dataframe['sar'] = ta.SAR(dataframe) use_custom_stoploss = True def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe) last_candle = dataframe.iloc[-1].squeeze() # Use parabolic sar as absolute stoploss price stoploss_price = last_candle['sar'] # Convert absolute price to percentage relative to current_rate if stoploss_price < current_rate: return (stoploss_price / current_rate) - 1 # return maximum stoploss value, keeping current stoploss price unchanged return 1 ``` See Dataframe access for more information about dataframe use in strategy callbacks. Custom order timeout rules \u00b6 Simple, time-based order-timeouts can be configured either via strategy or in the configuration in the unfilledtimeout section. However, freqtrade also offers a custom callback for both order types, which allows you to decide based on custom criteria if an order did time out or not. Note Unfilled order timeouts are not relevant during backtesting or hyperopt, and are only relevant during real (live) trading. Therefore these methods are only called in these circumstances. Custom order timeout example \u00b6 A simple example, which applies different unfilled-timeouts depending on the price of the asset can be seen below. It applies a tight timeout for higher priced assets, while allowing more time to fill on cheap coins. The function must return either True (cancel order) or False (keep order alive). ``` python from datetime import datetime, timedelta, timezone from freqtrade.persistence import Trade class AwesomeStrategy(IStrategy): # ... populate_* methods # Set unfilledtimeout to 25 hours, since our maximum timeout from below is 24 hours. unfilledtimeout = { 'buy': 60 * 25, 'sell': 60 * 25 } def check_buy_timeout(self, pair: str, trade: 'Trade', order: dict, **kwargs) -> bool: if trade.open_rate > 100 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(minutes=5): return True elif trade.open_rate > 10 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(minutes=3): return True elif trade.open_rate < 1 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(hours=24): return True return False def check_sell_timeout(self, pair: str, trade: 'Trade', order: dict, **kwargs) -> bool: if trade.open_rate > 100 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(minutes=5): return True elif trade.open_rate > 10 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(minutes=3): return True elif trade.open_rate < 1 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(hours=24): return True return False ``` Note For the above example, unfilledtimeout must be set to something bigger than 24h, otherwise that type of timeout will apply first. Custom order timeout example (using additional data) \u00b6 ``` python from datetime import datetime from freqtrade.persistence import Trade class AwesomeStrategy(IStrategy): # ... populate_* methods # Set unfilledtimeout to 25 hours, since our maximum timeout from below is 24 hours. unfilledtimeout = { 'buy': 60 * 25, 'sell': 60 * 25 } def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: ob = self.dp.orderbook(pair, 1) current_price = ob['bids'][0][0] # Cancel buy order if price is more than 2% above the order. if current_price > order['price'] * 1.02: return True return False def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: ob = self.dp.orderbook(pair, 1) current_price = ob['asks'][0][0] # Cancel sell order if price is more than 2% below the order. if current_price < order['price'] * 0.98: return True return False ``` Bot loop start callback \u00b6 A simple callback which is called once at the start of every bot throttling iteration. This can be used to perform calculations which are pair independent (apply to all pairs), loading of external data, etc. ``` python import requests class AwesomeStrategy(IStrategy): # ... populate_* methods def bot_loop_start(self, **kwargs) -> None: \"\"\" Called at the start of the bot iteration (one loop). Might be used to perform pair-independent tasks (e.g. gather some remote resource for comparison) :param **kwargs: Ensure to keep this here so updates to this won't break your strategy. \"\"\" if self.config['runmode'].value in ('live', 'dry_run'): # Assign this to the class by using self.* # can then be used by populate_* methods self.remote_data = requests.get('https://some_remote_source.example.com') ``` Bot order confirmation \u00b6 Trade entry (buy order) confirmation \u00b6 confirm_trade_entry() can be used to abort a trade entry at the latest second (maybe because the price is not what we expect). ``` python class AwesomeStrategy(IStrategy): # ... populate_* methods def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, current_time: datetime, **kwargs) -> bool: \"\"\" Called right before placing a buy order. Timing for this function is critical, so avoid doing heavy computations or network requests in this method. For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/ When not implemented by a strategy, returns True (always confirming). :param pair: Pair that's about to be bought. :param order_type: Order type (as configured in order_types). usually limit or market. :param amount: Amount in target (quote) currency that's going to be traded. :param rate: Rate that's going to be used when using limit orders :param time_in_force: Time in force. Defaults to GTC (Good-til-cancelled). :param current_time: datetime object, containing the current datetime :param **kwargs: Ensure to keep this here so updates to this won't break your strategy. :return bool: When True is returned, then the buy-order is placed on the exchange. False aborts the process \"\"\" return True ``` Trade exit (sell order) confirmation \u00b6 confirm_trade_exit() can be used to abort a trade exit (sell) at the latest second (maybe because the price is not what we expect). ``` python from freqtrade.persistence import Trade class AwesomeStrategy(IStrategy): # ... populate_* methods def confirm_trade_exit(self, pair: str, trade: Trade, order_type: str, amount: float, rate: float, time_in_force: str, sell_reason: str, current_time: datetime, **kwargs) -> bool: \"\"\" Called right before placing a regular sell order. Timing for this function is critical, so avoid doing heavy computations or network requests in this method. For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/ When not implemented by a strategy, returns True (always confirming). :param pair: Pair that's about to be sold. :param order_type: Order type (as configured in order_types). usually limit or market. :param amount: Amount in quote currency. :param rate: Rate that's going to be used when using limit orders :param time_in_force: Time in force. Defaults to GTC (Good-til-cancelled). :param sell_reason: Sell reason. Can be any of ['roi', 'stop_loss', 'stoploss_on_exchange', 'trailing_stop_loss', 'sell_signal', 'force_sell', 'emergency_sell'] :param current_time: datetime object, containing the current datetime :param **kwargs: Ensure to keep this here so updates to this won't break your strategy. :return bool: When True is returned, then the sell-order is placed on the exchange. False aborts the process \"\"\" if sell_reason == 'force_sell' and trade.calc_profit_ratio(rate) < 0: # Reject force-sells with negative profit # This is just a sample, please adjust to your needs # (this does not necessarily make sense, assuming you know when you're force-selling) return False return True ``` Stake size management \u00b6 It is possible to manage your risk by reducing or increasing stake amount when placing a new trade. ```python class AwesomeStrategy(IStrategy): def custom_stake_amount(self, pair: str, current_time: datetime, current_rate: float, proposed_stake: float, min_stake: float, max_stake: float, **kwargs) -> float: dataframe, _ = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe) current_candle = dataframe.iloc[-1].squeeze() if current_candle['fastk_rsi_1h'] > current_candle['fastd_rsi_1h']: if self.config['stake_amount'] == 'unlimited': # Use entire available wallet during favorable conditions when in compounding mode. return max_stake else: # Compound profits during favorable conditions instead of using a static stake. return self.wallets.get_total_stake_amount() / self.config['max_open_trades'] # Use default stake amount. return proposed_stake ``` Freqtrade will fall back to the proposed_stake value should your code raise an exception. The exception itself will be logged. Tip You do not have to ensure that min_stake <= returned_value <= max_stake . Trades will succeed as the returned value will be clamped to supported range and this acton will be logged. Tip Returning 0 or None will prevent trades from being placed. Derived strategies \u00b6 The strategies can be derived from other strategies. This avoids duplication of your custom strategy code. You can use this technique to override small parts of your main strategy, leaving the rest untouched: ``` python class MyAwesomeStrategy(IStrategy): ... stoploss = 0.13 trailing_stop = False # All other attributes and methods are here as they # should be in any custom strategy... ... class MyAwesomeStrategy2(MyAwesomeStrategy): # Override something stoploss = 0.08 trailing_stop = True ``` Both attributes and methods may be overridden, altering behavior of the original strategy in a way you need. Parent-strategy in different files If you have the parent-strategy in a different file, you'll need to add the following to the top of your \"child\"-file to ensure proper loading, otherwise freqtrade may not be able to load the parent strategy correctly. ``` python import sys from pathlib import Path sys.path.append(str(Path( file ).parent)) from myawesomestrategy import MyAwesomeStrategy ``` Embedding Strategies \u00b6 Freqtrade provides you with an easy way to embed the strategy into your configuration file. This is done by utilizing BASE64 encoding and providing this string at the strategy configuration field, in your chosen config file. Encoding a string as BASE64 \u00b6 This is a quick example, how to generate the BASE64 string in python ```python from base64 import urlsafe_b64encode with open(file, 'r') as f: content = f.read() content = urlsafe_b64encode(content.encode('utf-8')) ``` The variable 'content', will contain the strategy file in a BASE64 encoded form. Which can now be set in your configurations file as following json \"strategy\": \"NameOfStrategy:BASE64String\" Please ensure that 'NameOfStrategy' is identical to the strategy name!","title":"Advanced Strategy"},{"location":"strategy-advanced/#advanced-strategies","text":"This page explains some advanced concepts available for strategies. If you're just getting started, please be familiar with the methods described in the Strategy Customization documentation and with the Freqtrade basics first. Freqtrade basics describes in which sequence each method described below is called, which can be helpful to understand which method to use for your custom needs. Note All callback methods described below should only be implemented in a strategy if they are actually used. Tip You can get a strategy template containing all below methods by running freqtrade new-strategy --strategy MyAwesomeStrategy --template advanced","title":"Advanced Strategies"},{"location":"strategy-advanced/#storing-information","text":"Storing information can be accomplished by creating a new dictionary within the strategy class. The name of the variable can be chosen at will, but should be prefixed with cust_ to avoid naming collisions with predefined strategy variables. ```python class AwesomeStrategy(IStrategy): # Create custom dictionary custom_info = {} def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: # Check if the entry already exists if not metadata[\"pair\"] in self.custom_info: # Create empty entry for this pair self.custom_info[metadata[\"pair\"]] = {} if \"crosstime\" in self.custom_info[metadata[\"pair\"]]: self.custom_info[metadata[\"pair\"]][\"crosstime\"] += 1 else: self.custom_info[metadata[\"pair\"]][\"crosstime\"] = 1 ``` Warning The data is not persisted after a bot-restart (or config-reload). Also, the amount of data should be kept smallish (no DataFrames and such), otherwise the bot will start to consume a lot of memory and eventually run out of memory and crash. Note If the data is pair-specific, make sure to use pair as one of the keys in the dictionary.","title":"Storing information"},{"location":"strategy-advanced/#dataframe-access","text":"You may access dataframe in various strategy functions by querying it from dataprovider. ``` python from freqtrade.exchange import timeframe_to_prev_date class AwesomeStrategy(IStrategy): def confirm_trade_exit(self, pair: str, trade: 'Trade', order_type: str, amount: float, rate: float, time_in_force: str, sell_reason: str, current_time: 'datetime', **kwargs) -> bool: # Obtain pair dataframe. dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe) # Obtain last available candle. Do not use current_time to look up latest candle, because # current_time points to current incomplete candle whose data is not available. last_candle = dataframe.iloc[-1].squeeze() # <...> # In dry/live runs trade open date will not match candle open date therefore it must be # rounded. trade_date = timeframe_to_prev_date(self.timeframe, trade.open_date_utc) # Look up trade candle. trade_candle = dataframe.loc[dataframe['date'] == trade_date] # trade_candle may be empty for trades that just opened as it is still incomplete. if not trade_candle.empty: trade_candle = trade_candle.squeeze() # <...> ``` Using .iloc[-1] You can use .iloc[-1] here because get_analyzed_dataframe() only returns candles that backtesting is allowed to see. This will not work in populate_* methods, so make sure to not use .iloc[] in that area. Also, this will only work starting with version 2021.5.","title":"Dataframe access"},{"location":"strategy-advanced/#custom-sell-signal","text":"It is possible to define custom sell signals, indicating that specified position should be sold. This is very useful when we need to customize sell conditions for each individual trade, or if you need the trade profit to take the sell decision. For example you could implement a 1:2 risk-reward ROI with custom_sell() . Using custom_sell() signals in place of stoploss though is not recommended . It is a inferior method to using custom_stoploss() in this regard - which also allows you to keep the stoploss on exchange. Note Returning a string or True from this method is equal to setting sell signal on a candle at specified time. This method is not called when sell signal is set already, or if sell signals are disabled ( use_sell_signal=False or sell_profit_only=True while profit is below sell_profit_offset ). string max length is 64 characters. Exceeding this limit will cause the message to be truncated to 64 characters. An example of how we can use different indicators depending on the current profit and also sell trades that were open longer than one day: ``` python class AwesomeStrategy(IStrategy): def custom_sell(self, pair: str, trade: 'Trade', current_time: 'datetime', current_rate: float, current_profit: float, **kwargs): dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe) last_candle = dataframe.iloc[-1].squeeze() # Above 20% profit, sell when rsi < 80 if current_profit > 0.2: if last_candle['rsi'] < 80: return 'rsi_below_80' # Between 2% and 10%, sell if EMA-long above EMA-short if 0.02 < current_profit < 0.1: if last_candle['emalong'] > last_candle['emashort']: return 'ema_long_below_80' # Sell any positions at a loss if they are held for more than one day. if current_profit < 0.0 and (current_time - trade.open_date_utc).days >= 1: return 'unclog' ``` See Dataframe access for more information about dataframe use in strategy callbacks.","title":"Custom sell signal"},{"location":"strategy-advanced/#custom-stoploss","text":"The stoploss price can only ever move upwards - if the stoploss value returned from custom_stoploss would result in a lower stoploss price than was previously set, it will be ignored. The traditional stoploss value serves as an absolute lower level and will be instated as the initial stoploss. The usage of the custom stoploss method must be enabled by setting use_custom_stoploss=True on the strategy object. The method must return a stoploss value (float / number) as a percentage of the current price. E.g. If the current_rate is 200 USD, then returning 0.02 will set the stoploss price 2% lower, at 196 USD. The absolute value of the return value is used (the sign is ignored), so returning 0.05 or -0.05 have the same result, a stoploss 5% below the current price. To simulate a regular trailing stoploss of 4% (trailing 4% behind the maximum reached price) you would use the following very simple method: ``` python","title":"Custom stoploss"},{"location":"strategy-advanced/#additional-imports-required","text":"from datetime import datetime from freqtrade.persistence import Trade class AwesomeStrategy(IStrategy): # ... populate_* methods use_custom_stoploss = True def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: \"\"\" Custom stoploss logic, returning the new distance relative to current_rate (as ratio). e.g. returning -0.05 would create a stoploss 5% below current_rate. The custom stoploss can never be below self.stoploss, which serves as a hard maximum loss. For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/ When not implemented by a strategy, returns the initial stoploss value Only called when use_custom_stoploss is set to True. :param pair: Pair that's currently analyzed :param trade: trade object. :param current_time: datetime object, containing the current datetime :param current_rate: Rate, calculated based on pricing settings in ask_strategy. :param current_profit: Current profit (as ratio), calculated based on current_rate. :param **kwargs: Ensure to keep this here so updates to this won't break your strategy. :return float: New stoploss value, relative to the current rate \"\"\" return -0.04 ``` Stoploss on exchange works similar to trailing_stop , and the stoploss on exchange is updated as configured in stoploss_on_exchange_interval ( More details about stoploss on exchange ). Use of dates All time-based calculations should be done based on current_time - using datetime.now() or datetime.utcnow() is discouraged, as this will break backtesting support. Trailing stoploss It's recommended to disable trailing_stop when using custom stoploss values. Both can work in tandem, but you might encounter the trailing stop to move the price higher while your custom function would not want this, causing conflicting behavior.","title":"additional imports required"},{"location":"strategy-advanced/#custom-stoploss-examples","text":"The next section will show some examples on what's possible with the custom stoploss function. Of course, many more things are possible, and all examples can be combined at will.","title":"Custom stoploss examples"},{"location":"strategy-advanced/#time-based-trailing-stop","text":"Use the initial stoploss for the first 60 minutes, after this change to 10% trailing stoploss, and after 2 hours (120 minutes) we use a 5% trailing stoploss. ``` python from datetime import datetime, timedelta from freqtrade.persistence import Trade class AwesomeStrategy(IStrategy): # ... populate_* methods use_custom_stoploss = True def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: # Make sure you have the longest interval first - these conditions are evaluated from top to bottom. if current_time - timedelta(minutes=120) > trade.open_date_utc: return -0.05 elif current_time - timedelta(minutes=60) > trade.open_date_utc: return -0.10 return 1 ```","title":"Time based trailing stop"},{"location":"strategy-advanced/#different-stoploss-per-pair","text":"Use a different stoploss depending on the pair. In this example, we'll trail the highest price with 10% trailing stoploss for ETH/BTC and XRP/BTC , with 5% trailing stoploss for LTC/BTC and with 15% for all other pairs. ``` python from datetime import datetime from freqtrade.persistence import Trade class AwesomeStrategy(IStrategy): # ... populate_* methods use_custom_stoploss = True def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: if pair in ('ETH/BTC', 'XRP/BTC'): return -0.10 elif pair in ('LTC/BTC'): return -0.05 return -0.15 ```","title":"Different stoploss per pair"},{"location":"strategy-advanced/#trailing-stoploss-with-positive-offset","text":"Use the initial stoploss until the profit is above 4%, then use a trailing stoploss of 50% of the current profit with a minimum of 2.5% and a maximum of 5%. Please note that the stoploss can only increase, values lower than the current stoploss are ignored. ``` python from datetime import datetime, timedelta from freqtrade.persistence import Trade class AwesomeStrategy(IStrategy): # ... populate_* methods use_custom_stoploss = True def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: if current_profit < 0.04: return -1 # return a value bigger than the initial stoploss to keep using the initial stoploss # After reaching the desired offset, allow the stoploss to trail by half the profit desired_stoploss = current_profit / 2 # Use a minimum of 2.5% and a maximum of 5% return max(min(desired_stoploss, 0.05), 0.025) ```","title":"Trailing stoploss with positive offset"},{"location":"strategy-advanced/#calculating-stoploss-relative-to-open-price","text":"Stoploss values returned from custom_stoploss() always specify a percentage relative to current_rate . In order to set a stoploss relative to the open price, we need to use current_profit to calculate what percentage relative to the current_rate will give you the same result as if the percentage was specified from the open price. The helper function stoploss_from_open() can be used to convert from an open price relative stop, to a current price relative stop which can be returned from custom_stoploss() .","title":"Calculating stoploss relative to open price"},{"location":"strategy-advanced/#stepped-stoploss","text":"Instead of continuously trailing behind the current price, this example sets fixed stoploss price levels based on the current profit. Use the regular stoploss until 20% profit is reached Once profit is > 20% - set stoploss to 7% above open price. Once profit is > 25% - set stoploss to 15% above open price. Once profit is > 40% - set stoploss to 25% above open price. ``` python from datetime import datetime from freqtrade.persistence import Trade from freqtrade.strategy import stoploss_from_open class AwesomeStrategy(IStrategy): # ... populate_* methods use_custom_stoploss = True def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: # evaluate highest to lowest, so that highest possible stop is used if current_profit > 0.40: return stoploss_from_open(0.25, current_profit) elif current_profit > 0.25: return stoploss_from_open(0.15, current_profit) elif current_profit > 0.20: return stoploss_from_open(0.07, current_profit) # return maximum stoploss value, keeping current stoploss price unchanged return 1 ```","title":"Stepped stoploss"},{"location":"strategy-advanced/#custom-stoploss-using-an-indicator-from-dataframe-example","text":"Absolute stoploss value may be derived from indicators stored in dataframe. Example uses parabolic SAR below the price as stoploss. ``` python class AwesomeStrategy(IStrategy): def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: # <...> dataframe['sar'] = ta.SAR(dataframe) use_custom_stoploss = True def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe) last_candle = dataframe.iloc[-1].squeeze() # Use parabolic sar as absolute stoploss price stoploss_price = last_candle['sar'] # Convert absolute price to percentage relative to current_rate if stoploss_price < current_rate: return (stoploss_price / current_rate) - 1 # return maximum stoploss value, keeping current stoploss price unchanged return 1 ``` See Dataframe access for more information about dataframe use in strategy callbacks.","title":"Custom stoploss using an indicator from dataframe example"},{"location":"strategy-advanced/#custom-order-timeout-rules","text":"Simple, time-based order-timeouts can be configured either via strategy or in the configuration in the unfilledtimeout section. However, freqtrade also offers a custom callback for both order types, which allows you to decide based on custom criteria if an order did time out or not. Note Unfilled order timeouts are not relevant during backtesting or hyperopt, and are only relevant during real (live) trading. Therefore these methods are only called in these circumstances.","title":"Custom order timeout rules"},{"location":"strategy-advanced/#custom-order-timeout-example","text":"A simple example, which applies different unfilled-timeouts depending on the price of the asset can be seen below. It applies a tight timeout for higher priced assets, while allowing more time to fill on cheap coins. The function must return either True (cancel order) or False (keep order alive). ``` python from datetime import datetime, timedelta, timezone from freqtrade.persistence import Trade class AwesomeStrategy(IStrategy): # ... populate_* methods # Set unfilledtimeout to 25 hours, since our maximum timeout from below is 24 hours. unfilledtimeout = { 'buy': 60 * 25, 'sell': 60 * 25 } def check_buy_timeout(self, pair: str, trade: 'Trade', order: dict, **kwargs) -> bool: if trade.open_rate > 100 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(minutes=5): return True elif trade.open_rate > 10 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(minutes=3): return True elif trade.open_rate < 1 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(hours=24): return True return False def check_sell_timeout(self, pair: str, trade: 'Trade', order: dict, **kwargs) -> bool: if trade.open_rate > 100 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(minutes=5): return True elif trade.open_rate > 10 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(minutes=3): return True elif trade.open_rate < 1 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(hours=24): return True return False ``` Note For the above example, unfilledtimeout must be set to something bigger than 24h, otherwise that type of timeout will apply first.","title":"Custom order timeout example"},{"location":"strategy-advanced/#custom-order-timeout-example-using-additional-data","text":"``` python from datetime import datetime from freqtrade.persistence import Trade class AwesomeStrategy(IStrategy): # ... populate_* methods # Set unfilledtimeout to 25 hours, since our maximum timeout from below is 24 hours. unfilledtimeout = { 'buy': 60 * 25, 'sell': 60 * 25 } def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: ob = self.dp.orderbook(pair, 1) current_price = ob['bids'][0][0] # Cancel buy order if price is more than 2% above the order. if current_price > order['price'] * 1.02: return True return False def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: ob = self.dp.orderbook(pair, 1) current_price = ob['asks'][0][0] # Cancel sell order if price is more than 2% below the order. if current_price < order['price'] * 0.98: return True return False ```","title":"Custom order timeout example (using additional data)"},{"location":"strategy-advanced/#bot-loop-start-callback","text":"A simple callback which is called once at the start of every bot throttling iteration. This can be used to perform calculations which are pair independent (apply to all pairs), loading of external data, etc. ``` python import requests class AwesomeStrategy(IStrategy): # ... populate_* methods def bot_loop_start(self, **kwargs) -> None: \"\"\" Called at the start of the bot iteration (one loop). Might be used to perform pair-independent tasks (e.g. gather some remote resource for comparison) :param **kwargs: Ensure to keep this here so updates to this won't break your strategy. \"\"\" if self.config['runmode'].value in ('live', 'dry_run'): # Assign this to the class by using self.* # can then be used by populate_* methods self.remote_data = requests.get('https://some_remote_source.example.com') ```","title":"Bot loop start callback"},{"location":"strategy-advanced/#bot-order-confirmation","text":"","title":"Bot order confirmation"},{"location":"strategy-advanced/#trade-entry-buy-order-confirmation","text":"confirm_trade_entry() can be used to abort a trade entry at the latest second (maybe because the price is not what we expect). ``` python class AwesomeStrategy(IStrategy): # ... populate_* methods def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float, time_in_force: str, current_time: datetime, **kwargs) -> bool: \"\"\" Called right before placing a buy order. Timing for this function is critical, so avoid doing heavy computations or network requests in this method. For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/ When not implemented by a strategy, returns True (always confirming). :param pair: Pair that's about to be bought. :param order_type: Order type (as configured in order_types). usually limit or market. :param amount: Amount in target (quote) currency that's going to be traded. :param rate: Rate that's going to be used when using limit orders :param time_in_force: Time in force. Defaults to GTC (Good-til-cancelled). :param current_time: datetime object, containing the current datetime :param **kwargs: Ensure to keep this here so updates to this won't break your strategy. :return bool: When True is returned, then the buy-order is placed on the exchange. False aborts the process \"\"\" return True ```","title":"Trade entry (buy order) confirmation"},{"location":"strategy-advanced/#trade-exit-sell-order-confirmation","text":"confirm_trade_exit() can be used to abort a trade exit (sell) at the latest second (maybe because the price is not what we expect). ``` python from freqtrade.persistence import Trade class AwesomeStrategy(IStrategy): # ... populate_* methods def confirm_trade_exit(self, pair: str, trade: Trade, order_type: str, amount: float, rate: float, time_in_force: str, sell_reason: str, current_time: datetime, **kwargs) -> bool: \"\"\" Called right before placing a regular sell order. Timing for this function is critical, so avoid doing heavy computations or network requests in this method. For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/ When not implemented by a strategy, returns True (always confirming). :param pair: Pair that's about to be sold. :param order_type: Order type (as configured in order_types). usually limit or market. :param amount: Amount in quote currency. :param rate: Rate that's going to be used when using limit orders :param time_in_force: Time in force. Defaults to GTC (Good-til-cancelled). :param sell_reason: Sell reason. Can be any of ['roi', 'stop_loss', 'stoploss_on_exchange', 'trailing_stop_loss', 'sell_signal', 'force_sell', 'emergency_sell'] :param current_time: datetime object, containing the current datetime :param **kwargs: Ensure to keep this here so updates to this won't break your strategy. :return bool: When True is returned, then the sell-order is placed on the exchange. False aborts the process \"\"\" if sell_reason == 'force_sell' and trade.calc_profit_ratio(rate) < 0: # Reject force-sells with negative profit # This is just a sample, please adjust to your needs # (this does not necessarily make sense, assuming you know when you're force-selling) return False return True ```","title":"Trade exit (sell order) confirmation"},{"location":"strategy-advanced/#stake-size-management","text":"It is possible to manage your risk by reducing or increasing stake amount when placing a new trade. ```python class AwesomeStrategy(IStrategy): def custom_stake_amount(self, pair: str, current_time: datetime, current_rate: float, proposed_stake: float, min_stake: float, max_stake: float, **kwargs) -> float: dataframe, _ = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe) current_candle = dataframe.iloc[-1].squeeze() if current_candle['fastk_rsi_1h'] > current_candle['fastd_rsi_1h']: if self.config['stake_amount'] == 'unlimited': # Use entire available wallet during favorable conditions when in compounding mode. return max_stake else: # Compound profits during favorable conditions instead of using a static stake. return self.wallets.get_total_stake_amount() / self.config['max_open_trades'] # Use default stake amount. return proposed_stake ``` Freqtrade will fall back to the proposed_stake value should your code raise an exception. The exception itself will be logged. Tip You do not have to ensure that min_stake <= returned_value <= max_stake . Trades will succeed as the returned value will be clamped to supported range and this acton will be logged. Tip Returning 0 or None will prevent trades from being placed.","title":"Stake size management"},{"location":"strategy-advanced/#derived-strategies","text":"The strategies can be derived from other strategies. This avoids duplication of your custom strategy code. You can use this technique to override small parts of your main strategy, leaving the rest untouched: ``` python class MyAwesomeStrategy(IStrategy): ... stoploss = 0.13 trailing_stop = False # All other attributes and methods are here as they # should be in any custom strategy... ... class MyAwesomeStrategy2(MyAwesomeStrategy): # Override something stoploss = 0.08 trailing_stop = True ``` Both attributes and methods may be overridden, altering behavior of the original strategy in a way you need. Parent-strategy in different files If you have the parent-strategy in a different file, you'll need to add the following to the top of your \"child\"-file to ensure proper loading, otherwise freqtrade may not be able to load the parent strategy correctly. ``` python import sys from pathlib import Path sys.path.append(str(Path( file ).parent)) from myawesomestrategy import MyAwesomeStrategy ```","title":"Derived strategies"},{"location":"strategy-advanced/#embedding-strategies","text":"Freqtrade provides you with an easy way to embed the strategy into your configuration file. This is done by utilizing BASE64 encoding and providing this string at the strategy configuration field, in your chosen config file.","title":"Embedding Strategies"},{"location":"strategy-advanced/#encoding-a-string-as-base64","text":"This is a quick example, how to generate the BASE64 string in python ```python from base64 import urlsafe_b64encode with open(file, 'r') as f: content = f.read() content = urlsafe_b64encode(content.encode('utf-8')) ``` The variable 'content', will contain the strategy file in a BASE64 encoded form. Which can now be set in your configurations file as following json \"strategy\": \"NameOfStrategy:BASE64String\" Please ensure that 'NameOfStrategy' is identical to the strategy name!","title":"Encoding a string as BASE64"},{"location":"strategy-customization/","text":"Strategy Customization \u00b6 This page explains how to customize your strategies, add new indicators and set up trading rules. Please familiarize yourself with Freqtrade basics first, which provides overall info on how the bot operates. Install a custom strategy file \u00b6 This is very simple. Copy paste your strategy file into the directory user_data/strategies . Let assume you have a class called AwesomeStrategy in the file AwesomeStrategy.py : Move your file into user_data/strategies (you should have user_data/strategies/AwesomeStrategy.py Start the bot with the param --strategy AwesomeStrategy (the parameter is the class name) bash freqtrade trade --strategy AwesomeStrategy Develop your own strategy \u00b6 The bot includes a default strategy file. Also, several other strategies are available in the strategy repository . You will however most likely have your own idea for a strategy. This document intends to help you develop one for yourself. To get started, use freqtrade new-strategy --strategy AwesomeStrategy . This will create a new strategy file from a template, which will be located under user_data/strategies/AwesomeStrategy.py . Note This is just a template file, which will most likely not be profitable out of the box. Anatomy of a strategy \u00b6 A strategy file contains all the information needed to build a good strategy: Indicators Buy strategy rules Sell strategy rules Minimal ROI recommended Stoploss strongly recommended The bot also include a sample strategy called SampleStrategy you can update: user_data/strategies/sample_strategy.py . You can test it with the parameter: --strategy SampleStrategy Additionally, there is an attribute called INTERFACE_VERSION , which defines the version of the strategy interface the bot should use. The current version is 2 - which is also the default when it's not set explicitly in the strategy. Future versions will require this to be set. bash freqtrade trade --strategy AwesomeStrategy For the following section we will use the user_data/strategies/sample_strategy.py file as reference. Strategies and Backtesting To avoid problems and unexpected differences between Backtesting and dry/live modes, please be aware that during backtesting the full time range is passed to the populate_*() methods at once. It is therefore best to use vectorized operations (across the whole dataframe, not loops) and avoid index referencing ( df.iloc[-1] ), but instead use df.shift() to get to the previous candle. Warning: Using future data Since backtesting passes the full time range to the populate_*() methods, the strategy author needs to take care to avoid having the strategy utilize data from the future. Some common patterns for this are listed in the Common Mistakes section of this document. Customize Indicators \u00b6 Buy and sell strategies need indicators. You can add more indicators by extending the list contained in the method populate_indicators() from your strategy file. You should only add the indicators used in either populate_buy_trend() , populate_sell_trend() , or to populate another indicator, otherwise performance may suffer. It's important to always return the dataframe without removing/modifying the columns \"open\", \"high\", \"low\", \"close\", \"volume\" , otherwise these fields would contain something unexpected. Sample: ```python def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: \"\"\" Adds several different TA indicators to the given DataFrame Performance Note: For the best performance be frugal on the number of indicators you are using. Let uncomment only the indicator you are using in your strategies or your hyperopt configuration, otherwise you will waste your memory and CPU usage. :param dataframe: Dataframe with data from the exchange :param metadata: Additional information, like the currently traded pair :return: a Dataframe with all mandatory indicators for the strategies \"\"\" dataframe['sar'] = ta.SAR(dataframe) dataframe['adx'] = ta.ADX(dataframe) stoch = ta.STOCHF(dataframe) dataframe['fastd'] = stoch['fastd'] dataframe['fastk'] = stoch['fastk'] dataframe['blower'] = ta.BBANDS(dataframe, nbdevup=2, nbdevdn=2)['lowerband'] dataframe['sma'] = ta.SMA(dataframe, timeperiod=40) dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9) dataframe['mfi'] = ta.MFI(dataframe) dataframe['rsi'] = ta.RSI(dataframe) dataframe['ema5'] = ta.EMA(dataframe, timeperiod=5) dataframe['ema10'] = ta.EMA(dataframe, timeperiod=10) dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50) dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100) dataframe['ao'] = awesome_oscillator(dataframe) macd = ta.MACD(dataframe) dataframe['macd'] = macd['macd'] dataframe['macdsignal'] = macd['macdsignal'] dataframe['macdhist'] = macd['macdhist'] hilbert = ta.HT_SINE(dataframe) dataframe['htsine'] = hilbert['sine'] dataframe['htleadsine'] = hilbert['leadsine'] dataframe['plus_dm'] = ta.PLUS_DM(dataframe) dataframe['plus_di'] = ta.PLUS_DI(dataframe) dataframe['minus_dm'] = ta.MINUS_DM(dataframe) dataframe['minus_di'] = ta.MINUS_DI(dataframe) return dataframe ``` Want more indicator examples? Look into the user_data/strategies/sample_strategy.py . Then uncomment indicators you need. Strategy startup period \u00b6 Most indicators have an instable startup period, in which they are either not available, or the calculation is incorrect. This can lead to inconsistencies, since Freqtrade does not know how long this instable period should be. To account for this, the strategy can be assigned the startup_candle_count attribute. This should be set to the maximum number of candles that the strategy requires to calculate stable indicators. In this example strategy, this should be set to 100 ( startup_candle_count = 100 ), since the longest needed history is 100 candles. python dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100) By letting the bot know how much history is needed, backtest trades can start at the specified timerange during backtesting and hyperopt. Warning startup_candle_count should be below ohlcv_candle_limit (which is 500 for most exchanges) - since only this amount of candles will be available during Dry-Run/Live Trade operations. Example \u00b6 Let's try to backtest 1 month (January 2019) of 5m candles using an example strategy with EMA100, as above. bash freqtrade backtesting --timerange 20190101-20190201 --timeframe 5m Assuming startup_candle_count is set to 100, backtesting knows it needs 100 candles to generate valid buy signals. It will load data from 20190101 - (100 * 5m) - which is ~2018-12-31 15:30:00. If this data is available, indicators will be calculated with this extended timerange. The instable startup period (up to 2019-01-01 00:00:00) will then be removed before starting backtesting. Note If data for the startup period is not available, then the timerange will be adjusted to account for this startup period - so Backtesting would start at 2019-01-01 08:30:00. Buy signal rules \u00b6 Edit the method populate_buy_trend() in your strategy file to update your buy strategy. It's important to always return the dataframe without removing/modifying the columns \"open\", \"high\", \"low\", \"close\", \"volume\" , otherwise these fields would contain something unexpected. This method will also define a new column, \"buy\" , which needs to contain 1 for buys, and 0 for \"no action\". Sample from user_data/strategies/sample_strategy.py : ```python def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: \"\"\" Based on TA indicators, populates the buy signal for the given dataframe :param dataframe: DataFrame populated with indicators :param metadata: Additional information, like the currently traded pair :return: DataFrame with buy column \"\"\" dataframe.loc[ ( (qtpylib.crossed_above(dataframe['rsi'], 30)) & # Signal: RSI crosses above 30 (dataframe['tema'] <= dataframe['bb_middleband']) & # Guard (dataframe['tema'] > dataframe['tema'].shift(1)) & # Guard (dataframe['volume'] > 0) # Make sure Volume is not 0 ), 'buy'] = 1 return dataframe ``` Note Buying requires sellers to buy from - therefore volume needs to be > 0 ( dataframe['volume'] > 0 ) to make sure that the bot does not buy/sell in no-activity periods. Sell signal rules \u00b6 Edit the method populate_sell_trend() into your strategy file to update your sell strategy. Please note that the sell-signal is only used if use_sell_signal is set to true in the configuration. It's important to always return the dataframe without removing/modifying the columns \"open\", \"high\", \"low\", \"close\", \"volume\" , otherwise these fields would contain something unexpected. This method will also define a new column, \"sell\" , which needs to contain 1 for sells, and 0 for \"no action\". Sample from user_data/strategies/sample_strategy.py : python def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: \"\"\" Based on TA indicators, populates the sell signal for the given dataframe :param dataframe: DataFrame populated with indicators :param metadata: Additional information, like the currently traded pair :return: DataFrame with buy column \"\"\" dataframe.loc[ ( (qtpylib.crossed_above(dataframe['rsi'], 70)) & # Signal: RSI crosses above 70 (dataframe['tema'] > dataframe['bb_middleband']) & # Guard (dataframe['tema'] < dataframe['tema'].shift(1)) & # Guard (dataframe['volume'] > 0) # Make sure Volume is not 0 ), 'sell'] = 1 return dataframe Minimal ROI \u00b6 This dict defines the minimal Return On Investment (ROI) a trade should reach before selling, independent from the sell signal. It is of the following format, with the dict key (left side of the colon) being the minutes passed since the trade opened, and the value (right side of the colon) being the percentage. python minimal_roi = { \"40\": 0.0, \"30\": 0.01, \"20\": 0.02, \"0\": 0.04 } The above configuration would therefore mean: Sell whenever 4% profit was reached Sell when 2% profit was reached (in effect after 20 minutes) Sell when 1% profit was reached (in effect after 30 minutes) Sell when trade is non-loosing (in effect after 40 minutes) The calculation does include fees. To disable ROI completely, set it to an insanely high number: python minimal_roi = { \"0\": 100 } While technically not completely disabled, this would sell once the trade reaches 10000% Profit. To use times based on candle duration (timeframe), the following snippet can be handy. This will allow you to change the timeframe for the strategy, and ROI times will still be set as candles (e.g. after 3 candles ...) ``` python from freqtrade.exchange import timeframe_to_minutes class AwesomeStrategy(IStrategy): timeframe = \"1d\" timeframe_mins = timeframe_to_minutes(timeframe) minimal_roi = { \"0\": 0.05, # 5% for the first 3 candles str(timeframe_mins * 3)): 0.02, # 2% after 3 candles str(timeframe_mins * 6)): 0.01, # 1% After 6 candles } ``` Stoploss \u00b6 Setting a stoploss is highly recommended to protect your capital from strong moves against you. Sample: python stoploss = -0.10 This would signify a stoploss of -10%. For the full documentation on stoploss features, look at the dedicated stoploss page . If your exchange supports it, it's recommended to also set \"stoploss_on_exchange\" in the order_types dictionary, so your stoploss is on the exchange and cannot be missed due to network problems, high load or other reasons. For more information on order_types please look here . Timeframe (formerly ticker interval) \u00b6 This is the set of candles the bot should download and use for the analysis. Common values are \"1m\" , \"5m\" , \"15m\" , \"1h\" , however all values supported by your exchange should work. Please note that the same buy/sell signals may work well with one timeframe, but not with the others. This setting is accessible within the strategy methods as the self.timeframe attribute. Metadata dict \u00b6 The metadata-dict (available for populate_buy_trend , populate_sell_trend , populate_indicators ) contains additional information. Currently this is pair , which can be accessed using metadata['pair'] - and will return a pair in the format XRP/BTC . The Metadata-dict should not be modified and does not persist information across multiple calls. Instead, have a look at the section Storing information Additional data (informative_pairs) \u00b6 Get data for non-tradeable pairs \u00b6 Data for additional, informative pairs (reference pairs) can be beneficial for some strategies. OHLCV data for these pairs will be downloaded as part of the regular whitelist refresh process and is available via DataProvider just as other pairs (see below). These parts will not be traded unless they are also specified in the pair whitelist, or have been selected by Dynamic Whitelisting. The pairs need to be specified as tuples in the format (\"pair\", \"timeframe\") , with pair as the first and timeframe as the second argument. Sample: python def informative_pairs(self): return [(\"ETH/USDT\", \"5m\"), (\"BTC/TUSD\", \"15m\"), ] A full sample can be found in the DataProvider section . Warning As these pairs will be refreshed as part of the regular whitelist refresh, it's best to keep this list short. All timeframes and all pairs can be specified as long as they are available (and active) on the used exchange. It is however better to use resampling to longer timeframes whenever possible to avoid hammering the exchange with too many requests and risk being blocked. Additional data (DataProvider) \u00b6 The strategy provides access to the DataProvider . This allows you to get additional data to use in your strategy. All methods return None in case of failure (do not raise an exception). Please always check the mode of operation to select the correct method to get data (samples see below). Hyperopt Dataprovider is available during hyperopt, however it can only be used in populate_indicators() within a strategy. It is not available in populate_buy() and populate_sell() methods, nor in populate_indicators() , if this method located in the hyperopt file. Possible options for DataProvider \u00b6 available_pairs - Property with tuples listing cached pairs with their timeframe (pair, timeframe). current_whitelist() - Returns a current list of whitelisted pairs. Useful for accessing dynamic whitelists (i.e. VolumePairlist) get_pair_dataframe(pair, timeframe) - This is a universal method, which returns either historical data (for backtesting) or cached live data (for the Dry-Run and Live-Run modes). get_analyzed_dataframe(pair, timeframe) - Returns the analyzed dataframe (after calling populate_indicators() , populate_buy() , populate_sell() ) and the time of the latest analysis. historic_ohlcv(pair, timeframe) - Returns historical data stored on disk. market(pair) - Returns market data for the pair: fees, limits, precisions, activity flag, etc. See ccxt documentation for more details on the Market data structure. ohlcv(pair, timeframe) - Currently cached candle (OHLCV) data for the pair, returns DataFrame or empty DataFrame. orderbook(pair, maximum) - Returns latest orderbook data for the pair, a dict with bids/asks with a total of maximum entries. ticker(pair) - Returns current ticker data for the pair. See ccxt documentation for more details on the Ticker data structure. runmode - Property containing the current runmode. Example Usages \u00b6 available_pairs \u00b6 python if self.dp: for pair, timeframe in self.dp.available_pairs: print(f\"available {pair}, {timeframe}\") current_whitelist() \u00b6 Imagine you've developed a strategy that trades the 5m timeframe using signals generated from a 1d timeframe on the top 10 volume pairs by volume. The strategy might look something like this: Scan through the top 10 pairs by volume using the VolumePairList every 5 minutes and use a 14 day RSI to buy and sell. Due to the limited available data, it's very difficult to resample our 5m candles into daily candles for use in a 14 day RSI. Most exchanges limit us to just 500 candles which effectively gives us around 1.74 daily candles. We need 14 days at least! Since we can't resample our data we will have to use an informative pair; and since our whitelist will be dynamic we don't know which pair(s) to use. This is where calling self.dp.current_whitelist() comes in handy. ```python def informative_pairs(self): # get access to all pairs available in whitelist. pairs = self.dp.current_whitelist() # Assign tf to each pair so they can be downloaded and cached for strategy. informative_pairs = [(pair, '1d') for pair in pairs] return informative_pairs ``` get_pair_dataframe(pair, timeframe) \u00b6 ``` python fetch live / historical candle (OHLCV) data for the first informative pair \u00b6 if self.dp: inf_pair, inf_timeframe = self.informative_pairs()[0] informative = self.dp.get_pair_dataframe(pair=inf_pair, timeframe=inf_timeframe) ``` Warning about backtesting Be careful when using dataprovider in backtesting. historic_ohlcv() (and get_pair_dataframe() for the backtesting runmode) provides the full time-range in one go, so please be aware of it and make sure to not \"look into the future\" to avoid surprises when running in dry/live mode. get_analyzed_dataframe(pair, timeframe) \u00b6 This method is used by freqtrade internally to determine the last signal. It can also be used in specific callbacks to get the signal that caused the action (see Advanced Strategy Documentation for more details on available callbacks). ``` python fetch current dataframe \u00b6 if self.dp: if self.dp.runmode.value in ('live', 'dry_run'): dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=metadata['pair'], timeframe=self.timeframe) ``` No data available Returns an empty dataframe if the requested pair was not cached. This should not happen when using whitelisted pairs. orderbook(pair, maximum) \u00b6 python if self.dp: if self.dp.runmode.value in ('live', 'dry_run'): ob = self.dp.orderbook(metadata['pair'], 1) dataframe['best_bid'] = ob['bids'][0][0] dataframe['best_ask'] = ob['asks'][0][0] The orderbook structure is aligned with the order structure from ccxt , so the result will look as follows: js { 'bids': [ [ price, amount ], // [ float, float ] [ price, amount ], ... ], 'asks': [ [ price, amount ], [ price, amount ], //... ], //... } Therefore, using ob['bids'][0][0] as demonstrated above will result in using the best bid price. ob['bids'][0][1] would look at the amount at this orderbook position. Warning about backtesting The order book is not part of the historic data which means backtesting and hyperopt will not work correctly if this method is used, as the method will return uptodate values. ticker(pair) \u00b6 python if self.dp: if self.dp.runmode.value in ('live', 'dry_run'): ticker = self.dp.ticker(metadata['pair']) dataframe['last_price'] = ticker['last'] dataframe['volume24h'] = ticker['quoteVolume'] dataframe['vwap'] = ticker['vwap'] Warning Although the ticker data structure is a part of the ccxt Unified Interface, the values returned by this method can vary for different exchanges. For instance, many exchanges do not return vwap values, the FTX exchange does not always fills in the last field (so it can be None), etc. So you need to carefully verify the ticker data returned from the exchange and add appropriate error handling / defaults. Warning about backtesting This method will always return up-to-date values - so usage during backtesting / hyperopt will lead to wrong results. Complete Data-provider sample \u00b6 ```python from freqtrade.strategy import IStrategy, merge_informative_pair from pandas import DataFrame class SampleStrategy(IStrategy): # strategy init stuff... timeframe = '5m' # more strategy init stuff.. def informative_pairs(self): # get access to all pairs available in whitelist. pairs = self.dp.current_whitelist() # Assign tf to each pair so they can be downloaded and cached for strategy. informative_pairs = [(pair, '1d') for pair in pairs] # Optionally Add additional \"static\" pairs informative_pairs += [(\"ETH/USDT\", \"5m\"), (\"BTC/TUSD\", \"15m\"), ] return informative_pairs def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: if not self.dp: # Don't do anything if DataProvider is not available. return dataframe inf_tf = '1d' # Get the informative pair informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=inf_tf) # Get the 14 day rsi informative['rsi'] = ta.RSI(informative, timeperiod=14) # Use the helper function merge_informative_pair to safely merge the pair # Automatically renames the columns and merges a shorter timeframe dataframe and a longer timeframe informative pair # use ffill to have the 1d value available in every row throughout the day. # Without this, comparisons between columns of the original and the informative pair would only work once per day. # Full documentation of this method, see below dataframe = merge_informative_pair(dataframe, informative, self.timeframe, inf_tf, ffill=True) # Calculate rsi of the original dataframe (5m timeframe) dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14) # Do other stuff # ... return dataframe def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe.loc[ ( (qtpylib.crossed_above(dataframe['rsi'], 30)) & # Signal: RSI crosses above 30 (dataframe['rsi_1d'] < 30) & # Ensure daily RSI is < 30 (dataframe['volume'] > 0) # Ensure this candle had volume (important for backtesting) ), 'buy'] = 1 ``` Helper functions \u00b6 merge_informative_pair() \u00b6 This method helps you merge an informative pair to a regular dataframe without lookahead bias. It's there to help you merge the dataframe in a safe and consistent way. Options: Rename the columns for you to create unique columns Merge the dataframe without lookahead bias Forward-fill (optional) All columns of the informative dataframe will be available on the returning dataframe in a renamed fashion: Column renaming Assuming inf_tf = '1d' the resulting columns will be: python 'date', 'open', 'high', 'low', 'close', 'rsi' # from the original dataframe 'date_1d', 'open_1d', 'high_1d', 'low_1d', 'close_1d', 'rsi_1d' # from the informative dataframe Column renaming - 1h Assuming inf_tf = '1h' the resulting columns will be: python 'date', 'open', 'high', 'low', 'close', 'rsi' # from the original dataframe 'date_1h', 'open_1h', 'high_1h', 'low_1h', 'close_1h', 'rsi_1h' # from the informative dataframe Custom implementation A custom implementation for this is possible, and can be done as follows: ``` python Shift date by 1 candle \u00b6 This is necessary since the data is always the \"open date\" \u00b6 and a 15m candle starting at 12:15 should not know the close of the 1h candle from 12:00 to 13:00 \u00b6 minutes = timeframe_to_minutes(inf_tf) Only do this if the timeframes are different: \u00b6 informative['date_merge'] = informative[\"date\"] + pd.to_timedelta(minutes, 'm') Rename columns to be unique \u00b6 informative.columns = [f\"{col}_{inf_tf}\" for col in informative.columns] Assuming inf_tf = '1d' - then the columns will now be: \u00b6 date_1d, open_1d, high_1d, low_1d, close_1d, rsi_1d \u00b6 Combine the 2 dataframes \u00b6 all indicators on the informative sample MUST be calculated before this point \u00b6 dataframe = pd.merge(dataframe, informative, left_on='date', right_on=f'date_merge_{inf_tf}', how='left') FFill to have the 1d value available in every row throughout the day. \u00b6 Without this, comparisons would only work once per day. \u00b6 dataframe = dataframe.ffill() ``` Informative timeframe < timeframe Using informative timeframes smaller than the dataframe timeframe is not recommended with this method, as it will not use any of the additional information this would provide. To use the more detailed information properly, more advanced methods should be applied (which are out of scope for freqtrade documentation, as it'll depend on the respective need). stoploss_from_open() \u00b6 Stoploss values returned from custom_stoploss must specify a percentage relative to current_rate , but sometimes you may want to specify a stoploss relative to the open price instead. stoploss_from_open() is a helper function to calculate a stoploss value that can be returned from custom_stoploss which will be equivalent to the desired percentage above the open price. Returning a stoploss relative to the open price from the custom stoploss function Say the open price was $100, and current_price is $121 ( current_profit will be 0.21 ). If we want a stop price at 7% above the open price we can call stoploss_from_open(0.07, current_profit) which will return 0.1157024793 . 11.57% below $121 is $107, which is the same as 7% above $100. ``` python from datetime import datetime from freqtrade.persistence import Trade from freqtrade.strategy import IStrategy, stoploss_from_open class AwesomeStrategy(IStrategy): # ... populate_* methods use_custom_stoploss = True def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: # once the profit has risen above 10%, keep the stoploss at 7% above the open price if current_profit > 0.10: return stoploss_from_open(0.07, current_profit) return 1 ``` Full examples can be found in the Custom stoploss section of the Documentation. Additional data (Wallets) \u00b6 The strategy provides access to the Wallets object. This contains the current balances on the exchange. Note Wallets is not available during backtesting / hyperopt. Please always check if Wallets is available to avoid failures during backtesting. python if self.wallets: free_eth = self.wallets.get_free('ETH') used_eth = self.wallets.get_used('ETH') total_eth = self.wallets.get_total('ETH') Possible options for Wallets \u00b6 get_free(asset) - currently available balance to trade get_used(asset) - currently tied up balance (open orders) get_total(asset) - total available balance - sum of the 2 above Additional data (Trades) \u00b6 A history of Trades can be retrieved in the strategy by querying the database. At the top of the file, import Trade. python from freqtrade.persistence import Trade The following example queries for the current pair and trades from today, however other filters can easily be added. python if self.config['runmode'].value in ('live', 'dry_run'): trades = Trade.get_trades([Trade.pair == metadata['pair'], Trade.open_date > datetime.utcnow() - timedelta(days=1), Trade.is_open.is_(False), ]).order_by(Trade.close_date).all() # Summarize profit for this pair. curdayprofit = sum(trade.close_profit for trade in trades) Get amount of stake_currency currently invested in Trades: python if self.config['runmode'].value in ('live', 'dry_run'): total_stakes = Trade.total_open_trades_stakes() Retrieve performance per pair. Returns a List of dicts per pair. python if self.config['runmode'].value in ('live', 'dry_run'): performance = Trade.get_overall_performance() Sample return value: ETH/BTC had 5 trades, with a total profit of 1.5% (ratio of 0.015). json {'pair': \"ETH/BTC\", 'profit': 0.015, 'count': 5} Warning Trade history is not available during backtesting or hyperopt. Prevent trades from happening for a specific pair \u00b6 Freqtrade locks pairs automatically for the current candle (until that candle is over) when a pair is sold, preventing an immediate re-buy of that pair. Locked pairs will show the message Pair is currently locked. . Locking pairs from within the strategy \u00b6 Sometimes it may be desired to lock a pair after certain events happen (e.g. multiple losing trades in a row). Freqtrade has an easy method to do this from within the strategy, by calling self.lock_pair(pair, until, [reason]) . until must be a datetime object in the future, after which trading will be re-enabled for that pair, while reason is an optional string detailing why the pair was locked. Locks can also be lifted manually, by calling self.unlock_pair(pair) . To verify if a pair is currently locked, use self.is_pair_locked(pair) . Note Locked pairs will always be rounded up to the next candle. So assuming a 5m timeframe, a lock with until set to 10:18 will lock the pair until the candle from 10:15-10:20 will be finished. Warning Manually locking pairs is not available during backtesting, only locks via Protections are allowed. Pair locking example \u00b6 ``` python from freqtrade.persistence import Trade from datetime import timedelta, datetime, timezone Put the above lines a the top of the strategy file, next to all the other imports \u00b6 -------- \u00b6 Within populate indicators (or populate_buy): \u00b6 if self.config['runmode'].value in ('live', 'dry_run'): # fetch closed trades for the last 2 days trades = Trade.get_trades([Trade.pair == metadata['pair'], Trade.open_date > datetime.utcnow() - timedelta(days=2), Trade.is_open.is_(False), ]).all() # Analyze the conditions you'd like to lock the pair .... will probably be different for every strategy sumprofit = sum(trade.close_profit for trade in trades) if sumprofit < 0: # Lock pair for 12 hours self.lock_pair(metadata['pair'], until=datetime.now(timezone.utc) + timedelta(hours=12)) ``` Print created dataframe \u00b6 To inspect the created dataframe, you can issue a print-statement in either populate_buy_trend() or populate_sell_trend() . You may also want to print the pair so it's clear what data is currently shown. ``` python def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe.loc[ ( #>> whatever condition<<< ), 'buy'] = 1 # Print the Analyzed pair print(f\"result for {metadata['pair']}\") # Inspect the last 5 rows print(dataframe.tail()) return dataframe ``` Printing more than a few rows is also possible (simply use print(dataframe) instead of print(dataframe.tail()) ), however not recommended, as that will be very verbose (~500 lines per pair every 5 seconds). Common mistakes when developing strategies \u00b6 Backtesting analyzes the whole time-range at once for performance reasons. Because of this, strategy authors need to make sure that strategies do not look-ahead into the future. This is a common pain-point, which can cause huge differences between backtesting and dry/live run methods, since they all use data which is not available during dry/live runs, so these strategies will perform well during backtesting, but will fail / perform badly in real conditions. The following lists some common patterns which should be avoided to prevent frustration: don't use shift(-1) . This uses data from the future, which is not available. don't use .iloc[-1] or any other absolute position in the dataframe, this will be different between dry-run and backtesting. don't use dataframe['volume'].mean() . This uses the full DataFrame for backtesting, including data from the future. Use dataframe['volume'].rolling().mean() instead don't use .resample('1h') . This uses the left border of the interval, so moves data from an hour to the start of the hour. Use .resample('1h', label='right') instead. Further strategy ideas \u00b6 To get additional Ideas for strategies, head over to our strategy repository . Feel free to use them as they are - but results will depend on the current market situation, pairs used etc. - therefore please backtest the strategy for your exchange/desired pairs first, evaluate carefully, use at your own risk. Feel free to use any of them as inspiration for your own strategies. We're happy to accept Pull Requests containing new Strategies to that repo. Next step \u00b6 Now you have a perfect strategy you probably want to backtest it. Your next step is to learn How to use the Backtesting .","title":"Strategy Customization"},{"location":"strategy-customization/#strategy-customization","text":"This page explains how to customize your strategies, add new indicators and set up trading rules. Please familiarize yourself with Freqtrade basics first, which provides overall info on how the bot operates.","title":"Strategy Customization"},{"location":"strategy-customization/#install-a-custom-strategy-file","text":"This is very simple. Copy paste your strategy file into the directory user_data/strategies . Let assume you have a class called AwesomeStrategy in the file AwesomeStrategy.py : Move your file into user_data/strategies (you should have user_data/strategies/AwesomeStrategy.py Start the bot with the param --strategy AwesomeStrategy (the parameter is the class name) bash freqtrade trade --strategy AwesomeStrategy","title":"Install a custom strategy file"},{"location":"strategy-customization/#develop-your-own-strategy","text":"The bot includes a default strategy file. Also, several other strategies are available in the strategy repository . You will however most likely have your own idea for a strategy. This document intends to help you develop one for yourself. To get started, use freqtrade new-strategy --strategy AwesomeStrategy . This will create a new strategy file from a template, which will be located under user_data/strategies/AwesomeStrategy.py . Note This is just a template file, which will most likely not be profitable out of the box.","title":"Develop your own strategy"},{"location":"strategy-customization/#anatomy-of-a-strategy","text":"A strategy file contains all the information needed to build a good strategy: Indicators Buy strategy rules Sell strategy rules Minimal ROI recommended Stoploss strongly recommended The bot also include a sample strategy called SampleStrategy you can update: user_data/strategies/sample_strategy.py . You can test it with the parameter: --strategy SampleStrategy Additionally, there is an attribute called INTERFACE_VERSION , which defines the version of the strategy interface the bot should use. The current version is 2 - which is also the default when it's not set explicitly in the strategy. Future versions will require this to be set. bash freqtrade trade --strategy AwesomeStrategy For the following section we will use the user_data/strategies/sample_strategy.py file as reference. Strategies and Backtesting To avoid problems and unexpected differences between Backtesting and dry/live modes, please be aware that during backtesting the full time range is passed to the populate_*() methods at once. It is therefore best to use vectorized operations (across the whole dataframe, not loops) and avoid index referencing ( df.iloc[-1] ), but instead use df.shift() to get to the previous candle. Warning: Using future data Since backtesting passes the full time range to the populate_*() methods, the strategy author needs to take care to avoid having the strategy utilize data from the future. Some common patterns for this are listed in the Common Mistakes section of this document.","title":"Anatomy of a strategy"},{"location":"strategy-customization/#customize-indicators","text":"Buy and sell strategies need indicators. You can add more indicators by extending the list contained in the method populate_indicators() from your strategy file. You should only add the indicators used in either populate_buy_trend() , populate_sell_trend() , or to populate another indicator, otherwise performance may suffer. It's important to always return the dataframe without removing/modifying the columns \"open\", \"high\", \"low\", \"close\", \"volume\" , otherwise these fields would contain something unexpected. Sample: ```python def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: \"\"\" Adds several different TA indicators to the given DataFrame Performance Note: For the best performance be frugal on the number of indicators you are using. Let uncomment only the indicator you are using in your strategies or your hyperopt configuration, otherwise you will waste your memory and CPU usage. :param dataframe: Dataframe with data from the exchange :param metadata: Additional information, like the currently traded pair :return: a Dataframe with all mandatory indicators for the strategies \"\"\" dataframe['sar'] = ta.SAR(dataframe) dataframe['adx'] = ta.ADX(dataframe) stoch = ta.STOCHF(dataframe) dataframe['fastd'] = stoch['fastd'] dataframe['fastk'] = stoch['fastk'] dataframe['blower'] = ta.BBANDS(dataframe, nbdevup=2, nbdevdn=2)['lowerband'] dataframe['sma'] = ta.SMA(dataframe, timeperiod=40) dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9) dataframe['mfi'] = ta.MFI(dataframe) dataframe['rsi'] = ta.RSI(dataframe) dataframe['ema5'] = ta.EMA(dataframe, timeperiod=5) dataframe['ema10'] = ta.EMA(dataframe, timeperiod=10) dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50) dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100) dataframe['ao'] = awesome_oscillator(dataframe) macd = ta.MACD(dataframe) dataframe['macd'] = macd['macd'] dataframe['macdsignal'] = macd['macdsignal'] dataframe['macdhist'] = macd['macdhist'] hilbert = ta.HT_SINE(dataframe) dataframe['htsine'] = hilbert['sine'] dataframe['htleadsine'] = hilbert['leadsine'] dataframe['plus_dm'] = ta.PLUS_DM(dataframe) dataframe['plus_di'] = ta.PLUS_DI(dataframe) dataframe['minus_dm'] = ta.MINUS_DM(dataframe) dataframe['minus_di'] = ta.MINUS_DI(dataframe) return dataframe ``` Want more indicator examples? Look into the user_data/strategies/sample_strategy.py . Then uncomment indicators you need.","title":"Customize Indicators"},{"location":"strategy-customization/#strategy-startup-period","text":"Most indicators have an instable startup period, in which they are either not available, or the calculation is incorrect. This can lead to inconsistencies, since Freqtrade does not know how long this instable period should be. To account for this, the strategy can be assigned the startup_candle_count attribute. This should be set to the maximum number of candles that the strategy requires to calculate stable indicators. In this example strategy, this should be set to 100 ( startup_candle_count = 100 ), since the longest needed history is 100 candles. python dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100) By letting the bot know how much history is needed, backtest trades can start at the specified timerange during backtesting and hyperopt. Warning startup_candle_count should be below ohlcv_candle_limit (which is 500 for most exchanges) - since only this amount of candles will be available during Dry-Run/Live Trade operations.","title":"Strategy startup period"},{"location":"strategy-customization/#example","text":"Let's try to backtest 1 month (January 2019) of 5m candles using an example strategy with EMA100, as above. bash freqtrade backtesting --timerange 20190101-20190201 --timeframe 5m Assuming startup_candle_count is set to 100, backtesting knows it needs 100 candles to generate valid buy signals. It will load data from 20190101 - (100 * 5m) - which is ~2018-12-31 15:30:00. If this data is available, indicators will be calculated with this extended timerange. The instable startup period (up to 2019-01-01 00:00:00) will then be removed before starting backtesting. Note If data for the startup period is not available, then the timerange will be adjusted to account for this startup period - so Backtesting would start at 2019-01-01 08:30:00.","title":"Example"},{"location":"strategy-customization/#buy-signal-rules","text":"Edit the method populate_buy_trend() in your strategy file to update your buy strategy. It's important to always return the dataframe without removing/modifying the columns \"open\", \"high\", \"low\", \"close\", \"volume\" , otherwise these fields would contain something unexpected. This method will also define a new column, \"buy\" , which needs to contain 1 for buys, and 0 for \"no action\". Sample from user_data/strategies/sample_strategy.py : ```python def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: \"\"\" Based on TA indicators, populates the buy signal for the given dataframe :param dataframe: DataFrame populated with indicators :param metadata: Additional information, like the currently traded pair :return: DataFrame with buy column \"\"\" dataframe.loc[ ( (qtpylib.crossed_above(dataframe['rsi'], 30)) & # Signal: RSI crosses above 30 (dataframe['tema'] <= dataframe['bb_middleband']) & # Guard (dataframe['tema'] > dataframe['tema'].shift(1)) & # Guard (dataframe['volume'] > 0) # Make sure Volume is not 0 ), 'buy'] = 1 return dataframe ``` Note Buying requires sellers to buy from - therefore volume needs to be > 0 ( dataframe['volume'] > 0 ) to make sure that the bot does not buy/sell in no-activity periods.","title":"Buy signal rules"},{"location":"strategy-customization/#sell-signal-rules","text":"Edit the method populate_sell_trend() into your strategy file to update your sell strategy. Please note that the sell-signal is only used if use_sell_signal is set to true in the configuration. It's important to always return the dataframe without removing/modifying the columns \"open\", \"high\", \"low\", \"close\", \"volume\" , otherwise these fields would contain something unexpected. This method will also define a new column, \"sell\" , which needs to contain 1 for sells, and 0 for \"no action\". Sample from user_data/strategies/sample_strategy.py : python def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: \"\"\" Based on TA indicators, populates the sell signal for the given dataframe :param dataframe: DataFrame populated with indicators :param metadata: Additional information, like the currently traded pair :return: DataFrame with buy column \"\"\" dataframe.loc[ ( (qtpylib.crossed_above(dataframe['rsi'], 70)) & # Signal: RSI crosses above 70 (dataframe['tema'] > dataframe['bb_middleband']) & # Guard (dataframe['tema'] < dataframe['tema'].shift(1)) & # Guard (dataframe['volume'] > 0) # Make sure Volume is not 0 ), 'sell'] = 1 return dataframe","title":"Sell signal rules"},{"location":"strategy-customization/#minimal-roi","text":"This dict defines the minimal Return On Investment (ROI) a trade should reach before selling, independent from the sell signal. It is of the following format, with the dict key (left side of the colon) being the minutes passed since the trade opened, and the value (right side of the colon) being the percentage. python minimal_roi = { \"40\": 0.0, \"30\": 0.01, \"20\": 0.02, \"0\": 0.04 } The above configuration would therefore mean: Sell whenever 4% profit was reached Sell when 2% profit was reached (in effect after 20 minutes) Sell when 1% profit was reached (in effect after 30 minutes) Sell when trade is non-loosing (in effect after 40 minutes) The calculation does include fees. To disable ROI completely, set it to an insanely high number: python minimal_roi = { \"0\": 100 } While technically not completely disabled, this would sell once the trade reaches 10000% Profit. To use times based on candle duration (timeframe), the following snippet can be handy. This will allow you to change the timeframe for the strategy, and ROI times will still be set as candles (e.g. after 3 candles ...) ``` python from freqtrade.exchange import timeframe_to_minutes class AwesomeStrategy(IStrategy): timeframe = \"1d\" timeframe_mins = timeframe_to_minutes(timeframe) minimal_roi = { \"0\": 0.05, # 5% for the first 3 candles str(timeframe_mins * 3)): 0.02, # 2% after 3 candles str(timeframe_mins * 6)): 0.01, # 1% After 6 candles } ```","title":"Minimal ROI"},{"location":"strategy-customization/#stoploss","text":"Setting a stoploss is highly recommended to protect your capital from strong moves against you. Sample: python stoploss = -0.10 This would signify a stoploss of -10%. For the full documentation on stoploss features, look at the dedicated stoploss page . If your exchange supports it, it's recommended to also set \"stoploss_on_exchange\" in the order_types dictionary, so your stoploss is on the exchange and cannot be missed due to network problems, high load or other reasons. For more information on order_types please look here .","title":"Stoploss"},{"location":"strategy-customization/#timeframe-formerly-ticker-interval","text":"This is the set of candles the bot should download and use for the analysis. Common values are \"1m\" , \"5m\" , \"15m\" , \"1h\" , however all values supported by your exchange should work. Please note that the same buy/sell signals may work well with one timeframe, but not with the others. This setting is accessible within the strategy methods as the self.timeframe attribute.","title":"Timeframe (formerly ticker interval)"},{"location":"strategy-customization/#metadata-dict","text":"The metadata-dict (available for populate_buy_trend , populate_sell_trend , populate_indicators ) contains additional information. Currently this is pair , which can be accessed using metadata['pair'] - and will return a pair in the format XRP/BTC . The Metadata-dict should not be modified and does not persist information across multiple calls. Instead, have a look at the section Storing information","title":"Metadata dict"},{"location":"strategy-customization/#additional-data-informative_pairs","text":"","title":"Additional data (informative_pairs)"},{"location":"strategy-customization/#get-data-for-non-tradeable-pairs","text":"Data for additional, informative pairs (reference pairs) can be beneficial for some strategies. OHLCV data for these pairs will be downloaded as part of the regular whitelist refresh process and is available via DataProvider just as other pairs (see below). These parts will not be traded unless they are also specified in the pair whitelist, or have been selected by Dynamic Whitelisting. The pairs need to be specified as tuples in the format (\"pair\", \"timeframe\") , with pair as the first and timeframe as the second argument. Sample: python def informative_pairs(self): return [(\"ETH/USDT\", \"5m\"), (\"BTC/TUSD\", \"15m\"), ] A full sample can be found in the DataProvider section . Warning As these pairs will be refreshed as part of the regular whitelist refresh, it's best to keep this list short. All timeframes and all pairs can be specified as long as they are available (and active) on the used exchange. It is however better to use resampling to longer timeframes whenever possible to avoid hammering the exchange with too many requests and risk being blocked.","title":"Get data for non-tradeable pairs"},{"location":"strategy-customization/#additional-data-dataprovider","text":"The strategy provides access to the DataProvider . This allows you to get additional data to use in your strategy. All methods return None in case of failure (do not raise an exception). Please always check the mode of operation to select the correct method to get data (samples see below). Hyperopt Dataprovider is available during hyperopt, however it can only be used in populate_indicators() within a strategy. It is not available in populate_buy() and populate_sell() methods, nor in populate_indicators() , if this method located in the hyperopt file.","title":"Additional data (DataProvider)"},{"location":"strategy-customization/#possible-options-for-dataprovider","text":"available_pairs - Property with tuples listing cached pairs with their timeframe (pair, timeframe). current_whitelist() - Returns a current list of whitelisted pairs. Useful for accessing dynamic whitelists (i.e. VolumePairlist) get_pair_dataframe(pair, timeframe) - This is a universal method, which returns either historical data (for backtesting) or cached live data (for the Dry-Run and Live-Run modes). get_analyzed_dataframe(pair, timeframe) - Returns the analyzed dataframe (after calling populate_indicators() , populate_buy() , populate_sell() ) and the time of the latest analysis. historic_ohlcv(pair, timeframe) - Returns historical data stored on disk. market(pair) - Returns market data for the pair: fees, limits, precisions, activity flag, etc. See ccxt documentation for more details on the Market data structure. ohlcv(pair, timeframe) - Currently cached candle (OHLCV) data for the pair, returns DataFrame or empty DataFrame. orderbook(pair, maximum) - Returns latest orderbook data for the pair, a dict with bids/asks with a total of maximum entries. ticker(pair) - Returns current ticker data for the pair. See ccxt documentation for more details on the Ticker data structure. runmode - Property containing the current runmode.","title":"Possible options for DataProvider"},{"location":"strategy-customization/#example-usages","text":"","title":"Example Usages"},{"location":"strategy-customization/#available_pairs","text":"python if self.dp: for pair, timeframe in self.dp.available_pairs: print(f\"available {pair}, {timeframe}\")","title":"available_pairs"},{"location":"strategy-customization/#current_whitelist","text":"Imagine you've developed a strategy that trades the 5m timeframe using signals generated from a 1d timeframe on the top 10 volume pairs by volume. The strategy might look something like this: Scan through the top 10 pairs by volume using the VolumePairList every 5 minutes and use a 14 day RSI to buy and sell. Due to the limited available data, it's very difficult to resample our 5m candles into daily candles for use in a 14 day RSI. Most exchanges limit us to just 500 candles which effectively gives us around 1.74 daily candles. We need 14 days at least! Since we can't resample our data we will have to use an informative pair; and since our whitelist will be dynamic we don't know which pair(s) to use. This is where calling self.dp.current_whitelist() comes in handy. ```python def informative_pairs(self): # get access to all pairs available in whitelist. pairs = self.dp.current_whitelist() # Assign tf to each pair so they can be downloaded and cached for strategy. informative_pairs = [(pair, '1d') for pair in pairs] return informative_pairs ```","title":"current_whitelist()"},{"location":"strategy-customization/#get_pair_dataframepair-timeframe","text":"``` python","title":"get_pair_dataframe(pair, timeframe)"},{"location":"strategy-customization/#fetch-live-historical-candle-ohlcv-data-for-the-first-informative-pair","text":"if self.dp: inf_pair, inf_timeframe = self.informative_pairs()[0] informative = self.dp.get_pair_dataframe(pair=inf_pair, timeframe=inf_timeframe) ``` Warning about backtesting Be careful when using dataprovider in backtesting. historic_ohlcv() (and get_pair_dataframe() for the backtesting runmode) provides the full time-range in one go, so please be aware of it and make sure to not \"look into the future\" to avoid surprises when running in dry/live mode.","title":"fetch live / historical candle (OHLCV) data for the first informative pair"},{"location":"strategy-customization/#get_analyzed_dataframepair-timeframe","text":"This method is used by freqtrade internally to determine the last signal. It can also be used in specific callbacks to get the signal that caused the action (see Advanced Strategy Documentation for more details on available callbacks). ``` python","title":"get_analyzed_dataframe(pair, timeframe)"},{"location":"strategy-customization/#fetch-current-dataframe","text":"if self.dp: if self.dp.runmode.value in ('live', 'dry_run'): dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=metadata['pair'], timeframe=self.timeframe) ``` No data available Returns an empty dataframe if the requested pair was not cached. This should not happen when using whitelisted pairs.","title":"fetch current dataframe"},{"location":"strategy-customization/#orderbookpair-maximum","text":"python if self.dp: if self.dp.runmode.value in ('live', 'dry_run'): ob = self.dp.orderbook(metadata['pair'], 1) dataframe['best_bid'] = ob['bids'][0][0] dataframe['best_ask'] = ob['asks'][0][0] The orderbook structure is aligned with the order structure from ccxt , so the result will look as follows: js { 'bids': [ [ price, amount ], // [ float, float ] [ price, amount ], ... ], 'asks': [ [ price, amount ], [ price, amount ], //... ], //... } Therefore, using ob['bids'][0][0] as demonstrated above will result in using the best bid price. ob['bids'][0][1] would look at the amount at this orderbook position. Warning about backtesting The order book is not part of the historic data which means backtesting and hyperopt will not work correctly if this method is used, as the method will return uptodate values.","title":"orderbook(pair, maximum)"},{"location":"strategy-customization/#tickerpair","text":"python if self.dp: if self.dp.runmode.value in ('live', 'dry_run'): ticker = self.dp.ticker(metadata['pair']) dataframe['last_price'] = ticker['last'] dataframe['volume24h'] = ticker['quoteVolume'] dataframe['vwap'] = ticker['vwap'] Warning Although the ticker data structure is a part of the ccxt Unified Interface, the values returned by this method can vary for different exchanges. For instance, many exchanges do not return vwap values, the FTX exchange does not always fills in the last field (so it can be None), etc. So you need to carefully verify the ticker data returned from the exchange and add appropriate error handling / defaults. Warning about backtesting This method will always return up-to-date values - so usage during backtesting / hyperopt will lead to wrong results.","title":"ticker(pair)"},{"location":"strategy-customization/#complete-data-provider-sample","text":"```python from freqtrade.strategy import IStrategy, merge_informative_pair from pandas import DataFrame class SampleStrategy(IStrategy): # strategy init stuff... timeframe = '5m' # more strategy init stuff.. def informative_pairs(self): # get access to all pairs available in whitelist. pairs = self.dp.current_whitelist() # Assign tf to each pair so they can be downloaded and cached for strategy. informative_pairs = [(pair, '1d') for pair in pairs] # Optionally Add additional \"static\" pairs informative_pairs += [(\"ETH/USDT\", \"5m\"), (\"BTC/TUSD\", \"15m\"), ] return informative_pairs def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: if not self.dp: # Don't do anything if DataProvider is not available. return dataframe inf_tf = '1d' # Get the informative pair informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=inf_tf) # Get the 14 day rsi informative['rsi'] = ta.RSI(informative, timeperiod=14) # Use the helper function merge_informative_pair to safely merge the pair # Automatically renames the columns and merges a shorter timeframe dataframe and a longer timeframe informative pair # use ffill to have the 1d value available in every row throughout the day. # Without this, comparisons between columns of the original and the informative pair would only work once per day. # Full documentation of this method, see below dataframe = merge_informative_pair(dataframe, informative, self.timeframe, inf_tf, ffill=True) # Calculate rsi of the original dataframe (5m timeframe) dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14) # Do other stuff # ... return dataframe def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe.loc[ ( (qtpylib.crossed_above(dataframe['rsi'], 30)) & # Signal: RSI crosses above 30 (dataframe['rsi_1d'] < 30) & # Ensure daily RSI is < 30 (dataframe['volume'] > 0) # Ensure this candle had volume (important for backtesting) ), 'buy'] = 1 ```","title":"Complete Data-provider sample"},{"location":"strategy-customization/#helper-functions","text":"","title":"Helper functions"},{"location":"strategy-customization/#merge_informative_pair","text":"This method helps you merge an informative pair to a regular dataframe without lookahead bias. It's there to help you merge the dataframe in a safe and consistent way. Options: Rename the columns for you to create unique columns Merge the dataframe without lookahead bias Forward-fill (optional) All columns of the informative dataframe will be available on the returning dataframe in a renamed fashion: Column renaming Assuming inf_tf = '1d' the resulting columns will be: python 'date', 'open', 'high', 'low', 'close', 'rsi' # from the original dataframe 'date_1d', 'open_1d', 'high_1d', 'low_1d', 'close_1d', 'rsi_1d' # from the informative dataframe Column renaming - 1h Assuming inf_tf = '1h' the resulting columns will be: python 'date', 'open', 'high', 'low', 'close', 'rsi' # from the original dataframe 'date_1h', 'open_1h', 'high_1h', 'low_1h', 'close_1h', 'rsi_1h' # from the informative dataframe Custom implementation A custom implementation for this is possible, and can be done as follows: ``` python","title":"merge_informative_pair()"},{"location":"strategy-customization/#shift-date-by-1-candle","text":"","title":"Shift date by 1 candle"},{"location":"strategy-customization/#this-is-necessary-since-the-data-is-always-the-open-date","text":"","title":"This is necessary since the data is always the \"open date\""},{"location":"strategy-customization/#and-a-15m-candle-starting-at-1215-should-not-know-the-close-of-the-1h-candle-from-1200-to-1300","text":"minutes = timeframe_to_minutes(inf_tf)","title":"and a 15m candle starting at 12:15 should not know the close of the 1h candle from 12:00 to 13:00"},{"location":"strategy-customization/#only-do-this-if-the-timeframes-are-different","text":"informative['date_merge'] = informative[\"date\"] + pd.to_timedelta(minutes, 'm')","title":"Only do this if the timeframes are different:"},{"location":"strategy-customization/#rename-columns-to-be-unique","text":"informative.columns = [f\"{col}_{inf_tf}\" for col in informative.columns]","title":"Rename columns to be unique"},{"location":"strategy-customization/#assuming-inf_tf-1d-then-the-columns-will-now-be","text":"","title":"Assuming inf_tf = '1d' - then the columns will now be:"},{"location":"strategy-customization/#date_1d-open_1d-high_1d-low_1d-close_1d-rsi_1d","text":"","title":"date_1d, open_1d, high_1d, low_1d, close_1d, rsi_1d"},{"location":"strategy-customization/#combine-the-2-dataframes","text":"","title":"Combine the 2 dataframes"},{"location":"strategy-customization/#all-indicators-on-the-informative-sample-must-be-calculated-before-this-point","text":"dataframe = pd.merge(dataframe, informative, left_on='date', right_on=f'date_merge_{inf_tf}', how='left')","title":"all indicators on the informative sample MUST be calculated before this point"},{"location":"strategy-customization/#ffill-to-have-the-1d-value-available-in-every-row-throughout-the-day","text":"","title":"FFill to have the 1d value available in every row throughout the day."},{"location":"strategy-customization/#without-this-comparisons-would-only-work-once-per-day","text":"dataframe = dataframe.ffill() ``` Informative timeframe < timeframe Using informative timeframes smaller than the dataframe timeframe is not recommended with this method, as it will not use any of the additional information this would provide. To use the more detailed information properly, more advanced methods should be applied (which are out of scope for freqtrade documentation, as it'll depend on the respective need).","title":"Without this, comparisons would only work once per day."},{"location":"strategy-customization/#stoploss_from_open","text":"Stoploss values returned from custom_stoploss must specify a percentage relative to current_rate , but sometimes you may want to specify a stoploss relative to the open price instead. stoploss_from_open() is a helper function to calculate a stoploss value that can be returned from custom_stoploss which will be equivalent to the desired percentage above the open price. Returning a stoploss relative to the open price from the custom stoploss function Say the open price was $100, and current_price is $121 ( current_profit will be 0.21 ). If we want a stop price at 7% above the open price we can call stoploss_from_open(0.07, current_profit) which will return 0.1157024793 . 11.57% below $121 is $107, which is the same as 7% above $100. ``` python from datetime import datetime from freqtrade.persistence import Trade from freqtrade.strategy import IStrategy, stoploss_from_open class AwesomeStrategy(IStrategy): # ... populate_* methods use_custom_stoploss = True def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: # once the profit has risen above 10%, keep the stoploss at 7% above the open price if current_profit > 0.10: return stoploss_from_open(0.07, current_profit) return 1 ``` Full examples can be found in the Custom stoploss section of the Documentation.","title":"stoploss_from_open()"},{"location":"strategy-customization/#additional-data-wallets","text":"The strategy provides access to the Wallets object. This contains the current balances on the exchange. Note Wallets is not available during backtesting / hyperopt. Please always check if Wallets is available to avoid failures during backtesting. python if self.wallets: free_eth = self.wallets.get_free('ETH') used_eth = self.wallets.get_used('ETH') total_eth = self.wallets.get_total('ETH')","title":"Additional data (Wallets)"},{"location":"strategy-customization/#possible-options-for-wallets","text":"get_free(asset) - currently available balance to trade get_used(asset) - currently tied up balance (open orders) get_total(asset) - total available balance - sum of the 2 above","title":"Possible options for Wallets"},{"location":"strategy-customization/#additional-data-trades","text":"A history of Trades can be retrieved in the strategy by querying the database. At the top of the file, import Trade. python from freqtrade.persistence import Trade The following example queries for the current pair and trades from today, however other filters can easily be added. python if self.config['runmode'].value in ('live', 'dry_run'): trades = Trade.get_trades([Trade.pair == metadata['pair'], Trade.open_date > datetime.utcnow() - timedelta(days=1), Trade.is_open.is_(False), ]).order_by(Trade.close_date).all() # Summarize profit for this pair. curdayprofit = sum(trade.close_profit for trade in trades) Get amount of stake_currency currently invested in Trades: python if self.config['runmode'].value in ('live', 'dry_run'): total_stakes = Trade.total_open_trades_stakes() Retrieve performance per pair. Returns a List of dicts per pair. python if self.config['runmode'].value in ('live', 'dry_run'): performance = Trade.get_overall_performance() Sample return value: ETH/BTC had 5 trades, with a total profit of 1.5% (ratio of 0.015). json {'pair': \"ETH/BTC\", 'profit': 0.015, 'count': 5} Warning Trade history is not available during backtesting or hyperopt.","title":"Additional data (Trades)"},{"location":"strategy-customization/#prevent-trades-from-happening-for-a-specific-pair","text":"Freqtrade locks pairs automatically for the current candle (until that candle is over) when a pair is sold, preventing an immediate re-buy of that pair. Locked pairs will show the message Pair is currently locked. .","title":"Prevent trades from happening for a specific pair"},{"location":"strategy-customization/#locking-pairs-from-within-the-strategy","text":"Sometimes it may be desired to lock a pair after certain events happen (e.g. multiple losing trades in a row). Freqtrade has an easy method to do this from within the strategy, by calling self.lock_pair(pair, until, [reason]) . until must be a datetime object in the future, after which trading will be re-enabled for that pair, while reason is an optional string detailing why the pair was locked. Locks can also be lifted manually, by calling self.unlock_pair(pair) . To verify if a pair is currently locked, use self.is_pair_locked(pair) . Note Locked pairs will always be rounded up to the next candle. So assuming a 5m timeframe, a lock with until set to 10:18 will lock the pair until the candle from 10:15-10:20 will be finished. Warning Manually locking pairs is not available during backtesting, only locks via Protections are allowed.","title":"Locking pairs from within the strategy"},{"location":"strategy-customization/#pair-locking-example","text":"``` python from freqtrade.persistence import Trade from datetime import timedelta, datetime, timezone","title":"Pair locking example"},{"location":"strategy-customization/#put-the-above-lines-a-the-top-of-the-strategy-file-next-to-all-the-other-imports","text":"","title":"Put the above lines a the top of the strategy file, next to all the other imports"},{"location":"strategy-customization/#-","text":"","title":"--------"},{"location":"strategy-customization/#within-populate-indicators-or-populate_buy","text":"if self.config['runmode'].value in ('live', 'dry_run'): # fetch closed trades for the last 2 days trades = Trade.get_trades([Trade.pair == metadata['pair'], Trade.open_date > datetime.utcnow() - timedelta(days=2), Trade.is_open.is_(False), ]).all() # Analyze the conditions you'd like to lock the pair .... will probably be different for every strategy sumprofit = sum(trade.close_profit for trade in trades) if sumprofit < 0: # Lock pair for 12 hours self.lock_pair(metadata['pair'], until=datetime.now(timezone.utc) + timedelta(hours=12)) ```","title":"Within populate indicators (or populate_buy):"},{"location":"strategy-customization/#print-created-dataframe","text":"To inspect the created dataframe, you can issue a print-statement in either populate_buy_trend() or populate_sell_trend() . You may also want to print the pair so it's clear what data is currently shown. ``` python def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe.loc[ ( #>> whatever condition<<< ), 'buy'] = 1 # Print the Analyzed pair print(f\"result for {metadata['pair']}\") # Inspect the last 5 rows print(dataframe.tail()) return dataframe ``` Printing more than a few rows is also possible (simply use print(dataframe) instead of print(dataframe.tail()) ), however not recommended, as that will be very verbose (~500 lines per pair every 5 seconds).","title":"Print created dataframe"},{"location":"strategy-customization/#common-mistakes-when-developing-strategies","text":"Backtesting analyzes the whole time-range at once for performance reasons. Because of this, strategy authors need to make sure that strategies do not look-ahead into the future. This is a common pain-point, which can cause huge differences between backtesting and dry/live run methods, since they all use data which is not available during dry/live runs, so these strategies will perform well during backtesting, but will fail / perform badly in real conditions. The following lists some common patterns which should be avoided to prevent frustration: don't use shift(-1) . This uses data from the future, which is not available. don't use .iloc[-1] or any other absolute position in the dataframe, this will be different between dry-run and backtesting. don't use dataframe['volume'].mean() . This uses the full DataFrame for backtesting, including data from the future. Use dataframe['volume'].rolling().mean() instead don't use .resample('1h') . This uses the left border of the interval, so moves data from an hour to the start of the hour. Use .resample('1h', label='right') instead.","title":"Common mistakes when developing strategies"},{"location":"strategy-customization/#further-strategy-ideas","text":"To get additional Ideas for strategies, head over to our strategy repository . Feel free to use them as they are - but results will depend on the current market situation, pairs used etc. - therefore please backtest the strategy for your exchange/desired pairs first, evaluate carefully, use at your own risk. Feel free to use any of them as inspiration for your own strategies. We're happy to accept Pull Requests containing new Strategies to that repo.","title":"Further strategy ideas"},{"location":"strategy-customization/#next-step","text":"Now you have a perfect strategy you probably want to backtest it. Your next step is to learn How to use the Backtesting .","title":"Next step"},{"location":"strategy_analysis_example/","text":"Strategy analysis example \u00b6 Debugging a strategy can be time-consuming. Freqtrade offers helper functions to visualize raw data. The following assumes you work with SampleStrategy, data for 5m timeframe from Binance and have downloaded them into the data directory in the default location. Setup \u00b6 ```python from pathlib import Path from freqtrade.configuration import Configuration Customize these according to your needs. \u00b6 Initialize empty configuration object \u00b6 config = Configuration.from_files([]) Optionally, use existing configuration file \u00b6 config = Configuration.from_files([\"config.json\"]) \u00b6 Define some constants \u00b6 config[\"timeframe\"] = \"5m\" Name of the strategy class \u00b6 config[\"strategy\"] = \"SampleStrategy\" Location of the data \u00b6 data_location = Path(config['user_data_dir'], 'data', 'binance') Pair to analyze - Only use one pair here \u00b6 pair = \"BTC/USDT\" ``` ```python Load data using values set above \u00b6 from freqtrade.data.history import load_pair_history candles = load_pair_history(datadir=data_location, timeframe=config[\"timeframe\"], pair=pair, data_format = \"hdf5\", ) Confirm success \u00b6 print(\"Loaded \" + str(len(candles)) + f\" rows of data for {pair} from {data_location}\") candles.head() ``` Load and run strategy \u00b6 Rerun each time the strategy file is changed ```python Load strategy using values set above \u00b6 from freqtrade.resolvers import StrategyResolver strategy = StrategyResolver.load_strategy(config) Generate buy/sell signals using strategy \u00b6 df = strategy.analyze_ticker(candles, {'pair': pair}) df.tail() ``` Display the trade details \u00b6 Note that using data.head() would also work, however most indicators have some \"startup\" data at the top of the dataframe. Some possible problems * Columns with NaN values at the end of the dataframe * Columns used in crossed*() functions with completely different units Comparison with full backtest * having 200 buy signals as output for one pair from analyze_ticker() does not necessarily mean that 200 trades will be made during backtesting. * Assuming you use only one condition such as, df['rsi'] < 30 as buy condition, this will generate multiple \"buy\" signals for each pair in sequence (until rsi returns > 29). The bot will only buy on the first of these signals (and also only if a trade-slot (\"max_open_trades\") is still available), or on one of the middle signals, as soon as a \"slot\" becomes available. ```python Report results \u00b6 print(f\"Generated {df['buy'].sum()} buy signals\") data = df.set_index('date', drop=False) data.tail() ``` Load existing objects into a Jupyter notebook \u00b6 The following cells assume that you have already generated data using the cli. They will allow you to drill deeper into your results, and perform analysis which otherwise would make the output very difficult to digest due to information overload. Load backtest results to pandas dataframe \u00b6 Analyze a trades dataframe (also used below for plotting) ```python from freqtrade.data.btanalysis import load_backtest_data, load_backtest_stats if backtest_dir points to a directory, it'll automatically load the last backtest file. \u00b6 backtest_dir = config[\"user_data_dir\"] / \"backtest_results\" backtest_dir can also point to a specific file \u00b6 backtest_dir = config[\"user_data_dir\"] / \"backtest_results/backtest-result-2020-07-01_20-04-22.json\" \u00b6 ``` ```python You can get the full backtest statistics by using the following command. \u00b6 This contains all information used to generate the backtest result. \u00b6 stats = load_backtest_stats(backtest_dir) strategy = 'SampleStrategy' All statistics are available per strategy, so if --strategy-list was used during backtest, this will be reflected here as well. \u00b6 Example usages: \u00b6 print(stats['strategy'][strategy]['results_per_pair']) Get pairlist used for this backtest \u00b6 print(stats['strategy'][strategy]['pairlist']) Get market change (average change of all pairs from start to end of the backtest period) \u00b6 print(stats['strategy'][strategy]['market_change']) Maximum drawdown () \u00b6 print(stats['strategy'][strategy]['max_drawdown']) Maximum drawdown start and end \u00b6 print(stats['strategy'][strategy]['drawdown_start']) print(stats['strategy'][strategy]['drawdown_end']) Get strategy comparison (only relevant if multiple strategies were compared) \u00b6 print(stats['strategy_comparison']) ``` ```python Load backtested trades as dataframe \u00b6 trades = load_backtest_data(backtest_dir) Show value-counts per pair \u00b6 trades.groupby(\"pair\")[\"sell_reason\"].value_counts() ``` Plotting daily profit / equity line \u00b6 ```python Plotting equity line (starting with 0 on day 1 and adding daily profit for each backtested day) \u00b6 from freqtrade.configuration import Configuration from freqtrade.data.btanalysis import load_backtest_data, load_backtest_stats import plotly.express as px import pandas as pd strategy = 'SampleStrategy' \u00b6 config = Configuration.from_files([\"user_data/config.json\"]) \u00b6 backtest_dir = config[\"user_data_dir\"] / \"backtest_results\" \u00b6 stats = load_backtest_stats(backtest_dir) strategy_stats = stats['strategy'][strategy] dates = [] profits = [] for date_profit in strategy_stats['daily_profit']: dates.append(date_profit[0]) profits.append(date_profit[1]) equity = 0 equity_daily = [] for daily_profit in profits: equity_daily.append(equity) equity += float(daily_profit) df = pd.DataFrame({'dates': dates,'equity_daily': equity_daily}) fig = px.line(df, x=\"dates\", y=\"equity_daily\") fig.show() ``` Load live trading results into a pandas dataframe \u00b6 In case you did already some trading and want to analyze your performance ```python from freqtrade.data.btanalysis import load_trades_from_db Fetch trades from database \u00b6 trades = load_trades_from_db(\"sqlite:///tradesv3.sqlite\") Display results \u00b6 trades.groupby(\"pair\")[\"sell_reason\"].value_counts() ``` Analyze the loaded trades for trade parallelism \u00b6 This can be useful to find the best max_open_trades parameter, when used with backtesting in conjunction with --disable-max-market-positions . analyze_trade_parallelism() returns a timeseries dataframe with an \"open_trades\" column, specifying the number of open trades for each candle. ```python from freqtrade.data.btanalysis import analyze_trade_parallelism Analyze the above \u00b6 parallel_trades = analyze_trade_parallelism(trades, '5m') parallel_trades.plot() ``` Plot results \u00b6 Freqtrade offers interactive plotting capabilities based on plotly. ```python from freqtrade.plot.plotting import generate_candlestick_graph Limit graph period to keep plotly quick and reactive \u00b6 Filter trades to one pair \u00b6 trades_red = trades.loc[trades['pair'] == pair] data_red = data['2019-06-01':'2019-06-10'] Generate candlestick graph \u00b6 graph = generate_candlestick_graph(pair=pair, data=data_red, trades=trades_red, indicators1=['sma20', 'ema50', 'ema55'], indicators2=['rsi', 'macd', 'macdsignal', 'macdhist'] ) ``` ```python Show graph inline \u00b6 graph.show() \u00b6 Render graph in a seperate window \u00b6 graph.show(renderer=\"browser\") ``` Plot average profit per trade as distribution graph \u00b6 ```python import plotly.figure_factory as ff hist_data = [trades.profit_ratio] group_labels = ['profit_ratio'] # name of the dataset fig = ff.create_distplot(hist_data, group_labels,bin_size=0.01) fig.show() ``` Feel free to submit an issue or Pull Request enhancing this document if you would like to share ideas on how to best analyze the data.","title":"Strategy analysis"},{"location":"strategy_analysis_example/#strategy-analysis-example","text":"Debugging a strategy can be time-consuming. Freqtrade offers helper functions to visualize raw data. The following assumes you work with SampleStrategy, data for 5m timeframe from Binance and have downloaded them into the data directory in the default location.","title":"Strategy analysis example"},{"location":"strategy_analysis_example/#setup","text":"```python from pathlib import Path from freqtrade.configuration import Configuration","title":"Setup"},{"location":"strategy_analysis_example/#customize-these-according-to-your-needs","text":"","title":"Customize these according to your needs."},{"location":"strategy_analysis_example/#initialize-empty-configuration-object","text":"config = Configuration.from_files([])","title":"Initialize empty configuration object"},{"location":"strategy_analysis_example/#optionally-use-existing-configuration-file","text":"","title":"Optionally, use existing configuration file"},{"location":"strategy_analysis_example/#config-configurationfrom_filesconfigjson","text":"","title":"config = Configuration.from_files([\"config.json\"])"},{"location":"strategy_analysis_example/#define-some-constants","text":"config[\"timeframe\"] = \"5m\"","title":"Define some constants"},{"location":"strategy_analysis_example/#name-of-the-strategy-class","text":"config[\"strategy\"] = \"SampleStrategy\"","title":"Name of the strategy class"},{"location":"strategy_analysis_example/#location-of-the-data","text":"data_location = Path(config['user_data_dir'], 'data', 'binance')","title":"Location of the data"},{"location":"strategy_analysis_example/#pair-to-analyze-only-use-one-pair-here","text":"pair = \"BTC/USDT\" ``` ```python","title":"Pair to analyze - Only use one pair here"},{"location":"strategy_analysis_example/#load-data-using-values-set-above","text":"from freqtrade.data.history import load_pair_history candles = load_pair_history(datadir=data_location, timeframe=config[\"timeframe\"], pair=pair, data_format = \"hdf5\", )","title":"Load data using values set above"},{"location":"strategy_analysis_example/#confirm-success","text":"print(\"Loaded \" + str(len(candles)) + f\" rows of data for {pair} from {data_location}\") candles.head() ```","title":"Confirm success"},{"location":"strategy_analysis_example/#load-and-run-strategy","text":"Rerun each time the strategy file is changed ```python","title":"Load and run strategy"},{"location":"strategy_analysis_example/#load-strategy-using-values-set-above","text":"from freqtrade.resolvers import StrategyResolver strategy = StrategyResolver.load_strategy(config)","title":"Load strategy using values set above"},{"location":"strategy_analysis_example/#generate-buysell-signals-using-strategy","text":"df = strategy.analyze_ticker(candles, {'pair': pair}) df.tail() ```","title":"Generate buy/sell signals using strategy"},{"location":"strategy_analysis_example/#display-the-trade-details","text":"Note that using data.head() would also work, however most indicators have some \"startup\" data at the top of the dataframe. Some possible problems * Columns with NaN values at the end of the dataframe * Columns used in crossed*() functions with completely different units Comparison with full backtest * having 200 buy signals as output for one pair from analyze_ticker() does not necessarily mean that 200 trades will be made during backtesting. * Assuming you use only one condition such as, df['rsi'] < 30 as buy condition, this will generate multiple \"buy\" signals for each pair in sequence (until rsi returns > 29). The bot will only buy on the first of these signals (and also only if a trade-slot (\"max_open_trades\") is still available), or on one of the middle signals, as soon as a \"slot\" becomes available. ```python","title":"Display the trade details"},{"location":"strategy_analysis_example/#report-results","text":"print(f\"Generated {df['buy'].sum()} buy signals\") data = df.set_index('date', drop=False) data.tail() ```","title":"Report results"},{"location":"strategy_analysis_example/#load-existing-objects-into-a-jupyter-notebook","text":"The following cells assume that you have already generated data using the cli. They will allow you to drill deeper into your results, and perform analysis which otherwise would make the output very difficult to digest due to information overload.","title":"Load existing objects into a Jupyter notebook"},{"location":"strategy_analysis_example/#load-backtest-results-to-pandas-dataframe","text":"Analyze a trades dataframe (also used below for plotting) ```python from freqtrade.data.btanalysis import load_backtest_data, load_backtest_stats","title":"Load backtest results to pandas dataframe"},{"location":"strategy_analysis_example/#if-backtest_dir-points-to-a-directory-itll-automatically-load-the-last-backtest-file","text":"backtest_dir = config[\"user_data_dir\"] / \"backtest_results\"","title":"if backtest_dir points to a directory, it'll automatically load the last backtest file."},{"location":"strategy_analysis_example/#backtest_dir-can-also-point-to-a-specific-file","text":"","title":"backtest_dir can also point to a specific file"},{"location":"strategy_analysis_example/#backtest_dir-configuser_data_dir-backtest_resultsbacktest-result-2020-07-01_20-04-22json","text":"``` ```python","title":"backtest_dir = config[\"user_data_dir\"] / \"backtest_results/backtest-result-2020-07-01_20-04-22.json\""},{"location":"strategy_analysis_example/#you-can-get-the-full-backtest-statistics-by-using-the-following-command","text":"","title":"You can get the full backtest statistics by using the following command."},{"location":"strategy_analysis_example/#this-contains-all-information-used-to-generate-the-backtest-result","text":"stats = load_backtest_stats(backtest_dir) strategy = 'SampleStrategy'","title":"This contains all information used to generate the backtest result."},{"location":"strategy_analysis_example/#all-statistics-are-available-per-strategy-so-if-strategy-list-was-used-during-backtest-this-will-be-reflected-here-as-well","text":"","title":"All statistics are available per strategy, so if --strategy-list was used during backtest, this will be reflected here as well."},{"location":"strategy_analysis_example/#example-usages","text":"print(stats['strategy'][strategy]['results_per_pair'])","title":"Example usages:"},{"location":"strategy_analysis_example/#get-pairlist-used-for-this-backtest","text":"print(stats['strategy'][strategy]['pairlist'])","title":"Get pairlist used for this backtest"},{"location":"strategy_analysis_example/#get-market-change-average-change-of-all-pairs-from-start-to-end-of-the-backtest-period","text":"print(stats['strategy'][strategy]['market_change'])","title":"Get market change (average change of all pairs from start to end of the backtest period)"},{"location":"strategy_analysis_example/#maximum-drawdown","text":"print(stats['strategy'][strategy]['max_drawdown'])","title":"Maximum drawdown ()"},{"location":"strategy_analysis_example/#maximum-drawdown-start-and-end","text":"print(stats['strategy'][strategy]['drawdown_start']) print(stats['strategy'][strategy]['drawdown_end'])","title":"Maximum drawdown start and end"},{"location":"strategy_analysis_example/#get-strategy-comparison-only-relevant-if-multiple-strategies-were-compared","text":"print(stats['strategy_comparison']) ``` ```python","title":"Get strategy comparison (only relevant if multiple strategies were compared)"},{"location":"strategy_analysis_example/#load-backtested-trades-as-dataframe","text":"trades = load_backtest_data(backtest_dir)","title":"Load backtested trades as dataframe"},{"location":"strategy_analysis_example/#show-value-counts-per-pair","text":"trades.groupby(\"pair\")[\"sell_reason\"].value_counts() ```","title":"Show value-counts per pair"},{"location":"strategy_analysis_example/#plotting-daily-profit-equity-line","text":"```python","title":"Plotting daily profit / equity line"},{"location":"strategy_analysis_example/#plotting-equity-line-starting-with-0-on-day-1-and-adding-daily-profit-for-each-backtested-day","text":"from freqtrade.configuration import Configuration from freqtrade.data.btanalysis import load_backtest_data, load_backtest_stats import plotly.express as px import pandas as pd","title":"Plotting equity line (starting with 0 on day 1 and adding daily profit for each backtested day)"},{"location":"strategy_analysis_example/#strategy-samplestrategy","text":"","title":"strategy = 'SampleStrategy'"},{"location":"strategy_analysis_example/#config-configurationfrom_filesuser_dataconfigjson","text":"","title":"config = Configuration.from_files([\"user_data/config.json\"])"},{"location":"strategy_analysis_example/#backtest_dir-configuser_data_dir-backtest_results","text":"stats = load_backtest_stats(backtest_dir) strategy_stats = stats['strategy'][strategy] dates = [] profits = [] for date_profit in strategy_stats['daily_profit']: dates.append(date_profit[0]) profits.append(date_profit[1]) equity = 0 equity_daily = [] for daily_profit in profits: equity_daily.append(equity) equity += float(daily_profit) df = pd.DataFrame({'dates': dates,'equity_daily': equity_daily}) fig = px.line(df, x=\"dates\", y=\"equity_daily\") fig.show() ```","title":"backtest_dir = config[\"user_data_dir\"] / \"backtest_results\""},{"location":"strategy_analysis_example/#load-live-trading-results-into-a-pandas-dataframe","text":"In case you did already some trading and want to analyze your performance ```python from freqtrade.data.btanalysis import load_trades_from_db","title":"Load live trading results into a pandas dataframe"},{"location":"strategy_analysis_example/#fetch-trades-from-database","text":"trades = load_trades_from_db(\"sqlite:///tradesv3.sqlite\")","title":"Fetch trades from database"},{"location":"strategy_analysis_example/#display-results","text":"trades.groupby(\"pair\")[\"sell_reason\"].value_counts() ```","title":"Display results"},{"location":"strategy_analysis_example/#analyze-the-loaded-trades-for-trade-parallelism","text":"This can be useful to find the best max_open_trades parameter, when used with backtesting in conjunction with --disable-max-market-positions . analyze_trade_parallelism() returns a timeseries dataframe with an \"open_trades\" column, specifying the number of open trades for each candle. ```python from freqtrade.data.btanalysis import analyze_trade_parallelism","title":"Analyze the loaded trades for trade parallelism"},{"location":"strategy_analysis_example/#analyze-the-above","text":"parallel_trades = analyze_trade_parallelism(trades, '5m') parallel_trades.plot() ```","title":"Analyze the above"},{"location":"strategy_analysis_example/#plot-results","text":"Freqtrade offers interactive plotting capabilities based on plotly. ```python from freqtrade.plot.plotting import generate_candlestick_graph","title":"Plot results"},{"location":"strategy_analysis_example/#limit-graph-period-to-keep-plotly-quick-and-reactive","text":"","title":"Limit graph period to keep plotly quick and reactive"},{"location":"strategy_analysis_example/#filter-trades-to-one-pair","text":"trades_red = trades.loc[trades['pair'] == pair] data_red = data['2019-06-01':'2019-06-10']","title":"Filter trades to one pair"},{"location":"strategy_analysis_example/#generate-candlestick-graph","text":"graph = generate_candlestick_graph(pair=pair, data=data_red, trades=trades_red, indicators1=['sma20', 'ema50', 'ema55'], indicators2=['rsi', 'macd', 'macdsignal', 'macdhist'] ) ``` ```python","title":"Generate candlestick graph"},{"location":"strategy_analysis_example/#show-graph-inline","text":"","title":"Show graph inline"},{"location":"strategy_analysis_example/#graphshow","text":"","title":"graph.show()"},{"location":"strategy_analysis_example/#render-graph-in-a-seperate-window","text":"graph.show(renderer=\"browser\") ```","title":"Render graph in a seperate window"},{"location":"strategy_analysis_example/#plot-average-profit-per-trade-as-distribution-graph","text":"```python import plotly.figure_factory as ff hist_data = [trades.profit_ratio] group_labels = ['profit_ratio'] # name of the dataset fig = ff.create_distplot(hist_data, group_labels,bin_size=0.01) fig.show() ``` Feel free to submit an issue or Pull Request enhancing this document if you would like to share ideas on how to best analyze the data.","title":"Plot average profit per trade as distribution graph"},{"location":"telegram-usage/","text":"Telegram usage \u00b6 Setup your Telegram bot \u00b6 Below we explain how to create your Telegram Bot, and how to get your Telegram user id. 1. Create your Telegram bot \u00b6 Start a chat with the Telegram BotFather Send the message /newbot . BotFather response: Alright, a new bot. How are we going to call it? Please choose a name for your bot. Choose the public name of your bot (e.x. Freqtrade bot ) BotFather response: Good. Now let's choose a username for your bot. It must end in bot . Like this, for example: TetrisBot or tetris_bot. Choose the name id of your bot and send it to the BotFather (e.g. \" My_own_freqtrade_bot \") BotFather response: Done! Congratulations on your new bot. You will find it at t.me/yourbots_name_bot . You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you've finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this. Use this token to access the HTTP API: 22222222:APITOKEN For a description of the Bot API, see this page: https://core.telegram.org/bots/api Father bot will return you the token (API key) Copy the API Token ( 22222222:APITOKEN in the above example) and keep use it for the config parameter token . Don't forget to start the conversation with your bot, by clicking /START button 2. Telegram user_id \u00b6 Get your user id \u00b6 Talk to the userinfobot Get your \"Id\", you will use it for the config parameter chat_id . Use Group id \u00b6 You can use bots in telegram groups by just adding them to the group. You can find the group id by first adding a RawDataBot to your group. The Group id is shown as id in the \"chat\" section, which the RawDataBot will send to you: json \"chat\":{ \"id\":-1001332619709 } For the Freqtrade configuration, you can then use the the full value (including - if it's there) as string: json \"chat_id\": \"-1001332619709\" Control telegram noise \u00b6 Freqtrade provides means to control the verbosity of your telegram bot. Each setting has the following possible values: on - Messages will be sent, and user will be notified. silent - Message will be sent, Notification will be without sound / vibration. off - Skip sending a message-type all together. Example configuration showing the different settings: json \"telegram\": { \"enabled\": true, \"token\": \"your_telegram_token\", \"chat_id\": \"your_telegram_chat_id\", \"notification_settings\": { \"status\": \"silent\", \"warning\": \"on\", \"startup\": \"off\", \"buy\": \"silent\", \"sell\": { \"roi\": \"silent\", \"emergency_sell\": \"on\", \"force_sell\": \"on\", \"sell_signal\": \"silent\", \"trailing_stop_loss\": \"on\", \"stop_loss\": \"on\", \"stoploss_on_exchange\": \"on\", \"custom_sell\": \"silent\" }, \"buy_cancel\": \"silent\", \"sell_cancel\": \"on\", \"buy_fill\": \"off\", \"sell_fill\": \"off\" }, \"reload\": true, \"balance_dust_level\": 0.01 }, buy notifications are sent when the order is placed, while buy_fill notifications are sent when the order is filled on the exchange. sell notifications are sent when the order is placed, while sell_fill notifications are sent when the order is filled on the exchange. *_fill notifications are off by default and must be explicitly enabled. balance_dust_level will define what the /balance command takes as \"dust\" - Currencies with a balance below this will be shown. reload allows you to disable reload-buttons on selected messages. Create a custom keyboard (command shortcut buttons) \u00b6 Telegram allows us to create a custom keyboard with buttons for commands. The default custom keyboard looks like this. python [ [\"/daily\", \"/profit\", \"/balance\"], # row 1, 3 commands [\"/status\", \"/status table\", \"/performance\"], # row 2, 3 commands [\"/count\", \"/start\", \"/stop\", \"/help\"] # row 3, 4 commands ] Usage \u00b6 You can create your own keyboard in config.json : json \"telegram\": { \"enabled\": true, \"token\": \"your_telegram_token\", \"chat_id\": \"your_telegram_chat_id\", \"keyboard\": [ [\"/daily\", \"/stats\", \"/balance\", \"/profit\"], [\"/status table\", \"/performance\"], [\"/reload_config\", \"/count\", \"/logs\"] ] }, Supported Commands Only the following commands are allowed. Command arguments are not supported! /start , /stop , /status , /status table , /trades , /profit , /performance , /daily , /stats , /count , /locks , /balance , /stopbuy , /reload_config , /show_config , /logs , /whitelist , /blacklist , /edge , /help , /version Telegram commands \u00b6 Per default, the Telegram bot shows predefined commands. Some commands are only available by sending them to the bot. The table below list the official commands. You can ask at any moment for help with /help . Command Description /start Starts the trader /stop Stops the trader /stopbuy Stops the trader from opening new trades. Gracefully closes open trades according to their rules. /reload_config Reloads the configuration file /show_config Shows part of the current configuration with relevant settings to operation /logs [limit] Show last log messages. /status Lists all open trades /status Lists one or more specific trade. Separate multiple with a blank space. /status table List all open trades in a table format. Pending buy orders are marked with an asterisk ( ) Pending sell orders are marked with a double asterisk ( *) /trades [limit] List all recently closed trades in a table format. /delete Delete a specific trade from the Database. Tries to close open orders. Requires manual handling of this trade on the exchange. /count Displays number of trades used and available /locks Show currently locked pairs. /unlock Remove the lock for this pair (or for this lock id). /profit [] Display a summary of your profit/loss from close trades and some stats about your performance, over the last n days (all trades by default) /forcesell Instantly sells the given trade (Ignoring minimum_roi ). /forcesell all Instantly sells all open trades (Ignoring minimum_roi ). /forcebuy [rate] Instantly buys the given pair. Rate is optional. ( forcebuy_enable must be set to True) /performance Show performance of each finished trade grouped by pair /balance Show account balance per currency /daily Shows profit or loss per day, over the last n days (n defaults to 7) /stats Shows Wins / losses by Sell reason as well as Avg. holding durations for buys and sells /whitelist Show the current whitelist /blacklist [pair] Show the current blacklist, or adds a pair to the blacklist. /edge Show validated pairs by Edge if it is enabled. /help Show help message /version Show version Telegram commands in action \u00b6 Below, example of Telegram message you will receive for each command. /start \u00b6 Status: running /stop \u00b6 Stopping trader ... Status: stopped /stopbuy \u00b6 status: Setting max_open_trades to 0. Run /reload_config to reset. Prevents the bot from opening new trades by temporarily setting \"max_open_trades\" to 0. Open trades will be handled via their regular rules (ROI / Sell-signal, stoploss, ...). After this, give the bot time to close off open trades (can be checked via /status table ). Once all positions are sold, run /stop to completely stop the bot. /reload_config resets \"max_open_trades\" to the value set in the configuration and resets this command. Warning The stop-buy signal is ONLY active while the bot is running, and is not persisted anyway, so restarting the bot will cause this to reset. /status \u00b6 For each open trade, the bot will send you the following message. Trade ID: 123 (since 1 days ago) Current Pair: CVC/BTC Open Since: 1 days ago Amount: 26.64180098 Open Rate: 0.00007489 Current Rate: 0.00007489 Current Profit: 12.95% Stoploss: 0.00007389 (-0.02%) /status table \u00b6 Return the status of all open trades in a table format. ``` ID Pair Since Profit 67 SC/BTC 1 d 13.33% 123 CVC/BTC 1 h 12.95% ``` /count \u00b6 Return the number of trades used and available. ``` current max 2 10 ``` /profit \u00b6 Return a summary of your profit/loss and performance. ROI: Close trades \u2219 0.00485701 BTC (2.2%) (15.2 \u03a3%) \u2219 62.968 USD ROI: All trades \u2219 0.00255280 BTC (1.5%) (6.43 \u03a3%) \u2219 33.095 EUR Total Trade Count: 138 First Trade opened: 3 days ago Latest Trade opened: 2 minutes ago Avg. Duration: 2:33:45 Best Performing: PAY/BTC: 50.23% The relative profit of 1.2% is the average profit per trade. The relative profit of 15.2 \u03a3% is be based on the starting capital - so in this case, the starting capital was 0.00485701 * 1.152 = 0.00738 BTC . Starting capital is either taken from the available_capital setting, or calculated by using current wallet size - profits. /forcesell \u00b6 BITTREX: Selling BTC/LTC with limit 0.01650000 (profit: ~-4.07%, -0.00008168) /forcebuy [rate] \u00b6 BITTREX: Buying ETH/BTC with limit 0.03400000 ( 1.000000 ETH , 225.290 USD ) Omitting the pair will open a query asking for the pair to buy (based on the current whitelist). Note that for this to work, forcebuy_enable needs to be set to true. More details /performance \u00b6 Return the performance of each crypto-currency the bot has sold. Performance: 1. RCN/BTC 0.003 BTC (57.77%) (1) 2. PAY/BTC 0.0012 BTC (56.91%) (1) 3. VIB/BTC 0.0011 BTC (47.07%) (1) 4. SALT/BTC 0.0010 BTC (30.24%) (1) 5. STORJ/BTC 0.0009 BTC (27.24%) (1) ... /balance \u00b6 Return the balance of all crypto-currency your have on the exchange. Currency: BTC Available: 3.05890234 Balance: 3.05890234 Pending: 0.0 Currency: CVC Available: 86.64180098 Balance: 86.64180098 Pending: 0.0 /daily \u00b6 Per default /daily will return the 7 last days. The example below if for /daily 3 : Daily Profit over the last 3 days: ``` Day Profit BTC Profit USD 2018-01-03 0.00224175 BTC 29,142 USD 2018-01-02 0.00033131 BTC 4,307 USD 2018-01-01 0.00269130 BTC 34.986 USD ``` /whitelist \u00b6 Shows the current whitelist Using whitelist StaticPairList with 22 pairs IOTA/BTC, NEO/BTC, TRX/BTC, VET/BTC, ADA/BTC, ETC/BTC, NCASH/BTC, DASH/BTC, XRP/BTC, XVG/BTC, EOS/BTC, LTC/BTC, OMG/BTC, BTG/BTC, LSK/BTC, ZEC/BTC, HOT/BTC, IOTX/BTC, XMR/BTC, AST/BTC, XLM/BTC, NANO/BTC /blacklist [pair] \u00b6 Shows the current blacklist. If Pair is set, then this pair will be added to the pairlist. Also supports multiple pairs, separated by a space. Use /reload_config to reset the blacklist. Using blacklist StaticPairList with 2 pairs DODGE/BTC , HOT/BTC . /edge \u00b6 Shows pairs validated by Edge along with their corresponding win-rate, expectancy and stoploss values. Edge only validated following pairs: ``` Pair Winrate Expectancy Stoploss DOCK/ETH 0.522727 0.881821 -0.03 PHX/ETH 0.677419 0.560488 -0.03 HOT/ETH 0.733333 0.490492 -0.03 HC/ETH 0.588235 0.280988 -0.02 ARDR/ETH 0.366667 0.143059 -0.01 ``` /version \u00b6 Version: 0.14.3","title":"Telegram"},{"location":"telegram-usage/#telegram-usage","text":"","title":"Telegram usage"},{"location":"telegram-usage/#setup-your-telegram-bot","text":"Below we explain how to create your Telegram Bot, and how to get your Telegram user id.","title":"Setup your Telegram bot"},{"location":"telegram-usage/#1-create-your-telegram-bot","text":"Start a chat with the Telegram BotFather Send the message /newbot . BotFather response: Alright, a new bot. How are we going to call it? Please choose a name for your bot. Choose the public name of your bot (e.x. Freqtrade bot ) BotFather response: Good. Now let's choose a username for your bot. It must end in bot . Like this, for example: TetrisBot or tetris_bot. Choose the name id of your bot and send it to the BotFather (e.g. \" My_own_freqtrade_bot \") BotFather response: Done! Congratulations on your new bot. You will find it at t.me/yourbots_name_bot . You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you've finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this. Use this token to access the HTTP API: 22222222:APITOKEN For a description of the Bot API, see this page: https://core.telegram.org/bots/api Father bot will return you the token (API key) Copy the API Token ( 22222222:APITOKEN in the above example) and keep use it for the config parameter token . Don't forget to start the conversation with your bot, by clicking /START button","title":"1. Create your Telegram bot"},{"location":"telegram-usage/#2-telegram-user_id","text":"","title":"2. Telegram user_id"},{"location":"telegram-usage/#get-your-user-id","text":"Talk to the userinfobot Get your \"Id\", you will use it for the config parameter chat_id .","title":"Get your user id"},{"location":"telegram-usage/#use-group-id","text":"You can use bots in telegram groups by just adding them to the group. You can find the group id by first adding a RawDataBot to your group. The Group id is shown as id in the \"chat\" section, which the RawDataBot will send to you: json \"chat\":{ \"id\":-1001332619709 } For the Freqtrade configuration, you can then use the the full value (including - if it's there) as string: json \"chat_id\": \"-1001332619709\"","title":"Use Group id"},{"location":"telegram-usage/#control-telegram-noise","text":"Freqtrade provides means to control the verbosity of your telegram bot. Each setting has the following possible values: on - Messages will be sent, and user will be notified. silent - Message will be sent, Notification will be without sound / vibration. off - Skip sending a message-type all together. Example configuration showing the different settings: json \"telegram\": { \"enabled\": true, \"token\": \"your_telegram_token\", \"chat_id\": \"your_telegram_chat_id\", \"notification_settings\": { \"status\": \"silent\", \"warning\": \"on\", \"startup\": \"off\", \"buy\": \"silent\", \"sell\": { \"roi\": \"silent\", \"emergency_sell\": \"on\", \"force_sell\": \"on\", \"sell_signal\": \"silent\", \"trailing_stop_loss\": \"on\", \"stop_loss\": \"on\", \"stoploss_on_exchange\": \"on\", \"custom_sell\": \"silent\" }, \"buy_cancel\": \"silent\", \"sell_cancel\": \"on\", \"buy_fill\": \"off\", \"sell_fill\": \"off\" }, \"reload\": true, \"balance_dust_level\": 0.01 }, buy notifications are sent when the order is placed, while buy_fill notifications are sent when the order is filled on the exchange. sell notifications are sent when the order is placed, while sell_fill notifications are sent when the order is filled on the exchange. *_fill notifications are off by default and must be explicitly enabled. balance_dust_level will define what the /balance command takes as \"dust\" - Currencies with a balance below this will be shown. reload allows you to disable reload-buttons on selected messages.","title":"Control telegram noise"},{"location":"telegram-usage/#create-a-custom-keyboard-command-shortcut-buttons","text":"Telegram allows us to create a custom keyboard with buttons for commands. The default custom keyboard looks like this. python [ [\"/daily\", \"/profit\", \"/balance\"], # row 1, 3 commands [\"/status\", \"/status table\", \"/performance\"], # row 2, 3 commands [\"/count\", \"/start\", \"/stop\", \"/help\"] # row 3, 4 commands ]","title":"Create a custom keyboard (command shortcut buttons)"},{"location":"telegram-usage/#usage","text":"You can create your own keyboard in config.json : json \"telegram\": { \"enabled\": true, \"token\": \"your_telegram_token\", \"chat_id\": \"your_telegram_chat_id\", \"keyboard\": [ [\"/daily\", \"/stats\", \"/balance\", \"/profit\"], [\"/status table\", \"/performance\"], [\"/reload_config\", \"/count\", \"/logs\"] ] }, Supported Commands Only the following commands are allowed. Command arguments are not supported! /start , /stop , /status , /status table , /trades , /profit , /performance , /daily , /stats , /count , /locks , /balance , /stopbuy , /reload_config , /show_config , /logs , /whitelist , /blacklist , /edge , /help , /version","title":"Usage"},{"location":"telegram-usage/#telegram-commands","text":"Per default, the Telegram bot shows predefined commands. Some commands are only available by sending them to the bot. The table below list the official commands. You can ask at any moment for help with /help . Command Description /start Starts the trader /stop Stops the trader /stopbuy Stops the trader from opening new trades. Gracefully closes open trades according to their rules. /reload_config Reloads the configuration file /show_config Shows part of the current configuration with relevant settings to operation /logs [limit] Show last log messages. /status Lists all open trades /status Lists one or more specific trade. Separate multiple with a blank space. /status table List all open trades in a table format. Pending buy orders are marked with an asterisk ( ) Pending sell orders are marked with a double asterisk ( *) /trades [limit] List all recently closed trades in a table format. /delete Delete a specific trade from the Database. Tries to close open orders. Requires manual handling of this trade on the exchange. /count Displays number of trades used and available /locks Show currently locked pairs. /unlock Remove the lock for this pair (or for this lock id). /profit [] Display a summary of your profit/loss from close trades and some stats about your performance, over the last n days (all trades by default) /forcesell Instantly sells the given trade (Ignoring minimum_roi ). /forcesell all Instantly sells all open trades (Ignoring minimum_roi ). /forcebuy [rate] Instantly buys the given pair. Rate is optional. ( forcebuy_enable must be set to True) /performance Show performance of each finished trade grouped by pair /balance Show account balance per currency /daily Shows profit or loss per day, over the last n days (n defaults to 7) /stats Shows Wins / losses by Sell reason as well as Avg. holding durations for buys and sells /whitelist Show the current whitelist /blacklist [pair] Show the current blacklist, or adds a pair to the blacklist. /edge Show validated pairs by Edge if it is enabled. /help Show help message /version Show version","title":"Telegram commands"},{"location":"telegram-usage/#telegram-commands-in-action","text":"Below, example of Telegram message you will receive for each command.","title":"Telegram commands in action"},{"location":"telegram-usage/#start","text":"Status: running","title":"/start"},{"location":"telegram-usage/#stop","text":"Stopping trader ... Status: stopped","title":"/stop"},{"location":"telegram-usage/#stopbuy","text":"status: Setting max_open_trades to 0. Run /reload_config to reset. Prevents the bot from opening new trades by temporarily setting \"max_open_trades\" to 0. Open trades will be handled via their regular rules (ROI / Sell-signal, stoploss, ...). After this, give the bot time to close off open trades (can be checked via /status table ). Once all positions are sold, run /stop to completely stop the bot. /reload_config resets \"max_open_trades\" to the value set in the configuration and resets this command. Warning The stop-buy signal is ONLY active while the bot is running, and is not persisted anyway, so restarting the bot will cause this to reset.","title":"/stopbuy"},{"location":"telegram-usage/#status","text":"For each open trade, the bot will send you the following message. Trade ID: 123 (since 1 days ago) Current Pair: CVC/BTC Open Since: 1 days ago Amount: 26.64180098 Open Rate: 0.00007489 Current Rate: 0.00007489 Current Profit: 12.95% Stoploss: 0.00007389 (-0.02%)","title":"/status"},{"location":"telegram-usage/#status-table","text":"Return the status of all open trades in a table format. ``` ID Pair Since Profit 67 SC/BTC 1 d 13.33% 123 CVC/BTC 1 h 12.95% ```","title":"/status table"},{"location":"telegram-usage/#count","text":"Return the number of trades used and available. ``` current max 2 10 ```","title":"/count"},{"location":"telegram-usage/#profit","text":"Return a summary of your profit/loss and performance. ROI: Close trades \u2219 0.00485701 BTC (2.2%) (15.2 \u03a3%) \u2219 62.968 USD ROI: All trades \u2219 0.00255280 BTC (1.5%) (6.43 \u03a3%) \u2219 33.095 EUR Total Trade Count: 138 First Trade opened: 3 days ago Latest Trade opened: 2 minutes ago Avg. Duration: 2:33:45 Best Performing: PAY/BTC: 50.23% The relative profit of 1.2% is the average profit per trade. The relative profit of 15.2 \u03a3% is be based on the starting capital - so in this case, the starting capital was 0.00485701 * 1.152 = 0.00738 BTC . Starting capital is either taken from the available_capital setting, or calculated by using current wallet size - profits.","title":"/profit"},{"location":"telegram-usage/#forcesell","text":"BITTREX: Selling BTC/LTC with limit 0.01650000 (profit: ~-4.07%, -0.00008168)","title":"/forcesell "},{"location":"telegram-usage/#forcebuy-rate","text":"BITTREX: Buying ETH/BTC with limit 0.03400000 ( 1.000000 ETH , 225.290 USD ) Omitting the pair will open a query asking for the pair to buy (based on the current whitelist). Note that for this to work, forcebuy_enable needs to be set to true. More details","title":"/forcebuy [rate]"},{"location":"telegram-usage/#performance","text":"Return the performance of each crypto-currency the bot has sold. Performance: 1. RCN/BTC 0.003 BTC (57.77%) (1) 2. PAY/BTC 0.0012 BTC (56.91%) (1) 3. VIB/BTC 0.0011 BTC (47.07%) (1) 4. SALT/BTC 0.0010 BTC (30.24%) (1) 5. STORJ/BTC 0.0009 BTC (27.24%) (1) ...","title":"/performance"},{"location":"telegram-usage/#balance","text":"Return the balance of all crypto-currency your have on the exchange. Currency: BTC Available: 3.05890234 Balance: 3.05890234 Pending: 0.0 Currency: CVC Available: 86.64180098 Balance: 86.64180098 Pending: 0.0","title":"/balance"},{"location":"telegram-usage/#daily","text":"Per default /daily will return the 7 last days. The example below if for /daily 3 : Daily Profit over the last 3 days: ``` Day Profit BTC Profit USD 2018-01-03 0.00224175 BTC 29,142 USD 2018-01-02 0.00033131 BTC 4,307 USD 2018-01-01 0.00269130 BTC 34.986 USD ```","title":"/daily "},{"location":"telegram-usage/#whitelist","text":"Shows the current whitelist Using whitelist StaticPairList with 22 pairs IOTA/BTC, NEO/BTC, TRX/BTC, VET/BTC, ADA/BTC, ETC/BTC, NCASH/BTC, DASH/BTC, XRP/BTC, XVG/BTC, EOS/BTC, LTC/BTC, OMG/BTC, BTG/BTC, LSK/BTC, ZEC/BTC, HOT/BTC, IOTX/BTC, XMR/BTC, AST/BTC, XLM/BTC, NANO/BTC","title":"/whitelist"},{"location":"telegram-usage/#blacklist-pair","text":"Shows the current blacklist. If Pair is set, then this pair will be added to the pairlist. Also supports multiple pairs, separated by a space. Use /reload_config to reset the blacklist. Using blacklist StaticPairList with 2 pairs DODGE/BTC , HOT/BTC .","title":"/blacklist [pair]"},{"location":"telegram-usage/#edge","text":"Shows pairs validated by Edge along with their corresponding win-rate, expectancy and stoploss values. Edge only validated following pairs: ``` Pair Winrate Expectancy Stoploss DOCK/ETH 0.522727 0.881821 -0.03 PHX/ETH 0.677419 0.560488 -0.03 HOT/ETH 0.733333 0.490492 -0.03 HC/ETH 0.588235 0.280988 -0.02 ARDR/ETH 0.366667 0.143059 -0.01 ```","title":"/edge"},{"location":"telegram-usage/#version","text":"Version: 0.14.3","title":"/version"},{"location":"updating/","text":"How to update \u00b6 To update your freqtrade installation, please use one of the below methods, corresponding to your installation method. docker-compose \u00b6 Legacy installations using the master image We're switching from master to stable for the release Images - please adjust your docker-file and replace freqtradeorg/freqtrade:master with freqtradeorg/freqtrade:stable bash docker-compose pull docker-compose up -d Installation via setup script \u00b6 bash ./setup.sh --update Note Make sure to run this command with your virtual environment disabled! Plain native installation \u00b6 Please ensure that you're also updating dependencies - otherwise things might break without you noticing. bash git pull pip install -U -r requirements.txt","title":"Updating Freqtrade"},{"location":"updating/#how-to-update","text":"To update your freqtrade installation, please use one of the below methods, corresponding to your installation method.","title":"How to update"},{"location":"updating/#docker-compose","text":"Legacy installations using the master image We're switching from master to stable for the release Images - please adjust your docker-file and replace freqtradeorg/freqtrade:master with freqtradeorg/freqtrade:stable bash docker-compose pull docker-compose up -d","title":"docker-compose"},{"location":"updating/#installation-via-setup-script","text":"bash ./setup.sh --update Note Make sure to run this command with your virtual environment disabled!","title":"Installation via setup script"},{"location":"updating/#plain-native-installation","text":"Please ensure that you're also updating dependencies - otherwise things might break without you noticing. bash git pull pip install -U -r requirements.txt","title":"Plain native installation"},{"location":"utils/","text":"Utility Subcommands \u00b6 Besides the Live-Trade and Dry-Run run modes, the backtesting , edge and hyperopt optimization subcommands, and the download-data subcommand which prepares historical data, the bot contains a number of utility subcommands. They are described in this section. Create userdir \u00b6 Creates the directory structure to hold your files for freqtrade. Will also create strategy and hyperopt examples for you to get started. Can be used multiple times - using --reset will reset the sample strategy and hyperopt files to their default state. ``` usage: freqtrade create-userdir [-h] [--userdir PATH] [--reset] optional arguments: -h, --help show this help message and exit --userdir PATH, --user-data-dir PATH Path to userdata directory. --reset Reset sample files to their original state. ``` Warning Using --reset may result in loss of data, since this will overwrite all sample files without asking again. \u251c\u2500\u2500 backtest_results \u251c\u2500\u2500 data \u251c\u2500\u2500 hyperopt_results \u251c\u2500\u2500 hyperopts \u2502 \u251c\u2500\u2500 sample_hyperopt_advanced.py \u2502 \u251c\u2500\u2500 sample_hyperopt_loss.py \u2502 \u2514\u2500\u2500 sample_hyperopt.py \u251c\u2500\u2500 notebooks \u2502 \u2514\u2500\u2500 strategy_analysis_example.ipynb \u251c\u2500\u2500 plot \u2514\u2500\u2500 strategies \u2514\u2500\u2500 sample_strategy.py Create new config \u00b6 Creates a new configuration file, asking some questions which are important selections for a configuration. ``` usage: freqtrade new-config [-h] [-c PATH] optional arguments: -h, --help show this help message and exit -c PATH, --config PATH Specify configuration file (default: config.json ). Multiple --config options may be used. Can be set to - to read config from stdin. ``` Warning Only vital questions are asked. Freqtrade offers a lot more configuration possibilities, which are listed in the Configuration documentation Create config examples \u00b6 ``` $ freqtrade new-config --config config_binance.json ? Do you want to enable Dry-run (simulated trades)? Yes ? Please insert your stake currency: BTC ? Please insert your stake amount: 0.05 ? Please insert max_open_trades (Integer or 'unlimited'): 3 ? Please insert your desired timeframe (e.g. 5m): 5m ? Please insert your display Currency (for reporting): USD ? Select exchange binance ? Do you want to enable Telegram? No ``` Create new strategy \u00b6 Creates a new strategy from a template similar to SampleStrategy. The file will be named inline with your class name, and will not overwrite existing files. Results will be located in user_data/strategies/.py . ``` output usage: freqtrade new-strategy [-h] [--userdir PATH] [-s NAME] [--template {full,minimal,advanced}] optional arguments: -h, --help show this help message and exit --userdir PATH, --user-data-dir PATH Path to userdata directory. -s NAME, --strategy NAME Specify strategy class name which will be used by the bot. --template {full,minimal,advanced} Use a template which is either minimal , full (containing multiple sample indicators) or advanced . Default: full . ``` Sample usage of new-strategy \u00b6 bash freqtrade new-strategy --strategy AwesomeStrategy With custom user directory bash freqtrade new-strategy --userdir ~/.freqtrade/ --strategy AwesomeStrategy Using the advanced template (populates all optional functions and methods) bash freqtrade new-strategy --strategy AwesomeStrategy --template advanced Create new hyperopt \u00b6 Creates a new hyperopt from a template similar to SampleHyperopt. The file will be named inline with your class name, and will not overwrite existing files. Results will be located in user_data/hyperopts/.py . ``` output usage: freqtrade new-hyperopt [-h] [--userdir PATH] [--hyperopt NAME] [--template {full,minimal,advanced}] optional arguments: -h, --help show this help message and exit --userdir PATH, --user-data-dir PATH Path to userdata directory. --hyperopt NAME Specify hyperopt class name which will be used by the bot. --template {full,minimal,advanced} Use a template which is either minimal , full (containing multiple sample indicators) or advanced . Default: full . ``` Sample usage of new-hyperopt \u00b6 bash freqtrade new-hyperopt --hyperopt AwesomeHyperopt With custom user directory bash freqtrade new-hyperopt --userdir ~/.freqtrade/ --hyperopt AwesomeHyperopt List Strategies and List Hyperopts \u00b6 Use the list-strategies subcommand to see all strategies in one particular directory and the list-hyperopts subcommand to list custom Hyperopts. These subcommands are useful for finding problems in your environment with loading strategies or hyperopt classes: modules with strategies or hyperopt classes that contain errors and failed to load are printed in red (LOAD FAILED), while strategies or hyperopt classes with duplicate names are printed in yellow (DUPLICATE NAME). ``` usage: freqtrade list-strategies [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--strategy-path PATH] [-1] [--no-color] optional arguments: -h, --help show this help message and exit --strategy-path PATH Specify additional strategy lookup path. -1, --one-column Print output in one column. --no-color Disable colorization of hyperopt results. May be useful if you are redirecting output to a file. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: config.json ). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. usage: freqtrade list-hyperopts [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--hyperopt-path PATH] [-1] [--no-color] optional arguments: -h, --help show this help message and exit --hyperopt-path PATH Specify additional lookup path for Hyperopt and Hyperopt Loss functions. -1, --one-column Print output in one column. --no-color Disable colorization of hyperopt results. May be useful if you are redirecting output to a file. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: config.json ). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. ``` Warning Using these commands will try to load all python files from a directory. This can be a security risk if untrusted files reside in this directory, since all module-level code is executed. Example: Search default strategies and hyperopts directories (within the default userdir). bash freqtrade list-strategies freqtrade list-hyperopts Example: Search strategies and hyperopts directory within the userdir. bash freqtrade list-strategies --userdir ~/.freqtrade/ freqtrade list-hyperopts --userdir ~/.freqtrade/ Example: Search dedicated strategy path. bash freqtrade list-strategies --strategy-path ~/.freqtrade/strategies/ Example: Search dedicated hyperopt path. bash freqtrade list-hyperopt --hyperopt-path ~/.freqtrade/hyperopts/ List Exchanges \u00b6 Use the list-exchanges subcommand to see the exchanges available for the bot. ``` usage: freqtrade list-exchanges [-h] [-1] [-a] optional arguments: -h, --help show this help message and exit -1, --one-column Print output in one column. -a, --all Print all exchanges known to the ccxt library. ``` Example: see exchanges available for the bot: ``` $ freqtrade list-exchanges Exchanges available for Freqtrade: Exchange name Valid reason aax True ascendex True missing opt: fetchMyTrades bequant True bibox True bigone True binance True binanceus True bitbank True missing opt: fetchTickers bitcoincom True bitfinex True bitforex True missing opt: fetchMyTrades, fetchTickers bitget True bithumb True missing opt: fetchMyTrades bitkk True missing opt: fetchMyTrades bitmart True bitmax True missing opt: fetchMyTrades bitpanda True bittrex True bitvavo True bitz True missing opt: fetchMyTrades btcalpha True missing opt: fetchTicker, fetchTickers btcmarkets True missing opt: fetchTickers buda True missing opt: fetchMyTrades, fetchTickers bw True missing opt: fetchMyTrades, fetchL2OrderBook bybit True bytetrade True cdax True cex True missing opt: fetchMyTrades coinbaseprime True missing opt: fetchTickers coinbasepro True missing opt: fetchTickers coinex True crex24 True deribit True digifinex True equos True missing opt: fetchTicker, fetchTickers eterbase True fcoin True missing opt: fetchMyTrades, fetchTickers fcoinjp True missing opt: fetchMyTrades, fetchTickers ftx True gateio True gemini True gopax True hbtc True hitbtc True huobijp True huobipro True idex True kraken True kucoin True lbank True missing opt: fetchMyTrades mercado True missing opt: fetchTickers ndax True missing opt: fetchTickers novadax True okcoin True okex True probit True qtrade True stex True timex True upbit True missing opt: fetchMyTrades vcc True zb True missing opt: fetchMyTrades ``` missing opt exchanges Values with \"missing opt:\" might need special configuration (e.g. using orderbook if fetchTickers is missing) - but should in theory work (although we cannot guarantee they will). Example: see all exchanges supported by the ccxt library (including 'bad' ones, i.e. those that are known to not work with Freqtrade): ``` $ freqtrade list-exchanges -a All exchanges supported by the ccxt library: Exchange name Valid reason aax True aofex False missing: fetchOrder ascendex True missing opt: fetchMyTrades bequant True bibox True bigone True binance True binanceus True bit2c False missing: fetchOrder, fetchOHLCV bitbank True missing opt: fetchTickers bitbay False missing: fetchOrder bitcoincom True bitfinex True bitfinex2 False missing: fetchOrder bitflyer False missing: fetchOrder, fetchOHLCV bitforex True missing opt: fetchMyTrades, fetchTickers bitget True bithumb True missing opt: fetchMyTrades bitkk True missing opt: fetchMyTrades bitmart True bitmax True missing opt: fetchMyTrades bitmex False Various reasons. bitpanda True bitso False missing: fetchOHLCV bitstamp False Does not provide history. Details in https://github.com/freqtrade/freqtrade/issues/1983 bitstamp1 False missing: fetchOrder, fetchOHLCV bittrex True bitvavo True bitz True missing opt: fetchMyTrades bl3p False missing: fetchOrder, fetchOHLCV bleutrade False missing: fetchOrder braziliex False missing: fetchOHLCV btcalpha True missing opt: fetchTicker, fetchTickers btcbox False missing: fetchOHLCV btcmarkets True missing opt: fetchTickers btctradeua False missing: fetchOrder, fetchOHLCV btcturk False missing: fetchOrder buda True missing opt: fetchMyTrades, fetchTickers bw True missing opt: fetchMyTrades, fetchL2OrderBook bybit True bytetrade True cdax True cex True missing opt: fetchMyTrades chilebit False missing: fetchOrder, fetchOHLCV coinbase False missing: fetchOrder, cancelOrder, createOrder, fetchOHLCV coinbaseprime True missing opt: fetchTickers coinbasepro True missing opt: fetchTickers coincheck False missing: fetchOrder, fetchOHLCV coinegg False missing: fetchOHLCV coinex True coinfalcon False missing: fetchOHLCV coinfloor False missing: fetchOrder, fetchOHLCV coingi False missing: fetchOrder, fetchOHLCV coinmarketcap False missing: fetchOrder, cancelOrder, createOrder, fetchBalance, fetchOHLCV coinmate False missing: fetchOHLCV coinone False missing: fetchOHLCV coinspot False missing: fetchOrder, cancelOrder, fetchOHLCV crex24 True currencycom False missing: fetchOrder delta False missing: fetchOrder deribit True digifinex True equos True missing opt: fetchTicker, fetchTickers eterbase True exmo False missing: fetchOrder exx False missing: fetchOHLCV fcoin True missing opt: fetchMyTrades, fetchTickers fcoinjp True missing opt: fetchMyTrades, fetchTickers flowbtc False missing: fetchOrder, fetchOHLCV foxbit False missing: fetchOrder, fetchOHLCV ftx True gateio True gemini True gopax True hbtc True hitbtc True hollaex False missing: fetchOrder huobijp True huobipro True idex True independentreserve False missing: fetchOHLCV indodax False missing: fetchOHLCV itbit False missing: fetchOHLCV kraken True kucoin True kuna False missing: fetchOHLCV lakebtc False missing: fetchOrder, fetchOHLCV latoken False missing: fetchOrder, fetchOHLCV lbank True missing opt: fetchMyTrades liquid False missing: fetchOHLCV luno False missing: fetchOHLCV lykke False missing: fetchOHLCV mercado True missing opt: fetchTickers mixcoins False missing: fetchOrder, fetchOHLCV ndax True missing opt: fetchTickers novadax True oceanex False missing: fetchOHLCV okcoin True okex True paymium False missing: fetchOrder, fetchOHLCV phemex False Does not provide history. poloniex False missing: fetchOrder probit True qtrade True rightbtc False missing: fetchOrder ripio False missing: fetchOHLCV southxchange False missing: fetchOrder, fetchOHLCV stex True surbitcoin False missing: fetchOrder, fetchOHLCV therock False missing: fetchOHLCV tidebit False missing: fetchOrder tidex False missing: fetchOHLCV timex True upbit True missing opt: fetchMyTrades vbtc False missing: fetchOrder, fetchOHLCV vcc True wavesexchange False missing: fetchOrder whitebit False missing: fetchOrder, cancelOrder, createOrder, fetchBalance xbtce False missing: fetchOrder, fetchOHLCV xena False missing: fetchOrder yobit False missing: fetchOHLCV zaif False missing: fetchOrder, fetchOHLCV zb True missing opt: fetchMyTrades ``` List Timeframes \u00b6 Use the list-timeframes subcommand to see the list of timeframes available for the exchange. ``` usage: freqtrade list-timeframes [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--exchange EXCHANGE] [-1] optional arguments: -h, --help show this help message and exit --exchange EXCHANGE Exchange name (default: bittrex ). Only valid if no config is provided. -1, --one-column Print output in one column. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: config.json ). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. ``` Example: see the timeframes for the 'binance' exchange, set in the configuration file: $ freqtrade list-timeframes -c config_binance.json ... Timeframes available for the exchange `binance`: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M Example: enumerate exchanges available for Freqtrade and print timeframes supported by each of them: $ for i in `freqtrade list-exchanges -1`; do freqtrade list-timeframes --exchange $i; done List pairs/list markets \u00b6 The list-pairs and list-markets subcommands allow to see the pairs/markets available on exchange. Pairs are markets with the '/' character between the base currency part and the quote currency part in the market symbol. For example, in the 'ETH/BTC' pair 'ETH' is the base currency, while 'BTC' is the quote currency. For pairs traded by Freqtrade the pair quote currency is defined by the value of the stake_currency configuration setting. You can print info about any pair/market with these subcommands - and you can filter output by quote-currency using --quote BTC , or by base-currency using --base ETH options correspondingly. These subcommands have same usage and same set of available options: ``` usage: freqtrade list-markets [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--exchange EXCHANGE] [--print-list] [--print-json] [-1] [--print-csv] [--base BASE_CURRENCY [BASE_CURRENCY ...]] [--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]] [-a] usage: freqtrade list-pairs [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--exchange EXCHANGE] [--print-list] [--print-json] [-1] [--print-csv] [--base BASE_CURRENCY [BASE_CURRENCY ...]] [--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]] [-a] optional arguments: -h, --help show this help message and exit --exchange EXCHANGE Exchange name (default: bittrex ). Only valid if no config is provided. --print-list Print list of pairs or market symbols. By default data is printed in the tabular format. --print-json Print list of pairs or market symbols in JSON format. -1, --one-column Print output in one column. --print-csv Print exchange pair or market data in the csv format. --base BASE_CURRENCY [BASE_CURRENCY ...] Specify base currency(-ies). Space-separated list. --quote QUOTE_CURRENCY [QUOTE_CURRENCY ...] Specify quote currency(-ies). Space-separated list. -a, --all Print all pairs or market symbols. By default only active ones are shown. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: config.json ). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. ``` By default, only active pairs/markets are shown. Active pairs/markets are those that can currently be traded on the exchange. The see the list of all pairs/markets (not only the active ones), use the -a / -all option. Pairs/markets are sorted by its symbol string in the printed output. Examples \u00b6 Print the list of active pairs with quote currency USD on exchange, specified in the default configuration file (i.e. pairs on the \"Bittrex\" exchange) in JSON format: $ freqtrade list-pairs --quote USD --print-json Print the list of all pairs on the exchange, specified in the config_binance.json configuration file (i.e. on the \"Binance\" exchange) with base currencies BTC or ETH and quote currencies USDT or USD, as the human-readable list with summary: $ freqtrade list-pairs -c config_binance.json --all --base BTC ETH --quote USDT USD --print-list Print all markets on exchange \"Kraken\", in the tabular format: $ freqtrade list-markets --exchange kraken --all Test pairlist \u00b6 Use the test-pairlist subcommand to test the configuration of dynamic pairlists . Requires a configuration with specified pairlists attribute. Can be used to generate static pairlists to be used during backtesting / hyperopt. ``` usage: freqtrade test-pairlist [-h] [-c PATH] [--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]] [-1] [--print-json] optional arguments: -h, --help show this help message and exit -c PATH, --config PATH Specify configuration file (default: config.json ). Multiple --config options may be used. Can be set to - to read config from stdin. --quote QUOTE_CURRENCY [QUOTE_CURRENCY ...] Specify quote currency(-ies). Space-separated list. -1, --one-column Print output in one column. --print-json Print list of pairs or market symbols in JSON format. ``` Examples \u00b6 Show whitelist when using a dynamic pairlist . freqtrade test-pairlist --config config.json --quote USDT BTC Webserver mode \u00b6 Experimental Webserver mode is an experimental mode to increase backesting and strategy development productivity. There may still be bugs - so if you happen to stumble across these, please report them as github issues, thanks. Run freqtrade in webserver mode. Freqtrade will start the webserver and allow FreqUI to start and control backtesting processes. This has the advantage that data will not be reloaded between backtesting runs (as long as timeframe and timerange remain identical). FreqUI will also show the backtesting results. ``` usage: freqtrade webserver [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-s NAME] [--strategy-path PATH] optional arguments: -h, --help show this help message and exit Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. Strategy arguments: -s NAME, --strategy NAME Specify strategy class name which will be used by the bot. --strategy-path PATH Specify additional strategy lookup path. ``` List Hyperopt results \u00b6 You can list the hyperoptimization epochs the Hyperopt module evaluated previously with the hyperopt-list sub-command. ``` usage: freqtrade hyperopt-list [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--best] [--profitable] [--min-trades INT] [--max-trades INT] [--min-avg-time FLOAT] [--max-avg-time FLOAT] [--min-avg-profit FLOAT] [--max-avg-profit FLOAT] [--min-total-profit FLOAT] [--max-total-profit FLOAT] [--min-objective FLOAT] [--max-objective FLOAT] [--no-color] [--print-json] [--no-details] [--hyperopt-filename PATH] [--export-csv FILE] optional arguments: -h, --help show this help message and exit --best Select only best epochs. --profitable Select only profitable epochs. --min-trades INT Select epochs with more than INT trades. --max-trades INT Select epochs with less than INT trades. --min-avg-time FLOAT Select epochs above average time. --max-avg-time FLOAT Select epochs below average time. --min-avg-profit FLOAT Select epochs above average profit. --max-avg-profit FLOAT Select epochs below average profit. --min-total-profit FLOAT Select epochs above total profit. --max-total-profit FLOAT Select epochs below total profit. --min-objective FLOAT Select epochs above objective. --max-objective FLOAT Select epochs below objective. --no-color Disable colorization of hyperopt results. May be useful if you are redirecting output to a file. --print-json Print output in JSON format. --no-details Do not print best epoch details. --hyperopt-filename FILENAME Hyperopt result filename.Example: --hyperopt- filename=hyperopt_results_2020-09-27_16-20-48.pickle --export-csv FILE Export to CSV-File. This will disable table print. Example: --export-csv hyperopt.csv Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. ``` Note hyperopt-list will automatically use the latest available hyperopt results file. You can override this using the --hyperopt-filename argument, and specify another, available filename (without path!). Examples \u00b6 List all results, print details of the best result at the end: freqtrade hyperopt-list List only epochs with positive profit. Do not print the details of the best epoch, so that the list can be iterated in a script: freqtrade hyperopt-list --profitable --no-details Show details of Hyperopt results \u00b6 You can show the details of any hyperoptimization epoch previously evaluated by the Hyperopt module with the hyperopt-show subcommand. ``` usage: freqtrade hyperopt-show [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--best] [--profitable] [-n INT] [--print-json] [--hyperopt-filename FILENAME] [--no-header] [--disable-param-export] optional arguments: -h, --help show this help message and exit --best Select only best epochs. --profitable Select only profitable epochs. -n INT, --index INT Specify the index of the epoch to print details for. --print-json Print output in JSON format. --hyperopt-filename FILENAME Hyperopt result filename.Example: --hyperopt- filename=hyperopt_results_2020-09-27_16-20-48.pickle --no-header Do not print epoch details header. --disable-param-export Disable automatic hyperopt parameter export. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. ``` Note hyperopt-show will automatically use the latest available hyperopt results file. You can override this using the --hyperopt-filename argument, and specify another, available filename (without path!). Examples \u00b6 Print details for the epoch 168 (the number of the epoch is shown by the hyperopt-list subcommand or by Hyperopt itself during hyperoptimization run): freqtrade hyperopt-show -n 168 Prints JSON data with details for the last best epoch (i.e., the best of all epochs): freqtrade hyperopt-show --best -n -1 --print-json --no-header Show trades \u00b6 Print selected (or all) trades from database to screen. ``` usage: freqtrade show-trades [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--db-url PATH] [--trade-ids TRADE_IDS [TRADE_IDS ...]] [--print-json] optional arguments: -h, --help show this help message and exit --db-url PATH Override trades database URL, this is useful in custom deployments (default: sqlite:///tradesv3.sqlite for Live Run mode, sqlite:///tradesv3.dryrun.sqlite for Dry Run). --trade-ids TRADE_IDS [TRADE_IDS ...] Specify the list of trade ids. --print-json Print output in JSON format. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. ``` Examples \u00b6 Print trades with id 2 and 3 as json bash freqtrade show-trades --db-url sqlite:///tradesv3.sqlite --trade-ids 2 3 --print-json","title":"Utility Sub-commands"},{"location":"utils/#utility-subcommands","text":"Besides the Live-Trade and Dry-Run run modes, the backtesting , edge and hyperopt optimization subcommands, and the download-data subcommand which prepares historical data, the bot contains a number of utility subcommands. They are described in this section.","title":"Utility Subcommands"},{"location":"utils/#create-userdir","text":"Creates the directory structure to hold your files for freqtrade. Will also create strategy and hyperopt examples for you to get started. Can be used multiple times - using --reset will reset the sample strategy and hyperopt files to their default state. ``` usage: freqtrade create-userdir [-h] [--userdir PATH] [--reset] optional arguments: -h, --help show this help message and exit --userdir PATH, --user-data-dir PATH Path to userdata directory. --reset Reset sample files to their original state. ``` Warning Using --reset may result in loss of data, since this will overwrite all sample files without asking again. \u251c\u2500\u2500 backtest_results \u251c\u2500\u2500 data \u251c\u2500\u2500 hyperopt_results \u251c\u2500\u2500 hyperopts \u2502 \u251c\u2500\u2500 sample_hyperopt_advanced.py \u2502 \u251c\u2500\u2500 sample_hyperopt_loss.py \u2502 \u2514\u2500\u2500 sample_hyperopt.py \u251c\u2500\u2500 notebooks \u2502 \u2514\u2500\u2500 strategy_analysis_example.ipynb \u251c\u2500\u2500 plot \u2514\u2500\u2500 strategies \u2514\u2500\u2500 sample_strategy.py","title":"Create userdir"},{"location":"utils/#create-new-config","text":"Creates a new configuration file, asking some questions which are important selections for a configuration. ``` usage: freqtrade new-config [-h] [-c PATH] optional arguments: -h, --help show this help message and exit -c PATH, --config PATH Specify configuration file (default: config.json ). Multiple --config options may be used. Can be set to - to read config from stdin. ``` Warning Only vital questions are asked. Freqtrade offers a lot more configuration possibilities, which are listed in the Configuration documentation","title":"Create new config"},{"location":"utils/#create-config-examples","text":"``` $ freqtrade new-config --config config_binance.json ? Do you want to enable Dry-run (simulated trades)? Yes ? Please insert your stake currency: BTC ? Please insert your stake amount: 0.05 ? Please insert max_open_trades (Integer or 'unlimited'): 3 ? Please insert your desired timeframe (e.g. 5m): 5m ? Please insert your display Currency (for reporting): USD ? Select exchange binance ? Do you want to enable Telegram? No ```","title":"Create config examples"},{"location":"utils/#create-new-strategy","text":"Creates a new strategy from a template similar to SampleStrategy. The file will be named inline with your class name, and will not overwrite existing files. Results will be located in user_data/strategies/.py . ``` output usage: freqtrade new-strategy [-h] [--userdir PATH] [-s NAME] [--template {full,minimal,advanced}] optional arguments: -h, --help show this help message and exit --userdir PATH, --user-data-dir PATH Path to userdata directory. -s NAME, --strategy NAME Specify strategy class name which will be used by the bot. --template {full,minimal,advanced} Use a template which is either minimal , full (containing multiple sample indicators) or advanced . Default: full . ```","title":"Create new strategy"},{"location":"utils/#sample-usage-of-new-strategy","text":"bash freqtrade new-strategy --strategy AwesomeStrategy With custom user directory bash freqtrade new-strategy --userdir ~/.freqtrade/ --strategy AwesomeStrategy Using the advanced template (populates all optional functions and methods) bash freqtrade new-strategy --strategy AwesomeStrategy --template advanced","title":"Sample usage of new-strategy"},{"location":"utils/#create-new-hyperopt","text":"Creates a new hyperopt from a template similar to SampleHyperopt. The file will be named inline with your class name, and will not overwrite existing files. Results will be located in user_data/hyperopts/.py . ``` output usage: freqtrade new-hyperopt [-h] [--userdir PATH] [--hyperopt NAME] [--template {full,minimal,advanced}] optional arguments: -h, --help show this help message and exit --userdir PATH, --user-data-dir PATH Path to userdata directory. --hyperopt NAME Specify hyperopt class name which will be used by the bot. --template {full,minimal,advanced} Use a template which is either minimal , full (containing multiple sample indicators) or advanced . Default: full . ```","title":"Create new hyperopt"},{"location":"utils/#sample-usage-of-new-hyperopt","text":"bash freqtrade new-hyperopt --hyperopt AwesomeHyperopt With custom user directory bash freqtrade new-hyperopt --userdir ~/.freqtrade/ --hyperopt AwesomeHyperopt","title":"Sample usage of new-hyperopt"},{"location":"utils/#list-strategies-and-list-hyperopts","text":"Use the list-strategies subcommand to see all strategies in one particular directory and the list-hyperopts subcommand to list custom Hyperopts. These subcommands are useful for finding problems in your environment with loading strategies or hyperopt classes: modules with strategies or hyperopt classes that contain errors and failed to load are printed in red (LOAD FAILED), while strategies or hyperopt classes with duplicate names are printed in yellow (DUPLICATE NAME). ``` usage: freqtrade list-strategies [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--strategy-path PATH] [-1] [--no-color] optional arguments: -h, --help show this help message and exit --strategy-path PATH Specify additional strategy lookup path. -1, --one-column Print output in one column. --no-color Disable colorization of hyperopt results. May be useful if you are redirecting output to a file. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: config.json ). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. usage: freqtrade list-hyperopts [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--hyperopt-path PATH] [-1] [--no-color] optional arguments: -h, --help show this help message and exit --hyperopt-path PATH Specify additional lookup path for Hyperopt and Hyperopt Loss functions. -1, --one-column Print output in one column. --no-color Disable colorization of hyperopt results. May be useful if you are redirecting output to a file. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: config.json ). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. ``` Warning Using these commands will try to load all python files from a directory. This can be a security risk if untrusted files reside in this directory, since all module-level code is executed. Example: Search default strategies and hyperopts directories (within the default userdir). bash freqtrade list-strategies freqtrade list-hyperopts Example: Search strategies and hyperopts directory within the userdir. bash freqtrade list-strategies --userdir ~/.freqtrade/ freqtrade list-hyperopts --userdir ~/.freqtrade/ Example: Search dedicated strategy path. bash freqtrade list-strategies --strategy-path ~/.freqtrade/strategies/ Example: Search dedicated hyperopt path. bash freqtrade list-hyperopt --hyperopt-path ~/.freqtrade/hyperopts/","title":"List Strategies and List Hyperopts"},{"location":"utils/#list-exchanges","text":"Use the list-exchanges subcommand to see the exchanges available for the bot. ``` usage: freqtrade list-exchanges [-h] [-1] [-a] optional arguments: -h, --help show this help message and exit -1, --one-column Print output in one column. -a, --all Print all exchanges known to the ccxt library. ``` Example: see exchanges available for the bot: ``` $ freqtrade list-exchanges Exchanges available for Freqtrade: Exchange name Valid reason aax True ascendex True missing opt: fetchMyTrades bequant True bibox True bigone True binance True binanceus True bitbank True missing opt: fetchTickers bitcoincom True bitfinex True bitforex True missing opt: fetchMyTrades, fetchTickers bitget True bithumb True missing opt: fetchMyTrades bitkk True missing opt: fetchMyTrades bitmart True bitmax True missing opt: fetchMyTrades bitpanda True bittrex True bitvavo True bitz True missing opt: fetchMyTrades btcalpha True missing opt: fetchTicker, fetchTickers btcmarkets True missing opt: fetchTickers buda True missing opt: fetchMyTrades, fetchTickers bw True missing opt: fetchMyTrades, fetchL2OrderBook bybit True bytetrade True cdax True cex True missing opt: fetchMyTrades coinbaseprime True missing opt: fetchTickers coinbasepro True missing opt: fetchTickers coinex True crex24 True deribit True digifinex True equos True missing opt: fetchTicker, fetchTickers eterbase True fcoin True missing opt: fetchMyTrades, fetchTickers fcoinjp True missing opt: fetchMyTrades, fetchTickers ftx True gateio True gemini True gopax True hbtc True hitbtc True huobijp True huobipro True idex True kraken True kucoin True lbank True missing opt: fetchMyTrades mercado True missing opt: fetchTickers ndax True missing opt: fetchTickers novadax True okcoin True okex True probit True qtrade True stex True timex True upbit True missing opt: fetchMyTrades vcc True zb True missing opt: fetchMyTrades ``` missing opt exchanges Values with \"missing opt:\" might need special configuration (e.g. using orderbook if fetchTickers is missing) - but should in theory work (although we cannot guarantee they will). Example: see all exchanges supported by the ccxt library (including 'bad' ones, i.e. those that are known to not work with Freqtrade): ``` $ freqtrade list-exchanges -a All exchanges supported by the ccxt library: Exchange name Valid reason aax True aofex False missing: fetchOrder ascendex True missing opt: fetchMyTrades bequant True bibox True bigone True binance True binanceus True bit2c False missing: fetchOrder, fetchOHLCV bitbank True missing opt: fetchTickers bitbay False missing: fetchOrder bitcoincom True bitfinex True bitfinex2 False missing: fetchOrder bitflyer False missing: fetchOrder, fetchOHLCV bitforex True missing opt: fetchMyTrades, fetchTickers bitget True bithumb True missing opt: fetchMyTrades bitkk True missing opt: fetchMyTrades bitmart True bitmax True missing opt: fetchMyTrades bitmex False Various reasons. bitpanda True bitso False missing: fetchOHLCV bitstamp False Does not provide history. Details in https://github.com/freqtrade/freqtrade/issues/1983 bitstamp1 False missing: fetchOrder, fetchOHLCV bittrex True bitvavo True bitz True missing opt: fetchMyTrades bl3p False missing: fetchOrder, fetchOHLCV bleutrade False missing: fetchOrder braziliex False missing: fetchOHLCV btcalpha True missing opt: fetchTicker, fetchTickers btcbox False missing: fetchOHLCV btcmarkets True missing opt: fetchTickers btctradeua False missing: fetchOrder, fetchOHLCV btcturk False missing: fetchOrder buda True missing opt: fetchMyTrades, fetchTickers bw True missing opt: fetchMyTrades, fetchL2OrderBook bybit True bytetrade True cdax True cex True missing opt: fetchMyTrades chilebit False missing: fetchOrder, fetchOHLCV coinbase False missing: fetchOrder, cancelOrder, createOrder, fetchOHLCV coinbaseprime True missing opt: fetchTickers coinbasepro True missing opt: fetchTickers coincheck False missing: fetchOrder, fetchOHLCV coinegg False missing: fetchOHLCV coinex True coinfalcon False missing: fetchOHLCV coinfloor False missing: fetchOrder, fetchOHLCV coingi False missing: fetchOrder, fetchOHLCV coinmarketcap False missing: fetchOrder, cancelOrder, createOrder, fetchBalance, fetchOHLCV coinmate False missing: fetchOHLCV coinone False missing: fetchOHLCV coinspot False missing: fetchOrder, cancelOrder, fetchOHLCV crex24 True currencycom False missing: fetchOrder delta False missing: fetchOrder deribit True digifinex True equos True missing opt: fetchTicker, fetchTickers eterbase True exmo False missing: fetchOrder exx False missing: fetchOHLCV fcoin True missing opt: fetchMyTrades, fetchTickers fcoinjp True missing opt: fetchMyTrades, fetchTickers flowbtc False missing: fetchOrder, fetchOHLCV foxbit False missing: fetchOrder, fetchOHLCV ftx True gateio True gemini True gopax True hbtc True hitbtc True hollaex False missing: fetchOrder huobijp True huobipro True idex True independentreserve False missing: fetchOHLCV indodax False missing: fetchOHLCV itbit False missing: fetchOHLCV kraken True kucoin True kuna False missing: fetchOHLCV lakebtc False missing: fetchOrder, fetchOHLCV latoken False missing: fetchOrder, fetchOHLCV lbank True missing opt: fetchMyTrades liquid False missing: fetchOHLCV luno False missing: fetchOHLCV lykke False missing: fetchOHLCV mercado True missing opt: fetchTickers mixcoins False missing: fetchOrder, fetchOHLCV ndax True missing opt: fetchTickers novadax True oceanex False missing: fetchOHLCV okcoin True okex True paymium False missing: fetchOrder, fetchOHLCV phemex False Does not provide history. poloniex False missing: fetchOrder probit True qtrade True rightbtc False missing: fetchOrder ripio False missing: fetchOHLCV southxchange False missing: fetchOrder, fetchOHLCV stex True surbitcoin False missing: fetchOrder, fetchOHLCV therock False missing: fetchOHLCV tidebit False missing: fetchOrder tidex False missing: fetchOHLCV timex True upbit True missing opt: fetchMyTrades vbtc False missing: fetchOrder, fetchOHLCV vcc True wavesexchange False missing: fetchOrder whitebit False missing: fetchOrder, cancelOrder, createOrder, fetchBalance xbtce False missing: fetchOrder, fetchOHLCV xena False missing: fetchOrder yobit False missing: fetchOHLCV zaif False missing: fetchOrder, fetchOHLCV zb True missing opt: fetchMyTrades ```","title":"List Exchanges"},{"location":"utils/#list-timeframes","text":"Use the list-timeframes subcommand to see the list of timeframes available for the exchange. ``` usage: freqtrade list-timeframes [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--exchange EXCHANGE] [-1] optional arguments: -h, --help show this help message and exit --exchange EXCHANGE Exchange name (default: bittrex ). Only valid if no config is provided. -1, --one-column Print output in one column. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: config.json ). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. ``` Example: see the timeframes for the 'binance' exchange, set in the configuration file: $ freqtrade list-timeframes -c config_binance.json ... Timeframes available for the exchange `binance`: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M Example: enumerate exchanges available for Freqtrade and print timeframes supported by each of them: $ for i in `freqtrade list-exchanges -1`; do freqtrade list-timeframes --exchange $i; done","title":"List Timeframes"},{"location":"utils/#list-pairslist-markets","text":"The list-pairs and list-markets subcommands allow to see the pairs/markets available on exchange. Pairs are markets with the '/' character between the base currency part and the quote currency part in the market symbol. For example, in the 'ETH/BTC' pair 'ETH' is the base currency, while 'BTC' is the quote currency. For pairs traded by Freqtrade the pair quote currency is defined by the value of the stake_currency configuration setting. You can print info about any pair/market with these subcommands - and you can filter output by quote-currency using --quote BTC , or by base-currency using --base ETH options correspondingly. These subcommands have same usage and same set of available options: ``` usage: freqtrade list-markets [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--exchange EXCHANGE] [--print-list] [--print-json] [-1] [--print-csv] [--base BASE_CURRENCY [BASE_CURRENCY ...]] [--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]] [-a] usage: freqtrade list-pairs [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--exchange EXCHANGE] [--print-list] [--print-json] [-1] [--print-csv] [--base BASE_CURRENCY [BASE_CURRENCY ...]] [--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]] [-a] optional arguments: -h, --help show this help message and exit --exchange EXCHANGE Exchange name (default: bittrex ). Only valid if no config is provided. --print-list Print list of pairs or market symbols. By default data is printed in the tabular format. --print-json Print list of pairs or market symbols in JSON format. -1, --one-column Print output in one column. --print-csv Print exchange pair or market data in the csv format. --base BASE_CURRENCY [BASE_CURRENCY ...] Specify base currency(-ies). Space-separated list. --quote QUOTE_CURRENCY [QUOTE_CURRENCY ...] Specify quote currency(-ies). Space-separated list. -a, --all Print all pairs or market symbols. By default only active ones are shown. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: config.json ). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. ``` By default, only active pairs/markets are shown. Active pairs/markets are those that can currently be traded on the exchange. The see the list of all pairs/markets (not only the active ones), use the -a / -all option. Pairs/markets are sorted by its symbol string in the printed output.","title":"List pairs/list markets"},{"location":"utils/#examples","text":"Print the list of active pairs with quote currency USD on exchange, specified in the default configuration file (i.e. pairs on the \"Bittrex\" exchange) in JSON format: $ freqtrade list-pairs --quote USD --print-json Print the list of all pairs on the exchange, specified in the config_binance.json configuration file (i.e. on the \"Binance\" exchange) with base currencies BTC or ETH and quote currencies USDT or USD, as the human-readable list with summary: $ freqtrade list-pairs -c config_binance.json --all --base BTC ETH --quote USDT USD --print-list Print all markets on exchange \"Kraken\", in the tabular format: $ freqtrade list-markets --exchange kraken --all","title":"Examples"},{"location":"utils/#test-pairlist","text":"Use the test-pairlist subcommand to test the configuration of dynamic pairlists . Requires a configuration with specified pairlists attribute. Can be used to generate static pairlists to be used during backtesting / hyperopt. ``` usage: freqtrade test-pairlist [-h] [-c PATH] [--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]] [-1] [--print-json] optional arguments: -h, --help show this help message and exit -c PATH, --config PATH Specify configuration file (default: config.json ). Multiple --config options may be used. Can be set to - to read config from stdin. --quote QUOTE_CURRENCY [QUOTE_CURRENCY ...] Specify quote currency(-ies). Space-separated list. -1, --one-column Print output in one column. --print-json Print list of pairs or market symbols in JSON format. ```","title":"Test pairlist"},{"location":"utils/#examples_1","text":"Show whitelist when using a dynamic pairlist . freqtrade test-pairlist --config config.json --quote USDT BTC","title":"Examples"},{"location":"utils/#webserver-mode","text":"Experimental Webserver mode is an experimental mode to increase backesting and strategy development productivity. There may still be bugs - so if you happen to stumble across these, please report them as github issues, thanks. Run freqtrade in webserver mode. Freqtrade will start the webserver and allow FreqUI to start and control backtesting processes. This has the advantage that data will not be reloaded between backtesting runs (as long as timeframe and timerange remain identical). FreqUI will also show the backtesting results. ``` usage: freqtrade webserver [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-s NAME] [--strategy-path PATH] optional arguments: -h, --help show this help message and exit Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. Strategy arguments: -s NAME, --strategy NAME Specify strategy class name which will be used by the bot. --strategy-path PATH Specify additional strategy lookup path. ```","title":"Webserver mode"},{"location":"utils/#list-hyperopt-results","text":"You can list the hyperoptimization epochs the Hyperopt module evaluated previously with the hyperopt-list sub-command. ``` usage: freqtrade hyperopt-list [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--best] [--profitable] [--min-trades INT] [--max-trades INT] [--min-avg-time FLOAT] [--max-avg-time FLOAT] [--min-avg-profit FLOAT] [--max-avg-profit FLOAT] [--min-total-profit FLOAT] [--max-total-profit FLOAT] [--min-objective FLOAT] [--max-objective FLOAT] [--no-color] [--print-json] [--no-details] [--hyperopt-filename PATH] [--export-csv FILE] optional arguments: -h, --help show this help message and exit --best Select only best epochs. --profitable Select only profitable epochs. --min-trades INT Select epochs with more than INT trades. --max-trades INT Select epochs with less than INT trades. --min-avg-time FLOAT Select epochs above average time. --max-avg-time FLOAT Select epochs below average time. --min-avg-profit FLOAT Select epochs above average profit. --max-avg-profit FLOAT Select epochs below average profit. --min-total-profit FLOAT Select epochs above total profit. --max-total-profit FLOAT Select epochs below total profit. --min-objective FLOAT Select epochs above objective. --max-objective FLOAT Select epochs below objective. --no-color Disable colorization of hyperopt results. May be useful if you are redirecting output to a file. --print-json Print output in JSON format. --no-details Do not print best epoch details. --hyperopt-filename FILENAME Hyperopt result filename.Example: --hyperopt- filename=hyperopt_results_2020-09-27_16-20-48.pickle --export-csv FILE Export to CSV-File. This will disable table print. Example: --export-csv hyperopt.csv Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. ``` Note hyperopt-list will automatically use the latest available hyperopt results file. You can override this using the --hyperopt-filename argument, and specify another, available filename (without path!).","title":"List Hyperopt results"},{"location":"utils/#examples_2","text":"List all results, print details of the best result at the end: freqtrade hyperopt-list List only epochs with positive profit. Do not print the details of the best epoch, so that the list can be iterated in a script: freqtrade hyperopt-list --profitable --no-details","title":"Examples"},{"location":"utils/#show-details-of-hyperopt-results","text":"You can show the details of any hyperoptimization epoch previously evaluated by the Hyperopt module with the hyperopt-show subcommand. ``` usage: freqtrade hyperopt-show [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--best] [--profitable] [-n INT] [--print-json] [--hyperopt-filename FILENAME] [--no-header] [--disable-param-export] optional arguments: -h, --help show this help message and exit --best Select only best epochs. --profitable Select only profitable epochs. -n INT, --index INT Specify the index of the epoch to print details for. --print-json Print output in JSON format. --hyperopt-filename FILENAME Hyperopt result filename.Example: --hyperopt- filename=hyperopt_results_2020-09-27_16-20-48.pickle --no-header Do not print epoch details header. --disable-param-export Disable automatic hyperopt parameter export. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. ``` Note hyperopt-show will automatically use the latest available hyperopt results file. You can override this using the --hyperopt-filename argument, and specify another, available filename (without path!).","title":"Show details of Hyperopt results"},{"location":"utils/#examples_3","text":"Print details for the epoch 168 (the number of the epoch is shown by the hyperopt-list subcommand or by Hyperopt itself during hyperoptimization run): freqtrade hyperopt-show -n 168 Prints JSON data with details for the last best epoch (i.e., the best of all epochs): freqtrade hyperopt-show --best -n -1 --print-json --no-header","title":"Examples"},{"location":"utils/#show-trades","text":"Print selected (or all) trades from database to screen. ``` usage: freqtrade show-trades [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--db-url PATH] [--trade-ids TRADE_IDS [TRADE_IDS ...]] [--print-json] optional arguments: -h, --help show this help message and exit --db-url PATH Override trades database URL, this is useful in custom deployments (default: sqlite:///tradesv3.sqlite for Live Run mode, sqlite:///tradesv3.dryrun.sqlite for Dry Run). --trade-ids TRADE_IDS [TRADE_IDS ...] Specify the list of trade ids. --print-json Print output in JSON format. Common arguments: -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. -V, --version show program's version number and exit -c PATH, --config PATH Specify configuration file (default: userdir/config.json or config.json whichever exists). Multiple --config options may be used. Can be set to - to read config from stdin. -d PATH, --datadir PATH Path to directory with historical backtesting data. --userdir PATH, --user-data-dir PATH Path to userdata directory. ```","title":"Show trades"},{"location":"utils/#examples_4","text":"Print trades with id 2 and 3 as json bash freqtrade show-trades --db-url sqlite:///tradesv3.sqlite --trade-ids 2 3 --print-json","title":"Examples"},{"location":"webhook-config/","text":"Webhook usage \u00b6 Configuration \u00b6 Enable webhooks by adding a webhook-section to your configuration file, and setting webhook.enabled to true . Sample configuration (tested using IFTTT). json \"webhook\": { \"enabled\": true, \"url\": \"https://maker.ifttt.com/trigger//with/key//\", \"webhookbuy\": { \"value1\": \"Buying {pair}\", \"value2\": \"limit {limit:8f}\", \"value3\": \"{stake_amount:8f} {stake_currency}\" }, \"webhookbuycancel\": { \"value1\": \"Cancelling Open Buy Order for {pair}\", \"value2\": \"limit {limit:8f}\", \"value3\": \"{stake_amount:8f} {stake_currency}\" }, \"webhookbuyfill\": { \"value1\": \"Buy Order for {pair} filled\", \"value2\": \"at {open_rate:8f}\", \"value3\": \"\" }, \"webhooksell\": { \"value1\": \"Selling {pair}\", \"value2\": \"limit {limit:8f}\", \"value3\": \"profit: {profit_amount:8f} {stake_currency} ({profit_ratio})\" }, \"webhooksellcancel\": { \"value1\": \"Cancelling Open Sell Order for {pair}\", \"value2\": \"limit {limit:8f}\", \"value3\": \"profit: {profit_amount:8f} {stake_currency} ({profit_ratio})\" }, \"webhooksellfill\": { \"value1\": \"Sell Order for {pair} filled\", \"value2\": \"at {close_rate:8f}.\", \"value3\": \"\" }, \"webhookstatus\": { \"value1\": \"Status: {status}\", \"value2\": \"\", \"value3\": \"\" } }, The url in webhook.url should point to the correct url for your webhook. If you're using IFTTT (as shown in the sample above) please insert our event and key to the url. You can set the POST body format to Form-Encoded (default) or JSON-Encoded. Use \"format\": \"form\" or \"format\": \"json\" respectively. Example configuration for Mattermost Cloud integration: json \"webhook\": { \"enabled\": true, \"url\": \"https://.cloud.mattermost.com/hooks/\", \"format\": \"json\", \"webhookstatus\": { \"text\": \"Status: {status}\" } }, The result would be POST request with e.g. {\"text\":\"Status: running\"} body and Content-Type: application/json header which results Status: running message in the Mattermost channel. Different payloads can be configured for different events. Not all fields are necessary, but you should configure at least one of the dicts, otherwise the webhook will never be called. Webhookbuy \u00b6 The fields in webhook.webhookbuy are filled when the bot executes a buy. Parameters are filled using string.format. Possible parameters are: trade_id exchange pair limit amount open_date stake_amount stake_currency fiat_currency order_type current_rate Webhookbuycancel \u00b6 The fields in webhook.webhookbuycancel are filled when the bot cancels a buy order. Parameters are filled using string.format. Possible parameters are: trade_id exchange pair limit amount open_date stake_amount stake_currency fiat_currency order_type current_rate Webhookbuyfill \u00b6 The fields in webhook.webhookbuyfill are filled when the bot filled a buy order. Parameters are filled using string.format. Possible parameters are: trade_id exchange pair open_rate amount open_date stake_amount stake_currency fiat_currency Webhooksell \u00b6 The fields in webhook.webhooksell are filled when the bot sells a trade. Parameters are filled using string.format. Possible parameters are: trade_id exchange pair gain limit amount open_rate profit_amount profit_ratio stake_currency fiat_currency sell_reason order_type open_date close_date Webhooksellfill \u00b6 The fields in webhook.webhooksellfill are filled when the bot fills a sell order (closes a Trae). Parameters are filled using string.format. Possible parameters are: trade_id exchange pair gain close_rate amount open_rate current_rate profit_amount profit_ratio stake_currency fiat_currency sell_reason order_type open_date close_date Webhooksellcancel \u00b6 The fields in webhook.webhooksellcancel are filled when the bot cancels a sell order. Parameters are filled using string.format. Possible parameters are: trade_id exchange pair gain limit amount open_rate current_rate profit_amount profit_ratio stake_currency fiat_currency sell_reason order_type open_date close_date Webhookstatus \u00b6 The fields in webhook.webhookstatus are used for regular status messages (Started / Stopped / ...). Parameters are filled using string.format. The only possible value here is {status} .","title":"Web Hook"},{"location":"webhook-config/#webhook-usage","text":"","title":"Webhook usage"},{"location":"webhook-config/#configuration","text":"Enable webhooks by adding a webhook-section to your configuration file, and setting webhook.enabled to true . Sample configuration (tested using IFTTT). json \"webhook\": { \"enabled\": true, \"url\": \"https://maker.ifttt.com/trigger//with/key//\", \"webhookbuy\": { \"value1\": \"Buying {pair}\", \"value2\": \"limit {limit:8f}\", \"value3\": \"{stake_amount:8f} {stake_currency}\" }, \"webhookbuycancel\": { \"value1\": \"Cancelling Open Buy Order for {pair}\", \"value2\": \"limit {limit:8f}\", \"value3\": \"{stake_amount:8f} {stake_currency}\" }, \"webhookbuyfill\": { \"value1\": \"Buy Order for {pair} filled\", \"value2\": \"at {open_rate:8f}\", \"value3\": \"\" }, \"webhooksell\": { \"value1\": \"Selling {pair}\", \"value2\": \"limit {limit:8f}\", \"value3\": \"profit: {profit_amount:8f} {stake_currency} ({profit_ratio})\" }, \"webhooksellcancel\": { \"value1\": \"Cancelling Open Sell Order for {pair}\", \"value2\": \"limit {limit:8f}\", \"value3\": \"profit: {profit_amount:8f} {stake_currency} ({profit_ratio})\" }, \"webhooksellfill\": { \"value1\": \"Sell Order for {pair} filled\", \"value2\": \"at {close_rate:8f}.\", \"value3\": \"\" }, \"webhookstatus\": { \"value1\": \"Status: {status}\", \"value2\": \"\", \"value3\": \"\" } }, The url in webhook.url should point to the correct url for your webhook. If you're using IFTTT (as shown in the sample above) please insert our event and key to the url. You can set the POST body format to Form-Encoded (default) or JSON-Encoded. Use \"format\": \"form\" or \"format\": \"json\" respectively. Example configuration for Mattermost Cloud integration: json \"webhook\": { \"enabled\": true, \"url\": \"https://.cloud.mattermost.com/hooks/\", \"format\": \"json\", \"webhookstatus\": { \"text\": \"Status: {status}\" } }, The result would be POST request with e.g. {\"text\":\"Status: running\"} body and Content-Type: application/json header which results Status: running message in the Mattermost channel. Different payloads can be configured for different events. Not all fields are necessary, but you should configure at least one of the dicts, otherwise the webhook will never be called.","title":"Configuration"},{"location":"webhook-config/#webhookbuy","text":"The fields in webhook.webhookbuy are filled when the bot executes a buy. Parameters are filled using string.format. Possible parameters are: trade_id exchange pair limit amount open_date stake_amount stake_currency fiat_currency order_type current_rate","title":"Webhookbuy"},{"location":"webhook-config/#webhookbuycancel","text":"The fields in webhook.webhookbuycancel are filled when the bot cancels a buy order. Parameters are filled using string.format. Possible parameters are: trade_id exchange pair limit amount open_date stake_amount stake_currency fiat_currency order_type current_rate","title":"Webhookbuycancel"},{"location":"webhook-config/#webhookbuyfill","text":"The fields in webhook.webhookbuyfill are filled when the bot filled a buy order. Parameters are filled using string.format. Possible parameters are: trade_id exchange pair open_rate amount open_date stake_amount stake_currency fiat_currency","title":"Webhookbuyfill"},{"location":"webhook-config/#webhooksell","text":"The fields in webhook.webhooksell are filled when the bot sells a trade. Parameters are filled using string.format. Possible parameters are: trade_id exchange pair gain limit amount open_rate profit_amount profit_ratio stake_currency fiat_currency sell_reason order_type open_date close_date","title":"Webhooksell"},{"location":"webhook-config/#webhooksellfill","text":"The fields in webhook.webhooksellfill are filled when the bot fills a sell order (closes a Trae). Parameters are filled using string.format. Possible parameters are: trade_id exchange pair gain close_rate amount open_rate current_rate profit_amount profit_ratio stake_currency fiat_currency sell_reason order_type open_date close_date","title":"Webhooksellfill"},{"location":"webhook-config/#webhooksellcancel","text":"The fields in webhook.webhooksellcancel are filled when the bot cancels a sell order. Parameters are filled using string.format. Possible parameters are: trade_id exchange pair gain limit amount open_rate current_rate profit_amount profit_ratio stake_currency fiat_currency sell_reason order_type open_date close_date","title":"Webhooksellcancel"},{"location":"webhook-config/#webhookstatus","text":"The fields in webhook.webhookstatus are used for regular status messages (Started / Stopped / ...). Parameters are filled using string.format. The only possible value here is {status} .","title":"Webhookstatus"},{"location":"windows_installation/","text":"Windows installation \u00b6 We strongly recommend that Windows users use Docker as this will work much easier and smoother (also more secure). If that is not possible, try using the Windows Linux subsystem (WSL) - for which the Ubuntu instructions should work. Otherwise, try the instructions below. Install freqtrade manually \u00b6 Note Make sure to use 64bit Windows and 64bit Python to avoid problems with backtesting or hyperopt due to the memory constraints 32bit applications have under Windows. Hint Using the Anaconda Distribution under Windows can greatly help with installation problems. Check out the Anaconda installation section in this document for more information. 1. Clone the git repository \u00b6 bash git clone https://github.com/freqtrade/freqtrade.git 2. Install ta-lib \u00b6 Install ta-lib according to the ta-lib documentation . As compiling from source on windows has heavy dependencies (requires a partial visual studio installation), there is also a repository of unofficial pre-compiled windows Wheels here , which need to be downloaded and installed using pip install TA_Lib-0.4.21-cp38-cp38-win_amd64.whl (make sure to use the version matching your python version). Freqtrade provides these dependencies for the latest 2 Python versions (3.7 and 3.8) and for 64bit Windows. Other versions must be downloaded from the above link. ``` powershell cd \\path\\freqtrade python -m venv .env .env\\Scripts\\activate.ps1 optionally install ta-lib from wheel \u00b6 Eventually adjust the below filename to match the downloaded wheel \u00b6 pip install build_helpers/TA_Lib-0.4.19-cp38-cp38-win_amd64.whl pip install -r requirements.txt pip install -e . freqtrade ``` Use Powershell The above installation script assumes you're using powershell on a 64bit windows. Commands for the legacy CMD windows console may differ. Thanks Owdr for the commands. Source: Issue #222 Error during installation on Windows \u00b6 bash error: Microsoft Visual C++ 14.0 is required. Get it with \"Microsoft Visual C++ Build Tools\": http://landinghub.visualstudio.com/visual-cpp-build-tools Unfortunately, many packages requiring compilation don't provide a pre-built wheel. It is therefore mandatory to have a C/C++ compiler installed and available for your python environment to use. The easiest way is to download install Microsoft Visual Studio Community here and make sure to install \"Common Tools for Visual C++\" to enable building C code on Windows. Unfortunately, this is a heavy download / dependency (~4Gb) so you might want to consider WSL or docker compose first.","title":"Windows"},{"location":"windows_installation/#windows-installation","text":"We strongly recommend that Windows users use Docker as this will work much easier and smoother (also more secure). If that is not possible, try using the Windows Linux subsystem (WSL) - for which the Ubuntu instructions should work. Otherwise, try the instructions below.","title":"Windows installation"},{"location":"windows_installation/#install-freqtrade-manually","text":"Note Make sure to use 64bit Windows and 64bit Python to avoid problems with backtesting or hyperopt due to the memory constraints 32bit applications have under Windows. Hint Using the Anaconda Distribution under Windows can greatly help with installation problems. Check out the Anaconda installation section in this document for more information.","title":"Install freqtrade manually"},{"location":"windows_installation/#1-clone-the-git-repository","text":"bash git clone https://github.com/freqtrade/freqtrade.git","title":"1. Clone the git repository"},{"location":"windows_installation/#2-install-ta-lib","text":"Install ta-lib according to the ta-lib documentation . As compiling from source on windows has heavy dependencies (requires a partial visual studio installation), there is also a repository of unofficial pre-compiled windows Wheels here , which need to be downloaded and installed using pip install TA_Lib-0.4.21-cp38-cp38-win_amd64.whl (make sure to use the version matching your python version). Freqtrade provides these dependencies for the latest 2 Python versions (3.7 and 3.8) and for 64bit Windows. Other versions must be downloaded from the above link. ``` powershell cd \\path\\freqtrade python -m venv .env .env\\Scripts\\activate.ps1","title":"2. Install ta-lib"},{"location":"windows_installation/#optionally-install-ta-lib-from-wheel","text":"","title":"optionally install ta-lib from wheel"},{"location":"windows_installation/#eventually-adjust-the-below-filename-to-match-the-downloaded-wheel","text":"pip install build_helpers/TA_Lib-0.4.19-cp38-cp38-win_amd64.whl pip install -r requirements.txt pip install -e . freqtrade ``` Use Powershell The above installation script assumes you're using powershell on a 64bit windows. Commands for the legacy CMD windows console may differ. Thanks Owdr for the commands. Source: Issue #222","title":"Eventually adjust the below filename to match the downloaded wheel"},{"location":"windows_installation/#error-during-installation-on-windows","text":"bash error: Microsoft Visual C++ 14.0 is required. Get it with \"Microsoft Visual C++ Build Tools\": http://landinghub.visualstudio.com/visual-cpp-build-tools Unfortunately, many packages requiring compilation don't provide a pre-built wheel. It is therefore mandatory to have a C/C++ compiler installed and available for your python environment to use. The easiest way is to download install Microsoft Visual Studio Community here and make sure to install \"Common Tools for Visual C++\" to enable building C code on Windows. Unfortunately, this is a heavy download / dependency (~4Gb) so you might want to consider WSL or docker compose first.","title":"Error during installation on Windows"},{"location":"includes/pairlists/","text":"Pairlists and Pairlist Handlers \u00b6 Pairlist Handlers define the list of pairs (pairlist) that the bot should trade. They are configured in the pairlists section of the configuration settings. In your configuration, you can use Static Pairlist (defined by the StaticPairList Pairlist Handler) and Dynamic Pairlist (defined by the VolumePairList Pairlist Handler). Additionally, AgeFilter , PrecisionFilter , PriceFilter , ShuffleFilter , SpreadFilter and VolatilityFilter act as Pairlist Filters, removing certain pairs and/or moving their positions in the pairlist. If multiple Pairlist Handlers are used, they are chained and a combination of all Pairlist Handlers forms the resulting pairlist the bot uses for trading and backtesting. Pairlist Handlers are executed in the sequence they are configured. You should always configure either StaticPairList or VolumePairList as the starting Pairlist Handler. Inactive markets are always removed from the resulting pairlist. Explicitly blacklisted pairs (those in the pair_blacklist configuration setting) are also always removed from the resulting pairlist. Pair blacklist \u00b6 The pair blacklist (configured via exchange.pair_blacklist in the configuration) disallows certain pairs from trading. This can be as simple as excluding DOGE/BTC - which will remove exactly this pair. The pair-blacklist does also support wildcards (in regex-style) - so BNB/.* will exclude ALL pairs that start with BNB. You may also use something like .*DOWN/BTC or .*UP/BTC to exclude leveraged tokens (check Pair naming conventions for your exchange!) Available Pairlist Handlers \u00b6 StaticPairList (default, if not configured differently) VolumePairList AgeFilter OffsetFilter PerformanceFilter PrecisionFilter PriceFilter ShuffleFilter SpreadFilter RangeStabilityFilter VolatilityFilter Testing pairlists Pairlist configurations can be quite tricky to get right. Best use the test-pairlist utility sub-command to test your configuration quickly. Static Pair List \u00b6 By default, the StaticPairList method is used, which uses a statically defined pair whitelist from the configuration. The pairlist also supports wildcards (in regex-style) - so .*/BTC will include all pairs with BTC as a stake. It uses configuration from exchange.pair_whitelist and exchange.pair_blacklist . json \"pairlists\": [ {\"method\": \"StaticPairList\"} ], By default, only currently enabled pairs are allowed. To skip pair validation against active markets, set \"allow_inactive\": true within the StaticPairList configuration. This can be useful for backtesting expired pairs (like quarterly spot-markets). This option must be configured along with exchange.skip_pair_validation in the exchange configuration. Volume Pair List \u00b6 VolumePairList employs sorting/filtering of pairs by their trading volume. It selects number_assets top pairs with sorting based on the sort_key (which can only be quoteVolume ). When used in the chain of Pairlist Handlers in a non-leading position (after StaticPairList and other Pairlist Filters), VolumePairList considers outputs of previous Pairlist Handlers, adding its sorting/selection of the pairs by the trading volume. When used on the leading position of the chain of Pairlist Handlers, it does not consider pair_whitelist configuration setting, but selects the top assets from all available markets (with matching stake-currency) on the exchange. The refresh_period setting allows to define the period (in seconds), at which the pairlist will be refreshed. Defaults to 1800s (30 minutes). The pairlist cache ( refresh_period ) on VolumePairList is only applicable to generating pairlists. Filtering instances (not the first position in the list) will not apply any cache and will always use up-to-date data. VolumePairList is per default based on the ticker data from exchange, as reported by the ccxt library: The quoteVolume is the amount of quote (stake) currency traded (bought or sold) in last 24 hours. json \"pairlists\": [ { \"method\": \"VolumePairList\", \"number_assets\": 20, \"sort_key\": \"quoteVolume\", \"refresh_period\": 1800 } ], VolumePairList can also operate in an advanced mode to build volume over a given timerange of specified candle size. It utilizes exchange historical candle data, builds a typical price (calculated by (open+high+low)/3) and multiplies the typical price with every candle's volume. The sum is the quoteVolume over the given range. This allows different scenarios, for a more smoothened volume, when using longer ranges with larger candle sizes, or the opposite when using a short range with small candles. For convenience lookback_days can be specified, which will imply that 1d candles will be used for the lookback. In the example below the pairlist would be created based on the last 7 days: json \"pairlists\": [ { \"method\": \"VolumePairList\", \"number_assets\": 20, \"sort_key\": \"quoteVolume\", \"refresh_period\": 86400, \"lookback_days\": 7 } ], Range look back and refresh period When used in conjunction with lookback_days and lookback_timeframe the refresh_period can not be smaller than the candle size in seconds. As this will result in unnecessary requests to the exchanges API. Performance implications when using lookback range If used in first position in combination with lookback, the computation of the range based volume can be time and resource consuming, as it downloads candles for all tradable pairs. Hence it's highly advised to use the standard approach with VolumeFilter to narrow the pairlist down for further range volume calculation. More sophisticated approach can be used, by using lookback_timeframe for candle size and lookback_period which specifies the amount of candles. This example will build the volume pairs based on a rolling period of 3 days of 1h candles: json \"pairlists\": [ { \"method\": \"VolumePairList\", \"number_assets\": 20, \"sort_key\": \"quoteVolume\", \"refresh_period\": 3600, \"lookback_timeframe\": \"1h\", \"lookback_period\": 72 } ], Note VolumePairList does not support backtesting mode. AgeFilter \u00b6 Removes pairs that have been listed on the exchange for less than min_days_listed days (defaults to 10 ) or more than max_days_listed days (defaults None mean infinity). When pairs are first listed on an exchange they can suffer huge price drops and volatility in the first few days while the pair goes through its price-discovery period. Bots can often be caught out buying before the pair has finished dropping in price. This filter allows freqtrade to ignore pairs until they have been listed for at least min_days_listed days and listed before max_days_listed . OffsetFilter \u00b6 Offsets an incoming pairlist by a given offset value. As an example it can be used in conjunction with VolumeFilter to remove the top X volume pairs. Or to split a larger pairlist on two bot instances. Example to remove the first 10 pairs from the pairlist: json \"pairlists\": [ { \"method\": \"OffsetFilter\", \"offset\": 10 } ], Warning When OffsetFilter is used to split a larger pairlist among multiple bots in combination with VolumeFilter it can not be guaranteed that pairs won't overlap due to slightly different refresh intervals for the VolumeFilter . Note An offset larger then the total length of the incoming pairlist will result in an empty pairlist. PerformanceFilter \u00b6 Sorts pairs by past trade performance, as follows: Positive performance. No closed trades yet. Negative performance. Trade count is used as a tie breaker. Note PerformanceFilter does not support backtesting mode. PrecisionFilter \u00b6 Filters low-value coins which would not allow setting stoplosses. PriceFilter \u00b6 The PriceFilter allows filtering of pairs by price. Currently the following price filters are supported: min_price max_price max_value low_price_ratio The min_price setting removes pairs where the price is below the specified price. This is useful if you wish to avoid trading very low-priced pairs. This option is disabled by default, and will only apply if set to > 0. The max_price setting removes pairs where the price is above the specified price. This is useful if you wish to trade only low-priced pairs. This option is disabled by default, and will only apply if set to > 0. The max_value setting removes pairs where the minimum value change is above a specified value. This is useful when an exchange has unbalanced limits. For example, if step-size = 1 (so you can only buy 1, or 2, or 3, but not 1.1 Coins) - and the price is pretty high (like 20$) as the coin has risen sharply since the last limit adaption. As a result of the above, you can only buy for 20$, or 40$ - but not for 25$. On exchanges that deduct fees from the receiving currency (e.g. FTX) - this can result in high value coins / amounts that are unsellable as the amount is slightly below the limit. The low_price_ratio setting removes pairs where a raise of 1 price unit (pip) is above the low_price_ratio ratio. This option is disabled by default, and will only apply if set to > 0. For PriceFiler at least one of its min_price , max_price or low_price_ratio settings must be applied. Calculation example: Min price precision for SHITCOIN/BTC is 8 decimals. If its price is 0.00000011 - one price step above would be 0.00000012, which is ~9% higher than the previous price value. You may filter out this pair by using PriceFilter with low_price_ratio set to 0.09 (9%) or with min_price set to 0.00000011, correspondingly. Low priced pairs Low priced pairs with high \"1 pip movements\" are dangerous since they are often illiquid and it may also be impossible to place the desired stoploss, which can often result in high losses since price needs to be rounded to the next tradable price - so instead of having a stoploss of -5%, you could end up with a stoploss of -9% simply due to price rounding. ShuffleFilter \u00b6 Shuffles (randomizes) pairs in the pairlist. It can be used for preventing the bot from trading some of the pairs more frequently then others when you want all pairs be treated with the same priority. Tip You may set the seed value for this Pairlist to obtain reproducible results, which can be useful for repeated backtesting sessions. If seed is not set, the pairs are shuffled in the non-repeatable random order. SpreadFilter \u00b6 Removes pairs that have a difference between asks and bids above the specified ratio, max_spread_ratio (defaults to 0.005 ). Example: If DOGE/BTC maximum bid is 0.00000026 and minimum ask is 0.00000027, the ratio is calculated as: 1 - bid/ask ~= 0.037 which is > 0.005 and this pair will be filtered out. RangeStabilityFilter \u00b6 Removes pairs where the difference between lowest low and highest high over lookback_days days is below min_rate_of_change . Since this is a filter that requires additional data, the results are cached for refresh_period . In the below example: If the trading range over the last 10 days is <1%, remove the pair from the whitelist. json \"pairlists\": [ { \"method\": \"RangeStabilityFilter\", \"lookback_days\": 10, \"min_rate_of_change\": 0.01, \"refresh_period\": 1440 } ] Tip This Filter can be used to automatically remove stable coin pairs, which have a very low trading range, and are therefore extremely difficult to trade with profit. VolatilityFilter \u00b6 Volatility is the degree of historical variation of a pairs over time, is is measured by the standard deviation of logarithmic daily returns. Returns are assumed to be normally distributed, although actual distribution might be different. In a normal distribution, 68% of observations fall within one standard deviation and 95% of observations fall within two standard deviations. Assuming a volatility of 0.05 means that the expected returns for 20 out of 30 days is expected to be less than 5% (one standard deviation). Volatility is a positive ratio of the expected deviation of return and can be greater than 1.00. Please refer to the wikipedia definition of volatility . This filter removes pairs if the average volatility over a lookback_days days is below min_volatility or above max_volatility . Since this is a filter that requires additional data, the results are cached for refresh_period . This filter can be used to narrow down your pairs to a certain volatility or avoid very volatile pairs. In the below example: If the volatility over the last 10 days is not in the range of 0.05-0.50, remove the pair from the whitelist. The filter is applied every 24h. json \"pairlists\": [ { \"method\": \"VolatilityFilter\", \"lookback_days\": 10, \"min_volatility\": 0.05, \"max_volatility\": 0.50, \"refresh_period\": 86400 } ] Full example of Pairlist Handlers \u00b6 The below example blacklists BNB/BTC , uses VolumePairList with 20 assets, sorting pairs by quoteVolume and applies PrecisionFilter and PriceFilter , filtering all assets where 1 price unit is > 1%. Then the SpreadFilter and VolatilityFilter is applied and pairs are finally shuffled with the random seed set to some predefined value. json \"exchange\": { \"pair_whitelist\": [], \"pair_blacklist\": [\"BNB/BTC\"] }, \"pairlists\": [ { \"method\": \"VolumePairList\", \"number_assets\": 20, \"sort_key\": \"quoteVolume\" }, {\"method\": \"AgeFilter\", \"min_days_listed\": 10}, {\"method\": \"PrecisionFilter\"}, {\"method\": \"PriceFilter\", \"low_price_ratio\": 0.01}, {\"method\": \"SpreadFilter\", \"max_spread_ratio\": 0.005}, { \"method\": \"RangeStabilityFilter\", \"lookback_days\": 10, \"min_rate_of_change\": 0.01, \"refresh_period\": 1440 }, { \"method\": \"VolatilityFilter\", \"lookback_days\": 10, \"min_volatility\": 0.05, \"max_volatility\": 0.50, \"refresh_period\": 86400 }, {\"method\": \"ShuffleFilter\", \"seed\": 42} ],","title":"Pairlists"},{"location":"includes/pairlists/#pairlists-and-pairlist-handlers","text":"Pairlist Handlers define the list of pairs (pairlist) that the bot should trade. They are configured in the pairlists section of the configuration settings. In your configuration, you can use Static Pairlist (defined by the StaticPairList Pairlist Handler) and Dynamic Pairlist (defined by the VolumePairList Pairlist Handler). Additionally, AgeFilter , PrecisionFilter , PriceFilter , ShuffleFilter , SpreadFilter and VolatilityFilter act as Pairlist Filters, removing certain pairs and/or moving their positions in the pairlist. If multiple Pairlist Handlers are used, they are chained and a combination of all Pairlist Handlers forms the resulting pairlist the bot uses for trading and backtesting. Pairlist Handlers are executed in the sequence they are configured. You should always configure either StaticPairList or VolumePairList as the starting Pairlist Handler. Inactive markets are always removed from the resulting pairlist. Explicitly blacklisted pairs (those in the pair_blacklist configuration setting) are also always removed from the resulting pairlist.","title":"Pairlists and Pairlist Handlers"},{"location":"includes/pairlists/#pair-blacklist","text":"The pair blacklist (configured via exchange.pair_blacklist in the configuration) disallows certain pairs from trading. This can be as simple as excluding DOGE/BTC - which will remove exactly this pair. The pair-blacklist does also support wildcards (in regex-style) - so BNB/.* will exclude ALL pairs that start with BNB. You may also use something like .*DOWN/BTC or .*UP/BTC to exclude leveraged tokens (check Pair naming conventions for your exchange!)","title":"Pair blacklist"},{"location":"includes/pairlists/#available-pairlist-handlers","text":"StaticPairList (default, if not configured differently) VolumePairList AgeFilter OffsetFilter PerformanceFilter PrecisionFilter PriceFilter ShuffleFilter SpreadFilter RangeStabilityFilter VolatilityFilter Testing pairlists Pairlist configurations can be quite tricky to get right. Best use the test-pairlist utility sub-command to test your configuration quickly.","title":"Available Pairlist Handlers"},{"location":"includes/pairlists/#static-pair-list","text":"By default, the StaticPairList method is used, which uses a statically defined pair whitelist from the configuration. The pairlist also supports wildcards (in regex-style) - so .*/BTC will include all pairs with BTC as a stake. It uses configuration from exchange.pair_whitelist and exchange.pair_blacklist . json \"pairlists\": [ {\"method\": \"StaticPairList\"} ], By default, only currently enabled pairs are allowed. To skip pair validation against active markets, set \"allow_inactive\": true within the StaticPairList configuration. This can be useful for backtesting expired pairs (like quarterly spot-markets). This option must be configured along with exchange.skip_pair_validation in the exchange configuration.","title":"Static Pair List"},{"location":"includes/pairlists/#volume-pair-list","text":"VolumePairList employs sorting/filtering of pairs by their trading volume. It selects number_assets top pairs with sorting based on the sort_key (which can only be quoteVolume ). When used in the chain of Pairlist Handlers in a non-leading position (after StaticPairList and other Pairlist Filters), VolumePairList considers outputs of previous Pairlist Handlers, adding its sorting/selection of the pairs by the trading volume. When used on the leading position of the chain of Pairlist Handlers, it does not consider pair_whitelist configuration setting, but selects the top assets from all available markets (with matching stake-currency) on the exchange. The refresh_period setting allows to define the period (in seconds), at which the pairlist will be refreshed. Defaults to 1800s (30 minutes). The pairlist cache ( refresh_period ) on VolumePairList is only applicable to generating pairlists. Filtering instances (not the first position in the list) will not apply any cache and will always use up-to-date data. VolumePairList is per default based on the ticker data from exchange, as reported by the ccxt library: The quoteVolume is the amount of quote (stake) currency traded (bought or sold) in last 24 hours. json \"pairlists\": [ { \"method\": \"VolumePairList\", \"number_assets\": 20, \"sort_key\": \"quoteVolume\", \"refresh_period\": 1800 } ], VolumePairList can also operate in an advanced mode to build volume over a given timerange of specified candle size. It utilizes exchange historical candle data, builds a typical price (calculated by (open+high+low)/3) and multiplies the typical price with every candle's volume. The sum is the quoteVolume over the given range. This allows different scenarios, for a more smoothened volume, when using longer ranges with larger candle sizes, or the opposite when using a short range with small candles. For convenience lookback_days can be specified, which will imply that 1d candles will be used for the lookback. In the example below the pairlist would be created based on the last 7 days: json \"pairlists\": [ { \"method\": \"VolumePairList\", \"number_assets\": 20, \"sort_key\": \"quoteVolume\", \"refresh_period\": 86400, \"lookback_days\": 7 } ], Range look back and refresh period When used in conjunction with lookback_days and lookback_timeframe the refresh_period can not be smaller than the candle size in seconds. As this will result in unnecessary requests to the exchanges API. Performance implications when using lookback range If used in first position in combination with lookback, the computation of the range based volume can be time and resource consuming, as it downloads candles for all tradable pairs. Hence it's highly advised to use the standard approach with VolumeFilter to narrow the pairlist down for further range volume calculation. More sophisticated approach can be used, by using lookback_timeframe for candle size and lookback_period which specifies the amount of candles. This example will build the volume pairs based on a rolling period of 3 days of 1h candles: json \"pairlists\": [ { \"method\": \"VolumePairList\", \"number_assets\": 20, \"sort_key\": \"quoteVolume\", \"refresh_period\": 3600, \"lookback_timeframe\": \"1h\", \"lookback_period\": 72 } ], Note VolumePairList does not support backtesting mode.","title":"Volume Pair List"},{"location":"includes/pairlists/#agefilter","text":"Removes pairs that have been listed on the exchange for less than min_days_listed days (defaults to 10 ) or more than max_days_listed days (defaults None mean infinity). When pairs are first listed on an exchange they can suffer huge price drops and volatility in the first few days while the pair goes through its price-discovery period. Bots can often be caught out buying before the pair has finished dropping in price. This filter allows freqtrade to ignore pairs until they have been listed for at least min_days_listed days and listed before max_days_listed .","title":"AgeFilter"},{"location":"includes/pairlists/#offsetfilter","text":"Offsets an incoming pairlist by a given offset value. As an example it can be used in conjunction with VolumeFilter to remove the top X volume pairs. Or to split a larger pairlist on two bot instances. Example to remove the first 10 pairs from the pairlist: json \"pairlists\": [ { \"method\": \"OffsetFilter\", \"offset\": 10 } ], Warning When OffsetFilter is used to split a larger pairlist among multiple bots in combination with VolumeFilter it can not be guaranteed that pairs won't overlap due to slightly different refresh intervals for the VolumeFilter . Note An offset larger then the total length of the incoming pairlist will result in an empty pairlist.","title":"OffsetFilter"},{"location":"includes/pairlists/#performancefilter","text":"Sorts pairs by past trade performance, as follows: Positive performance. No closed trades yet. Negative performance. Trade count is used as a tie breaker. Note PerformanceFilter does not support backtesting mode.","title":"PerformanceFilter"},{"location":"includes/pairlists/#precisionfilter","text":"Filters low-value coins which would not allow setting stoplosses.","title":"PrecisionFilter"},{"location":"includes/pairlists/#pricefilter","text":"The PriceFilter allows filtering of pairs by price. Currently the following price filters are supported: min_price max_price max_value low_price_ratio The min_price setting removes pairs where the price is below the specified price. This is useful if you wish to avoid trading very low-priced pairs. This option is disabled by default, and will only apply if set to > 0. The max_price setting removes pairs where the price is above the specified price. This is useful if you wish to trade only low-priced pairs. This option is disabled by default, and will only apply if set to > 0. The max_value setting removes pairs where the minimum value change is above a specified value. This is useful when an exchange has unbalanced limits. For example, if step-size = 1 (so you can only buy 1, or 2, or 3, but not 1.1 Coins) - and the price is pretty high (like 20$) as the coin has risen sharply since the last limit adaption. As a result of the above, you can only buy for 20$, or 40$ - but not for 25$. On exchanges that deduct fees from the receiving currency (e.g. FTX) - this can result in high value coins / amounts that are unsellable as the amount is slightly below the limit. The low_price_ratio setting removes pairs where a raise of 1 price unit (pip) is above the low_price_ratio ratio. This option is disabled by default, and will only apply if set to > 0. For PriceFiler at least one of its min_price , max_price or low_price_ratio settings must be applied. Calculation example: Min price precision for SHITCOIN/BTC is 8 decimals. If its price is 0.00000011 - one price step above would be 0.00000012, which is ~9% higher than the previous price value. You may filter out this pair by using PriceFilter with low_price_ratio set to 0.09 (9%) or with min_price set to 0.00000011, correspondingly. Low priced pairs Low priced pairs with high \"1 pip movements\" are dangerous since they are often illiquid and it may also be impossible to place the desired stoploss, which can often result in high losses since price needs to be rounded to the next tradable price - so instead of having a stoploss of -5%, you could end up with a stoploss of -9% simply due to price rounding.","title":"PriceFilter"},{"location":"includes/pairlists/#shufflefilter","text":"Shuffles (randomizes) pairs in the pairlist. It can be used for preventing the bot from trading some of the pairs more frequently then others when you want all pairs be treated with the same priority. Tip You may set the seed value for this Pairlist to obtain reproducible results, which can be useful for repeated backtesting sessions. If seed is not set, the pairs are shuffled in the non-repeatable random order.","title":"ShuffleFilter"},{"location":"includes/pairlists/#spreadfilter","text":"Removes pairs that have a difference between asks and bids above the specified ratio, max_spread_ratio (defaults to 0.005 ). Example: If DOGE/BTC maximum bid is 0.00000026 and minimum ask is 0.00000027, the ratio is calculated as: 1 - bid/ask ~= 0.037 which is > 0.005 and this pair will be filtered out.","title":"SpreadFilter"},{"location":"includes/pairlists/#rangestabilityfilter","text":"Removes pairs where the difference between lowest low and highest high over lookback_days days is below min_rate_of_change . Since this is a filter that requires additional data, the results are cached for refresh_period . In the below example: If the trading range over the last 10 days is <1%, remove the pair from the whitelist. json \"pairlists\": [ { \"method\": \"RangeStabilityFilter\", \"lookback_days\": 10, \"min_rate_of_change\": 0.01, \"refresh_period\": 1440 } ] Tip This Filter can be used to automatically remove stable coin pairs, which have a very low trading range, and are therefore extremely difficult to trade with profit.","title":"RangeStabilityFilter"},{"location":"includes/pairlists/#volatilityfilter","text":"Volatility is the degree of historical variation of a pairs over time, is is measured by the standard deviation of logarithmic daily returns. Returns are assumed to be normally distributed, although actual distribution might be different. In a normal distribution, 68% of observations fall within one standard deviation and 95% of observations fall within two standard deviations. Assuming a volatility of 0.05 means that the expected returns for 20 out of 30 days is expected to be less than 5% (one standard deviation). Volatility is a positive ratio of the expected deviation of return and can be greater than 1.00. Please refer to the wikipedia definition of volatility . This filter removes pairs if the average volatility over a lookback_days days is below min_volatility or above max_volatility . Since this is a filter that requires additional data, the results are cached for refresh_period . This filter can be used to narrow down your pairs to a certain volatility or avoid very volatile pairs. In the below example: If the volatility over the last 10 days is not in the range of 0.05-0.50, remove the pair from the whitelist. The filter is applied every 24h. json \"pairlists\": [ { \"method\": \"VolatilityFilter\", \"lookback_days\": 10, \"min_volatility\": 0.05, \"max_volatility\": 0.50, \"refresh_period\": 86400 } ]","title":"VolatilityFilter"},{"location":"includes/pairlists/#full-example-of-pairlist-handlers","text":"The below example blacklists BNB/BTC , uses VolumePairList with 20 assets, sorting pairs by quoteVolume and applies PrecisionFilter and PriceFilter , filtering all assets where 1 price unit is > 1%. Then the SpreadFilter and VolatilityFilter is applied and pairs are finally shuffled with the random seed set to some predefined value. json \"exchange\": { \"pair_whitelist\": [], \"pair_blacklist\": [\"BNB/BTC\"] }, \"pairlists\": [ { \"method\": \"VolumePairList\", \"number_assets\": 20, \"sort_key\": \"quoteVolume\" }, {\"method\": \"AgeFilter\", \"min_days_listed\": 10}, {\"method\": \"PrecisionFilter\"}, {\"method\": \"PriceFilter\", \"low_price_ratio\": 0.01}, {\"method\": \"SpreadFilter\", \"max_spread_ratio\": 0.005}, { \"method\": \"RangeStabilityFilter\", \"lookback_days\": 10, \"min_rate_of_change\": 0.01, \"refresh_period\": 1440 }, { \"method\": \"VolatilityFilter\", \"lookback_days\": 10, \"min_volatility\": 0.05, \"max_volatility\": 0.50, \"refresh_period\": 86400 }, {\"method\": \"ShuffleFilter\", \"seed\": 42} ],","title":"Full example of Pairlist Handlers"},{"location":"includes/pricing/","text":"Prices used for orders \u00b6 Prices for regular orders can be controlled via the parameter structures bid_strategy for buying and ask_strategy for selling. Prices are always retrieved right before an order is placed, either by querying the exchange tickers or by using the orderbook data. Note Orderbook data used by Freqtrade are the data retrieved from exchange by the ccxt's function fetch_order_book() , i.e. are usually data from the L2-aggregated orderbook, while the ticker data are the structures returned by the ccxt's fetch_ticker() / fetch_tickers() functions. Refer to the ccxt library documentation for more details. Using market orders Please read the section Market order pricing section when using market orders. Buy price \u00b6 Check depth of market \u00b6 When check depth of market is enabled ( bid_strategy.check_depth_of_market.enabled=True ), the buy signals are filtered based on the orderbook depth (sum of all amounts) for each orderbook side. Orderbook bid (buy) side depth is then divided by the orderbook ask (sell) side depth and the resulting delta is compared to the value of the bid_strategy.check_depth_of_market.bids_to_ask_delta parameter. The buy order is only executed if the orderbook delta is greater than or equal to the configured delta value. Note A delta value below 1 means that ask (sell) orderbook side depth is greater than the depth of the bid (buy) orderbook side, while a value greater than 1 means opposite (depth of the buy side is higher than the depth of the sell side). Buy price side \u00b6 The configuration setting bid_strategy.price_side defines the side of the spread the bot looks for when buying. The following displays an orderbook. explanation ... 103 102 101 # ask -------------Current spread 99 # bid 98 97 ... If bid_strategy.price_side is set to \"bid\" , then the bot will use 99 as buying price. In line with that, if bid_strategy.price_side is set to \"ask\" , then the bot will use 101 as buying price. Using ask price often guarantees quicker filled orders, but the bot can also end up paying more than what would have been necessary. Taker fees instead of maker fees will most likely apply even when using limit buy orders. Also, prices at the \"ask\" side of the spread are higher than prices at the \"bid\" side in the orderbook, so the order behaves similar to a market order (however with a maximum price). Buy price with Orderbook enabled \u00b6 When buying with the orderbook enabled ( bid_strategy.use_order_book=True ), Freqtrade fetches the bid_strategy.order_book_top entries from the orderbook and uses the entry specified as bid_strategy.order_book_top on the configured side ( bid_strategy.price_side ) of the orderbook. 1 specifies the topmost entry in the orderbook, while 2 would use the 2 nd entry in the orderbook, and so on. Buy price without Orderbook enabled \u00b6 The following section uses side as the configured bid_strategy.price_side . When not using orderbook ( bid_strategy.use_order_book=False ), Freqtrade uses the best side price from the ticker if it's below the last traded price from the ticker. Otherwise (when the side price is above the last price), it calculates a rate between side and last price. The bid_strategy.ask_last_balance configuration parameter controls this. A value of 0.0 will use side price, while 1.0 will use the last price and values between those interpolate between ask and last price. Sell price \u00b6 Sell price side \u00b6 The configuration setting ask_strategy.price_side defines the side of the spread the bot looks for when selling. The following displays an orderbook: explanation ... 103 102 101 # ask -------------Current spread 99 # bid 98 97 ... If ask_strategy.price_side is set to \"ask\" , then the bot will use 101 as selling price. In line with that, if ask_strategy.price_side is set to \"bid\" , then the bot will use 99 as selling price. Sell price with Orderbook enabled \u00b6 When selling with the orderbook enabled ( ask_strategy.use_order_book=True ), Freqtrade fetches the ask_strategy.order_book_top entries in the orderbook and uses the entry specified as ask_strategy.order_book_top from the configured side ( ask_strategy.price_side ) as selling price. 1 specifies the topmost entry in the orderbook, while 2 would use the 2 nd entry in the orderbook, and so on. Sell price without Orderbook enabled \u00b6 When not using orderbook ( ask_strategy.use_order_book=False ), the price at the ask_strategy.price_side side (defaults to \"ask\" ) from the ticker will be used as the sell price. When not using orderbook ( ask_strategy.use_order_book=False ), Freqtrade uses the best side price from the ticker if it's below the last traded price from the ticker. Otherwise (when the side price is above the last price), it calculates a rate between side and last price. The ask_strategy.bid_last_balance configuration parameter controls this. A value of 0.0 will use side price, while 1.0 will use the last price and values between those interpolate between side and last price. Market order pricing \u00b6 When using market orders, prices should be configured to use the \"correct\" side of the orderbook to allow realistic pricing detection. Assuming both buy and sell are using market orders, a configuration similar to the following might be used jsonc \"order_types\": { \"buy\": \"market\", \"sell\": \"market\" // ... }, \"bid_strategy\": { \"price_side\": \"ask\", // ... }, \"ask_strategy\":{ \"price_side\": \"bid\", // ... }, Obviously, if only one side is using limit orders, different pricing combinations can be used.","title":"Pricing"},{"location":"includes/pricing/#prices-used-for-orders","text":"Prices for regular orders can be controlled via the parameter structures bid_strategy for buying and ask_strategy for selling. Prices are always retrieved right before an order is placed, either by querying the exchange tickers or by using the orderbook data. Note Orderbook data used by Freqtrade are the data retrieved from exchange by the ccxt's function fetch_order_book() , i.e. are usually data from the L2-aggregated orderbook, while the ticker data are the structures returned by the ccxt's fetch_ticker() / fetch_tickers() functions. Refer to the ccxt library documentation for more details. Using market orders Please read the section Market order pricing section when using market orders.","title":"Prices used for orders"},{"location":"includes/pricing/#buy-price","text":"","title":"Buy price"},{"location":"includes/pricing/#check-depth-of-market","text":"When check depth of market is enabled ( bid_strategy.check_depth_of_market.enabled=True ), the buy signals are filtered based on the orderbook depth (sum of all amounts) for each orderbook side. Orderbook bid (buy) side depth is then divided by the orderbook ask (sell) side depth and the resulting delta is compared to the value of the bid_strategy.check_depth_of_market.bids_to_ask_delta parameter. The buy order is only executed if the orderbook delta is greater than or equal to the configured delta value. Note A delta value below 1 means that ask (sell) orderbook side depth is greater than the depth of the bid (buy) orderbook side, while a value greater than 1 means opposite (depth of the buy side is higher than the depth of the sell side).","title":"Check depth of market"},{"location":"includes/pricing/#buy-price-side","text":"The configuration setting bid_strategy.price_side defines the side of the spread the bot looks for when buying. The following displays an orderbook. explanation ... 103 102 101 # ask -------------Current spread 99 # bid 98 97 ... If bid_strategy.price_side is set to \"bid\" , then the bot will use 99 as buying price. In line with that, if bid_strategy.price_side is set to \"ask\" , then the bot will use 101 as buying price. Using ask price often guarantees quicker filled orders, but the bot can also end up paying more than what would have been necessary. Taker fees instead of maker fees will most likely apply even when using limit buy orders. Also, prices at the \"ask\" side of the spread are higher than prices at the \"bid\" side in the orderbook, so the order behaves similar to a market order (however with a maximum price).","title":"Buy price side"},{"location":"includes/pricing/#buy-price-with-orderbook-enabled","text":"When buying with the orderbook enabled ( bid_strategy.use_order_book=True ), Freqtrade fetches the bid_strategy.order_book_top entries from the orderbook and uses the entry specified as bid_strategy.order_book_top on the configured side ( bid_strategy.price_side ) of the orderbook. 1 specifies the topmost entry in the orderbook, while 2 would use the 2 nd entry in the orderbook, and so on.","title":"Buy price with Orderbook enabled"},{"location":"includes/pricing/#buy-price-without-orderbook-enabled","text":"The following section uses side as the configured bid_strategy.price_side . When not using orderbook ( bid_strategy.use_order_book=False ), Freqtrade uses the best side price from the ticker if it's below the last traded price from the ticker. Otherwise (when the side price is above the last price), it calculates a rate between side and last price. The bid_strategy.ask_last_balance configuration parameter controls this. A value of 0.0 will use side price, while 1.0 will use the last price and values between those interpolate between ask and last price.","title":"Buy price without Orderbook enabled"},{"location":"includes/pricing/#sell-price","text":"","title":"Sell price"},{"location":"includes/pricing/#sell-price-side","text":"The configuration setting ask_strategy.price_side defines the side of the spread the bot looks for when selling. The following displays an orderbook: explanation ... 103 102 101 # ask -------------Current spread 99 # bid 98 97 ... If ask_strategy.price_side is set to \"ask\" , then the bot will use 101 as selling price. In line with that, if ask_strategy.price_side is set to \"bid\" , then the bot will use 99 as selling price.","title":"Sell price side"},{"location":"includes/pricing/#sell-price-with-orderbook-enabled","text":"When selling with the orderbook enabled ( ask_strategy.use_order_book=True ), Freqtrade fetches the ask_strategy.order_book_top entries in the orderbook and uses the entry specified as ask_strategy.order_book_top from the configured side ( ask_strategy.price_side ) as selling price. 1 specifies the topmost entry in the orderbook, while 2 would use the 2 nd entry in the orderbook, and so on.","title":"Sell price with Orderbook enabled"},{"location":"includes/pricing/#sell-price-without-orderbook-enabled","text":"When not using orderbook ( ask_strategy.use_order_book=False ), the price at the ask_strategy.price_side side (defaults to \"ask\" ) from the ticker will be used as the sell price. When not using orderbook ( ask_strategy.use_order_book=False ), Freqtrade uses the best side price from the ticker if it's below the last traded price from the ticker. Otherwise (when the side price is above the last price), it calculates a rate between side and last price. The ask_strategy.bid_last_balance configuration parameter controls this. A value of 0.0 will use side price, while 1.0 will use the last price and values between those interpolate between side and last price.","title":"Sell price without Orderbook enabled"},{"location":"includes/pricing/#market-order-pricing","text":"When using market orders, prices should be configured to use the \"correct\" side of the orderbook to allow realistic pricing detection. Assuming both buy and sell are using market orders, a configuration similar to the following might be used jsonc \"order_types\": { \"buy\": \"market\", \"sell\": \"market\" // ... }, \"bid_strategy\": { \"price_side\": \"ask\", // ... }, \"ask_strategy\":{ \"price_side\": \"bid\", // ... }, Obviously, if only one side is using limit orders, different pricing combinations can be used.","title":"Market order pricing"},{"location":"includes/protections/","text":"Protections \u00b6 Beta feature This feature is still in it's testing phase. Should you notice something you think is wrong please let us know via Discord or via Github Issue. Protections will protect your strategy from unexpected events and market conditions by temporarily stop trading for either one pair, or for all pairs. All protection end times are rounded up to the next candle to avoid sudden, unexpected intra-candle buys. Note Not all Protections will work for all strategies, and parameters will need to be tuned for your strategy to improve performance. Tip Each Protection can be configured multiple times with different parameters, to allow different levels of protection (short-term / long-term). Backtesting Protections are supported by backtesting and hyperopt, but must be explicitly enabled by using the --enable-protections flag. Available Protections \u00b6 StoplossGuard Stop trading if a certain amount of stoploss occurred within a certain time window. MaxDrawdown Stop trading if max-drawdown is reached. LowProfitPairs Lock pairs with low profits CooldownPeriod Don't enter a trade right after selling a trade. Common settings to all Protections \u00b6 Parameter Description method Protection name to use. Datatype: String, selected from available Protections stop_duration_candles For how many candles should the lock be set? Datatype: Positive integer (in candles) stop_duration how many minutes should protections be locked. Cannot be used together with stop_duration_candles . Datatype: Float (in minutes) lookback_period_candles Only trades that completed within the last lookback_period_candles candles will be considered. This setting may be ignored by some Protections. Datatype: Positive integer (in candles). lookback_period Only trades that completed after current_time - lookback_period will be considered. Cannot be used together with lookback_period_candles . This setting may be ignored by some Protections. Datatype: Float (in minutes) trade_limit Number of trades required at minimum (not used by all Protections). Datatype: Positive integer Durations Durations ( stop_duration* and lookback_period* can be defined in either minutes or candles). For more flexibility when testing different timeframes, all below examples will use the \"candle\" definition. Stoploss Guard \u00b6 StoplossGuard selects all trades within lookback_period in minutes (or in candles when using lookback_period_candles ). If trade_limit or more trades resulted in stoploss, trading will stop for stop_duration in minutes (or in candles when using stop_duration_candles ). This applies across all pairs, unless only_per_pair is set to true, which will then only look at one pair at a time. The below example stops trading for all pairs for 4 candles after the last trade if the bot hit stoploss 4 times within the last 24 candles. python protections = [ { \"method\": \"StoplossGuard\", \"lookback_period_candles\": 24, \"trade_limit\": 4, \"stop_duration_candles\": 4, \"only_per_pair\": False } ] Note StoplossGuard considers all trades with the results \"stop_loss\" , \"stoploss_on_exchange\" and \"trailing_stop_loss\" if the resulting profit was negative. trade_limit and lookback_period will need to be tuned for your strategy. MaxDrawdown \u00b6 MaxDrawdown uses all trades within lookback_period in minutes (or in candles when using lookback_period_candles ) to determine the maximum drawdown. If the drawdown is below max_allowed_drawdown , trading will stop for stop_duration in minutes (or in candles when using stop_duration_candles ) after the last trade - assuming that the bot needs some time to let markets recover. The below sample stops trading for 12 candles if max-drawdown is > 20% considering all pairs - with a minimum of trade_limit trades - within the last 48 candles. If desired, lookback_period and/or stop_duration can be used. python protections = [ { \"method\": \"MaxDrawdown\", \"lookback_period_candles\": 48, \"trade_limit\": 20, \"stop_duration_candles\": 12, \"max_allowed_drawdown\": 0.2 }, ] Low Profit Pairs \u00b6 LowProfitPairs uses all trades for a pair within lookback_period in minutes (or in candles when using lookback_period_candles ) to determine the overall profit ratio. If that ratio is below required_profit , that pair will be locked for stop_duration in minutes (or in candles when using stop_duration_candles ). The below example will stop trading a pair for 60 minutes if the pair does not have a required profit of 2% (and a minimum of 2 trades) within the last 6 candles. python protections = [ { \"method\": \"LowProfitPairs\", \"lookback_period_candles\": 6, \"trade_limit\": 2, \"stop_duration\": 60, \"required_profit\": 0.02 } ] Cooldown Period \u00b6 CooldownPeriod locks a pair for stop_duration in minutes (or in candles when using stop_duration_candles ) after selling, avoiding a re-entry for this pair for stop_duration minutes. The below example will stop trading a pair for 2 candles after closing a trade, allowing this pair to \"cool down\". python protections = [ { \"method\": \"CooldownPeriod\", \"stop_duration_candles\": 2 } ] Note This Protection applies only at pair-level, and will never lock all pairs globally. This Protection does not consider lookback_period as it only looks at the latest trade. Full example of Protections \u00b6 All protections can be combined at will, also with different parameters, creating a increasing wall for under-performing pairs. All protections are evaluated in the sequence they are defined. The below example assumes a timeframe of 1 hour: Locks each pair after selling for an additional 5 candles ( CooldownPeriod ), giving other pairs a chance to get filled. Stops trading for 4 hours ( 4 * 1h candles ) if the last 2 days ( 48 * 1h candles ) had 20 trades, which caused a max-drawdown of more than 20%. ( MaxDrawdown ). Stops trading if more than 4 stoploss occur for all pairs within a 1 day ( 24 * 1h candles ) limit ( StoplossGuard ). Locks all pairs that had 4 Trades within the last 6 hours ( 6 * 1h candles ) with a combined profit ratio of below 0.02 (<2%) ( LowProfitPairs ). Locks all pairs for 2 candles that had a profit of below 0.01 (<1%) within the last 24h ( 24 * 1h candles ), a minimum of 4 trades. ``` python from freqtrade.strategy import IStrategy class AwesomeStrategy(IStrategy) timeframe = '1h' protections = [ { \"method\": \"CooldownPeriod\", \"stop_duration_candles\": 5 }, { \"method\": \"MaxDrawdown\", \"lookback_period_candles\": 48, \"trade_limit\": 20, \"stop_duration_candles\": 4, \"max_allowed_drawdown\": 0.2 }, { \"method\": \"StoplossGuard\", \"lookback_period_candles\": 24, \"trade_limit\": 4, \"stop_duration_candles\": 2, \"only_per_pair\": False }, { \"method\": \"LowProfitPairs\", \"lookback_period_candles\": 6, \"trade_limit\": 2, \"stop_duration_candles\": 60, \"required_profit\": 0.02 }, { \"method\": \"LowProfitPairs\", \"lookback_period_candles\": 24, \"trade_limit\": 4, \"stop_duration_candles\": 2, \"required_profit\": 0.01 } ] # ... ```","title":"Protections"},{"location":"includes/protections/#protections","text":"Beta feature This feature is still in it's testing phase. Should you notice something you think is wrong please let us know via Discord or via Github Issue. Protections will protect your strategy from unexpected events and market conditions by temporarily stop trading for either one pair, or for all pairs. All protection end times are rounded up to the next candle to avoid sudden, unexpected intra-candle buys. Note Not all Protections will work for all strategies, and parameters will need to be tuned for your strategy to improve performance. Tip Each Protection can be configured multiple times with different parameters, to allow different levels of protection (short-term / long-term). Backtesting Protections are supported by backtesting and hyperopt, but must be explicitly enabled by using the --enable-protections flag.","title":"Protections"},{"location":"includes/protections/#available-protections","text":"StoplossGuard Stop trading if a certain amount of stoploss occurred within a certain time window. MaxDrawdown Stop trading if max-drawdown is reached. LowProfitPairs Lock pairs with low profits CooldownPeriod Don't enter a trade right after selling a trade.","title":"Available Protections"},{"location":"includes/protections/#common-settings-to-all-protections","text":"Parameter Description method Protection name to use. Datatype: String, selected from available Protections stop_duration_candles For how many candles should the lock be set? Datatype: Positive integer (in candles) stop_duration how many minutes should protections be locked. Cannot be used together with stop_duration_candles . Datatype: Float (in minutes) lookback_period_candles Only trades that completed within the last lookback_period_candles candles will be considered. This setting may be ignored by some Protections. Datatype: Positive integer (in candles). lookback_period Only trades that completed after current_time - lookback_period will be considered. Cannot be used together with lookback_period_candles . This setting may be ignored by some Protections. Datatype: Float (in minutes) trade_limit Number of trades required at minimum (not used by all Protections). Datatype: Positive integer Durations Durations ( stop_duration* and lookback_period* can be defined in either minutes or candles). For more flexibility when testing different timeframes, all below examples will use the \"candle\" definition.","title":"Common settings to all Protections"},{"location":"includes/protections/#stoploss-guard","text":"StoplossGuard selects all trades within lookback_period in minutes (or in candles when using lookback_period_candles ). If trade_limit or more trades resulted in stoploss, trading will stop for stop_duration in minutes (or in candles when using stop_duration_candles ). This applies across all pairs, unless only_per_pair is set to true, which will then only look at one pair at a time. The below example stops trading for all pairs for 4 candles after the last trade if the bot hit stoploss 4 times within the last 24 candles. python protections = [ { \"method\": \"StoplossGuard\", \"lookback_period_candles\": 24, \"trade_limit\": 4, \"stop_duration_candles\": 4, \"only_per_pair\": False } ] Note StoplossGuard considers all trades with the results \"stop_loss\" , \"stoploss_on_exchange\" and \"trailing_stop_loss\" if the resulting profit was negative. trade_limit and lookback_period will need to be tuned for your strategy.","title":"Stoploss Guard"},{"location":"includes/protections/#maxdrawdown","text":"MaxDrawdown uses all trades within lookback_period in minutes (or in candles when using lookback_period_candles ) to determine the maximum drawdown. If the drawdown is below max_allowed_drawdown , trading will stop for stop_duration in minutes (or in candles when using stop_duration_candles ) after the last trade - assuming that the bot needs some time to let markets recover. The below sample stops trading for 12 candles if max-drawdown is > 20% considering all pairs - with a minimum of trade_limit trades - within the last 48 candles. If desired, lookback_period and/or stop_duration can be used. python protections = [ { \"method\": \"MaxDrawdown\", \"lookback_period_candles\": 48, \"trade_limit\": 20, \"stop_duration_candles\": 12, \"max_allowed_drawdown\": 0.2 }, ]","title":"MaxDrawdown"},{"location":"includes/protections/#low-profit-pairs","text":"LowProfitPairs uses all trades for a pair within lookback_period in minutes (or in candles when using lookback_period_candles ) to determine the overall profit ratio. If that ratio is below required_profit , that pair will be locked for stop_duration in minutes (or in candles when using stop_duration_candles ). The below example will stop trading a pair for 60 minutes if the pair does not have a required profit of 2% (and a minimum of 2 trades) within the last 6 candles. python protections = [ { \"method\": \"LowProfitPairs\", \"lookback_period_candles\": 6, \"trade_limit\": 2, \"stop_duration\": 60, \"required_profit\": 0.02 } ]","title":"Low Profit Pairs"},{"location":"includes/protections/#cooldown-period","text":"CooldownPeriod locks a pair for stop_duration in minutes (or in candles when using stop_duration_candles ) after selling, avoiding a re-entry for this pair for stop_duration minutes. The below example will stop trading a pair for 2 candles after closing a trade, allowing this pair to \"cool down\". python protections = [ { \"method\": \"CooldownPeriod\", \"stop_duration_candles\": 2 } ] Note This Protection applies only at pair-level, and will never lock all pairs globally. This Protection does not consider lookback_period as it only looks at the latest trade.","title":"Cooldown Period"},{"location":"includes/protections/#full-example-of-protections","text":"All protections can be combined at will, also with different parameters, creating a increasing wall for under-performing pairs. All protections are evaluated in the sequence they are defined. The below example assumes a timeframe of 1 hour: Locks each pair after selling for an additional 5 candles ( CooldownPeriod ), giving other pairs a chance to get filled. Stops trading for 4 hours ( 4 * 1h candles ) if the last 2 days ( 48 * 1h candles ) had 20 trades, which caused a max-drawdown of more than 20%. ( MaxDrawdown ). Stops trading if more than 4 stoploss occur for all pairs within a 1 day ( 24 * 1h candles ) limit ( StoplossGuard ). Locks all pairs that had 4 Trades within the last 6 hours ( 6 * 1h candles ) with a combined profit ratio of below 0.02 (<2%) ( LowProfitPairs ). Locks all pairs for 2 candles that had a profit of below 0.01 (<1%) within the last 24h ( 24 * 1h candles ), a minimum of 4 trades. ``` python from freqtrade.strategy import IStrategy class AwesomeStrategy(IStrategy) timeframe = '1h' protections = [ { \"method\": \"CooldownPeriod\", \"stop_duration_candles\": 5 }, { \"method\": \"MaxDrawdown\", \"lookback_period_candles\": 48, \"trade_limit\": 20, \"stop_duration_candles\": 4, \"max_allowed_drawdown\": 0.2 }, { \"method\": \"StoplossGuard\", \"lookback_period_candles\": 24, \"trade_limit\": 4, \"stop_duration_candles\": 2, \"only_per_pair\": False }, { \"method\": \"LowProfitPairs\", \"lookback_period_candles\": 6, \"trade_limit\": 2, \"stop_duration_candles\": 60, \"required_profit\": 0.02 }, { \"method\": \"LowProfitPairs\", \"lookback_period_candles\": 24, \"trade_limit\": 4, \"stop_duration_candles\": 2, \"required_profit\": 0.01 } ] # ... ```","title":"Full example of Protections"}]} \ No newline at end of file diff --git a/en/2021.7/sitemap.xml b/en/2021.7/sitemap.xml new file mode 100644 index 000000000..a8dbc15f4 --- /dev/null +++ b/en/2021.7/sitemap.xml @@ -0,0 +1,173 @@ + + + + https://www.freqtrade.io/2021.7/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/advanced-hyperopt/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/advanced-setup/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/backtesting/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/bot-basics/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/bot-usage/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/configuration/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/data-analysis/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/data-download/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/deprecated/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/developer/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/docker_quickstart/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/edge/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/exchanges/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/faq/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/hyperopt/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/installation/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/plotting/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/plugins/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/rest-api/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/sandbox-testing/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/sql_cheatsheet/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/stoploss/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/strategy-advanced/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/strategy-customization/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/strategy_analysis_example/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/telegram-usage/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/updating/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/utils/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/webhook-config/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/windows_installation/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/includes/pairlists/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/includes/pricing/ + 2024-08-20 + daily + + + https://www.freqtrade.io/2021.7/includes/protections/ + 2024-08-20 + daily + + \ No newline at end of file diff --git a/en/2021.7/sitemap.xml.gz b/en/2021.7/sitemap.xml.gz new file mode 100644 index 000000000..7bfe96cb3 Binary files /dev/null and b/en/2021.7/sitemap.xml.gz differ diff --git a/en/2021.7/sql_cheatsheet/index.html b/en/2021.7/sql_cheatsheet/index.html new file mode 100644 index 000000000..61ba9b421 --- /dev/null +++ b/en/2021.7/sql_cheatsheet/index.html @@ -0,0 +1,1300 @@ + + + + + + + + + + + + + + + + + + + SQL Cheat-sheet - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + + + + +
    +
    + + + + + + + +

    SQL Helper

    +

    This page contains some help if you want to edit your sqlite db.

    +

    Install sqlite3

    +

    Sqlite3 is a terminal based sqlite application. +Feel free to use a visual Database editor like SqliteBrowser if you feel more comfortable with that.

    +

    Ubuntu/Debian installation

    +

    bash +sudo apt-get install sqlite3

    +

    Using sqlite3 via docker-compose

    +

    The freqtrade docker image does contain sqlite3, so you can edit the database without having to install anything on the host system.

    +

    bash +docker-compose exec freqtrade /bin/bash +sqlite3 <database-file>.sqlite

    +

    Open the DB

    +

    bash +sqlite3 +.open <filepath>

    +

    Table structure

    +

    List tables

    +

    bash +.tables

    +

    Display table structure

    +

    bash +.schema <table_name>

    +

    Get all trades in the table

    +

    sql +SELECT * FROM trades;

    +

    Fix trade still open after a manual sell on the exchange

    +
    +

    Warning

    +

    Manually selling a pair on the exchange will not be detected by the bot and it will try to sell anyway. Whenever possible, forcesell should be used to accomplish the same thing.
    +It is strongly advised to backup your database file before making any manual changes.

    +
    +
    +

    Note

    +

    This should not be necessary after /forcesell, as forcesell orders are closed automatically by the bot on the next iteration.

    +
    +

    sql +UPDATE trades +SET is_open=0, + close_date=<close_date>, + close_rate=<close_rate>, + close_profit = close_rate / open_rate - 1, + close_profit_abs = (amount * <close_rate> * (1 - fee_close) - (amount * (open_rate * (1 - fee_open)))), + sell_reason=<sell_reason> +WHERE id=<trade_ID_to_update>;

    +

    Example

    +

    sql +UPDATE trades +SET is_open=0, + close_date='2020-06-20 03:08:45.103418', + close_rate=0.19638016, + close_profit=0.0496, + close_profit_abs = (amount * 0.19638016 * (1 - fee_close) - (amount * (open_rate * (1 - fee_open)))), + sell_reason='force_sell' +WHERE id=31;

    +

    Remove trade from the database

    +
    +

    Use RPC Methods to delete trades

    +

    Consider using /delete <tradeid> via telegram or rest API. That's the recommended way to deleting trades.

    +
    +

    If you'd still like to remove a trade from the database directly, you can use the below query.

    +

    sql +DELETE FROM trades WHERE id = <tradeid>;

    +

    sql +DELETE FROM trades WHERE id = 31;

    +
    +

    Warning

    +

    This will remove this trade from the database. Please make sure you got the correct id and NEVER run this query without the where clause.

    +
    +

    Use a different database system

    +
    +

    Warning

    +

    By using one of the below database systems, you acknowledge that you know how to manage such a system. Freqtrade will not provide any support with setup or maintenance (or backups) of the below database systems.

    +
    +

    PostgreSQL

    +

    Freqtrade supports PostgreSQL by using SQLAlchemy, which supports multiple different database systems.

    +

    Installation: +pip install psycopg2

    +

    Usage: +... --db-url postgresql+psycopg2://<username>:<password>@localhost:5432/<database>

    +

    Freqtrade will automatically create the tables necessary upon startup.

    +

    If you're running different instances of Freqtrade, you must either setup one database per Instance or use different users / schemas for your connections.

    +

    MariaDB / MySQL

    +

    Freqtrade supports MariaDB by using SQLAlchemy, which supports multiple different database systems.

    +

    Installation: +pip install pymysql

    +

    Usage: +... --db-url mysql+pymysql://<username>:<password>@localhost:3306/<database>

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/stoploss/index.html b/en/2021.7/stoploss/index.html new file mode 100644 index 000000000..7338c0d47 --- /dev/null +++ b/en/2021.7/stoploss/index.html @@ -0,0 +1,1337 @@ + + + + + + + + + + + + + + + + + + + Stoploss - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + + + + +
    +
    + + + + + + + +

    Stop Loss

    +

    The stoploss configuration parameter is loss as ratio that should trigger a sale. +For example, value -0.10 will cause immediate sell if the profit dips below -10% for a given trade. This parameter is optional.

    +

    Most of the strategy files already include the optimal stoploss value.

    +
    +

    Info

    +

    All stoploss properties mentioned in this file can be set in the Strategy, or in the configuration.
    +Configuration values will override the strategy values.

    +
    +

    Stop Loss On-Exchange/Freqtrade

    +

    Those stoploss modes can be on exchange or off exchange.

    +

    These modes can be configured with these values:

    +

    python + 'emergencysell': 'market', + 'stoploss_on_exchange': False + 'stoploss_on_exchange_interval': 60, + 'stoploss_on_exchange_limit_ratio': 0.99

    +
    +

    Note

    +

    Stoploss on exchange is only supported for Binance (stop-loss-limit), Kraken (stop-loss-market, stop-loss-limit) and FTX (stop limit and stop-market) as of now.
    +Do not set too low/tight stoploss value if using stop loss on exchange!
    +If set to low/tight then you have greater risk of missing fill on the order and stoploss will not work.

    +
    +

    stoploss_on_exchange and stoploss_on_exchange_limit_ratio

    +

    Enable or Disable stop loss on exchange. +If the stoploss is on exchange it means a stoploss limit order is placed on the exchange immediately after buy order happens successfully. This will protect you against sudden crashes in market as the order will be in the queue immediately and if market goes down then the order has more chance of being fulfilled.

    +

    If stoploss_on_exchange uses limit orders, the exchange needs 2 prices, the stoploss_price and the Limit price.
    +stoploss defines the stop-price where the limit order is placed - and limit should be slightly below this.
    +If an exchange supports both limit and market stoploss orders, then the value of stoploss will be used to determine the stoploss type.

    +

    Calculation example: we bought the asset at 100$.
    +Stop-price is 95$, then limit would be 95 * 0.99 = 94.05$ - so the limit order fill can happen between 95$ and 94.05$.

    +

    For example, assuming the stoploss is on exchange, and trailing stoploss is enabled, and the market is going up, then the bot automatically cancels the previous stoploss order and puts a new one with a stop value higher than the previous stoploss order.

    +
    +

    Note

    +

    If stoploss_on_exchange is enabled and the stoploss is cancelled manually on the exchange, then the bot will create a new stoploss order.

    +
    +

    stoploss_on_exchange_interval

    +

    In case of stoploss on exchange there is another parameter called stoploss_on_exchange_interval. This configures the interval in seconds at which the bot will check the stoploss and update it if necessary.
    +The bot cannot do these every 5 seconds (at each iteration), otherwise it would get banned by the exchange. +So this parameter will tell the bot how often it should update the stoploss order. The default value is 60 (1 minute). +This same logic will reapply a stoploss order on the exchange should you cancel it accidentally.

    +

    forcesell

    +

    forcesell is an optional value, which defaults to the same value as sell and is used when sending a /forcesell command from Telegram or from the Rest API.

    +

    forcebuy

    +

    forcebuy is an optional value, which defaults to the same value as buy and is used when sending a /forcebuy command from Telegram or from the Rest API.

    +

    emergencysell

    +

    emergencysell is an optional value, which defaults to market and is used when creating stop loss on exchange orders fails. +The below is the default which is used if not changed in strategy or configuration file.

    +

    Example from strategy file:

    +

    python +order_types = { + 'buy': 'limit', + 'sell': 'limit', + 'emergencysell': 'market', + 'stoploss': 'market', + 'stoploss_on_exchange': True, + 'stoploss_on_exchange_interval': 60, + 'stoploss_on_exchange_limit_ratio': 0.99 +}

    +

    Stop Loss Types

    +

    At this stage the bot contains the following stoploss support modes:

    +
      +
    1. Static stop loss.
    2. +
    3. Trailing stop loss.
    4. +
    5. Trailing stop loss, custom positive loss.
    6. +
    7. Trailing stop loss only once the trade has reached a certain offset.
    8. +
    9. Custom stoploss function
    10. +
    +

    Static Stop Loss

    +

    This is very simple, you define a stop loss of x (as a ratio of price, i.e. x * 100% of price). This will try to sell the asset once the loss exceeds the defined loss.

    +

    Example of stop loss:

    +

    python + stoploss = -0.10

    +

    For example, simplified math:

    +
      +
    • the bot buys an asset at a price of 100$
    • +
    • the stop loss is defined at -10%
    • +
    • the stop loss would get triggered once the asset drops below 90$
    • +
    +

    Trailing Stop Loss

    +

    The initial value for this is stoploss, just as you would define your static Stop loss. +To enable trailing stoploss:

    +

    python + stoploss = -0.10 + trailing_stop = True

    +

    This will now activate an algorithm, which automatically moves the stop loss up every time the price of your asset increases.

    +

    For example, simplified math:

    +
      +
    • the bot buys an asset at a price of 100$
    • +
    • the stop loss is defined at -10%
    • +
    • the stop loss would get triggered once the asset drops below 90$
    • +
    • assuming the asset now increases to 102$
    • +
    • the stop loss will now be -10% of 102$ = 91.8$
    • +
    • now the asset drops in value to 101$, the stop loss will still be 91.8$ and would trigger at 91.8$.
    • +
    +

    In summary: The stoploss will be adjusted to be always be -10% of the highest observed price.

    +

    Trailing stop loss, custom positive loss

    +

    It is also possible to have a default stop loss, when you are in the red with your buy (buy - fee), but once you hit positive result the system will utilize a new stop loss, which can have a different value. +For example, your default stop loss is -10%, but once you have more than 0% profit (example 0.1%) a different trailing stoploss will be used.

    +
    +

    Note

    +

    If you want the stoploss to only be changed when you break even of making a profit (what most users want) please refer to next section with offset enabled.

    +
    +

    Both values require trailing_stop to be set to true and trailing_stop_positive with a value.

    +

    python + stoploss = -0.10 + trailing_stop = True + trailing_stop_positive = 0.02

    +

    For example, simplified math:

    +
      +
    • the bot buys an asset at a price of 100$
    • +
    • the stop loss is defined at -10%
    • +
    • the stop loss would get triggered once the asset drops below 90$
    • +
    • assuming the asset now increases to 102$
    • +
    • the stop loss will now be -2% of 102$ = 99.96$ (99.96$ stop loss will be locked in and will follow asset price increments with -2%)
    • +
    • now the asset drops in value to 101$, the stop loss will still be 99.96$ and would trigger at 99.96$
    • +
    +

    The 0.02 would translate to a -2% stop loss. +Before this, stoploss is used for the trailing stoploss.

    +

    Trailing stop loss only once the trade has reached a certain offset

    +

    It is also possible to use a static stoploss until the offset is reached, and then trail the trade to take profits once the market turns.

    +

    If "trailing_only_offset_is_reached": true then the trailing stoploss is only activated once the offset is reached. Until then, the stoploss remains at the configured stoploss. +This option can be used with or without trailing_stop_positive, but uses trailing_stop_positive_offset as offset.

    +

    python + trailing_stop_positive_offset = 0.011 + trailing_only_offset_is_reached = True

    +

    Configuration (offset is buy-price + 3%):

    +

    python + stoploss = -0.10 + trailing_stop = True + trailing_stop_positive = 0.02 + trailing_stop_positive_offset = 0.03 + trailing_only_offset_is_reached = True

    +

    For example, simplified math:

    +
      +
    • the bot buys an asset at a price of 100$
    • +
    • the stop loss is defined at -10%
    • +
    • the stop loss would get triggered once the asset drops below 90$
    • +
    • stoploss will remain at 90$ unless asset increases to or above our configured offset
    • +
    • assuming the asset now increases to 103$ (where we have the offset configured)
    • +
    • the stop loss will now be -2% of 103$ = 100.94$
    • +
    • now the asset drops in value to 101$, the stop loss will still be 100.94$ and would trigger at 100.94$
    • +
    +
    +

    Tip

    +

    Make sure to have this value (trailing_stop_positive_offset) lower than minimal ROI, otherwise minimal ROI will apply first and sell the trade.

    +
    +

    Changing stoploss on open trades

    +

    A stoploss on an open trade can be changed by changing the value in the configuration or strategy and use the /reload_config command (alternatively, completely stopping and restarting the bot also works).

    +

    The new stoploss value will be applied to open trades (and corresponding log-messages will be generated).

    +

    Limitations

    +

    Stoploss values cannot be changed if trailing_stop is enabled and the stoploss has already been adjusted, or if Edge is enabled (since Edge would recalculate stoploss based on the current market situation).

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/strategy-advanced/index.html b/en/2021.7/strategy-advanced/index.html new file mode 100644 index 000000000..65ba4ad19 --- /dev/null +++ b/en/2021.7/strategy-advanced/index.html @@ -0,0 +1,1569 @@ + + + + + + + + + + + + + + + + + + + Advanced Strategy - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + + + + + + +

    Advanced Strategies

    +

    This page explains some advanced concepts available for strategies. +If you're just getting started, please be familiar with the methods described in the Strategy Customization documentation and with the Freqtrade basics first.

    +

    Freqtrade basics describes in which sequence each method described below is called, which can be helpful to understand which method to use for your custom needs.

    +
    +

    Note

    +

    All callback methods described below should only be implemented in a strategy if they are actually used.

    +
    +
    +

    Tip

    +

    You can get a strategy template containing all below methods by running freqtrade new-strategy --strategy MyAwesomeStrategy --template advanced

    +
    +

    Storing information

    +

    Storing information can be accomplished by creating a new dictionary within the strategy class.

    +

    The name of the variable can be chosen at will, but should be prefixed with cust_ to avoid naming collisions with predefined strategy variables.

    +

    ```python +class AwesomeStrategy(IStrategy): + # Create custom dictionary + custom_info = {}

    +
    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
    +    # Check if the entry already exists
    +    if not metadata["pair"] in self.custom_info:
    +        # Create empty entry for this pair
    +        self.custom_info[metadata["pair"]] = {}
    +
    +    if "crosstime" in self.custom_info[metadata["pair"]]:
    +        self.custom_info[metadata["pair"]]["crosstime"] += 1
    +    else:
    +        self.custom_info[metadata["pair"]]["crosstime"] = 1
    +
    + +

    ```

    +
    +

    Warning

    +

    The data is not persisted after a bot-restart (or config-reload). Also, the amount of data should be kept smallish (no DataFrames and such), otherwise the bot will start to consume a lot of memory and eventually run out of memory and crash.

    +
    +
    +

    Note

    +

    If the data is pair-specific, make sure to use pair as one of the keys in the dictionary.

    +
    +

    Dataframe access

    +

    You may access dataframe in various strategy functions by querying it from dataprovider.

    +

    ``` python +from freqtrade.exchange import timeframe_to_prev_date

    +

    class AwesomeStrategy(IStrategy): + def confirm_trade_exit(self, pair: str, trade: 'Trade', order_type: str, amount: float, + rate: float, time_in_force: str, sell_reason: str, + current_time: 'datetime', **kwargs) -> bool: + # Obtain pair dataframe. + dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)

    +
        # Obtain last available candle. Do not use current_time to look up latest candle, because 
    +    # current_time points to current incomplete candle whose data is not available.
    +    last_candle = dataframe.iloc[-1].squeeze()
    +    # <...>
    +
    +    # In dry/live runs trade open date will not match candle open date therefore it must be 
    +    # rounded.
    +    trade_date = timeframe_to_prev_date(self.timeframe, trade.open_date_utc)
    +    # Look up trade candle.
    +    trade_candle = dataframe.loc[dataframe['date'] == trade_date]
    +    # trade_candle may be empty for trades that just opened as it is still incomplete.
    +    if not trade_candle.empty:
    +        trade_candle = trade_candle.squeeze()
    +        # <...>
    +
    + +

    ```

    +
    +

    Using .iloc[-1]

    +

    You can use .iloc[-1] here because get_analyzed_dataframe() only returns candles that backtesting is allowed to see. +This will not work in populate_* methods, so make sure to not use .iloc[] in that area. +Also, this will only work starting with version 2021.5.

    +
    +
    +

    Custom sell signal

    +

    It is possible to define custom sell signals, indicating that specified position should be sold. This is very useful when we need to customize sell conditions for each individual trade, or if you need the trade profit to take the sell decision.

    +

    For example you could implement a 1:2 risk-reward ROI with custom_sell().

    +

    Using custom_sell() signals in place of stoploss though is not recommended. It is a inferior method to using custom_stoploss() in this regard - which also allows you to keep the stoploss on exchange.

    +
    +

    Note

    +

    Returning a string or True from this method is equal to setting sell signal on a candle at specified time. This method is not called when sell signal is set already, or if sell signals are disabled (use_sell_signal=False or sell_profit_only=True while profit is below sell_profit_offset). string max length is 64 characters. Exceeding this limit will cause the message to be truncated to 64 characters.

    +
    +

    An example of how we can use different indicators depending on the current profit and also sell trades that were open longer than one day:

    +

    ``` python +class AwesomeStrategy(IStrategy): + def custom_sell(self, pair: str, trade: 'Trade', current_time: 'datetime', current_rate: float, + current_profit: float, **kwargs): + dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe) + last_candle = dataframe.iloc[-1].squeeze()

    +
        # Above 20% profit, sell when rsi < 80
    +    if current_profit > 0.2:
    +        if last_candle['rsi'] < 80:
    +            return 'rsi_below_80'
    +
    +    # Between 2% and 10%, sell if EMA-long above EMA-short
    +    if 0.02 < current_profit < 0.1:
    +        if last_candle['emalong'] > last_candle['emashort']:
    +            return 'ema_long_below_80'
    +
    +    # Sell any positions at a loss if they are held for more than one day.
    +    if current_profit < 0.0 and (current_time - trade.open_date_utc).days >= 1:
    +        return 'unclog'
    +
    + +

    ```

    +

    See Dataframe access for more information about dataframe use in strategy callbacks.

    +

    Custom stoploss

    +

    The stoploss price can only ever move upwards - if the stoploss value returned from custom_stoploss would result in a lower stoploss price than was previously set, it will be ignored. The traditional stoploss value serves as an absolute lower level and will be instated as the initial stoploss.

    +

    The usage of the custom stoploss method must be enabled by setting use_custom_stoploss=True on the strategy object. +The method must return a stoploss value (float / number) as a percentage of the current price. +E.g. If the current_rate is 200 USD, then returning 0.02 will set the stoploss price 2% lower, at 196 USD.

    +

    The absolute value of the return value is used (the sign is ignored), so returning 0.05 or -0.05 have the same result, a stoploss 5% below the current price.

    +

    To simulate a regular trailing stoploss of 4% (trailing 4% behind the maximum reached price) you would use the following very simple method:

    +

    ``` python

    +

    additional imports required

    +

    from datetime import datetime +from freqtrade.persistence import Trade

    +

    class AwesomeStrategy(IStrategy):

    +
    # ... populate_* methods
    +
    +use_custom_stoploss = True
    +
    +def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
    +                    current_rate: float, current_profit: float, **kwargs) -> float:
    +    """
    +    Custom stoploss logic, returning the new distance relative to current_rate (as ratio).
    +    e.g. returning -0.05 would create a stoploss 5% below current_rate.
    +    The custom stoploss can never be below self.stoploss, which serves as a hard maximum loss.
    +
    +    For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
    +
    +    When not implemented by a strategy, returns the initial stoploss value
    +    Only called when use_custom_stoploss is set to True.
    +
    +    :param pair: Pair that's currently analyzed
    +    :param trade: trade object.
    +    :param current_time: datetime object, containing the current datetime
    +    :param current_rate: Rate, calculated based on pricing settings in ask_strategy.
    +    :param current_profit: Current profit (as ratio), calculated based on current_rate.
    +    :param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
    +    :return float: New stoploss value, relative to the current rate
    +    """
    +    return -0.04
    +
    + +

    ```

    +

    Stoploss on exchange works similar to trailing_stop, and the stoploss on exchange is updated as configured in stoploss_on_exchange_interval (More details about stoploss on exchange).

    +
    +

    Use of dates

    +

    All time-based calculations should be done based on current_time - using datetime.now() or datetime.utcnow() is discouraged, as this will break backtesting support.

    +
    +
    +

    Trailing stoploss

    +

    It's recommended to disable trailing_stop when using custom stoploss values. Both can work in tandem, but you might encounter the trailing stop to move the price higher while your custom function would not want this, causing conflicting behavior.

    +
    +

    Custom stoploss examples

    +

    The next section will show some examples on what's possible with the custom stoploss function. +Of course, many more things are possible, and all examples can be combined at will.

    +

    Time based trailing stop

    +

    Use the initial stoploss for the first 60 minutes, after this change to 10% trailing stoploss, and after 2 hours (120 minutes) we use a 5% trailing stoploss.

    +

    ``` python +from datetime import datetime, timedelta +from freqtrade.persistence import Trade

    +

    class AwesomeStrategy(IStrategy):

    +
    # ... populate_* methods
    +
    +use_custom_stoploss = True
    +
    +def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
    +                    current_rate: float, current_profit: float, **kwargs) -> float:
    +
    +    # Make sure you have the longest interval first - these conditions are evaluated from top to bottom.
    +    if current_time - timedelta(minutes=120) > trade.open_date_utc:
    +        return -0.05
    +    elif current_time - timedelta(minutes=60) > trade.open_date_utc:
    +        return -0.10
    +    return 1
    +
    + +

    ```

    +

    Different stoploss per pair

    +

    Use a different stoploss depending on the pair. +In this example, we'll trail the highest price with 10% trailing stoploss for ETH/BTC and XRP/BTC, with 5% trailing stoploss for LTC/BTC and with 15% for all other pairs.

    +

    ``` python +from datetime import datetime +from freqtrade.persistence import Trade

    +

    class AwesomeStrategy(IStrategy):

    +
    # ... populate_* methods
    +
    +use_custom_stoploss = True
    +
    +def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
    +                    current_rate: float, current_profit: float, **kwargs) -> float:
    +
    +    if pair in ('ETH/BTC', 'XRP/BTC'):
    +        return -0.10
    +    elif pair in ('LTC/BTC'):
    +        return -0.05
    +    return -0.15
    +
    + +

    ```

    +

    Trailing stoploss with positive offset

    +

    Use the initial stoploss until the profit is above 4%, then use a trailing stoploss of 50% of the current profit with a minimum of 2.5% and a maximum of 5%.

    +

    Please note that the stoploss can only increase, values lower than the current stoploss are ignored.

    +

    ``` python +from datetime import datetime, timedelta +from freqtrade.persistence import Trade

    +

    class AwesomeStrategy(IStrategy):

    +
    # ... populate_* methods
    +
    +use_custom_stoploss = True
    +
    +def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
    +                    current_rate: float, current_profit: float, **kwargs) -> float:
    +
    +    if current_profit < 0.04:
    +        return -1 # return a value bigger than the initial stoploss to keep using the initial stoploss
    +
    +    # After reaching the desired offset, allow the stoploss to trail by half the profit
    +    desired_stoploss = current_profit / 2
    +
    +    # Use a minimum of 2.5% and a maximum of 5%
    +    return max(min(desired_stoploss, 0.05), 0.025)
    +
    + +

    ```

    +

    Calculating stoploss relative to open price

    +

    Stoploss values returned from custom_stoploss() always specify a percentage relative to current_rate. In order to set a stoploss relative to the open price, we need to use current_profit to calculate what percentage relative to the current_rate will give you the same result as if the percentage was specified from the open price.

    +

    The helper function stoploss_from_open() can be used to convert from an open price relative stop, to a current price relative stop which can be returned from custom_stoploss().

    +

    Stepped stoploss

    +

    Instead of continuously trailing behind the current price, this example sets fixed stoploss price levels based on the current profit.

    +
      +
    • Use the regular stoploss until 20% profit is reached
    • +
    • Once profit is > 20% - set stoploss to 7% above open price.
    • +
    • Once profit is > 25% - set stoploss to 15% above open price.
    • +
    • Once profit is > 40% - set stoploss to 25% above open price.
    • +
    +

    ``` python +from datetime import datetime +from freqtrade.persistence import Trade +from freqtrade.strategy import stoploss_from_open

    +

    class AwesomeStrategy(IStrategy):

    +
    # ... populate_* methods
    +
    +use_custom_stoploss = True
    +
    +def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
    +                    current_rate: float, current_profit: float, **kwargs) -> float:
    +
    +    # evaluate highest to lowest, so that highest possible stop is used
    +    if current_profit > 0.40:
    +        return stoploss_from_open(0.25, current_profit)
    +    elif current_profit > 0.25:
    +        return stoploss_from_open(0.15, current_profit)
    +    elif current_profit > 0.20:
    +        return stoploss_from_open(0.07, current_profit)
    +
    +    # return maximum stoploss value, keeping current stoploss price unchanged
    +    return 1
    +
    + +

    ```

    +

    Custom stoploss using an indicator from dataframe example

    +

    Absolute stoploss value may be derived from indicators stored in dataframe. Example uses parabolic SAR below the price as stoploss.

    +

    ``` python +class AwesomeStrategy(IStrategy):

    +
    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
    +    # <...>
    +    dataframe['sar'] = ta.SAR(dataframe)
    +
    +use_custom_stoploss = True
    +
    +def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
    +                    current_rate: float, current_profit: float, **kwargs) -> float:
    +
    +    dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
    +    last_candle = dataframe.iloc[-1].squeeze()
    +
    +    # Use parabolic sar as absolute stoploss price
    +    stoploss_price = last_candle['sar']
    +
    +    # Convert absolute price to percentage relative to current_rate
    +    if stoploss_price < current_rate:
    +        return (stoploss_price / current_rate) - 1
    +
    +    # return maximum stoploss value, keeping current stoploss price unchanged
    +    return 1
    +
    + +

    ```

    +

    See Dataframe access for more information about dataframe use in strategy callbacks.

    +
    +

    Custom order timeout rules

    +

    Simple, time-based order-timeouts can be configured either via strategy or in the configuration in the unfilledtimeout section.

    +

    However, freqtrade also offers a custom callback for both order types, which allows you to decide based on custom criteria if an order did time out or not.

    +
    +

    Note

    +

    Unfilled order timeouts are not relevant during backtesting or hyperopt, and are only relevant during real (live) trading. Therefore these methods are only called in these circumstances.

    +
    +

    Custom order timeout example

    +

    A simple example, which applies different unfilled-timeouts depending on the price of the asset can be seen below. +It applies a tight timeout for higher priced assets, while allowing more time to fill on cheap coins.

    +

    The function must return either True (cancel order) or False (keep order alive).

    +

    ``` python +from datetime import datetime, timedelta, timezone +from freqtrade.persistence import Trade

    +

    class AwesomeStrategy(IStrategy):

    +
    # ... populate_* methods
    +
    +# Set unfilledtimeout to 25 hours, since our maximum timeout from below is 24 hours.
    +unfilledtimeout = {
    +    'buy': 60 * 25,
    +    'sell': 60 * 25
    +}
    +
    +def check_buy_timeout(self, pair: str, trade: 'Trade', order: dict, **kwargs) -> bool:
    +    if trade.open_rate > 100 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(minutes=5):
    +        return True
    +    elif trade.open_rate > 10 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(minutes=3):
    +        return True
    +    elif trade.open_rate < 1 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(hours=24):
    +       return True
    +    return False
    +
    +
    +def check_sell_timeout(self, pair: str, trade: 'Trade', order: dict, **kwargs) -> bool:
    +    if trade.open_rate > 100 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(minutes=5):
    +        return True
    +    elif trade.open_rate > 10 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(minutes=3):
    +        return True
    +    elif trade.open_rate < 1 and trade.open_date_utc < datetime.now(timezone.utc) - timedelta(hours=24):
    +       return True
    +    return False
    +
    + +

    ```

    +
    +

    Note

    +

    For the above example, unfilledtimeout must be set to something bigger than 24h, otherwise that type of timeout will apply first.

    +
    +

    Custom order timeout example (using additional data)

    +

    ``` python +from datetime import datetime +from freqtrade.persistence import Trade

    +

    class AwesomeStrategy(IStrategy):

    +
    # ... populate_* methods
    +
    +# Set unfilledtimeout to 25 hours, since our maximum timeout from below is 24 hours.
    +unfilledtimeout = {
    +    'buy': 60 * 25,
    +    'sell': 60 * 25
    +}
    +
    +def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool:
    +    ob = self.dp.orderbook(pair, 1)
    +    current_price = ob['bids'][0][0]
    +    # Cancel buy order if price is more than 2% above the order.
    +    if current_price > order['price'] * 1.02:
    +        return True
    +    return False
    +
    +
    +def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool:
    +    ob = self.dp.orderbook(pair, 1)
    +    current_price = ob['asks'][0][0]
    +    # Cancel sell order if price is more than 2% below the order.
    +    if current_price < order['price'] * 0.98:
    +        return True
    +    return False
    +
    + +

    ```

    +
    +

    Bot loop start callback

    +

    A simple callback which is called once at the start of every bot throttling iteration. +This can be used to perform calculations which are pair independent (apply to all pairs), loading of external data, etc.

    +

    ``` python +import requests

    +

    class AwesomeStrategy(IStrategy):

    +
    # ... populate_* methods
    +
    +def bot_loop_start(self, **kwargs) -> None:
    +    """
    +    Called at the start of the bot iteration (one loop).
    +    Might be used to perform pair-independent tasks
    +    (e.g. gather some remote resource for comparison)
    +    :param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
    +    """
    +    if self.config['runmode'].value in ('live', 'dry_run'):
    +        # Assign this to the class by using self.*
    +        # can then be used by populate_* methods
    +        self.remote_data = requests.get('https://some_remote_source.example.com')
    +
    + +

    ```

    +

    Bot order confirmation

    +

    Trade entry (buy order) confirmation

    +

    confirm_trade_entry() can be used to abort a trade entry at the latest second (maybe because the price is not what we expect).

    +

    ``` python +class AwesomeStrategy(IStrategy):

    +
    # ... populate_* methods
    +
    +def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float,
    +                        time_in_force: str, current_time: datetime, **kwargs) -> bool:
    +    """
    +    Called right before placing a buy order.
    +    Timing for this function is critical, so avoid doing heavy computations or
    +    network requests in this method.
    +
    +    For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
    +
    +    When not implemented by a strategy, returns True (always confirming).
    +
    +    :param pair: Pair that's about to be bought.
    +    :param order_type: Order type (as configured in order_types). usually limit or market.
    +    :param amount: Amount in target (quote) currency that's going to be traded.
    +    :param rate: Rate that's going to be used when using limit orders
    +    :param time_in_force: Time in force. Defaults to GTC (Good-til-cancelled).
    +    :param current_time: datetime object, containing the current datetime
    +    :param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
    +    :return bool: When True is returned, then the buy-order is placed on the exchange.
    +        False aborts the process
    +    """
    +    return True
    +
    + +

    ```

    +

    Trade exit (sell order) confirmation

    +

    confirm_trade_exit() can be used to abort a trade exit (sell) at the latest second (maybe because the price is not what we expect).

    +

    ``` python +from freqtrade.persistence import Trade

    +

    class AwesomeStrategy(IStrategy):

    +
    # ... populate_* methods
    +
    +def confirm_trade_exit(self, pair: str, trade: Trade, order_type: str, amount: float,
    +                       rate: float, time_in_force: str, sell_reason: str,
    +                       current_time: datetime, **kwargs) -> bool:
    +    """
    +    Called right before placing a regular sell order.
    +    Timing for this function is critical, so avoid doing heavy computations or
    +    network requests in this method.
    +
    +    For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/
    +
    +    When not implemented by a strategy, returns True (always confirming).
    +
    +    :param pair: Pair that's about to be sold.
    +    :param order_type: Order type (as configured in order_types). usually limit or market.
    +    :param amount: Amount in quote currency.
    +    :param rate: Rate that's going to be used when using limit orders
    +    :param time_in_force: Time in force. Defaults to GTC (Good-til-cancelled).
    +    :param sell_reason: Sell reason.
    +        Can be any of ['roi', 'stop_loss', 'stoploss_on_exchange', 'trailing_stop_loss',
    +                       'sell_signal', 'force_sell', 'emergency_sell']
    +    :param current_time: datetime object, containing the current datetime
    +    :param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
    +    :return bool: When True is returned, then the sell-order is placed on the exchange.
    +        False aborts the process
    +    """
    +    if sell_reason == 'force_sell' and trade.calc_profit_ratio(rate) < 0:
    +        # Reject force-sells with negative profit
    +        # This is just a sample, please adjust to your needs
    +        # (this does not necessarily make sense, assuming you know when you're force-selling)
    +        return False
    +    return True
    +
    + +

    ```

    +

    Stake size management

    +

    It is possible to manage your risk by reducing or increasing stake amount when placing a new trade.

    +

    ```python +class AwesomeStrategy(IStrategy): + def custom_stake_amount(self, pair: str, current_time: datetime, current_rate: float, + proposed_stake: float, min_stake: float, max_stake: float, + **kwargs) -> float:

    +
        dataframe, _ = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe)
    +    current_candle = dataframe.iloc[-1].squeeze()
    +
    +    if current_candle['fastk_rsi_1h'] > current_candle['fastd_rsi_1h']:
    +        if self.config['stake_amount'] == 'unlimited':
    +            # Use entire available wallet during favorable conditions when in compounding mode.
    +            return max_stake
    +        else:
    +            # Compound profits during favorable conditions instead of using a static stake.
    +            return self.wallets.get_total_stake_amount() / self.config['max_open_trades']
    +
    +    # Use default stake amount.
    +    return proposed_stake
    +
    + +

    ```

    +

    Freqtrade will fall back to the proposed_stake value should your code raise an exception. The exception itself will be logged.

    +
    +

    Tip

    +

    You do not have to ensure that min_stake <= returned_value <= max_stake. Trades will succeed as the returned value will be clamped to supported range and this acton will be logged.

    +
    +
    +

    Tip

    +

    Returning 0 or None will prevent trades from being placed.

    +
    +
    +

    Derived strategies

    +

    The strategies can be derived from other strategies. This avoids duplication of your custom strategy code. You can use this technique to override small parts of your main strategy, leaving the rest untouched:

    +

    ``` python +class MyAwesomeStrategy(IStrategy): + ... + stoploss = 0.13 + trailing_stop = False + # All other attributes and methods are here as they + # should be in any custom strategy... + ...

    +

    class MyAwesomeStrategy2(MyAwesomeStrategy): + # Override something + stoploss = 0.08 + trailing_stop = True +```

    +

    Both attributes and methods may be overridden, altering behavior of the original strategy in a way you need.

    +
    +

    Parent-strategy in different files

    +

    If you have the parent-strategy in a different file, you'll need to add the following to the top of your "child"-file to ensure proper loading, otherwise freqtrade may not be able to load the parent strategy correctly.

    +

    ``` python +import sys +from pathlib import Path +sys.path.append(str(Path(file).parent))

    +

    from myawesomestrategy import MyAwesomeStrategy +```

    +
    +

    Embedding Strategies

    +

    Freqtrade provides you with an easy way to embed the strategy into your configuration file. +This is done by utilizing BASE64 encoding and providing this string at the strategy configuration field, +in your chosen config file.

    +

    Encoding a string as BASE64

    +

    This is a quick example, how to generate the BASE64 string in python

    +

    ```python +from base64 import urlsafe_b64encode

    +

    with open(file, 'r') as f: + content = f.read() +content = urlsafe_b64encode(content.encode('utf-8')) +```

    +

    The variable 'content', will contain the strategy file in a BASE64 encoded form. Which can now be set in your configurations file as following

    +

    json +"strategy": "NameOfStrategy:BASE64String"

    +

    Please ensure that 'NameOfStrategy' is identical to the strategy name!

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/strategy-customization/index.html b/en/2021.7/strategy-customization/index.html new file mode 100644 index 000000000..fa7e8a5bf --- /dev/null +++ b/en/2021.7/strategy-customization/index.html @@ -0,0 +1,1938 @@ + + + + + + + + + + + + + + + + + + + Strategy Customization - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + + + + +
    +
    + + + + + + + +

    Strategy Customization

    +

    This page explains how to customize your strategies, add new indicators and set up trading rules.

    +

    Please familiarize yourself with Freqtrade basics first, which provides overall info on how the bot operates.

    +

    Install a custom strategy file

    +

    This is very simple. Copy paste your strategy file into the directory user_data/strategies.

    +

    Let assume you have a class called AwesomeStrategy in the file AwesomeStrategy.py:

    +
      +
    1. Move your file into user_data/strategies (you should have user_data/strategies/AwesomeStrategy.py
    2. +
    3. Start the bot with the param --strategy AwesomeStrategy (the parameter is the class name)
    4. +
    +

    bash +freqtrade trade --strategy AwesomeStrategy

    +

    Develop your own strategy

    +

    The bot includes a default strategy file. +Also, several other strategies are available in the strategy repository.

    +

    You will however most likely have your own idea for a strategy. +This document intends to help you develop one for yourself.

    +

    To get started, use freqtrade new-strategy --strategy AwesomeStrategy. +This will create a new strategy file from a template, which will be located under user_data/strategies/AwesomeStrategy.py.

    +
    +

    Note

    +

    This is just a template file, which will most likely not be profitable out of the box.

    +
    +

    Anatomy of a strategy

    +

    A strategy file contains all the information needed to build a good strategy:

    +
      +
    • Indicators
    • +
    • Buy strategy rules
    • +
    • Sell strategy rules
    • +
    • Minimal ROI recommended
    • +
    • Stoploss strongly recommended
    • +
    +

    The bot also include a sample strategy called SampleStrategy you can update: user_data/strategies/sample_strategy.py. +You can test it with the parameter: --strategy SampleStrategy

    +

    Additionally, there is an attribute called INTERFACE_VERSION, which defines the version of the strategy interface the bot should use. +The current version is 2 - which is also the default when it's not set explicitly in the strategy.

    +

    Future versions will require this to be set.

    +

    bash +freqtrade trade --strategy AwesomeStrategy

    +

    For the following section we will use the user_data/strategies/sample_strategy.py +file as reference.

    +
    +

    Strategies and Backtesting

    +

    To avoid problems and unexpected differences between Backtesting and dry/live modes, please be aware +that during backtesting the full time range is passed to the populate_*() methods at once. +It is therefore best to use vectorized operations (across the whole dataframe, not loops) and +avoid index referencing (df.iloc[-1]), but instead use df.shift() to get to the previous candle.

    +
    +
    +

    Warning: Using future data

    +

    Since backtesting passes the full time range to the populate_*() methods, the strategy author +needs to take care to avoid having the strategy utilize data from the future. +Some common patterns for this are listed in the Common Mistakes section of this document.

    +
    +

    Customize Indicators

    +

    Buy and sell strategies need indicators. You can add more indicators by extending the list contained in the method populate_indicators() from your strategy file.

    +

    You should only add the indicators used in either populate_buy_trend(), populate_sell_trend(), or to populate another indicator, otherwise performance may suffer.

    +

    It's important to always return the dataframe without removing/modifying the columns "open", "high", "low", "close", "volume", otherwise these fields would contain something unexpected.

    +

    Sample:

    +

    ```python +def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: + """ + Adds several different TA indicators to the given DataFrame

    +
    Performance Note: For the best performance be frugal on the number of indicators
    +you are using. Let uncomment only the indicator you are using in your strategies
    +or your hyperopt configuration, otherwise you will waste your memory and CPU usage.
    +:param dataframe: Dataframe with data from the exchange
    +:param metadata: Additional information, like the currently traded pair
    +:return: a Dataframe with all mandatory indicators for the strategies
    +"""
    +dataframe['sar'] = ta.SAR(dataframe)
    +dataframe['adx'] = ta.ADX(dataframe)
    +stoch = ta.STOCHF(dataframe)
    +dataframe['fastd'] = stoch['fastd']
    +dataframe['fastk'] = stoch['fastk']
    +dataframe['blower'] = ta.BBANDS(dataframe, nbdevup=2, nbdevdn=2)['lowerband']
    +dataframe['sma'] = ta.SMA(dataframe, timeperiod=40)
    +dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9)
    +dataframe['mfi'] = ta.MFI(dataframe)
    +dataframe['rsi'] = ta.RSI(dataframe)
    +dataframe['ema5'] = ta.EMA(dataframe, timeperiod=5)
    +dataframe['ema10'] = ta.EMA(dataframe, timeperiod=10)
    +dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50)
    +dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100)
    +dataframe['ao'] = awesome_oscillator(dataframe)
    +macd = ta.MACD(dataframe)
    +dataframe['macd'] = macd['macd']
    +dataframe['macdsignal'] = macd['macdsignal']
    +dataframe['macdhist'] = macd['macdhist']
    +hilbert = ta.HT_SINE(dataframe)
    +dataframe['htsine'] = hilbert['sine']
    +dataframe['htleadsine'] = hilbert['leadsine']
    +dataframe['plus_dm'] = ta.PLUS_DM(dataframe)
    +dataframe['plus_di'] = ta.PLUS_DI(dataframe)
    +dataframe['minus_dm'] = ta.MINUS_DM(dataframe)
    +dataframe['minus_di'] = ta.MINUS_DI(dataframe)
    +return dataframe
    +
    + +

    ```

    +
    +

    Want more indicator examples?

    +

    Look into the user_data/strategies/sample_strategy.py. +Then uncomment indicators you need.

    +
    +

    Strategy startup period

    +

    Most indicators have an instable startup period, in which they are either not available, or the calculation is incorrect. This can lead to inconsistencies, since Freqtrade does not know how long this instable period should be. +To account for this, the strategy can be assigned the startup_candle_count attribute. +This should be set to the maximum number of candles that the strategy requires to calculate stable indicators.

    +

    In this example strategy, this should be set to 100 (startup_candle_count = 100), since the longest needed history is 100 candles.

    +

    python + dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100)

    +

    By letting the bot know how much history is needed, backtest trades can start at the specified timerange during backtesting and hyperopt.

    +
    +

    Warning

    +

    startup_candle_count should be below ohlcv_candle_limit (which is 500 for most exchanges) - since only this amount of candles will be available during Dry-Run/Live Trade operations.

    +
    +

    Example

    +

    Let's try to backtest 1 month (January 2019) of 5m candles using an example strategy with EMA100, as above.

    +

    bash +freqtrade backtesting --timerange 20190101-20190201 --timeframe 5m

    +

    Assuming startup_candle_count is set to 100, backtesting knows it needs 100 candles to generate valid buy signals. It will load data from 20190101 - (100 * 5m) - which is ~2018-12-31 15:30:00. +If this data is available, indicators will be calculated with this extended timerange. The instable startup period (up to 2019-01-01 00:00:00) will then be removed before starting backtesting.

    +
    +

    Note

    +

    If data for the startup period is not available, then the timerange will be adjusted to account for this startup period - so Backtesting would start at 2019-01-01 08:30:00.

    +
    +

    Buy signal rules

    +

    Edit the method populate_buy_trend() in your strategy file to update your buy strategy.

    +

    It's important to always return the dataframe without removing/modifying the columns "open", "high", "low", "close", "volume", otherwise these fields would contain something unexpected.

    +

    This method will also define a new column, "buy", which needs to contain 1 for buys, and 0 for "no action".

    +

    Sample from user_data/strategies/sample_strategy.py:

    +

    ```python +def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: + """ + Based on TA indicators, populates the buy signal for the given dataframe + :param dataframe: DataFrame populated with indicators + :param metadata: Additional information, like the currently traded pair + :return: DataFrame with buy column + """ + dataframe.loc[ + ( + (qtpylib.crossed_above(dataframe['rsi'], 30)) & # Signal: RSI crosses above 30 + (dataframe['tema'] <= dataframe['bb_middleband']) & # Guard + (dataframe['tema'] > dataframe['tema'].shift(1)) & # Guard + (dataframe['volume'] > 0) # Make sure Volume is not 0 + ), + 'buy'] = 1

    +
    return dataframe
    +
    + +

    ```

    +
    +

    Note

    +

    Buying requires sellers to buy from - therefore volume needs to be > 0 (dataframe['volume'] > 0) to make sure that the bot does not buy/sell in no-activity periods.

    +
    +

    Sell signal rules

    +

    Edit the method populate_sell_trend() into your strategy file to update your sell strategy. +Please note that the sell-signal is only used if use_sell_signal is set to true in the configuration.

    +

    It's important to always return the dataframe without removing/modifying the columns "open", "high", "low", "close", "volume", otherwise these fields would contain something unexpected.

    +

    This method will also define a new column, "sell", which needs to contain 1 for sells, and 0 for "no action".

    +

    Sample from user_data/strategies/sample_strategy.py:

    +

    python +def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: + """ + Based on TA indicators, populates the sell signal for the given dataframe + :param dataframe: DataFrame populated with indicators + :param metadata: Additional information, like the currently traded pair + :return: DataFrame with buy column + """ + dataframe.loc[ + ( + (qtpylib.crossed_above(dataframe['rsi'], 70)) & # Signal: RSI crosses above 70 + (dataframe['tema'] > dataframe['bb_middleband']) & # Guard + (dataframe['tema'] < dataframe['tema'].shift(1)) & # Guard + (dataframe['volume'] > 0) # Make sure Volume is not 0 + ), + 'sell'] = 1 + return dataframe

    +

    Minimal ROI

    +

    This dict defines the minimal Return On Investment (ROI) a trade should reach before selling, independent from the sell signal.

    +

    It is of the following format, with the dict key (left side of the colon) being the minutes passed since the trade opened, and the value (right side of the colon) being the percentage.

    +

    python +minimal_roi = { + "40": 0.0, + "30": 0.01, + "20": 0.02, + "0": 0.04 +}

    +

    The above configuration would therefore mean:

    +
      +
    • Sell whenever 4% profit was reached
    • +
    • Sell when 2% profit was reached (in effect after 20 minutes)
    • +
    • Sell when 1% profit was reached (in effect after 30 minutes)
    • +
    • Sell when trade is non-loosing (in effect after 40 minutes)
    • +
    +

    The calculation does include fees.

    +

    To disable ROI completely, set it to an insanely high number:

    +

    python +minimal_roi = { + "0": 100 +}

    +

    While technically not completely disabled, this would sell once the trade reaches 10000% Profit.

    +

    To use times based on candle duration (timeframe), the following snippet can be handy. +This will allow you to change the timeframe for the strategy, and ROI times will still be set as candles (e.g. after 3 candles ...)

    +

    ``` python +from freqtrade.exchange import timeframe_to_minutes

    +

    class AwesomeStrategy(IStrategy):

    +
    timeframe = "1d"
    +timeframe_mins = timeframe_to_minutes(timeframe)
    +minimal_roi = {
    +    "0": 0.05,                             # 5% for the first 3 candles
    +    str(timeframe_mins * 3)): 0.02,  # 2% after 3 candles
    +    str(timeframe_mins * 6)): 0.01,  # 1% After 6 candles
    +}
    +
    + +

    ```

    +

    Stoploss

    +

    Setting a stoploss is highly recommended to protect your capital from strong moves against you.

    +

    Sample:

    +

    python +stoploss = -0.10

    +

    This would signify a stoploss of -10%.

    +

    For the full documentation on stoploss features, look at the dedicated stoploss page.

    +

    If your exchange supports it, it's recommended to also set "stoploss_on_exchange" in the order_types dictionary, so your stoploss is on the exchange and cannot be missed due to network problems, high load or other reasons.

    +

    For more information on order_types please look here.

    +

    Timeframe (formerly ticker interval)

    +

    This is the set of candles the bot should download and use for the analysis. +Common values are "1m", "5m", "15m", "1h", however all values supported by your exchange should work.

    +

    Please note that the same buy/sell signals may work well with one timeframe, but not with the others.

    +

    This setting is accessible within the strategy methods as the self.timeframe attribute.

    +

    Metadata dict

    +

    The metadata-dict (available for populate_buy_trend, populate_sell_trend, populate_indicators) contains additional information. +Currently this is pair, which can be accessed using metadata['pair'] - and will return a pair in the format XRP/BTC.

    +

    The Metadata-dict should not be modified and does not persist information across multiple calls. +Instead, have a look at the section Storing information

    +

    Additional data (informative_pairs)

    +

    Get data for non-tradeable pairs

    +

    Data for additional, informative pairs (reference pairs) can be beneficial for some strategies. +OHLCV data for these pairs will be downloaded as part of the regular whitelist refresh process and is available via DataProvider just as other pairs (see below). +These parts will not be traded unless they are also specified in the pair whitelist, or have been selected by Dynamic Whitelisting.

    +

    The pairs need to be specified as tuples in the format ("pair", "timeframe"), with pair as the first and timeframe as the second argument.

    +

    Sample:

    +

    python +def informative_pairs(self): + return [("ETH/USDT", "5m"), + ("BTC/TUSD", "15m"), + ]

    +

    A full sample can be found in the DataProvider section.

    +
    +

    Warning

    +

    As these pairs will be refreshed as part of the regular whitelist refresh, it's best to keep this list short. +All timeframes and all pairs can be specified as long as they are available (and active) on the used exchange. +It is however better to use resampling to longer timeframes whenever possible +to avoid hammering the exchange with too many requests and risk being blocked.

    +
    +
    +

    Additional data (DataProvider)

    +

    The strategy provides access to the DataProvider. This allows you to get additional data to use in your strategy.

    +

    All methods return None in case of failure (do not raise an exception).

    +

    Please always check the mode of operation to select the correct method to get data (samples see below).

    +
    +

    Hyperopt

    +

    Dataprovider is available during hyperopt, however it can only be used in populate_indicators() within a strategy. +It is not available in populate_buy() and populate_sell() methods, nor in populate_indicators(), if this method located in the hyperopt file.

    +
    +

    Possible options for DataProvider

    +
      +
    • available_pairs - Property with tuples listing cached pairs with their timeframe (pair, timeframe).
    • +
    • current_whitelist() - Returns a current list of whitelisted pairs. Useful for accessing dynamic whitelists (i.e. VolumePairlist)
    • +
    • get_pair_dataframe(pair, timeframe) - This is a universal method, which returns either historical data (for backtesting) or cached live data (for the Dry-Run and Live-Run modes).
    • +
    • get_analyzed_dataframe(pair, timeframe) - Returns the analyzed dataframe (after calling populate_indicators(), populate_buy(), populate_sell()) and the time of the latest analysis.
    • +
    • historic_ohlcv(pair, timeframe) - Returns historical data stored on disk.
    • +
    • market(pair) - Returns market data for the pair: fees, limits, precisions, activity flag, etc. See ccxt documentation for more details on the Market data structure.
    • +
    • ohlcv(pair, timeframe) - Currently cached candle (OHLCV) data for the pair, returns DataFrame or empty DataFrame.
    • +
    • orderbook(pair, maximum) - Returns latest orderbook data for the pair, a dict with bids/asks with a total of maximum entries.
    • +
    • ticker(pair) - Returns current ticker data for the pair. See ccxt documentation for more details on the Ticker data structure.
    • +
    • runmode - Property containing the current runmode.
    • +
    +

    Example Usages

    +

    available_pairs

    +

    python +if self.dp: + for pair, timeframe in self.dp.available_pairs: + print(f"available {pair}, {timeframe}")

    +

    current_whitelist()

    +

    Imagine you've developed a strategy that trades the 5m timeframe using signals generated from a 1d timeframe on the top 10 volume pairs by volume.

    +

    The strategy might look something like this:

    +

    Scan through the top 10 pairs by volume using the VolumePairList every 5 minutes and use a 14 day RSI to buy and sell.

    +

    Due to the limited available data, it's very difficult to resample our 5m candles into daily candles for use in a 14 day RSI. Most exchanges limit us to just 500 candles which effectively gives us around 1.74 daily candles. We need 14 days at least!

    +

    Since we can't resample our data we will have to use an informative pair; and since our whitelist will be dynamic we don't know which pair(s) to use.

    +

    This is where calling self.dp.current_whitelist() comes in handy.

    +

    ```python + def informative_pairs(self):

    +
        # get access to all pairs available in whitelist.
    +    pairs = self.dp.current_whitelist()
    +    # Assign tf to each pair so they can be downloaded and cached for strategy.
    +    informative_pairs = [(pair, '1d') for pair in pairs]
    +    return informative_pairs
    +
    + +

    ```

    +

    get_pair_dataframe(pair, timeframe)

    +

    ``` python

    +

    fetch live / historical candle (OHLCV) data for the first informative pair

    +

    if self.dp: + inf_pair, inf_timeframe = self.informative_pairs()[0] + informative = self.dp.get_pair_dataframe(pair=inf_pair, + timeframe=inf_timeframe) +```

    +
    +

    Warning about backtesting

    +

    Be careful when using dataprovider in backtesting. historic_ohlcv() (and get_pair_dataframe() +for the backtesting runmode) provides the full time-range in one go, +so please be aware of it and make sure to not "look into the future" to avoid surprises when running in dry/live mode.

    +
    +

    get_analyzed_dataframe(pair, timeframe)

    +

    This method is used by freqtrade internally to determine the last signal. +It can also be used in specific callbacks to get the signal that caused the action (see Advanced Strategy Documentation for more details on available callbacks).

    +

    ``` python

    +

    fetch current dataframe

    +

    if self.dp: + if self.dp.runmode.value in ('live', 'dry_run'): + dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=metadata['pair'], + timeframe=self.timeframe) +```

    +
    +

    No data available

    +

    Returns an empty dataframe if the requested pair was not cached. +This should not happen when using whitelisted pairs.

    +
    +

    orderbook(pair, maximum)

    +

    python +if self.dp: + if self.dp.runmode.value in ('live', 'dry_run'): + ob = self.dp.orderbook(metadata['pair'], 1) + dataframe['best_bid'] = ob['bids'][0][0] + dataframe['best_ask'] = ob['asks'][0][0]

    +

    The orderbook structure is aligned with the order structure from ccxt, so the result will look as follows:

    +

    js +{ + 'bids': [ + [ price, amount ], // [ float, float ] + [ price, amount ], + ... + ], + 'asks': [ + [ price, amount ], + [ price, amount ], + //... + ], + //... +}

    +

    Therefore, using ob['bids'][0][0] as demonstrated above will result in using the best bid price. ob['bids'][0][1] would look at the amount at this orderbook position.

    +
    +

    Warning about backtesting

    +

    The order book is not part of the historic data which means backtesting and hyperopt will not work correctly if this method is used, as the method will return uptodate values.

    +
    +

    ticker(pair)

    +

    python +if self.dp: + if self.dp.runmode.value in ('live', 'dry_run'): + ticker = self.dp.ticker(metadata['pair']) + dataframe['last_price'] = ticker['last'] + dataframe['volume24h'] = ticker['quoteVolume'] + dataframe['vwap'] = ticker['vwap']

    +
    +

    Warning

    +

    Although the ticker data structure is a part of the ccxt Unified Interface, the values returned by this method can +vary for different exchanges. For instance, many exchanges do not return vwap values, the FTX exchange +does not always fills in the last field (so it can be None), etc. So you need to carefully verify the ticker +data returned from the exchange and add appropriate error handling / defaults.

    +
    +
    +

    Warning about backtesting

    +

    This method will always return up-to-date values - so usage during backtesting / hyperopt will lead to wrong results.

    +
    +

    Complete Data-provider sample

    +

    ```python +from freqtrade.strategy import IStrategy, merge_informative_pair +from pandas import DataFrame

    +

    class SampleStrategy(IStrategy): + # strategy init stuff...

    +
    timeframe = '5m'
    +
    +# more strategy init stuff..
    +
    +def informative_pairs(self):
    +
    +    # get access to all pairs available in whitelist.
    +    pairs = self.dp.current_whitelist()
    +    # Assign tf to each pair so they can be downloaded and cached for strategy.
    +    informative_pairs = [(pair, '1d') for pair in pairs]
    +    # Optionally Add additional "static" pairs
    +    informative_pairs += [("ETH/USDT", "5m"),
    +                          ("BTC/TUSD", "15m"),
    +                        ]
    +    return informative_pairs
    +
    +def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
    +    if not self.dp:
    +        # Don't do anything if DataProvider is not available.
    +        return dataframe
    +
    +    inf_tf = '1d'
    +    # Get the informative pair
    +    informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=inf_tf)
    +    # Get the 14 day rsi
    +    informative['rsi'] = ta.RSI(informative, timeperiod=14)
    +
    +    # Use the helper function merge_informative_pair to safely merge the pair
    +    # Automatically renames the columns and merges a shorter timeframe dataframe and a longer timeframe informative pair
    +    # use ffill to have the 1d value available in every row throughout the day.
    +    # Without this, comparisons between columns of the original and the informative pair would only work once per day.
    +    # Full documentation of this method, see below
    +    dataframe = merge_informative_pair(dataframe, informative, self.timeframe, inf_tf, ffill=True)
    +
    +    # Calculate rsi of the original dataframe (5m timeframe)
    +    dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)
    +
    +    # Do other stuff
    +    # ...
    +
    +    return dataframe
    +
    +def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
    +
    +    dataframe.loc[
    +        (
    +            (qtpylib.crossed_above(dataframe['rsi'], 30)) &  # Signal: RSI crosses above 30
    +            (dataframe['rsi_1d'] < 30) &                     # Ensure daily RSI is < 30
    +            (dataframe['volume'] > 0)                        # Ensure this candle had volume (important for backtesting)
    +        ),
    +        'buy'] = 1
    +
    + +

    ```

    +
    +

    Helper functions

    +

    merge_informative_pair()

    +

    This method helps you merge an informative pair to a regular dataframe without lookahead bias. +It's there to help you merge the dataframe in a safe and consistent way.

    +

    Options:

    +
      +
    • Rename the columns for you to create unique columns
    • +
    • Merge the dataframe without lookahead bias
    • +
    • Forward-fill (optional)
    • +
    +

    All columns of the informative dataframe will be available on the returning dataframe in a renamed fashion:

    +
    +

    Column renaming

    +

    Assuming inf_tf = '1d' the resulting columns will be:

    +

    python +'date', 'open', 'high', 'low', 'close', 'rsi' # from the original dataframe +'date_1d', 'open_1d', 'high_1d', 'low_1d', 'close_1d', 'rsi_1d' # from the informative dataframe

    +
    +
    +Column renaming - 1h +

    Assuming inf_tf = '1h' the resulting columns will be:

    +

    python +'date', 'open', 'high', 'low', 'close', 'rsi' # from the original dataframe +'date_1h', 'open_1h', 'high_1h', 'low_1h', 'close_1h', 'rsi_1h' # from the informative dataframe

    +
    +
    +Custom implementation +

    A custom implementation for this is possible, and can be done as follows:

    +

    ``` python

    +

    Shift date by 1 candle

    +

    This is necessary since the data is always the "open date"

    +

    and a 15m candle starting at 12:15 should not know the close of the 1h candle from 12:00 to 13:00

    +

    minutes = timeframe_to_minutes(inf_tf)

    +

    Only do this if the timeframes are different:

    +

    informative['date_merge'] = informative["date"] + pd.to_timedelta(minutes, 'm')

    +

    Rename columns to be unique

    +

    informative.columns = [f"{col}_{inf_tf}" for col in informative.columns]

    +

    Assuming inf_tf = '1d' - then the columns will now be:

    +

    date_1d, open_1d, high_1d, low_1d, close_1d, rsi_1d

    +

    Combine the 2 dataframes

    +

    all indicators on the informative sample MUST be calculated before this point

    +

    dataframe = pd.merge(dataframe, informative, left_on='date', right_on=f'date_merge_{inf_tf}', how='left')

    +

    FFill to have the 1d value available in every row throughout the day.

    +

    Without this, comparisons would only work once per day.

    +

    dataframe = dataframe.ffill()

    +

    ```

    +
    +
    +

    Informative timeframe < timeframe

    +

    Using informative timeframes smaller than the dataframe timeframe is not recommended with this method, as it will not use any of the additional information this would provide. +To use the more detailed information properly, more advanced methods should be applied (which are out of scope for freqtrade documentation, as it'll depend on the respective need).

    +
    +
    +

    stoploss_from_open()

    +

    Stoploss values returned from custom_stoploss must specify a percentage relative to current_rate, but sometimes you may want to specify a stoploss relative to the open price instead. stoploss_from_open() is a helper function to calculate a stoploss value that can be returned from custom_stoploss which will be equivalent to the desired percentage above the open price.

    +
    +Returning a stoploss relative to the open price from the custom stoploss function +

    Say the open price was $100, and current_price is $121 (current_profit will be 0.21).

    +

    If we want a stop price at 7% above the open price we can call stoploss_from_open(0.07, current_profit) which will return 0.1157024793. 11.57% below $121 is $107, which is the same as 7% above $100.

    +

    ``` python

    +

    from datetime import datetime +from freqtrade.persistence import Trade +from freqtrade.strategy import IStrategy, stoploss_from_open

    +

    class AwesomeStrategy(IStrategy):

    +
    # ... populate_* methods
    +
    +use_custom_stoploss = True
    +
    +def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
    +                    current_rate: float, current_profit: float, **kwargs) -> float:
    +
    +    # once the profit has risen above 10%, keep the stoploss at 7% above the open price
    +    if current_profit > 0.10:
    +        return stoploss_from_open(0.07, current_profit)
    +
    +    return 1
    +
    + +

    ```

    +

    Full examples can be found in the Custom stoploss section of the Documentation.

    +
    +

    Additional data (Wallets)

    +

    The strategy provides access to the Wallets object. This contains the current balances on the exchange.

    +
    +

    Note

    +

    Wallets is not available during backtesting / hyperopt.

    +
    +

    Please always check if Wallets is available to avoid failures during backtesting.

    +

    python +if self.wallets: + free_eth = self.wallets.get_free('ETH') + used_eth = self.wallets.get_used('ETH') + total_eth = self.wallets.get_total('ETH')

    +

    Possible options for Wallets

    +
      +
    • get_free(asset) - currently available balance to trade
    • +
    • get_used(asset) - currently tied up balance (open orders)
    • +
    • get_total(asset) - total available balance - sum of the 2 above
    • +
    +
    +

    Additional data (Trades)

    +

    A history of Trades can be retrieved in the strategy by querying the database.

    +

    At the top of the file, import Trade.

    +

    python +from freqtrade.persistence import Trade

    +

    The following example queries for the current pair and trades from today, however other filters can easily be added.

    +

    python +if self.config['runmode'].value in ('live', 'dry_run'): + trades = Trade.get_trades([Trade.pair == metadata['pair'], + Trade.open_date > datetime.utcnow() - timedelta(days=1), + Trade.is_open.is_(False), + ]).order_by(Trade.close_date).all() + # Summarize profit for this pair. + curdayprofit = sum(trade.close_profit for trade in trades)

    +

    Get amount of stake_currency currently invested in Trades:

    +

    python +if self.config['runmode'].value in ('live', 'dry_run'): + total_stakes = Trade.total_open_trades_stakes()

    +

    Retrieve performance per pair. +Returns a List of dicts per pair.

    +

    python +if self.config['runmode'].value in ('live', 'dry_run'): + performance = Trade.get_overall_performance()

    +

    Sample return value: ETH/BTC had 5 trades, with a total profit of 1.5% (ratio of 0.015).

    +

    json +{'pair': "ETH/BTC", 'profit': 0.015, 'count': 5}

    +
    +

    Warning

    +

    Trade history is not available during backtesting or hyperopt.

    +
    +

    Prevent trades from happening for a specific pair

    +

    Freqtrade locks pairs automatically for the current candle (until that candle is over) when a pair is sold, preventing an immediate re-buy of that pair.

    +

    Locked pairs will show the message Pair <pair> is currently locked..

    +

    Locking pairs from within the strategy

    +

    Sometimes it may be desired to lock a pair after certain events happen (e.g. multiple losing trades in a row).

    +

    Freqtrade has an easy method to do this from within the strategy, by calling self.lock_pair(pair, until, [reason]). +until must be a datetime object in the future, after which trading will be re-enabled for that pair, while reason is an optional string detailing why the pair was locked.

    +

    Locks can also be lifted manually, by calling self.unlock_pair(pair).

    +

    To verify if a pair is currently locked, use self.is_pair_locked(pair).

    +
    +

    Note

    +

    Locked pairs will always be rounded up to the next candle. So assuming a 5m timeframe, a lock with until set to 10:18 will lock the pair until the candle from 10:15-10:20 will be finished.

    +
    +
    +

    Warning

    +

    Manually locking pairs is not available during backtesting, only locks via Protections are allowed.

    +
    +

    Pair locking example

    +

    ``` python +from freqtrade.persistence import Trade +from datetime import timedelta, datetime, timezone

    +

    Put the above lines a the top of the strategy file, next to all the other imports

    +

    --------

    +

    Within populate indicators (or populate_buy):

    +

    if self.config['runmode'].value in ('live', 'dry_run'): + # fetch closed trades for the last 2 days + trades = Trade.get_trades([Trade.pair == metadata['pair'], + Trade.open_date > datetime.utcnow() - timedelta(days=2), + Trade.is_open.is_(False), + ]).all() + # Analyze the conditions you'd like to lock the pair .... will probably be different for every strategy + sumprofit = sum(trade.close_profit for trade in trades) + if sumprofit < 0: + # Lock pair for 12 hours + self.lock_pair(metadata['pair'], until=datetime.now(timezone.utc) + timedelta(hours=12)) +```

    + +

    To inspect the created dataframe, you can issue a print-statement in either populate_buy_trend() or populate_sell_trend(). +You may also want to print the pair so it's clear what data is currently shown.

    +

    ``` python +def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: + dataframe.loc[ + ( + #>> whatever condition<<< + ), + 'buy'] = 1

    +
    # Print the Analyzed pair
    +print(f"result for {metadata['pair']}")
    +
    +# Inspect the last 5 rows
    +print(dataframe.tail())
    +
    +return dataframe
    +
    + +

    ```

    +

    Printing more than a few rows is also possible (simply use print(dataframe) instead of print(dataframe.tail())), however not recommended, as that will be very verbose (~500 lines per pair every 5 seconds).

    +

    Common mistakes when developing strategies

    +

    Backtesting analyzes the whole time-range at once for performance reasons. Because of this, strategy authors need to make sure that strategies do not look-ahead into the future. +This is a common pain-point, which can cause huge differences between backtesting and dry/live run methods, since they all use data which is not available during dry/live runs, so these strategies will perform well during backtesting, but will fail / perform badly in real conditions.

    +

    The following lists some common patterns which should be avoided to prevent frustration:

    +
      +
    • don't use shift(-1). This uses data from the future, which is not available.
    • +
    • don't use .iloc[-1] or any other absolute position in the dataframe, this will be different between dry-run and backtesting.
    • +
    • don't use dataframe['volume'].mean(). This uses the full DataFrame for backtesting, including data from the future. Use dataframe['volume'].rolling(<window>).mean() instead
    • +
    • don't use .resample('1h'). This uses the left border of the interval, so moves data from an hour to the start of the hour. Use .resample('1h', label='right') instead.
    • +
    +

    Further strategy ideas

    +

    To get additional Ideas for strategies, head over to our strategy repository. Feel free to use them as they are - but results will depend on the current market situation, pairs used etc. - therefore please backtest the strategy for your exchange/desired pairs first, evaluate carefully, use at your own risk. +Feel free to use any of them as inspiration for your own strategies. +We're happy to accept Pull Requests containing new Strategies to that repo.

    +

    Next step

    +

    Now you have a perfect strategy you probably want to backtest it. +Your next step is to learn How to use the Backtesting.

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/strategy_analysis_example/index.html b/en/2021.7/strategy_analysis_example/index.html new file mode 100644 index 000000000..9b1fafe3b --- /dev/null +++ b/en/2021.7/strategy_analysis_example/index.html @@ -0,0 +1,1157 @@ + + + + + + + + + + + + + + + + + + + Strategy analysis - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + + + + + + +

    Strategy analysis example

    +

    Debugging a strategy can be time-consuming. Freqtrade offers helper functions to visualize raw data. +The following assumes you work with SampleStrategy, data for 5m timeframe from Binance and have downloaded them into the data directory in the default location.

    +

    Setup

    +

    ```python +from pathlib import Path +from freqtrade.configuration import Configuration

    +

    Customize these according to your needs.

    +

    Initialize empty configuration object

    +

    config = Configuration.from_files([])

    +

    Optionally, use existing configuration file

    +

    config = Configuration.from_files(["config.json"])

    +

    Define some constants

    +

    config["timeframe"] = "5m"

    +

    Name of the strategy class

    +

    config["strategy"] = "SampleStrategy"

    +

    Location of the data

    +

    data_location = Path(config['user_data_dir'], 'data', 'binance')

    +

    Pair to analyze - Only use one pair here

    +

    pair = "BTC/USDT" +```

    +

    ```python

    +

    Load data using values set above

    +

    from freqtrade.data.history import load_pair_history

    +

    candles = load_pair_history(datadir=data_location, + timeframe=config["timeframe"], + pair=pair, + data_format = "hdf5", + )

    +

    Confirm success

    +

    print("Loaded " + str(len(candles)) + f" rows of data for {pair} from {data_location}") +candles.head() +```

    +

    Load and run strategy

    +
      +
    • Rerun each time the strategy file is changed
    • +
    +

    ```python

    +

    Load strategy using values set above

    +

    from freqtrade.resolvers import StrategyResolver +strategy = StrategyResolver.load_strategy(config)

    +

    Generate buy/sell signals using strategy

    +

    df = strategy.analyze_ticker(candles, {'pair': pair}) +df.tail() +```

    +

    Display the trade details

    +
      +
    • Note that using data.head() would also work, however most indicators have some "startup" data at the top of the dataframe.
    • +
    • Some possible problems + * Columns with NaN values at the end of the dataframe + * Columns used in crossed*() functions with completely different units
    • +
    • Comparison with full backtest + * having 200 buy signals as output for one pair from analyze_ticker() does not necessarily mean that 200 trades will be made during backtesting. + * Assuming you use only one condition such as, df['rsi'] < 30 as buy condition, this will generate multiple "buy" signals for each pair in sequence (until rsi returns > 29). The bot will only buy on the first of these signals (and also only if a trade-slot ("max_open_trades") is still available), or on one of the middle signals, as soon as a "slot" becomes available.
    • +
    +

    ```python

    +

    Report results

    +

    print(f"Generated {df['buy'].sum()} buy signals") +data = df.set_index('date', drop=False) +data.tail() +```

    +

    Load existing objects into a Jupyter notebook

    +

    The following cells assume that you have already generated data using the cli.
    +They will allow you to drill deeper into your results, and perform analysis which otherwise would make the output very difficult to digest due to information overload.

    +

    Load backtest results to pandas dataframe

    +

    Analyze a trades dataframe (also used below for plotting)

    +

    ```python +from freqtrade.data.btanalysis import load_backtest_data, load_backtest_stats

    +

    if backtest_dir points to a directory, it'll automatically load the last backtest file.

    +

    backtest_dir = config["user_data_dir"] / "backtest_results"

    +

    backtest_dir can also point to a specific file

    +

    backtest_dir = config["user_data_dir"] / "backtest_results/backtest-result-2020-07-01_20-04-22.json"

    +

    ```

    +

    ```python

    +

    You can get the full backtest statistics by using the following command.

    +

    This contains all information used to generate the backtest result.

    +

    stats = load_backtest_stats(backtest_dir)

    +

    strategy = 'SampleStrategy'

    +

    All statistics are available per strategy, so if --strategy-list was used during backtest, this will be reflected here as well.

    +

    Example usages:

    +

    print(stats['strategy'][strategy]['results_per_pair'])

    +

    Get pairlist used for this backtest

    +

    print(stats['strategy'][strategy]['pairlist'])

    +

    Get market change (average change of all pairs from start to end of the backtest period)

    +

    print(stats['strategy'][strategy]['market_change'])

    +

    Maximum drawdown ()

    +

    print(stats['strategy'][strategy]['max_drawdown'])

    +

    Maximum drawdown start and end

    +

    print(stats['strategy'][strategy]['drawdown_start']) +print(stats['strategy'][strategy]['drawdown_end'])

    +

    Get strategy comparison (only relevant if multiple strategies were compared)

    +

    print(stats['strategy_comparison'])

    +

    ```

    +

    ```python

    +

    Load backtested trades as dataframe

    +

    trades = load_backtest_data(backtest_dir)

    +

    Show value-counts per pair

    +

    trades.groupby("pair")["sell_reason"].value_counts() +```

    +

    Plotting daily profit / equity line

    +

    ```python

    +

    Plotting equity line (starting with 0 on day 1 and adding daily profit for each backtested day)

    +

    from freqtrade.configuration import Configuration +from freqtrade.data.btanalysis import load_backtest_data, load_backtest_stats +import plotly.express as px +import pandas as pd

    +

    strategy = 'SampleStrategy'

    +

    config = Configuration.from_files(["user_data/config.json"])

    +

    backtest_dir = config["user_data_dir"] / "backtest_results"

    +

    stats = load_backtest_stats(backtest_dir) +strategy_stats = stats['strategy'][strategy]

    +

    dates = [] +profits = [] +for date_profit in strategy_stats['daily_profit']: + dates.append(date_profit[0]) + profits.append(date_profit[1])

    +

    equity = 0 +equity_daily = [] +for daily_profit in profits: + equity_daily.append(equity) + equity += float(daily_profit)

    +

    df = pd.DataFrame({'dates': dates,'equity_daily': equity_daily})

    +

    fig = px.line(df, x="dates", y="equity_daily") +fig.show()

    +

    ```

    +

    Load live trading results into a pandas dataframe

    +

    In case you did already some trading and want to analyze your performance

    +

    ```python +from freqtrade.data.btanalysis import load_trades_from_db

    +

    Fetch trades from database

    +

    trades = load_trades_from_db("sqlite:///tradesv3.sqlite")

    +

    Display results

    +

    trades.groupby("pair")["sell_reason"].value_counts() +```

    +

    Analyze the loaded trades for trade parallelism

    +

    This can be useful to find the best max_open_trades parameter, when used with backtesting in conjunction with --disable-max-market-positions.

    +

    analyze_trade_parallelism() returns a timeseries dataframe with an "open_trades" column, specifying the number of open trades for each candle.

    +

    ```python +from freqtrade.data.btanalysis import analyze_trade_parallelism

    +

    Analyze the above

    +

    parallel_trades = analyze_trade_parallelism(trades, '5m')

    +

    parallel_trades.plot() +```

    +

    Plot results

    +

    Freqtrade offers interactive plotting capabilities based on plotly.

    +

    ```python +from freqtrade.plot.plotting import generate_candlestick_graph

    +

    Limit graph period to keep plotly quick and reactive

    +

    Filter trades to one pair

    +

    trades_red = trades.loc[trades['pair'] == pair]

    +

    data_red = data['2019-06-01':'2019-06-10']

    +

    Generate candlestick graph

    +

    graph = generate_candlestick_graph(pair=pair, + data=data_red, + trades=trades_red, + indicators1=['sma20', 'ema50', 'ema55'], + indicators2=['rsi', 'macd', 'macdsignal', 'macdhist'] + )

    +

    ```

    +

    ```python

    +

    Show graph inline

    +

    graph.show()

    +

    Render graph in a seperate window

    +

    graph.show(renderer="browser")

    +

    ```

    +

    Plot average profit per trade as distribution graph

    +

    ```python +import plotly.figure_factory as ff

    +

    hist_data = [trades.profit_ratio] +group_labels = ['profit_ratio'] # name of the dataset

    +

    fig = ff.create_distplot(hist_data, group_labels,bin_size=0.01) +fig.show()

    +

    ```

    +

    Feel free to submit an issue or Pull Request enhancing this document if you would like to share ideas on how to best analyze the data.

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/stylesheets/ft.extra.css b/en/2021.7/stylesheets/ft.extra.css new file mode 100644 index 000000000..f9ad980c6 --- /dev/null +++ b/en/2021.7/stylesheets/ft.extra.css @@ -0,0 +1,28 @@ +.rst-versions { + font-size: .7rem; + color: white; +} + +.rst-versions.rst-badge .rst-current-version { + font-size: .7rem; + color: white; +} + +.rst-versions .rst-other-versions { + color: white; +} + + +#widget-wrapper { + height: calc(220px * 0.5625 + 18px); + width: 220px; + margin: 0 auto 16px auto; + border-style: solid; + border-color: var(--md-code-bg-color); + border-width: 1px; + border-radius: 5px; +} + +@media screen and (max-width: calc(76.25em - 1px)) { + #widget-wrapper { display: none; } +} diff --git a/en/2021.7/telegram-usage/index.html b/en/2021.7/telegram-usage/index.html new file mode 100644 index 000000000..5c4bc4595 --- /dev/null +++ b/en/2021.7/telegram-usage/index.html @@ -0,0 +1,1761 @@ + + + + + + + + + + + + + + + + + + + Telegram - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + + + + +
    +
    + + + + + + + +

    Telegram usage

    +

    Setup your Telegram bot

    +

    Below we explain how to create your Telegram Bot, and how to get your +Telegram user id.

    +

    1. Create your Telegram bot

    +

    Start a chat with the Telegram BotFather

    +

    Send the message /newbot.

    +

    BotFather response:

    +
    +

    Alright, a new bot. How are we going to call it? Please choose a name for your bot.

    +
    +

    Choose the public name of your bot (e.x. Freqtrade bot)

    +

    BotFather response:

    +
    +

    Good. Now let's choose a username for your bot. It must end in bot. Like this, for example: TetrisBot or tetris_bot.

    +
    +

    Choose the name id of your bot and send it to the BotFather (e.g. "My_own_freqtrade_bot")

    +

    BotFather response:

    +
    +

    Done! Congratulations on your new bot. You will find it at t.me/yourbots_name_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you've finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.

    +

    Use this token to access the HTTP API: 22222222:APITOKEN

    +

    For a description of the Bot API, see this page: https://core.telegram.org/bots/api Father bot will return you the token (API key)

    +
    +

    Copy the API Token (22222222:APITOKEN in the above example) and keep use it for the config parameter token.

    +

    Don't forget to start the conversation with your bot, by clicking /START button

    +

    2. Telegram user_id

    +

    Get your user id

    +

    Talk to the userinfobot

    +

    Get your "Id", you will use it for the config parameter chat_id.

    +

    Use Group id

    +

    You can use bots in telegram groups by just adding them to the group. You can find the group id by first adding a RawDataBot to your group. The Group id is shown as id in the "chat" section, which the RawDataBot will send to you:

    +

    json +"chat":{ + "id":-1001332619709 +}

    +

    For the Freqtrade configuration, you can then use the the full value (including - if it's there) as string:

    +

    json + "chat_id": "-1001332619709"

    +

    Control telegram noise

    +

    Freqtrade provides means to control the verbosity of your telegram bot. +Each setting has the following possible values:

    +
      +
    • on - Messages will be sent, and user will be notified.
    • +
    • silent - Message will be sent, Notification will be without sound / vibration.
    • +
    • off - Skip sending a message-type all together.
    • +
    +

    Example configuration showing the different settings:

    +

    json +"telegram": { + "enabled": true, + "token": "your_telegram_token", + "chat_id": "your_telegram_chat_id", + "notification_settings": { + "status": "silent", + "warning": "on", + "startup": "off", + "buy": "silent", + "sell": { + "roi": "silent", + "emergency_sell": "on", + "force_sell": "on", + "sell_signal": "silent", + "trailing_stop_loss": "on", + "stop_loss": "on", + "stoploss_on_exchange": "on", + "custom_sell": "silent" + }, + "buy_cancel": "silent", + "sell_cancel": "on", + "buy_fill": "off", + "sell_fill": "off" + }, + "reload": true, + "balance_dust_level": 0.01 +},

    +

    buy notifications are sent when the order is placed, while buy_fill notifications are sent when the order is filled on the exchange. +sell notifications are sent when the order is placed, while sell_fill notifications are sent when the order is filled on the exchange. +*_fill notifications are off by default and must be explicitly enabled.

    +

    balance_dust_level will define what the /balance command takes as "dust" - Currencies with a balance below this will be shown. +reload allows you to disable reload-buttons on selected messages.

    +

    Create a custom keyboard (command shortcut buttons)

    +

    Telegram allows us to create a custom keyboard with buttons for commands. +The default custom keyboard looks like this.

    +

    python +[ + ["/daily", "/profit", "/balance"], # row 1, 3 commands + ["/status", "/status table", "/performance"], # row 2, 3 commands + ["/count", "/start", "/stop", "/help"] # row 3, 4 commands +]

    +

    Usage

    +

    You can create your own keyboard in config.json:

    +

    json +"telegram": { + "enabled": true, + "token": "your_telegram_token", + "chat_id": "your_telegram_chat_id", + "keyboard": [ + ["/daily", "/stats", "/balance", "/profit"], + ["/status table", "/performance"], + ["/reload_config", "/count", "/logs"] + ] + },

    +
    +

    Supported Commands

    +

    Only the following commands are allowed. Command arguments are not supported!

    +

    /start, /stop, /status, /status table, /trades, /profit, /performance, /daily, /stats, /count, /locks, /balance, /stopbuy, /reload_config, /show_config, /logs, /whitelist, /blacklist, /edge, /help, /version

    +
    +

    Telegram commands

    +

    Per default, the Telegram bot shows predefined commands. Some commands +are only available by sending them to the bot. The table below list the +official commands. You can ask at any moment for help with /help.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    CommandDescription
    /startStarts the trader
    /stopStops the trader
    /stopbuyStops the trader from opening new trades. Gracefully closes open trades according to their rules.
    /reload_configReloads the configuration file
    /show_configShows part of the current configuration with relevant settings to operation
    /logs [limit]Show last log messages.
    /statusLists all open trades
    /status <trade_id>Lists one or more specific trade. Separate multiple with a blank space.
    /status tableList all open trades in a table format. Pending buy orders are marked with an asterisk () Pending sell orders are marked with a double asterisk (*)
    /trades [limit]List all recently closed trades in a table format.
    /delete <trade_id>Delete a specific trade from the Database. Tries to close open orders. Requires manual handling of this trade on the exchange.
    /countDisplays number of trades used and available
    /locksShow currently locked pairs.
    /unlock <pair or lock_id>Remove the lock for this pair (or for this lock id).
    /profit [<n>]Display a summary of your profit/loss from close trades and some stats about your performance, over the last n days (all trades by default)
    /forcesell <trade_id>Instantly sells the given trade (Ignoring minimum_roi).
    /forcesell allInstantly sells all open trades (Ignoring minimum_roi).
    /forcebuy <pair> [rate]Instantly buys the given pair. Rate is optional. (forcebuy_enable must be set to True)
    /performanceShow performance of each finished trade grouped by pair
    /balanceShow account balance per currency
    /daily <n>Shows profit or loss per day, over the last n days (n defaults to 7)
    /statsShows Wins / losses by Sell reason as well as Avg. holding durations for buys and sells
    /whitelistShow the current whitelist
    /blacklist [pair]Show the current blacklist, or adds a pair to the blacklist.
    /edgeShow validated pairs by Edge if it is enabled.
    /helpShow help message
    /versionShow version
    +

    Telegram commands in action

    +

    Below, example of Telegram message you will receive for each command.

    +

    /start

    +
    +

    Status: running

    +
    +

    /stop

    +
    +

    Stopping trader ... +Status: stopped

    +
    +

    /stopbuy

    +
    +

    status: Setting max_open_trades to 0. Run /reload_config to reset.

    +
    +

    Prevents the bot from opening new trades by temporarily setting "max_open_trades" to 0. Open trades will be handled via their regular rules (ROI / Sell-signal, stoploss, ...).

    +

    After this, give the bot time to close off open trades (can be checked via /status table). +Once all positions are sold, run /stop to completely stop the bot.

    +

    /reload_config resets "max_open_trades" to the value set in the configuration and resets this command.

    +
    +

    Warning

    +
    +

    The stop-buy signal is ONLY active while the bot is running, and is not persisted anyway, so restarting the bot will cause this to reset.

    +

    /status

    +

    For each open trade, the bot will send you the following message.

    +
    +

    Trade ID: 123 (since 1 days ago)
    +Current Pair: CVC/BTC
    +Open Since: 1 days ago
    +Amount: 26.64180098
    +Open Rate: 0.00007489
    +Current Rate: 0.00007489
    +Current Profit: 12.95%
    +Stoploss: 0.00007389 (-0.02%)

    +
    +

    /status table

    +

    Return the status of all open trades in a table format.

    +

    ``` + ID Pair Since Profit

    +
    +

    67 SC/BTC 1 d 13.33% + 123 CVC/BTC 1 h 12.95% +```

    +

    /count

    +

    Return the number of trades used and available.

    +

    ``` +current max

    +
    +
     2     10
    +
    + +

    ```

    +

    /profit

    +

    Return a summary of your profit/loss and performance.

    +
    +

    ROI: Close trades
    + ∙ 0.00485701 BTC (2.2%) (15.2 Σ%)
    + ∙ 62.968 USD
    +ROI: All trades
    + ∙ 0.00255280 BTC (1.5%) (6.43 Σ%)
    + ∙ 33.095 EUR

    +

    Total Trade Count: 138
    +First Trade opened: 3 days ago
    +Latest Trade opened: 2 minutes ago
    +Avg. Duration: 2:33:45
    +Best Performing: PAY/BTC: 50.23%

    +
    +

    The relative profit of 1.2% is the average profit per trade.
    +The relative profit of 15.2 Σ% is be based on the starting capital - so in this case, the starting capital was 0.00485701 * 1.152 = 0.00738 BTC. +Starting capital is either taken from the available_capital setting, or calculated by using current wallet size - profits.

    +

    /forcesell

    +
    +

    BITTREX: Selling BTC/LTC with limit 0.01650000 (profit: ~-4.07%, -0.00008168)

    +
    +

    /forcebuy [rate]

    +
    +

    BITTREX: Buying ETH/BTC with limit 0.03400000 (1.000000 ETH, 225.290 USD)

    +
    +

    Omitting the pair will open a query asking for the pair to buy (based on the current whitelist).

    +

    Telegram force-buy screenshot

    +

    Note that for this to work, forcebuy_enable needs to be set to true.

    +

    More details

    +

    /performance

    +

    Return the performance of each crypto-currency the bot has sold.

    +
    +

    Performance:
    +1. RCN/BTC 0.003 BTC (57.77%) (1)
    +2. PAY/BTC 0.0012 BTC (56.91%) (1)
    +3. VIB/BTC 0.0011 BTC (47.07%) (1)
    +4. SALT/BTC 0.0010 BTC (30.24%) (1)
    +5. STORJ/BTC 0.0009 BTC (27.24%) (1)
    +...

    +
    +

    /balance

    +

    Return the balance of all crypto-currency your have on the exchange.

    +
    +

    Currency: BTC
    +Available: 3.05890234
    +Balance: 3.05890234
    +Pending: 0.0

    +

    Currency: CVC
    +Available: 86.64180098
    +Balance: 86.64180098
    +Pending: 0.0

    +
    +

    /daily

    +

    Per default /daily will return the 7 last days. +The example below if for /daily 3:

    +
    +

    Daily Profit over the last 3 days: +``` +Day Profit BTC Profit USD

    +
    +
    +

    2018-01-03 0.00224175 BTC 29,142 USD +2018-01-02 0.00033131 BTC 4,307 USD +2018-01-01 0.00269130 BTC 34.986 USD +```

    +

    /whitelist

    +

    Shows the current whitelist

    +
    +

    Using whitelist StaticPairList with 22 pairs
    +IOTA/BTC, NEO/BTC, TRX/BTC, VET/BTC, ADA/BTC, ETC/BTC, NCASH/BTC, DASH/BTC, XRP/BTC, XVG/BTC, EOS/BTC, LTC/BTC, OMG/BTC, BTG/BTC, LSK/BTC, ZEC/BTC, HOT/BTC, IOTX/BTC, XMR/BTC, AST/BTC, XLM/BTC, NANO/BTC

    +
    +

    /blacklist [pair]

    +

    Shows the current blacklist. +If Pair is set, then this pair will be added to the pairlist. +Also supports multiple pairs, separated by a space. +Use /reload_config to reset the blacklist.

    +
    +

    Using blacklist StaticPairList with 2 pairs
    +DODGE/BTC, HOT/BTC.

    +
    +

    /edge

    +

    Shows pairs validated by Edge along with their corresponding win-rate, expectancy and stoploss values.

    +
    +

    Edge only validated following pairs: +``` +Pair Winrate Expectancy Stoploss

    +
    +
    +

    DOCK/ETH 0.522727 0.881821 -0.03 +PHX/ETH 0.677419 0.560488 -0.03 +HOT/ETH 0.733333 0.490492 -0.03 +HC/ETH 0.588235 0.280988 -0.02 +ARDR/ETH 0.366667 0.143059 -0.01 +```

    +

    /version

    +
    +

    Version: 0.14.3

    +
    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/updating/index.html b/en/2021.7/updating/index.html new file mode 100644 index 000000000..18614c75b --- /dev/null +++ b/en/2021.7/updating/index.html @@ -0,0 +1,1031 @@ + + + + + + + + + + + + + + + + + + + Updating Freqtrade - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + + + + + + +

    How to update

    +

    To update your freqtrade installation, please use one of the below methods, corresponding to your installation method.

    +

    docker-compose

    +
    +

    Legacy installations using the master image

    +

    We're switching from master to stable for the release Images - please adjust your docker-file and replace freqtradeorg/freqtrade:master with freqtradeorg/freqtrade:stable

    +
    +

    bash +docker-compose pull +docker-compose up -d

    +

    Installation via setup script

    +

    bash +./setup.sh --update

    +
    +

    Note

    +

    Make sure to run this command with your virtual environment disabled!

    +
    +

    Plain native installation

    +

    Please ensure that you're also updating dependencies - otherwise things might break without you noticing.

    +

    bash +git pull +pip install -U -r requirements.txt

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/utils/index.html b/en/2021.7/utils/index.html new file mode 100644 index 000000000..22e46aeda --- /dev/null +++ b/en/2021.7/utils/index.html @@ -0,0 +1,2059 @@ + + + + + + + + + + + + + + + + + + + Utility Sub-commands - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + + + + + + +

    Utility Subcommands

    +

    Besides the Live-Trade and Dry-Run run modes, the backtesting, edge and hyperopt optimization subcommands, and the download-data subcommand which prepares historical data, the bot contains a number of utility subcommands. They are described in this section.

    +

    Create userdir

    +

    Creates the directory structure to hold your files for freqtrade. +Will also create strategy and hyperopt examples for you to get started. +Can be used multiple times - using --reset will reset the sample strategy and hyperopt files to their default state.

    +

    ``` +usage: freqtrade create-userdir [-h] [--userdir PATH] [--reset]

    +

    optional arguments: + -h, --help show this help message and exit + --userdir PATH, --user-data-dir PATH + Path to userdata directory. + --reset Reset sample files to their original state. +```

    +
    +

    Warning

    +

    Using --reset may result in loss of data, since this will overwrite all sample files without asking again.

    +
    +

    ├── backtest_results +├── data +├── hyperopt_results +├── hyperopts +│   ├── sample_hyperopt_advanced.py +│   ├── sample_hyperopt_loss.py +│   └── sample_hyperopt.py +├── notebooks +│   └── strategy_analysis_example.ipynb +├── plot +└── strategies + └── sample_strategy.py

    +

    Create new config

    +

    Creates a new configuration file, asking some questions which are important selections for a configuration.

    +

    ``` +usage: freqtrade new-config [-h] [-c PATH]

    +

    optional arguments: + -h, --help show this help message and exit + -c PATH, --config PATH + Specify configuration file (default: config.json). Multiple --config options may be used. Can be set to - + to read config from stdin. +```

    +
    +

    Warning

    +

    Only vital questions are asked. Freqtrade offers a lot more configuration possibilities, which are listed in the Configuration documentation

    +
    +

    Create config examples

    +

    ``` +$ freqtrade new-config --config config_binance.json

    +

    ? Do you want to enable Dry-run (simulated trades)? Yes +? Please insert your stake currency: BTC +? Please insert your stake amount: 0.05 +? Please insert max_open_trades (Integer or 'unlimited'): 3 +? Please insert your desired timeframe (e.g. 5m): 5m +? Please insert your display Currency (for reporting): USD +? Select exchange binance +? Do you want to enable Telegram? No +```

    +

    Create new strategy

    +

    Creates a new strategy from a template similar to SampleStrategy. +The file will be named inline with your class name, and will not overwrite existing files.

    +

    Results will be located in user_data/strategies/<strategyclassname>.py.

    +

    ``` output +usage: freqtrade new-strategy [-h] [--userdir PATH] [-s NAME] + [--template {full,minimal,advanced}]

    +

    optional arguments: + -h, --help show this help message and exit + --userdir PATH, --user-data-dir PATH + Path to userdata directory. + -s NAME, --strategy NAME + Specify strategy class name which will be used by the + bot. + --template {full,minimal,advanced} + Use a template which is either minimal, full + (containing multiple sample indicators) or advanced. + Default: full.

    +

    ```

    +

    Sample usage of new-strategy

    +

    bash +freqtrade new-strategy --strategy AwesomeStrategy

    +

    With custom user directory

    +

    bash +freqtrade new-strategy --userdir ~/.freqtrade/ --strategy AwesomeStrategy

    +

    Using the advanced template (populates all optional functions and methods)

    +

    bash +freqtrade new-strategy --strategy AwesomeStrategy --template advanced

    +

    Create new hyperopt

    +

    Creates a new hyperopt from a template similar to SampleHyperopt. +The file will be named inline with your class name, and will not overwrite existing files.

    +

    Results will be located in user_data/hyperopts/<classname>.py.

    +

    ``` output +usage: freqtrade new-hyperopt [-h] [--userdir PATH] [--hyperopt NAME] + [--template {full,minimal,advanced}]

    +

    optional arguments: + -h, --help show this help message and exit + --userdir PATH, --user-data-dir PATH + Path to userdata directory. + --hyperopt NAME Specify hyperopt class name which will be used by the + bot. + --template {full,minimal,advanced} + Use a template which is either minimal, full + (containing multiple sample indicators) or advanced. + Default: full. +```

    +

    Sample usage of new-hyperopt

    +

    bash +freqtrade new-hyperopt --hyperopt AwesomeHyperopt

    +

    With custom user directory

    +

    bash +freqtrade new-hyperopt --userdir ~/.freqtrade/ --hyperopt AwesomeHyperopt

    +

    List Strategies and List Hyperopts

    +

    Use the list-strategies subcommand to see all strategies in one particular directory and the list-hyperopts subcommand to list custom Hyperopts.

    +

    These subcommands are useful for finding problems in your environment with loading strategies or hyperopt classes: modules with strategies or hyperopt classes that contain errors and failed to load are printed in red (LOAD FAILED), while strategies or hyperopt classes with duplicate names are printed in yellow (DUPLICATE NAME).

    +

    ``` +usage: freqtrade list-strategies [-h] [-v] [--logfile FILE] [-V] [-c PATH] + [-d PATH] [--userdir PATH] + [--strategy-path PATH] [-1] [--no-color]

    +

    optional arguments: + -h, --help show this help message and exit + --strategy-path PATH Specify additional strategy lookup path. + -1, --one-column Print output in one column. + --no-color Disable colorization of hyperopt results. May be + useful if you are redirecting output to a file.

    +

    Common arguments: + -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). + --logfile FILE Log to the file specified. Special values are: + 'syslog', 'journald'. See the documentation for more + details. + -V, --version show program's version number and exit + -c PATH, --config PATH + Specify configuration file (default: config.json). + Multiple --config options may be used. Can be set to + - to read config from stdin. + -d PATH, --datadir PATH + Path to directory with historical backtesting data. + --userdir PATH, --user-data-dir PATH + Path to userdata directory. + +usage: freqtrade list-hyperopts [-h] [-v] [--logfile FILE] [-V] [-c PATH] + [-d PATH] [--userdir PATH] + [--hyperopt-path PATH] [-1] [--no-color]

    +

    optional arguments: + -h, --help show this help message and exit + --hyperopt-path PATH Specify additional lookup path for Hyperopt and + Hyperopt Loss functions. + -1, --one-column Print output in one column. + --no-color Disable colorization of hyperopt results. May be + useful if you are redirecting output to a file.

    +

    Common arguments: + -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). + --logfile FILE Log to the file specified. Special values are: + 'syslog', 'journald'. See the documentation for more + details. + -V, --version show program's version number and exit + -c PATH, --config PATH + Specify configuration file (default: config.json). + Multiple --config options may be used. Can be set to + - to read config from stdin. + -d PATH, --datadir PATH + Path to directory with historical backtesting data. + --userdir PATH, --user-data-dir PATH + Path to userdata directory. +```

    +
    +

    Warning

    +

    Using these commands will try to load all python files from a directory. This can be a security risk if untrusted files reside in this directory, since all module-level code is executed.

    +
    +

    Example: Search default strategies and hyperopts directories (within the default userdir).

    +

    bash +freqtrade list-strategies +freqtrade list-hyperopts

    +

    Example: Search strategies and hyperopts directory within the userdir.

    +

    bash +freqtrade list-strategies --userdir ~/.freqtrade/ +freqtrade list-hyperopts --userdir ~/.freqtrade/

    +

    Example: Search dedicated strategy path.

    +

    bash +freqtrade list-strategies --strategy-path ~/.freqtrade/strategies/

    +

    Example: Search dedicated hyperopt path.

    +

    bash +freqtrade list-hyperopt --hyperopt-path ~/.freqtrade/hyperopts/

    +

    List Exchanges

    +

    Use the list-exchanges subcommand to see the exchanges available for the bot.

    +

    ``` +usage: freqtrade list-exchanges [-h] [-1] [-a]

    +

    optional arguments: + -h, --help show this help message and exit + -1, --one-column Print output in one column. + -a, --all Print all exchanges known to the ccxt library. +```

    +
      +
    • Example: see exchanges available for the bot: +``` +$ freqtrade list-exchanges +Exchanges available for Freqtrade: +Exchange name Valid reason
    • +
    +
    +

    aax True +ascendex True missing opt: fetchMyTrades +bequant True +bibox True +bigone True +binance True +binanceus True +bitbank True missing opt: fetchTickers +bitcoincom True +bitfinex True +bitforex True missing opt: fetchMyTrades, fetchTickers +bitget True +bithumb True missing opt: fetchMyTrades +bitkk True missing opt: fetchMyTrades +bitmart True +bitmax True missing opt: fetchMyTrades +bitpanda True +bittrex True +bitvavo True +bitz True missing opt: fetchMyTrades +btcalpha True missing opt: fetchTicker, fetchTickers +btcmarkets True missing opt: fetchTickers +buda True missing opt: fetchMyTrades, fetchTickers +bw True missing opt: fetchMyTrades, fetchL2OrderBook +bybit True +bytetrade True +cdax True +cex True missing opt: fetchMyTrades +coinbaseprime True missing opt: fetchTickers +coinbasepro True missing opt: fetchTickers +coinex True +crex24 True +deribit True +digifinex True +equos True missing opt: fetchTicker, fetchTickers +eterbase True +fcoin True missing opt: fetchMyTrades, fetchTickers +fcoinjp True missing opt: fetchMyTrades, fetchTickers +ftx True +gateio True +gemini True +gopax True +hbtc True +hitbtc True +huobijp True +huobipro True +idex True +kraken True +kucoin True +lbank True missing opt: fetchMyTrades +mercado True missing opt: fetchTickers +ndax True missing opt: fetchTickers +novadax True +okcoin True +okex True +probit True +qtrade True +stex True +timex True +upbit True missing opt: fetchMyTrades +vcc True +zb True missing opt: fetchMyTrades

    +

    ```

    +
    +

    missing opt exchanges

    +

    Values with "missing opt:" might need special configuration (e.g. using orderbook if fetchTickers is missing) - but should in theory work (although we cannot guarantee they will).

    +
    +
      +
    • Example: see all exchanges supported by the ccxt library (including 'bad' ones, i.e. those that are known to not work with Freqtrade): +``` +$ freqtrade list-exchanges -a +All exchanges supported by the ccxt library: +Exchange name Valid reason
    • +
    +
    +

    aax True +aofex False missing: fetchOrder +ascendex True missing opt: fetchMyTrades +bequant True +bibox True +bigone True +binance True +binanceus True +bit2c False missing: fetchOrder, fetchOHLCV +bitbank True missing opt: fetchTickers +bitbay False missing: fetchOrder +bitcoincom True +bitfinex True +bitfinex2 False missing: fetchOrder +bitflyer False missing: fetchOrder, fetchOHLCV +bitforex True missing opt: fetchMyTrades, fetchTickers +bitget True +bithumb True missing opt: fetchMyTrades +bitkk True missing opt: fetchMyTrades +bitmart True +bitmax True missing opt: fetchMyTrades +bitmex False Various reasons. +bitpanda True +bitso False missing: fetchOHLCV +bitstamp False Does not provide history. Details in https://github.com/freqtrade/freqtrade/issues/1983 +bitstamp1 False missing: fetchOrder, fetchOHLCV +bittrex True +bitvavo True +bitz True missing opt: fetchMyTrades +bl3p False missing: fetchOrder, fetchOHLCV +bleutrade False missing: fetchOrder +braziliex False missing: fetchOHLCV +btcalpha True missing opt: fetchTicker, fetchTickers +btcbox False missing: fetchOHLCV +btcmarkets True missing opt: fetchTickers +btctradeua False missing: fetchOrder, fetchOHLCV +btcturk False missing: fetchOrder +buda True missing opt: fetchMyTrades, fetchTickers +bw True missing opt: fetchMyTrades, fetchL2OrderBook +bybit True +bytetrade True +cdax True +cex True missing opt: fetchMyTrades +chilebit False missing: fetchOrder, fetchOHLCV +coinbase False missing: fetchOrder, cancelOrder, createOrder, fetchOHLCV +coinbaseprime True missing opt: fetchTickers +coinbasepro True missing opt: fetchTickers +coincheck False missing: fetchOrder, fetchOHLCV +coinegg False missing: fetchOHLCV +coinex True +coinfalcon False missing: fetchOHLCV +coinfloor False missing: fetchOrder, fetchOHLCV +coingi False missing: fetchOrder, fetchOHLCV +coinmarketcap False missing: fetchOrder, cancelOrder, createOrder, fetchBalance, fetchOHLCV +coinmate False missing: fetchOHLCV +coinone False missing: fetchOHLCV +coinspot False missing: fetchOrder, cancelOrder, fetchOHLCV +crex24 True +currencycom False missing: fetchOrder +delta False missing: fetchOrder +deribit True +digifinex True +equos True missing opt: fetchTicker, fetchTickers +eterbase True +exmo False missing: fetchOrder +exx False missing: fetchOHLCV +fcoin True missing opt: fetchMyTrades, fetchTickers +fcoinjp True missing opt: fetchMyTrades, fetchTickers +flowbtc False missing: fetchOrder, fetchOHLCV +foxbit False missing: fetchOrder, fetchOHLCV +ftx True +gateio True +gemini True +gopax True +hbtc True +hitbtc True +hollaex False missing: fetchOrder +huobijp True +huobipro True +idex True +independentreserve False missing: fetchOHLCV +indodax False missing: fetchOHLCV +itbit False missing: fetchOHLCV +kraken True +kucoin True +kuna False missing: fetchOHLCV +lakebtc False missing: fetchOrder, fetchOHLCV +latoken False missing: fetchOrder, fetchOHLCV +lbank True missing opt: fetchMyTrades +liquid False missing: fetchOHLCV +luno False missing: fetchOHLCV +lykke False missing: fetchOHLCV +mercado True missing opt: fetchTickers +mixcoins False missing: fetchOrder, fetchOHLCV +ndax True missing opt: fetchTickers +novadax True +oceanex False missing: fetchOHLCV +okcoin True +okex True +paymium False missing: fetchOrder, fetchOHLCV +phemex False Does not provide history. +poloniex False missing: fetchOrder +probit True +qtrade True +rightbtc False missing: fetchOrder +ripio False missing: fetchOHLCV +southxchange False missing: fetchOrder, fetchOHLCV +stex True +surbitcoin False missing: fetchOrder, fetchOHLCV +therock False missing: fetchOHLCV +tidebit False missing: fetchOrder +tidex False missing: fetchOHLCV +timex True +upbit True missing opt: fetchMyTrades +vbtc False missing: fetchOrder, fetchOHLCV +vcc True +wavesexchange False missing: fetchOrder +whitebit False missing: fetchOrder, cancelOrder, createOrder, fetchBalance +xbtce False missing: fetchOrder, fetchOHLCV +xena False missing: fetchOrder +yobit False missing: fetchOHLCV +zaif False missing: fetchOrder, fetchOHLCV +zb True missing opt: fetchMyTrades +```

    +

    List Timeframes

    +

    Use the list-timeframes subcommand to see the list of timeframes available for the exchange.

    +

    ``` +usage: freqtrade list-timeframes [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--exchange EXCHANGE] [-1]

    +

    optional arguments: + -h, --help show this help message and exit + --exchange EXCHANGE Exchange name (default: bittrex). Only valid if no config is provided. + -1, --one-column Print output in one column.

    +

    Common arguments: + -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). + --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details. + -V, --version show program's version number and exit + -c PATH, --config PATH + Specify configuration file (default: config.json). Multiple --config options may be used. Can be set to - + to read config from stdin. + -d PATH, --datadir PATH + Path to directory with historical backtesting data. + --userdir PATH, --user-data-dir PATH + Path to userdata directory.

    +

    ```

    +
      +
    • Example: see the timeframes for the 'binance' exchange, set in the configuration file:
    • +
    +

    $ freqtrade list-timeframes -c config_binance.json +... +Timeframes available for the exchange `binance`: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M

    +
      +
    • Example: enumerate exchanges available for Freqtrade and print timeframes supported by each of them: +$ for i in `freqtrade list-exchanges -1`; do freqtrade list-timeframes --exchange $i; done
    • +
    +

    List pairs/list markets

    +

    The list-pairs and list-markets subcommands allow to see the pairs/markets available on exchange.

    +

    Pairs are markets with the '/' character between the base currency part and the quote currency part in the market symbol. +For example, in the 'ETH/BTC' pair 'ETH' is the base currency, while 'BTC' is the quote currency.

    +

    For pairs traded by Freqtrade the pair quote currency is defined by the value of the stake_currency configuration setting.

    +

    You can print info about any pair/market with these subcommands - and you can filter output by quote-currency using --quote BTC, or by base-currency using --base ETH options correspondingly.

    +

    These subcommands have same usage and same set of available options:

    +

    ``` +usage: freqtrade list-markets [-h] [-v] [--logfile FILE] [-V] [-c PATH] + [-d PATH] [--userdir PATH] [--exchange EXCHANGE] + [--print-list] [--print-json] [-1] [--print-csv] + [--base BASE_CURRENCY [BASE_CURRENCY ...]] + [--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]] + [-a]

    +

    usage: freqtrade list-pairs [-h] [-v] [--logfile FILE] [-V] [-c PATH] + [-d PATH] [--userdir PATH] [--exchange EXCHANGE] + [--print-list] [--print-json] [-1] [--print-csv] + [--base BASE_CURRENCY [BASE_CURRENCY ...]] + [--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]] [-a]

    +

    optional arguments: + -h, --help show this help message and exit + --exchange EXCHANGE Exchange name (default: bittrex). Only valid if no + config is provided. + --print-list Print list of pairs or market symbols. By default data + is printed in the tabular format. + --print-json Print list of pairs or market symbols in JSON format. + -1, --one-column Print output in one column. + --print-csv Print exchange pair or market data in the csv format. + --base BASE_CURRENCY [BASE_CURRENCY ...] + Specify base currency(-ies). Space-separated list. + --quote QUOTE_CURRENCY [QUOTE_CURRENCY ...] + Specify quote currency(-ies). Space-separated list. + -a, --all Print all pairs or market symbols. By default only + active ones are shown.

    +

    Common arguments: + -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). + --logfile FILE Log to the file specified. Special values are: + 'syslog', 'journald'. See the documentation for more + details. + -V, --version show program's version number and exit + -c PATH, --config PATH + Specify configuration file (default: config.json). + Multiple --config options may be used. Can be set to + - to read config from stdin. + -d PATH, --datadir PATH + Path to directory with historical backtesting data. + --userdir PATH, --user-data-dir PATH + Path to userdata directory.

    +

    ```

    +

    By default, only active pairs/markets are shown. Active pairs/markets are those that can currently be traded +on the exchange. The see the list of all pairs/markets (not only the active ones), use the -a/-all option.

    +

    Pairs/markets are sorted by its symbol string in the printed output.

    +

    Examples

    +
      +
    • Print the list of active pairs with quote currency USD on exchange, specified in the default +configuration file (i.e. pairs on the "Bittrex" exchange) in JSON format:
    • +
    +

    $ freqtrade list-pairs --quote USD --print-json

    +
      +
    • Print the list of all pairs on the exchange, specified in the config_binance.json configuration file +(i.e. on the "Binance" exchange) with base currencies BTC or ETH and quote currencies USDT or USD, as the +human-readable list with summary:
    • +
    +

    $ freqtrade list-pairs -c config_binance.json --all --base BTC ETH --quote USDT USD --print-list

    +
      +
    • Print all markets on exchange "Kraken", in the tabular format:
    • +
    +

    $ freqtrade list-markets --exchange kraken --all

    +

    Test pairlist

    +

    Use the test-pairlist subcommand to test the configuration of dynamic pairlists.

    +

    Requires a configuration with specified pairlists attribute. +Can be used to generate static pairlists to be used during backtesting / hyperopt.

    +

    ``` +usage: freqtrade test-pairlist [-h] [-c PATH] + [--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]] + [-1] [--print-json]

    +

    optional arguments: + -h, --help show this help message and exit + -c PATH, --config PATH + Specify configuration file (default: config.json). + Multiple --config options may be used. Can be set to + - to read config from stdin. + --quote QUOTE_CURRENCY [QUOTE_CURRENCY ...] + Specify quote currency(-ies). Space-separated list. + -1, --one-column Print output in one column. + --print-json Print list of pairs or market symbols in JSON format. +```

    +

    Examples

    +

    Show whitelist when using a dynamic pairlist.

    +

    freqtrade test-pairlist --config config.json --quote USDT BTC

    +

    Webserver mode

    +
    +

    Experimental

    +

    Webserver mode is an experimental mode to increase backesting and strategy development productivity. +There may still be bugs - so if you happen to stumble across these, please report them as github issues, thanks.

    +
    +

    Run freqtrade in webserver mode. +Freqtrade will start the webserver and allow FreqUI to start and control backtesting processes. +This has the advantage that data will not be reloaded between backtesting runs (as long as timeframe and timerange remain identical). +FreqUI will also show the backtesting results.

    +

    ``` +usage: freqtrade webserver [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] + [--userdir PATH] [-s NAME] [--strategy-path PATH]

    +

    optional arguments: + -h, --help show this help message and exit

    +

    Common arguments: + -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). + --logfile FILE Log to the file specified. Special values are: + 'syslog', 'journald'. See the documentation for more + details. + -V, --version show program's version number and exit + -c PATH, --config PATH + Specify configuration file (default: + userdir/config.json or config.json whichever + exists). Multiple --config options may be used. Can be + set to - to read config from stdin. + -d PATH, --datadir PATH + Path to directory with historical backtesting data. + --userdir PATH, --user-data-dir PATH + Path to userdata directory.

    +

    Strategy arguments: + -s NAME, --strategy NAME + Specify strategy class name which will be used by the + bot. + --strategy-path PATH Specify additional strategy lookup path.

    +

    ```

    +

    List Hyperopt results

    +

    You can list the hyperoptimization epochs the Hyperopt module evaluated previously with the hyperopt-list sub-command.

    +

    ``` +usage: freqtrade hyperopt-list [-h] [-v] [--logfile FILE] [-V] [-c PATH] + [-d PATH] [--userdir PATH] [--best] + [--profitable] [--min-trades INT] + [--max-trades INT] [--min-avg-time FLOAT] + [--max-avg-time FLOAT] [--min-avg-profit FLOAT] + [--max-avg-profit FLOAT] + [--min-total-profit FLOAT] + [--max-total-profit FLOAT] + [--min-objective FLOAT] [--max-objective FLOAT] + [--no-color] [--print-json] [--no-details] + [--hyperopt-filename PATH] [--export-csv FILE]

    +

    optional arguments: + -h, --help show this help message and exit + --best Select only best epochs. + --profitable Select only profitable epochs. + --min-trades INT Select epochs with more than INT trades. + --max-trades INT Select epochs with less than INT trades. + --min-avg-time FLOAT Select epochs above average time. + --max-avg-time FLOAT Select epochs below average time. + --min-avg-profit FLOAT + Select epochs above average profit. + --max-avg-profit FLOAT + Select epochs below average profit. + --min-total-profit FLOAT + Select epochs above total profit. + --max-total-profit FLOAT + Select epochs below total profit. + --min-objective FLOAT + Select epochs above objective. + --max-objective FLOAT + Select epochs below objective. + --no-color Disable colorization of hyperopt results. May be + useful if you are redirecting output to a file. + --print-json Print output in JSON format. + --no-details Do not print best epoch details. + --hyperopt-filename FILENAME + Hyperopt result filename.Example: --hyperopt- + filename=hyperopt_results_2020-09-27_16-20-48.pickle + --export-csv FILE Export to CSV-File. This will disable table print. + Example: --export-csv hyperopt.csv

    +

    Common arguments: + -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). + --logfile FILE Log to the file specified. Special values are: + 'syslog', 'journald'. See the documentation for more + details. + -V, --version show program's version number and exit + -c PATH, --config PATH + Specify configuration file (default: + userdir/config.json or config.json whichever + exists). Multiple --config options may be used. Can be + set to - to read config from stdin. + -d PATH, --datadir PATH + Path to directory with historical backtesting data. + --userdir PATH, --user-data-dir PATH + Path to userdata directory. +```

    +
    +

    Note

    +

    hyperopt-list will automatically use the latest available hyperopt results file. +You can override this using the --hyperopt-filename argument, and specify another, available filename (without path!).

    +
    +

    Examples

    +

    List all results, print details of the best result at the end: +freqtrade hyperopt-list

    +

    List only epochs with positive profit. Do not print the details of the best epoch, so that the list can be iterated in a script: +freqtrade hyperopt-list --profitable --no-details

    +

    Show details of Hyperopt results

    +

    You can show the details of any hyperoptimization epoch previously evaluated by the Hyperopt module with the hyperopt-show subcommand.

    +

    ``` +usage: freqtrade hyperopt-show [-h] [-v] [--logfile FILE] [-V] [-c PATH] + [-d PATH] [--userdir PATH] [--best] + [--profitable] [-n INT] [--print-json] + [--hyperopt-filename FILENAME] [--no-header] + [--disable-param-export]

    +

    optional arguments: + -h, --help show this help message and exit + --best Select only best epochs. + --profitable Select only profitable epochs. + -n INT, --index INT Specify the index of the epoch to print details for. + --print-json Print output in JSON format. + --hyperopt-filename FILENAME + Hyperopt result filename.Example: --hyperopt- + filename=hyperopt_results_2020-09-27_16-20-48.pickle + --no-header Do not print epoch details header. + --disable-param-export + Disable automatic hyperopt parameter export.

    +

    Common arguments: + -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). + --logfile FILE Log to the file specified. Special values are: + 'syslog', 'journald'. See the documentation for more + details. + -V, --version show program's version number and exit + -c PATH, --config PATH + Specify configuration file (default: + userdir/config.json or config.json whichever + exists). Multiple --config options may be used. Can be + set to - to read config from stdin. + -d PATH, --datadir PATH + Path to directory with historical backtesting data. + --userdir PATH, --user-data-dir PATH + Path to userdata directory.

    +

    ```

    +
    +

    Note

    +

    hyperopt-show will automatically use the latest available hyperopt results file. +You can override this using the --hyperopt-filename argument, and specify another, available filename (without path!).

    +
    +

    Examples

    +

    Print details for the epoch 168 (the number of the epoch is shown by the hyperopt-list subcommand or by Hyperopt itself during hyperoptimization run):

    +

    freqtrade hyperopt-show -n 168

    +

    Prints JSON data with details for the last best epoch (i.e., the best of all epochs):

    +

    freqtrade hyperopt-show --best -n -1 --print-json --no-header

    +

    Show trades

    +

    Print selected (or all) trades from database to screen.

    +

    ``` +usage: freqtrade show-trades [-h] [-v] [--logfile FILE] [-V] [-c PATH] + [-d PATH] [--userdir PATH] [--db-url PATH] + [--trade-ids TRADE_IDS [TRADE_IDS ...]] + [--print-json]

    +

    optional arguments: + -h, --help show this help message and exit + --db-url PATH Override trades database URL, this is useful in custom + deployments (default: sqlite:///tradesv3.sqlite for + Live Run mode, sqlite:///tradesv3.dryrun.sqlite for + Dry Run). + --trade-ids TRADE_IDS [TRADE_IDS ...] + Specify the list of trade ids. + --print-json Print output in JSON format.

    +

    Common arguments: + -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). + --logfile FILE Log to the file specified. Special values are: + 'syslog', 'journald'. See the documentation for more + details. + -V, --version show program's version number and exit + -c PATH, --config PATH + Specify configuration file (default: + userdir/config.json or config.json whichever + exists). Multiple --config options may be used. Can be + set to - to read config from stdin. + -d PATH, --datadir PATH + Path to directory with historical backtesting data. + --userdir PATH, --user-data-dir PATH + Path to userdata directory. +```

    +

    Examples

    +

    Print trades with id 2 and 3 as json

    +

    bash +freqtrade show-trades --db-url sqlite:///tradesv3.sqlite --trade-ids 2 3 --print-json

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/webhook-config/index.html b/en/2021.7/webhook-config/index.html new file mode 100644 index 000000000..761dbe26f --- /dev/null +++ b/en/2021.7/webhook-config/index.html @@ -0,0 +1,1261 @@ + + + + + + + + + + + + + + + + + + + Web Hook - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + + + + + + +

    Webhook usage

    +

    Configuration

    +

    Enable webhooks by adding a webhook-section to your configuration file, and setting webhook.enabled to true.

    +

    Sample configuration (tested using IFTTT).

    +

    json + "webhook": { + "enabled": true, + "url": "https://maker.ifttt.com/trigger/<YOUREVENT>/with/key/<YOURKEY>/", + "webhookbuy": { + "value1": "Buying {pair}", + "value2": "limit {limit:8f}", + "value3": "{stake_amount:8f} {stake_currency}" + }, + "webhookbuycancel": { + "value1": "Cancelling Open Buy Order for {pair}", + "value2": "limit {limit:8f}", + "value3": "{stake_amount:8f} {stake_currency}" + }, + "webhookbuyfill": { + "value1": "Buy Order for {pair} filled", + "value2": "at {open_rate:8f}", + "value3": "" + }, + "webhooksell": { + "value1": "Selling {pair}", + "value2": "limit {limit:8f}", + "value3": "profit: {profit_amount:8f} {stake_currency} ({profit_ratio})" + }, + "webhooksellcancel": { + "value1": "Cancelling Open Sell Order for {pair}", + "value2": "limit {limit:8f}", + "value3": "profit: {profit_amount:8f} {stake_currency} ({profit_ratio})" + }, + "webhooksellfill": { + "value1": "Sell Order for {pair} filled", + "value2": "at {close_rate:8f}.", + "value3": "" + }, + "webhookstatus": { + "value1": "Status: {status}", + "value2": "", + "value3": "" + } + },

    +

    The url in webhook.url should point to the correct url for your webhook. If you're using IFTTT (as shown in the sample above) please insert our event and key to the url.

    +

    You can set the POST body format to Form-Encoded (default) or JSON-Encoded. Use "format": "form" or "format": "json" respectively. Example configuration for Mattermost Cloud integration:

    +

    json + "webhook": { + "enabled": true, + "url": "https://<YOURSUBDOMAIN>.cloud.mattermost.com/hooks/<YOURHOOK>", + "format": "json", + "webhookstatus": { + "text": "Status: {status}" + } + },

    +

    The result would be POST request with e.g. {"text":"Status: running"} body and Content-Type: application/json header which results Status: running message in the Mattermost channel.

    +

    Different payloads can be configured for different events. Not all fields are necessary, but you should configure at least one of the dicts, otherwise the webhook will never be called.

    +

    Webhookbuy

    +

    The fields in webhook.webhookbuy are filled when the bot executes a buy. Parameters are filled using string.format. +Possible parameters are:

    +
      +
    • trade_id
    • +
    • exchange
    • +
    • pair
    • +
    • limit
    • +
    • amount
    • +
    • open_date
    • +
    • stake_amount
    • +
    • stake_currency
    • +
    • fiat_currency
    • +
    • order_type
    • +
    • current_rate
    • +
    +

    Webhookbuycancel

    +

    The fields in webhook.webhookbuycancel are filled when the bot cancels a buy order. Parameters are filled using string.format. +Possible parameters are:

    +
      +
    • trade_id
    • +
    • exchange
    • +
    • pair
    • +
    • limit
    • +
    • amount
    • +
    • open_date
    • +
    • stake_amount
    • +
    • stake_currency
    • +
    • fiat_currency
    • +
    • order_type
    • +
    • current_rate
    • +
    +

    Webhookbuyfill

    +

    The fields in webhook.webhookbuyfill are filled when the bot filled a buy order. Parameters are filled using string.format. +Possible parameters are:

    +
      +
    • trade_id
    • +
    • exchange
    • +
    • pair
    • +
    • open_rate
    • +
    • amount
    • +
    • open_date
    • +
    • stake_amount
    • +
    • stake_currency
    • +
    • fiat_currency
    • +
    +

    Webhooksell

    +

    The fields in webhook.webhooksell are filled when the bot sells a trade. Parameters are filled using string.format. +Possible parameters are:

    +
      +
    • trade_id
    • +
    • exchange
    • +
    • pair
    • +
    • gain
    • +
    • limit
    • +
    • amount
    • +
    • open_rate
    • +
    • profit_amount
    • +
    • profit_ratio
    • +
    • stake_currency
    • +
    • fiat_currency
    • +
    • sell_reason
    • +
    • order_type
    • +
    • open_date
    • +
    • close_date
    • +
    +

    Webhooksellfill

    +

    The fields in webhook.webhooksellfill are filled when the bot fills a sell order (closes a Trae). Parameters are filled using string.format. +Possible parameters are:

    +
      +
    • trade_id
    • +
    • exchange
    • +
    • pair
    • +
    • gain
    • +
    • close_rate
    • +
    • amount
    • +
    • open_rate
    • +
    • current_rate
    • +
    • profit_amount
    • +
    • profit_ratio
    • +
    • stake_currency
    • +
    • fiat_currency
    • +
    • sell_reason
    • +
    • order_type
    • +
    • open_date
    • +
    • close_date
    • +
    +

    Webhooksellcancel

    +

    The fields in webhook.webhooksellcancel are filled when the bot cancels a sell order. Parameters are filled using string.format. +Possible parameters are:

    +
      +
    • trade_id
    • +
    • exchange
    • +
    • pair
    • +
    • gain
    • +
    • limit
    • +
    • amount
    • +
    • open_rate
    • +
    • current_rate
    • +
    • profit_amount
    • +
    • profit_ratio
    • +
    • stake_currency
    • +
    • fiat_currency
    • +
    • sell_reason
    • +
    • order_type
    • +
    • open_date
    • +
    • close_date
    • +
    +

    Webhookstatus

    +

    The fields in webhook.webhookstatus are used for regular status messages (Started / Stopped / ...). Parameters are filled using string.format.

    +

    The only possible value here is {status}.

    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/2021.7/windows_installation/index.html b/en/2021.7/windows_installation/index.html new file mode 100644 index 000000000..4a2f4c02d --- /dev/null +++ b/en/2021.7/windows_installation/index.html @@ -0,0 +1,1069 @@ + + + + + + + + + + + + + + + + + + + Windows - Freqtrade + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + + + + +
    +
    + + + + + +
    +
    +
    + +
    +
    + + + + +
    +
    +
    + + + + + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + + + + + + +

    Windows installation

    +

    We strongly recommend that Windows users use Docker as this will work much easier and smoother (also more secure).

    +

    If that is not possible, try using the Windows Linux subsystem (WSL) - for which the Ubuntu instructions should work. +Otherwise, try the instructions below.

    +

    Install freqtrade manually

    +
    +

    Note

    +

    Make sure to use 64bit Windows and 64bit Python to avoid problems with backtesting or hyperopt due to the memory constraints 32bit applications have under Windows.

    +
    +
    +

    Hint

    +

    Using the Anaconda Distribution under Windows can greatly help with installation problems. Check out the Anaconda installation section in this document for more information.

    +
    +

    1. Clone the git repository

    +

    bash +git clone https://github.com/freqtrade/freqtrade.git

    +

    2. Install ta-lib

    +

    Install ta-lib according to the ta-lib documentation.

    +

    As compiling from source on windows has heavy dependencies (requires a partial visual studio installation), there is also a repository of unofficial pre-compiled windows Wheels here, which need to be downloaded and installed using pip install TA_Lib-0.4.21-cp38-cp38-win_amd64.whl (make sure to use the version matching your python version).

    +

    Freqtrade provides these dependencies for the latest 2 Python versions (3.7 and 3.8) and for 64bit Windows. +Other versions must be downloaded from the above link.

    +

    ``` powershell +cd \path\freqtrade +python -m venv .env +.env\Scripts\activate.ps1

    +

    optionally install ta-lib from wheel

    +

    Eventually adjust the below filename to match the downloaded wheel

    +

    pip install build_helpers/TA_Lib-0.4.19-cp38-cp38-win_amd64.whl +pip install -r requirements.txt +pip install -e . +freqtrade +```

    +
    +

    Use Powershell

    +

    The above installation script assumes you're using powershell on a 64bit windows. +Commands for the legacy CMD windows console may differ.

    +
    +
    +

    Thanks Owdr for the commands. Source: Issue #222

    +
    +

    Error during installation on Windows

    +

    bash +error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

    +

    Unfortunately, many packages requiring compilation don't provide a pre-built wheel. It is therefore mandatory to have a C/C++ compiler installed and available for your python environment to use.

    +

    The easiest way is to download install Microsoft Visual Studio Community here and make sure to install "Common Tools for Visual C++" to enable building C code on Windows. Unfortunately, this is a heavy download / dependency (~4Gb) so you might want to consider WSL or docker compose first.

    +
    + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/en/versions.json b/en/versions.json index 038754b0f..b5d50436d 100644 --- a/en/versions.json +++ b/en/versions.json @@ -1,4 +1,9 @@ [ + { + "version": "2021.7", + "title": "2021.7", + "aliases": [] + }, { "version": "2021.6", "title": "2021.6",