mirror of
https://github.com/freqtrade/freqtrade.git
synced 2024-11-15 04:33:57 +00:00
1 line
468 KiB
JSON
1 line
468 KiB
JSON
{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Freqtrade","text":"<p>Star</p> <p>Fork</p> <p>Download</p> <p>Follow @freqtrade</p>"},{"location":"#introduction","title":"Introduction","text":"<p>Freqtrade is a crypto-currency algorithmic trading software developed in python (3.7+) and supported on Windows, macOS and Linux.</p> <p>DISCLAIMER</p> <p>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.</p> <p>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.</p> <p>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.</p>"},{"location":"#features","title":"Features","text":"<ul> <li>Develop your Strategy: Write your strategy in python, using pandas. Example strategies to inspire you are available in the strategy repository.</li> <li>Download market data: Download historical data of the exchange and the markets your may want to trade with.</li> <li>Backtest: Test your strategy on downloaded historical data.</li> <li>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.</li> <li>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.</li> <li>Run: Test your strategy with simulated money (Dry-Run mode) or deploy it with real money (Live-Trade mode).</li> <li>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.</li> <li>Control/Monitor: Use Telegram or a REST API (start/stop the bot, show profit/loss, daily summary, current open trades results, etc.).</li> <li>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.</li> </ul>"},{"location":"#supported-exchange-marketplaces","title":"Supported exchange marketplaces","text":"<p>Please read the exchange specific notes to learn about eventual, special configurations needed for each exchange.</p> <ul> <li> Binance (*Note for binance users)</li> <li> Bittrex</li> <li> FTX</li> <li> Kraken</li> <li> potentially many others. (We cannot guarantee they will work)</li> </ul>"},{"location":"#community-tested","title":"Community tested","text":"<p>Exchanges confirmed working by the community:</p> <ul> <li> Bitvavo</li> </ul>"},{"location":"#requirements","title":"Requirements","text":""},{"location":"#hardware-requirements","title":"Hardware requirements","text":"<p>To run this bot we recommend you a linux cloud instance with a minimum of:</p> <ul> <li>2GB RAM</li> <li>1GB disk space</li> <li>2vCPU</li> </ul>"},{"location":"#software-requirements","title":"Software requirements","text":"<ul> <li>Docker (Recommended)</li> </ul> <p>Alternatively</p> <ul> <li>Python 3.7+</li> <li>pip (pip3)</li> <li>git</li> <li>TA-Lib</li> <li>virtualenv (Recommended)</li> </ul>"},{"location":"#support","title":"Support","text":""},{"location":"#help-discord-slack","title":"Help / Discord / Slack","text":"<p>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 our slack channel.</p> <p>Please check out our discord server.</p> <p>You can also join our Slack channel.</p>"},{"location":"#ready-to-try","title":"Ready to try?","text":"<p>Begin by reading our installation guide for docker (recommended), or for installation without docker.</p>"},{"location":"advanced-hyperopt/","title":"Advanced Hyperopt","text":"<p>This page explains some advanced Hyperopt topics that may require higher coding skills and Python knowledge than creation of an ordinal hyperoptimization class.</p>"},{"location":"advanced-hyperopt/#derived-hyperopt-classes","title":"Derived hyperopt classes","text":"<p>Custom hyperop classes can be derived in the same way it can be done for strategies.</p> <p>Applying to hyperoptimization, as an example, you may override how dimensions are defined in your optimization hyperspace:</p> <pre><code>class MyAwesomeHyperOpt(IHyperOpt):\n ...\n # Uses default stoploss dimension\n\nclass MyAwesomeHyperOpt2(MyAwesomeHyperOpt):\n @staticmethod\n def stoploss_space() -> List[Dimension]:\n # Override boundaries for stoploss\n return [\n Real(-0.33, -0.01, name='stoploss'),\n ]\n</code></pre> <p>and then quickly switch between hyperopt classes, running optimization process with hyperopt class you need in each particular case:</p> <pre><code>$ freqtrade hyperopt --hyperopt MyAwesomeHyperOpt --hyperopt-loss SharpeHyperOptLossDaily --strategy MyAwesomeStrategy ...\nor\n$ freqtrade hyperopt --hyperopt MyAwesomeHyperOpt2 --hyperopt-loss SharpeHyperOptLossDaily --strategy MyAwesomeStrategy ...\n</code></pre>"},{"location":"advanced-hyperopt/#creating-and-using-a-custom-loss-function","title":"Creating and using a custom loss function","text":"<p>To use a custom loss function class, make sure that the function <code>hyperopt_loss_function</code> is defined in your custom hyperopt loss class. For the sample below, you then need to add the command line parameter <code>--hyperopt-loss SuperDuperHyperOptLoss</code> to your hyperopt call so this function is being used.</p> <p>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.</p> <pre><code>from datetime import datetime\nfrom typing import Dict\n\nfrom pandas import DataFrame\n\nfrom freqtrade.optimize.hyperopt import IHyperOptLoss\n\nTARGET_TRADES = 600\nEXPECTED_MAX_PROFIT = 3.0\nMAX_ACCEPTED_TRADE_DURATION = 300\n\nclass SuperDuperHyperOptLoss(IHyperOptLoss):\n \"\"\"\n Defines the default loss function for hyperopt\n \"\"\"\n\n @staticmethod\n def hyperopt_loss_function(results: DataFrame, trade_count: int,\n min_date: datetime, max_date: datetime,\n config: Dict, processed: Dict[str, DataFrame],\n *args, **kwargs) -> float:\n \"\"\"\n Objective function, returns smaller number for better results\n This is the legacy algorithm (used until now in freqtrade).\n Weights are distributed as follows:\n * 0.4 to trade duration\n * 0.25: Avoiding trade loss\n * 1.0 to total profit, compared to the expected value (`EXPECTED_MAX_PROFIT`) defined above\n \"\"\"\n total_profit = results['profit_ratio'].sum()\n trade_duration = results['trade_duration'].mean()\n\n trade_loss = 1 - 0.25 * exp(-(trade_count - TARGET_TRADES) ** 2 / 10 ** 5.8)\n profit_loss = max(0, 1 - total_profit / EXPECTED_MAX_PROFIT)\n duration_loss = 0.4 * min(trade_duration / MAX_ACCEPTED_TRADE_DURATION, 1)\n result = trade_loss + profit_loss + duration_loss\n return result\n</code></pre> <p>Currently, the arguments are:</p> <ul> <li><code>results</code>: DataFrame containing the result The following columns are available in results (corresponds to the output-file of backtesting when used with <code>--export trades</code>): <code>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</code></li> <li><code>trade_count</code>: Amount of trades (identical to <code>len(results)</code>)</li> <li><code>min_date</code>: Start date of the timerange used</li> <li><code>min_date</code>: End date of the timerange used</li> <li><code>config</code>: Config object used (Note: Not all strategy-related parameters will be updated here if they are part of a hyperopt space).</li> <li><code>processed</code>: Dict of Dataframes with the pair as keys containing the data used for backtesting.</li> </ul> <p>This function needs to return a floating point number (<code>float</code>). Smaller numbers will be interpreted as better results. The parameters and balancing for this is up to you.</p> <p>Note</p> <p>This function is called once per iteration - so please make sure to have this as optimized as possible to not slow hyperopt down unnecessarily.</p> <p>Note</p> <p>Please keep the arguments <code>*args</code> and <code>**kwargs</code> in the interface to allow us to extend this interface later.</p>"},{"location":"advanced-setup/","title":"Advanced Post-installation Tasks","text":"<p>This page explains some advanced tasks and configuration options that can be performed after the bot installation and may be uselful in some environments.</p> <p>If you do not know what things mentioned here mean, you probably do not need it.</p>"},{"location":"advanced-setup/#running-multiple-instances-of-freqtrade","title":"Running multiple instances of Freqtrade","text":"<p>This section will show you how to run multiple bots at the same time, on the same machine.</p>"},{"location":"advanced-setup/#things-to-consider","title":"Things to consider","text":"<ul> <li>Use different database files.</li> <li>Use different Telegram bots (requires multiple different configuration files; applies only when Telegram is enabled).</li> <li>Use different ports (applies only when Freqtrade REST API webserver is enabled).</li> </ul>"},{"location":"advanced-setup/#different-database-files","title":"Different database files","text":"<p>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.</p> <p>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 <code>tradesv3.sqlite</code> and for dry-run it will be <code>tradesv3.dryrun.sqlite</code>.</p> <p>The optional argument to the trade command used to specify the path of these files is <code>--db-url</code>, 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.</p> <pre><code>freqtrade trade -c MyConfig.json -s MyStrategy\n# is equivalent to\nfreqtrade trade -c MyConfig.json -s MyStrategy --db-url sqlite:///tradesv3.dryrun.sqlite\n</code></pre> <p>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.</p> <p>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):</p> <pre><code># Terminal 1:\nfreqtrade trade -c MyConfigBTC.json -s MyCustomStrategy --db-url sqlite:///user_data/tradesBTC.dryrun.sqlite\n# Terminal 2:\nfreqtrade trade -c MyConfigUSDT.json -s MyCustomStrategy --db-url sqlite:///user_data/tradesUSDT.dryrun.sqlite\n</code></pre> <p>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:</p> <pre><code># Terminal 1:\nfreqtrade trade -c MyConfigBTC.json -s MyCustomStrategy --db-url sqlite:///user_data/tradesBTC.live.sqlite\n# Terminal 2:\nfreqtrade trade -c MyConfigUSDT.json -s MyCustomStrategy --db-url sqlite:///user_data/tradesUSDT.live.sqlite\n</code></pre> <p>For more information regarding usage of the sqlite databases, for example to manually enter or remove trades, please refer to the SQL Cheatsheet.</p>"},{"location":"advanced-setup/#configure-the-bot-running-as-a-systemd-service","title":"Configure the bot running as a systemd service","text":"<p>Copy the <code>freqtrade.service</code> file to your systemd user directory (usually <code>~/.config/systemd/user</code>) and update <code>WorkingDirectory</code> and <code>ExecStart</code> to match your setup.</p> <p>Note</p> <p>Certain systems (like Raspbian) don't load service unit files from the user directory. In this case, copy <code>freqtrade.service</code> into <code>/etc/systemd/user/</code> (requires superuser permissions).</p> <p>After that you can start the daemon with:</p> <pre><code>systemctl --user start freqtrade\n</code></pre> <p>For this to be persistent (run when user is logged out) you'll need to enable <code>linger</code> for your freqtrade user.</p> <pre><code>sudo loginctl enable-linger \"$USER\"\n</code></pre> <p>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 <code>internals.sd_notify</code> parameter is set to true in the configuration or the <code>--sd-notify</code> 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. </p> <p>The <code>freqtrade.service.watchdog</code> file contains an example of the service unit configuration file which uses systemd as the watchdog.</p> <p>Note</p> <p>The sd_notify communication between the bot and the systemd service manager will not work if the bot runs in a Docker container.</p>"},{"location":"advanced-setup/#advanced-logging","title":"Advanced Logging","text":"<p>On many Linux systems the bot can be configured to send its log messages to <code>syslog</code> or <code>journald</code> system services. Logging to a remote <code>syslog</code> server is also available on Windows. The special values for the <code>--logfile</code> command line option can be used for this.</p>"},{"location":"advanced-setup/#logging-to-syslog","title":"Logging to syslog","text":"<p>To send Freqtrade log messages to a local or remote <code>syslog</code> service use the <code>--logfile</code> command line option with the value in the following format:</p> <ul> <li><code>--logfile syslog:<syslog_address></code> -- send log messages to <code>syslog</code> service using the <code><syslog_address></code> as the syslog address.</li> </ul> <p>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 <code>:</code> character.</p> <p>So, the following are the examples of possible usages:</p> <ul> <li><code>--logfile syslog:/dev/log</code> -- log to syslog (rsyslog) using the <code>/dev/log</code> socket, suitable for most systems.</li> <li><code>--logfile syslog</code> -- same as above, the shortcut for <code>/dev/log</code>.</li> <li><code>--logfile syslog:/var/run/syslog</code> -- log to syslog (rsyslog) using the <code>/var/run/syslog</code> socket. Use this on MacOS.</li> <li><code>--logfile syslog:localhost:514</code> -- log to local syslog using UDP socket, if it listens on port 514.</li> <li><code>--logfile syslog:<ip>:514</code> -- log to remote syslog at IP address and port 514. This may be used on Windows for remote logging to an external syslog server.</li> </ul> <p>Log messages are send to <code>syslog</code> with the <code>user</code> facility. So you can see them with the following commands:</p> <ul> <li><code>tail -f /var/log/user</code>, or </li> <li>install a comprehensive graphical viewer (for instance, 'Log File Viewer' for Ubuntu).</li> </ul> <p>On many systems <code>syslog</code> (<code>rsyslog</code>) fetches data from <code>journald</code> (and vice versa), so both <code>--logfile syslog</code> or <code>--logfile journald</code> can be used and the messages be viewed with both <code>journalctl</code> and a syslog viewer utility. You can combine this in any way which suites you better.</p> <p>For <code>rsyslog</code> the messages from the bot can be redirected into a separate dedicated log file. To achieve this, add <pre><code>if $programname startswith \"freqtrade\" then -/var/log/freqtrade.log\n</code></pre> to one of the rsyslog configuration files, for example at the end of the <code>/etc/rsyslog.d/50-default.conf</code>.</p> <p>For <code>syslog</code> (<code>rsyslog</code>), 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 <code>/etc/rsyslog.conf</code>: <pre><code># Filter duplicated messages\n$RepeatedMsgReduction on\n</code></pre></p>"},{"location":"advanced-setup/#logging-to-journald","title":"Logging to journald","text":"<p>This needs the <code>systemd</code> 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.</p> <p>To send Freqtrade log messages to <code>journald</code> system service use the <code>--logfile</code> command line option with the value in the following format:</p> <ul> <li><code>--logfile journald</code> -- send log messages to <code>journald</code>.</li> </ul> <p>Log messages are send to <code>journald</code> with the <code>user</code> facility. So you can see them with the following commands:</p> <ul> <li><code>journalctl -f</code> -- shows Freqtrade log messages sent to <code>journald</code> along with other log messages fetched by <code>journald</code>.</li> <li><code>journalctl -f -u freqtrade.service</code> -- this command can be used when the bot is run as a <code>systemd</code> service.</li> </ul> <p>There are many other options in the <code>journalctl</code> utility to filter the messages, see manual pages for this utility.</p> <p>On many systems <code>syslog</code> (<code>rsyslog</code>) fetches data from <code>journald</code> (and vice versa), so both <code>--logfile syslog</code> or <code>--logfile journald</code> can be used and the messages be viewed with both <code>journalctl</code> and a syslog viewer utility. You can combine this in any way which suites you better.</p>"},{"location":"backtesting/","title":"Backtesting","text":"<p>This page explains how to validate your strategy performance by using Backtesting.</p> <p>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.</p>"},{"location":"backtesting/#backtesting-command-reference","title":"Backtesting command reference","text":"<pre><code>usage: freqtrade backtesting [-h] [-v] [--logfile FILE] [-V] [-c PATH]\n [-d PATH] [--userdir PATH] [-s NAME]\n [--strategy-path PATH] [-i TIMEFRAME]\n [--timerange TIMERANGE]\n [--data-format-ohlcv {json,jsongz,hdf5}]\n [--max-open-trades INT]\n [--stake-amount STAKE_AMOUNT] [--fee FLOAT]\n [--eps] [--dmmp] [--enable-protections]\n [--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]]\n [--export EXPORT] [--export-filename PATH]\n\noptional arguments:\n -h, --help show this help message and exit\n -i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME\n Specify ticker interval (`1m`, `5m`, `30m`, `1h`,\n `1d`).\n --timerange TIMERANGE\n Specify what timerange of data to use.\n --data-format-ohlcv {json,jsongz,hdf5}\n Storage format for downloaded candle (OHLCV) data.\n (default: `None`).\n --max-open-trades INT\n Override the value of the `max_open_trades`\n configuration setting.\n --stake-amount STAKE_AMOUNT\n Override the value of the `stake_amount` configuration\n setting.\n --fee FLOAT Specify fee ratio. Will be applied twice (on trade\n entry and exit).\n --eps, --enable-position-stacking\n Allow buying the same pair multiple times (position\n stacking).\n --dmmp, --disable-max-market-positions\n Disable applying `max_open_trades` during backtest\n (same as setting `max_open_trades` to a very high\n number).\n --enable-protections, --enableprotections\n Enable protections for backtesting.Will slow\n backtesting down by a considerable amount, but will\n include configured protections\n --strategy-list STRATEGY_LIST [STRATEGY_LIST ...]\n Provide a space-separated list of strategies to\n backtest. Please note that ticker-interval needs to be\n set either in config or via command line. When using\n this together with `--export trades`, the strategy-\n name is injected into the filename (so `backtest-\n data.json` becomes `backtest-data-\n DefaultStrategy.json`\n --export EXPORT Export backtest results, argument are: trades.\n Example: `--export=trades`\n --export-filename PATH\n Save backtest results to the file with this filename.\n Requires `--export` to be set as well. Example:\n `--export-filename=user_data/backtest_results/backtest\n _today.json`\n\nCommon arguments:\n -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).\n --logfile FILE Log to the file specified. Special values are:\n 'syslog', 'journald'. See the documentation for more\n details.\n -V, --version show program's version number and exit\n -c PATH, --config PATH\n Specify configuration file (default:\n `userdir/config.json` or `config.json` whichever\n exists). Multiple --config options may be used. Can be\n set to `-` to read config from stdin.\n -d PATH, --datadir PATH\n Path to directory with historical backtesting data.\n --userdir PATH, --user-data-dir PATH\n Path to userdata directory.\n\nStrategy arguments:\n -s NAME, --strategy NAME\n Specify strategy class name which will be used by the\n bot.\n --strategy-path PATH Specify additional strategy lookup path.\n</code></pre>"},{"location":"backtesting/#test-your-strategy-with-backtesting","title":"Test your strategy with Backtesting","text":"<p>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.</p> <p>Backtesting will use the crypto-currencies (pairs) from your config file and load historical candle (OHCLV) data from <code>user_data/data/<exchange></code> by default. If no data is available for the exchange / pair / timeframe combination, backtesting will ask you to download them first using <code>freqtrade download-data</code>. For details on downloading, please refer to the Data Downloading section in the documentation.</p> <p>The result of backtesting will confirm if your bot has better odds of making a profit than a loss.</p> <p>Using dynamic pairlists for backtesting</p> <p>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, reproducability of backtesting-results cannot be guaranteed. Please read the pairlists documentation for more information.</p> <p>To achieve reproducible results, best generate a pairlist via the <code>test-pairlist</code> command and use that as static pairlist.</p>"},{"location":"backtesting/#run-a-backtesting-against-the-currencies-listed-in-your-config-file","title":"Run a backtesting against the currencies listed in your config file","text":""},{"location":"backtesting/#with-5-min-candle-ohlcv-data-per-default","title":"With 5 min candle (OHLCV) data (per default)","text":"<pre><code>freqtrade backtesting\n</code></pre>"},{"location":"backtesting/#with-1-min-candle-ohlcv-data","title":"With 1 min candle (OHLCV) data","text":"<pre><code>freqtrade backtesting --timeframe 1m\n</code></pre>"},{"location":"backtesting/#using-a-different-on-disk-historical-candle-ohlcv-data-source","title":"Using a different on-disk historical candle (OHLCV) data source","text":"<p>Assume you downloaded the history data from the Bittrex exchange and kept it in the <code>user_data/data/bittrex-20180101</code> directory. You can then use this data for backtesting as follows:</p> <pre><code>freqtrade --datadir user_data/data/bittrex-20180101 backtesting\n</code></pre>"},{"location":"backtesting/#with-a-custom-strategy-file","title":"With a (custom) strategy file","text":"<pre><code>freqtrade backtesting -s SampleStrategy\n</code></pre> <p>Where <code>-s SampleStrategy</code> refers to the class name within the strategy file <code>sample_strategy.py</code> found in the <code>freqtrade/user_data/strategies</code> directory.</p>"},{"location":"backtesting/#comparing-multiple-strategies","title":"Comparing multiple Strategies","text":"<pre><code>freqtrade backtesting --strategy-list SampleStrategy1 AwesomeStrategy --timeframe 5m\n</code></pre> <p>Where <code>SampleStrategy1</code> and <code>AwesomeStrategy</code> refer to class names of strategies.</p>"},{"location":"backtesting/#exporting-trades-to-file","title":"Exporting trades to file","text":"<pre><code>freqtrade backtesting --export trades --config config.json --strategy SampleStrategy\n</code></pre> <p>The exported trades can be used for further analysis, or can be used by the plotting script <code>plot_dataframe.py</code> in the scripts directory.</p>"},{"location":"backtesting/#exporting-trades-to-file-specifying-a-custom-filename","title":"Exporting trades to file specifying a custom filename","text":"<pre><code>freqtrade backtesting --export trades --export-filename=backtest_samplestrategy.json\n</code></pre> <p>Please also read about the strategy startup period.</p>"},{"location":"backtesting/#supplying-custom-fee-value","title":"Supplying custom fee value","text":"<p>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 <code>--fee</code> 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).</p> <p>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:</p> <pre><code>freqtrade backtesting --fee 0.001\n</code></pre> <p>Note</p> <p>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.</p>"},{"location":"backtesting/#running-backtest-with-smaller-testset-by-using-timerange","title":"Running backtest with smaller testset by using timerange","text":"<p>Use the <code>--timerange</code> argument to change how much of the testset you want to use.</p> <p>For example, running backtesting with the <code>--timerange=20190501-</code> option will use all available data starting with May 1<sup>st</sup>, 2019 from your inputdata.</p> <pre><code>freqtrade backtesting --timerange=20190501-\n</code></pre> <p>You can also specify particular dates or a range span indexed by start and stop.</p> <p>The full timerange specification:</p> <ul> <li>Use tickframes till 2018/01/31: <code>--timerange=-20180131</code></li> <li>Use tickframes since 2018/01/31: <code>--timerange=20180131-</code></li> <li>Use tickframes since 2018/01/31 till 2018/03/01 : <code>--timerange=20180131-20180301</code></li> <li>Use tickframes between POSIX timestamps 1527595200 1527618600: <code>--timerange=1527595200-1527618600</code></li> </ul>"},{"location":"backtesting/#understand-the-backtesting-result","title":"Understand the backtesting result","text":"<p>The most important in the backtesting is to understand the result.</p> <p>A backtesting result will look like that:</p> <pre><code>========================================================= BACKTESTING REPORT ========================================================\n| Pair | Buys | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Wins | Draws | Losses |\n|:---------|-------:|---------------:|---------------:|-----------------:|---------------:|:---------------|------:|-------:|--------:|\n| ADA/BTC | 35 | -0.11 | -3.88 | -0.00019428 | -1.94 | 4:35:00 | 14 | 0 | 21 |\n| ARK/BTC | 11 | -0.41 | -4.52 | -0.00022647 | -2.26 | 2:03:00 | 3 | 0 | 8 |\n| BTS/BTC | 32 | 0.31 | 9.78 | 0.00048938 | 4.89 | 5:05:00 | 18 | 0 | 14 |\n| DASH/BTC | 13 | -0.08 | -1.07 | -0.00005343 | -0.53 | 4:39:00 | 6 | 0 | 7 |\n| ENG/BTC | 18 | 1.36 | 24.54 | 0.00122807 | 12.27 | 2:50:00 | 8 | 0 | 10 |\n| EOS/BTC | 36 | 0.08 | 3.06 | 0.00015304 | 1.53 | 3:34:00 | 16 | 0 | 20 |\n| ETC/BTC | 26 | 0.37 | 9.51 | 0.00047576 | 4.75 | 6:14:00 | 11 | 0 | 15 |\n| ETH/BTC | 33 | 0.30 | 9.96 | 0.00049856 | 4.98 | 7:31:00 | 16 | 0 | 17 |\n| IOTA/BTC | 32 | 0.03 | 1.09 | 0.00005444 | 0.54 | 3:12:00 | 14 | 0 | 18 |\n| LSK/BTC | 15 | 1.75 | 26.26 | 0.00131413 | 13.13 | 2:58:00 | 6 | 0 | 9 |\n| LTC/BTC | 32 | -0.04 | -1.38 | -0.00006886 | -0.69 | 4:49:00 | 11 | 0 | 21 |\n| NANO/BTC | 17 | 1.26 | 21.39 | 0.00107058 | 10.70 | 1:55:00 | 10 | 0 | 7 |\n| NEO/BTC | 23 | 0.82 | 18.97 | 0.00094936 | 9.48 | 2:59:00 | 10 | 0 | 13 |\n| REQ/BTC | 9 | 1.17 | 10.54 | 0.00052734 | 5.27 | 3:47:00 | 4 | 0 | 5 |\n| XLM/BTC | 16 | 1.22 | 19.54 | 0.00097800 | 9.77 | 3:15:00 | 7 | 0 | 9 |\n| XMR/BTC | 23 | -0.18 | -4.13 | -0.00020696 | -2.07 | 5:30:00 | 12 | 0 | 11 |\n| XRP/BTC | 35 | 0.66 | 22.96 | 0.00114897 | 11.48 | 3:49:00 | 12 | 0 | 23 |\n| ZEC/BTC | 22 | -0.46 | -10.18 | -0.00050971 | -5.09 | 2:22:00 | 7 | 0 | 15 |\n| TOTAL | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 0 | 243 |\n========================================================= SELL REASON STATS =========================================================\n| Sell Reason | Sells | Wins | Draws | Losses |\n|:-------------------|--------:|------:|-------:|--------:|\n| trailing_stop_loss | 205 | 150 | 0 | 55 |\n| stop_loss | 166 | 0 | 0 | 166 |\n| sell_signal | 56 | 36 | 0 | 20 |\n| force_sell | 2 | 0 | 0 | 2 |\n====================================================== LEFT OPEN TRADES REPORT ======================================================\n| Pair | Buys | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Wins | Draws | Losses |\n|:---------|-------:|---------------:|---------------:|-----------------:|---------------:|:---------------|------:|-------:|--------:|\n| ADA/BTC | 1 | 0.89 | 0.89 | 0.00004434 | 0.44 | 6:00:00 | 1 | 0 | 0 |\n| LTC/BTC | 1 | 0.68 | 0.68 | 0.00003421 | 0.34 | 2:00:00 | 1 | 0 | 0 |\n| TOTAL | 2 | 0.78 | 1.57 | 0.00007855 | 0.78 | 4:00:00 | 2 | 0 | 0 |\n=============== SUMMARY METRICS ===============\n| Metric | Value |\n|-----------------------+---------------------|\n| Backtesting from | 2019-01-01 00:00:00 |\n| Backtesting to | 2019-05-01 00:00:00 |\n| Max open trades | 3 |\n| | |\n| Total trades | 429 |\n| Total Profit % | 152.41% |\n| Trades per day | 3.575 |\n| | |\n| Best Pair | LSK/BTC 26.26% |\n| Worst Pair | ZEC/BTC -10.18% |\n| Best Trade | LSK/BTC 4.25% |\n| Worst Trade | ZEC/BTC -10.25% |\n| Best day | 25.27% |\n| Worst day | -30.67% |\n| Avg. Duration Winners | 4:23:00 |\n| Avg. Duration Loser | 6:55:00 |\n| | |\n| Max Drawdown | 50.63% |\n| Drawdown Start | 2019-02-15 14:10:00 |\n| Drawdown End | 2019-04-11 18:15:00 |\n| Market change | -5.88% |\n===============================================\n</code></pre>"},{"location":"backtesting/#backtesting-report-table","title":"Backtesting report table","text":"<p>The 1<sup>st</sup> table contains all trades the bot made, including \"left open trades\".</p> <p>The last line will give you the overall performance of your strategy, here:</p> <pre><code>| TOTAL | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 243 |\n</code></pre> <p>The bot has made <code>429</code> trades for an average duration of <code>4:12:00</code>, with a performance of <code>76.20%</code> (profit), that means it has earned a total of <code>0.00762792 BTC</code> starting with a capital of 0.01 BTC.</p> <p>The column <code>avg profit %</code> shows the average profit for all trades made while the column <code>cum profit %</code> sums up all the profits/losses. The column <code>tot profit %</code> shows instead the total profit % in relation to allocated capital (<code>max_open_trades * stake_amount</code>). In the above results we have <code>max_open_trades=2</code> and <code>stake_amount=0.005</code> in config so <code>tot_profit %</code> will be <code>(76.20/100) * (0.005 * 2) =~ 0.00762792 BTC</code>.</p> <p>Your strategy performance is influenced by your buy strategy, your sell strategy, and also by the <code>minimal_roi</code> and <code>stop_loss</code> you have set.</p> <p>For example, if your <code>minimal_roi</code> is only <code>\"0\": 0.01</code> you cannot expect the bot to make more profit than 1% (because it will sell every time a trade reaches 1%).</p> <pre><code>\"minimal_roi\": {\n \"0\": 0.01\n},\n</code></pre> <p>On the other hand, if you set a too high <code>minimal_roi</code> like <code>\"0\": 0.55</code> (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.</p>"},{"location":"backtesting/#sell-reasons-table","title":"Sell reasons table","text":"<p>The 2<sup>nd</sup> 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 <code>sell_signal</code> trades are losses, so you should work on improving the sell signal, or consider disabling it).</p>"},{"location":"backtesting/#left-open-trades-table","title":"Left open trades table","text":"<p>The 3<sup>rd</sup> table contains all trades the bot had to <code>forcesell</code> 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.</p>"},{"location":"backtesting/#summary-metrics","title":"Summary metrics","text":"<p>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.</p> <pre><code>=============== SUMMARY METRICS ===============\n| Metric | Value |\n|-----------------------+---------------------|\n| Backtesting from | 2019-01-01 00:00:00 |\n| Backtesting to | 2019-05-01 00:00:00 |\n| Max open trades | 3 |\n| | |\n| Total trades | 429 |\n| Total Profit % | 152.41% |\n| Trades per day | 3.575 |\n| | |\n| Best Pair | LSK/BTC 26.26% |\n| Worst Pair | ZEC/BTC -10.18% |\n| Best Trade | LSK/BTC 4.25% |\n| Worst Trade | ZEC/BTC -10.25% |\n| Best day | 25.27% |\n| Worst day | -30.67% |\n| Avg. Duration Winners | 4:23:00 |\n| Avg. Duration Loser | 6:55:00 |\n| | |\n| Max Drawdown | 50.63% |\n| Drawdown Start | 2019-02-15 14:10:00 |\n| Drawdown End | 2019-04-11 18:15:00 |\n| Market change | -5.88% |\n===============================================\n</code></pre> <ul> <li><code>Backtesting from</code> / <code>Backtesting to</code>: Backtesting range (usually defined with the <code>--timerange</code> option).</li> <li><code>Max open trades</code>: Setting of <code>max_open_trades</code> (or <code>--max-open-trades</code>) - or number of pairs in the pairlist (whatever is lower).</li> <li><code>Total trades</code>: Identical to the total trades of the backtest output table.</li> <li><code>Total Profit %</code>: Total profit. Aligned to the <code>TOTAL</code> row's <code>Tot Profit %</code> from the first table.</li> <li><code>Trades per day</code>: Total trades divided by the backtesting duration in days (this will give you information about how many trades to expect from the strategy).</li> <li><code>Best Pair</code> / <code>Worst Pair</code>: Best and worst performing pair, and it's corresponding <code>Cum Profit %</code>.</li> <li><code>Best Trade</code> / <code>Worst Trade</code>: Biggest winning trade and biggest losing trade</li> <li><code>Best day</code> / <code>Worst day</code>: Best and worst day based on daily profit.</li> <li><code>Avg. Duration Winners</code> / <code>Avg. Duration Loser</code>: Average durations for winning and losing trades.</li> <li><code>Max Drawdown</code>: Maximum drawdown experienced. For example, the value of 50% means that from highest to subsequent lowest point, a 50% drop was experienced).</li> <li><code>Drawdown Start</code> / <code>Drawdown End</code>: Start and end datetime for this largest drawdown (can also be visualized via the <code>plot-dataframe</code> sub-command).</li> <li><code>Market change</code>: 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.</li> </ul>"},{"location":"backtesting/#assumptions-made-by-backtesting","title":"Assumptions made by backtesting","text":"<p>Since backtesting lacks some detailed information about what happens within a candle, it needs to take a few assumptions:</p> <ul> <li>Buys happen at open-price</li> <li>Sell-signal sells happen at open-price of the consecutive candle</li> <li>Sell-signal is favored over Stoploss, because sell-signals are assumed to trigger on candle's open</li> <li>ROI<ul> <li>sells are compared to high - but the ROI value is used (e.g. ROI = 2%, high=5% - so the sell will be at 2%)</li> <li>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</li> <li>Forcesells caused by <code><N>=-1</code> ROI entries use low as sell value, unless N falls on the candle open (e.g. <code>120: -1</code> for 1h candles)</li> </ul> </li> <li>Stoploss sells happen exactly at stoploss price, even if low was lower, but the loss will be <code>2 * fees</code> higher than the stoploss price</li> <li>Stoploss is evaluated before ROI within one candle. So you can often see more trades with the <code>stoploss</code> sell reason comparing to the results obtained with the same strategy in the Dry Run/Live Trade modes</li> <li>Low happens before high for stoploss, protecting capital first</li> <li>Trailing stoploss<ul> <li>High happens first - adjusting stoploss</li> <li>Low uses the adjusted stoploss (so sells with large high-low difference are backtested correctly)</li> <li>ROI applies before trailing-stop, ensuring profits are \"top-capped\" at ROI if both ROI and trailing stop applies</li> </ul> </li> <li>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)</li> <li>Evaluation sequence (if multiple signals happen on the same candle)<ul> <li>ROI (if not stoploss)</li> <li>Sell-signal</li> <li>Stoploss</li> </ul> </li> </ul> <p>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.</p> <p>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.</p>"},{"location":"backtesting/#further-backtest-result-analysis","title":"Further backtest-result analysis","text":"<p>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.</p>"},{"location":"backtesting/#backtesting-multiple-strategies","title":"Backtesting multiple strategies","text":"<p>To compare multiple strategies, a list of Strategies can be provided to backtesting.</p> <p>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.</p> <p>All listed Strategies need to be in the same directory.</p> <pre><code>freqtrade backtesting --timerange 20180401-20180410 --timeframe 5m --strategy-list Strategy001 Strategy002 --export trades\n</code></pre> <p>This will save the results to <code>user_data/backtest_results/backtest-result-<strategy>.json</code>, 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.</p> <pre><code>=========================================================== STRATEGY SUMMARY ===========================================================\n| Strategy | Buys | Avg Profit % | Cum Profit % | Tot Profit BTC | Tot Profit % | Avg Duration | Wins | Draws | Losses |\n|:------------|-------:|---------------:|---------------:|-----------------:|---------------:|:---------------|------:|-------:|-------:|\n| Strategy1 | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 0 | 243 |\n| Strategy2 | 1487 | -0.13 | -197.58 | -0.00988917 | -98.79 | 4:43:00 | 662 | 0 | 825 |\n</code></pre>"},{"location":"backtesting/#next-step","title":"Next step","text":"<p>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</p>"},{"location":"bot-basics/","title":"Freqtrade basics","text":"<p>This page provides you some basic concepts on how Freqtrade works and operates.</p>"},{"location":"bot-basics/#freqtrade-terminology","title":"Freqtrade terminology","text":"<ul> <li>Strategy: Your trading strategy, telling the bot what to do.</li> <li>Trade: Open position.</li> <li>Open Order: Order which is currently placed on the exchange, and is not yet complete.</li> <li>Pair: Tradable pair, usually in the format of Quote/Base (e.g. XRP/USDT).</li> <li>Timeframe: Candle length to use (e.g. <code>\"5m\"</code>, <code>\"1h\"</code>, ...).</li> <li>Indicators: Technical indicators (SMA, EMA, RSI, ...).</li> <li>Limit order: Limit orders which execute at the defined limit price or better.</li> <li>Market order: Guaranteed to fill, may move price depending on the order size.</li> </ul>"},{"location":"bot-basics/#fee-handling","title":"Fee handling","text":"<p>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.).</p>"},{"location":"bot-basics/#bot-execution-logic","title":"Bot execution logic","text":"<p>Starting freqtrade in dry-run or live mode (using <code>freqtrade trade</code>) will start the bot and start the bot iteration loop. By default, loop runs every few seconds (<code>internals.process_throttle_secs</code>) and does roughly the following in the following sequence:</p> <ul> <li>Fetch open trades from persistence.</li> <li>Calculate current list of tradable pairs.</li> <li>Download ohlcv data for the pairlist including all informative pairs This step is only executed once per Candle to avoid unnecessary network traffic.</li> <li>Call <code>bot_loop_start()</code> strategy callback.</li> <li>Analyze strategy per pair.<ul> <li>Call <code>populate_indicators()</code></li> <li>Call <code>populate_buy_trend()</code></li> <li>Call <code>populate_sell_trend()</code></li> </ul> </li> <li>Check timeouts for open orders.<ul> <li>Calls <code>check_buy_timeout()</code> strategy callback for open buy orders.</li> <li>Calls <code>check_sell_timeout()</code> strategy callback for open sell orders.</li> </ul> </li> <li>Verifies existing positions and eventually places sell orders.<ul> <li>Considers stoploss, ROI and sell-signal.</li> <li>Determine sell-price based on <code>ask_strategy</code> configuration setting.</li> <li>Before a sell order is placed, <code>confirm_trade_exit()</code> strategy callback is called.</li> </ul> </li> <li>Check if trade-slots are still available (if <code>max_open_trades</code> is reached).</li> <li>Verifies buy signal trying to enter new positions.<ul> <li>Determine buy-price based on <code>bid_strategy</code> configuration setting.</li> <li>Before a buy order is placed, <code>confirm_trade_entry()</code> strategy callback is called.</li> </ul> </li> </ul> <p>This loop will be repeated again and again until the bot is stopped.</p>"},{"location":"bot-basics/#backtesting-hyperopt-execution-logic","title":"Backtesting / Hyperopt execution logic","text":"<p>backtesting or hyperopt do only part of the above logic, since most of the trading operations are fully simulated.</p> <ul> <li>Load historic data for configured pairlist.</li> <li>Calls <code>bot_loop_start()</code> once.</li> <li>Calculate indicators (calls <code>populate_indicators()</code> once per pair).</li> <li>Calculate buy / sell signals (calls <code>populate_buy_trend()</code> and <code>populate_sell_trend()</code> once per pair)</li> <li>Loops per candle simulating entry and exit points.</li> <li>Generate backtest report output</li> </ul> <p>Note</p> <p>Both Backtesting and Hyperopt include exchange default Fees in the calculation. Custom fees can be passed to backtesting / hyperopt by specifying the <code>--fee</code> argument.</p>"},{"location":"bot-usage/","title":"Start the bot","text":"<p>This page explains the different parameters of the bot and how to run it.</p> <p>Note</p> <p>If you've used <code>setup.sh</code>, don't forget to activate your virtual environment (<code>source .env/bin/activate</code>) before running freqtrade commands.</p> <p>Up-to-date clock</p> <p>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.</p>"},{"location":"bot-usage/#bot-commands","title":"Bot commands","text":"<pre><code>usage: freqtrade [-h] [-V]\n {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}\n ...\n\nFree, open source crypto trading bot\n\npositional arguments:\n {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}\n trade Trade module.\n create-userdir Create user-data directory.\n new-config Create new config\n new-hyperopt Create new hyperopt\n new-strategy Create new strategy\n download-data Download backtesting data.\n convert-data Convert candle (OHLCV) data from one format to\n another.\n convert-trade-data Convert trade data from one format to another.\n backtesting Backtesting module.\n edge Edge module.\n hyperopt Hyperopt module.\n hyperopt-list List Hyperopt results\n hyperopt-show Show details of Hyperopt results\n list-exchanges Print available exchanges.\n list-hyperopts Print available hyperopt classes.\n list-markets Print markets on exchange.\n list-pairs Print pairs on exchange.\n list-strategies Print available strategies.\n list-timeframes Print available timeframes for the exchange.\n show-trades Show trades.\n test-pairlist Test your pairlist configuration.\n plot-dataframe Plot candles with indicators.\n plot-profit Generate plot showing profits.\n\noptional arguments:\n -h, --help show this help message and exit\n -V, --version show program's version number and exit\n</code></pre>"},{"location":"bot-usage/#bot-trading-commands","title":"Bot trading commands","text":"<pre><code>usage: freqtrade trade [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]\n [--userdir PATH] [-s NAME] [--strategy-path PATH]\n [--db-url PATH] [--sd-notify] [--dry-run]\n\noptional arguments:\n -h, --help show this help message and exit\n --db-url PATH Override trades database URL, this is useful in custom\n deployments (default: `sqlite:///tradesv3.sqlite` for\n Live Run mode, `sqlite:///tradesv3.dryrun.sqlite` for\n Dry Run).\n --sd-notify Notify systemd service manager.\n --dry-run Enforce dry-run for trading (removes Exchange secrets\n and simulates trades).\n\nCommon arguments:\n -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).\n --logfile FILE Log to the file specified. Special values are:\n 'syslog', 'journald'. See the documentation for more\n details.\n -V, --version show program's version number and exit\n -c PATH, --config PATH\n Specify configuration file (default:\n `userdir/config.json` or `config.json` whichever\n exists). Multiple --config options may be used. Can be\n set to `-` to read config from stdin.\n -d PATH, --datadir PATH\n Path to directory with historical backtesting data.\n --userdir PATH, --user-data-dir PATH\n Path to userdata directory.\n\nStrategy arguments:\n -s NAME, --strategy NAME\n Specify strategy class name which will be used by the\n bot.\n --strategy-path PATH Specify additional strategy lookup path.\n</code></pre>"},{"location":"bot-usage/#how-to-specify-which-configuration-file-be-used","title":"How to specify which configuration file be used?","text":"<p>The bot allows you to select which configuration file you want to use by means of the <code>-c/--config</code> command line option:</p> <pre><code>freqtrade trade -c path/far/far/away/config.json\n</code></pre> <p>Per default, the bot loads the <code>config.json</code> configuration file from the current working directory.</p>"},{"location":"bot-usage/#how-to-use-multiple-configuration-files","title":"How to use multiple configuration files?","text":"<p>The bot allows you to use multiple configuration files by specifying multiple <code>-c/--config</code> 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.</p> <p>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):</p> <pre><code>freqtrade trade -c ./config.json\n</code></pre> <p>and specify both configuration files when running in the normal Live Trade Mode:</p> <pre><code>freqtrade trade -c ./config.json -c path/to/secrets/keys.config.json\n</code></pre> <p>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.</p> <p>See more details on this technique with examples in the documentation page on configuration.</p>"},{"location":"bot-usage/#where-to-store-custom-data","title":"Where to store custom data","text":"<p>Freqtrade allows the creation of a user-data directory using <code>freqtrade create-userdir --userdir someDirectory</code>. This directory will look as follows:</p> <pre><code>user_data/\n\u251c\u2500\u2500 backtest_results\n\u251c\u2500\u2500 data\n\u251c\u2500\u2500 hyperopts\n\u251c\u2500\u2500 hyperopt_results\n\u251c\u2500\u2500 plot\n\u2514\u2500\u2500 strategies\n</code></pre> <p>You can add the entry \"user_data_dir\" setting to your configuration, to always point your bot to this directory. Alternatively, pass in <code>--userdir</code> to every command. The bot will fail to start if the directory does not exist, but will create necessary subdirectories.</p> <p>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.</p> <p>It is recommended to use version control to keep track of changes to your strategies.</p>"},{"location":"bot-usage/#how-to-use-strategy","title":"How to use --strategy?","text":"<p>This parameter will allow you to load your custom strategy class. To test the bot installation, you can use the <code>SampleStrategy</code> installed by the <code>create-userdir</code> subcommand (usually <code>user_data/strategy/sample_strategy.py</code>).</p> <p>The bot will search your strategy file within <code>user_data/strategies</code>. To use other directories, please read the next section about <code>--strategy-path</code>.</p> <p>To load a strategy, simply pass the class name (e.g.: <code>CustomStrategy</code>) in this parameter.</p> <p>Example: In <code>user_data/strategies</code> you have a file <code>my_awesome_strategy.py</code> which has a strategy class called <code>AwesomeStrategy</code> to load it:</p> <pre><code>freqtrade trade --strategy AwesomeStrategy\n</code></pre> <p>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).</p> <p>Learn more about strategy file in Strategy Customization.</p>"},{"location":"bot-usage/#how-to-use-strategy-path","title":"How to use --strategy-path?","text":"<p>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!):</p> <pre><code>freqtrade trade --strategy AwesomeStrategy --strategy-path /some/directory\n</code></pre>"},{"location":"bot-usage/#how-to-install-a-strategy","title":"How to install a strategy?","text":"<p>This is very simple. Copy paste your strategy file into the directory <code>user_data/strategies</code> or use <code>--strategy-path</code>. And voila, the bot is ready to use it.</p>"},{"location":"bot-usage/#how-to-use-db-url","title":"How to use --db-url?","text":"<p>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 <code>--db-url</code>. This can also be used to specify a custom database in production mode. Example command:</p> <pre><code>freqtrade trade -c config.json --db-url sqlite:///tradesv3.dry_run.sqlite\n</code></pre>"},{"location":"bot-usage/#next-step","title":"Next step","text":"<p>The optimal strategy of the bot will change with time depending of the market trends. The next step is to Strategy Customization.</p>"},{"location":"configuration/","title":"Configure the bot","text":"<p>Freqtrade has many configurable features and possibilities. By default, these settings are configured via the configuration file (see below).</p>"},{"location":"configuration/#the-freqtrade-configuration-file","title":"The Freqtrade configuration file","text":"<p>The bot uses a set of configuration parameters during its operation that all together conform the bot configuration. It normally reads its configuration from a file (Freqtrade configuration file).</p> <p>Per default, the bot loads the configuration from the <code>config.json</code> file, located in the current working directory.</p> <p>You can specify a different configuration file used by the bot with the <code>-c/--config</code> command line option.</p> <p>In some advanced use cases, 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.</p> <p>If you used the Quick start method for installing the bot, the installation script should have already created the default configuration file (<code>config.json</code>) for you.</p> <p>If default configuration file is not created we recommend you to use <code>freqtrade new-config --config config.json</code> to generate a basic configuration file.</p> <p>The Freqtrade configuration file is to be written in the JSON format.</p> <p>Additionally to the standard JSON syntax, you may use one-line <code>// ...</code> and multi-line <code>/* ... */</code> comments in your configuration files and trailing commas in the lists of parameters.</p> <p>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 syntax of the configuration file at startup and will warn you if you made any errors editing it, pointing out problematic lines.</p>"},{"location":"configuration/#configuration-parameters","title":"Configuration parameters","text":"<p>The table below will list all configuration parameters available.</p> <p>Freqtrade can also load many options via command line (CLI) arguments (check out the commands <code>--help</code> output for details). The prevelance for all Options is as follows:</p> <ul> <li>CLI arguments override any other option</li> <li>Configuration files are used in sequence (last file wins), and override Strategy configurations.</li> <li>Strategy configurations are only used if they are not set via configuration or via command line arguments. These options are marked with Strategy Override in the below table.</li> </ul> <p>Mandatory parameters are marked as Required, which means that they are required to be set in one of the possible ways.</p> Parameter Description <code>max_open_trades</code> 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 which 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. <code>stake_currency</code> Required. Crypto-currency used for trading. Strategy Override. Datatype: String <code>stake_amount</code> Required. Amount of crypto-currency your bot will use for each trade. Set it to <code>\"unlimited\"</code> to allow the bot to use all available balance. More information below. Strategy Override. Datatype: Positive float or <code>\"unlimited\"</code>. <code>tradable_balance_ratio</code> Ratio of the total account balance the bot is allowed to trade. More information below. Defaults to <code>0.99</code> 99%). Datatype: Positive float between <code>0.1</code> and <code>1.0</code>. <code>amend_last_stake_amount</code> Use reduced last stake amount if necessary. More information below. Defaults to <code>false</code>. Datatype: Boolean <code>last_stake_amount_min_ratio</code> 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 <code>amend_last_stake_amount</code> is set to <code>true</code>). More information below. Defaults to <code>0.5</code>. Datatype: Float (as ratio) <code>amount_reserve_percent</code> Reserve some amount in min pair stake amount. The bot will reserve <code>amount_reserve_percent</code> + stoploss value when calculating min pair stake amount in order to avoid possible trade refusals. Defaults to <code>0.05</code> (5%). Datatype: Positive Float as ratio. <code>timeframe</code> The timeframe (former ticker interval) to use (e.g <code>1m</code>, <code>5m</code>, <code>15m</code>, <code>30m</code>, <code>1h</code> ...). Strategy Override. Datatype: String <code>fiat_display_currency</code> Fiat currency used to show your profits. More information below. Datatype: String <code>dry_run</code> Required. Define if the bot must be in Dry Run or production mode. Defaults to <code>true</code>. Datatype: Boolean <code>dry_run_wallet</code> Define the starting amount in stake currency for the simulated wallet used by the bot running in the Dry Run mode.Defaults to <code>1000</code>. Datatype: Float <code>cancel_open_orders_on_exit</code> Cancel open orders when the <code>/stop</code> RPC command is issued, <code>Ctrl+C</code> is pressed or the bot dies unexpectedly. When set to <code>true</code>, this allows you to use <code>/stop</code> to cancel unfilled and partially filled orders in the event of a market crash. It does not impact open positions. Defaults to <code>false</code>. Datatype: Boolean <code>process_only_new_candles</code> 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 <code>false</code>. Datatype: Boolean <code>minimal_roi</code> Required. Set the threshold as ratio the bot will use to sell a trade. More information below. Strategy Override. Datatype: Dict <code>stoploss</code> Required. Value as ratio of the stoploss used by the bot. More details in the stoploss documentation. Strategy Override. Datatype: Float (as ratio) <code>trailing_stop</code> Enables trailing stoploss (based on <code>stoploss</code> in either configuration or strategy file). More details in the stoploss documentation. Strategy Override. Datatype: Boolean <code>trailing_stop_positive</code> Changes stoploss once profit has been reached. More details in the stoploss documentation. Strategy Override. Datatype: Float <code>trailing_stop_positive_offset</code> Offset on when to apply <code>trailing_stop_positive</code>. Percentage value which should be positive. More details in the stoploss documentation. Strategy Override. Defaults to <code>0.0</code> (no offset). Datatype: Float <code>trailing_only_offset_is_reached</code> Only apply trailing stoploss when the offset is reached. stoploss documentation. Strategy Override. Defaults to <code>false</code>. Datatype: Boolean <code>unfilledtimeout.buy</code> Required. How long (in minutes) 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 <code>unfilledtimeout.sell</code> Required. How long (in minutes) 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 <code>bid_strategy.price_side</code> Select the side of the spread the bot should look at to get the buy rate. More information below. Defaults to <code>bid</code>. Datatype: String (either <code>ask</code> or <code>bid</code>). <code>bid_strategy.ask_last_balance</code> Required. Set the bidding price. More information below. <code>bid_strategy.use_order_book</code> Enable buying using the rates in Order Book Bids. Datatype: Boolean <code>bid_strategy.order_book_top</code> Bot will use the top N rate in Order Book Bids to buy. I.e. a value of 2 will allow the bot to pick the 2<sup>nd</sup> bid rate in Order Book Bids. Defaults to <code>1</code>. Datatype: Positive Integer <code>bid_strategy. check_depth_of_market.enabled</code> Do not buy if the difference of buy orders and sell orders is met in Order Book. Check market depth. Defaults to <code>false</code>. Datatype: Boolean <code>bid_strategy. check_depth_of_market.bids_to_ask_delta</code> 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 <code>0</code>. Datatype: Float (as ratio) <code>ask_strategy.price_side</code> Select the side of the spread the bot should look at to get the sell rate. More information below. Defaults to <code>ask</code>. Datatype: String (either <code>ask</code> or <code>bid</code>). <code>ask_strategy.use_order_book</code> Enable selling of open trades using Order Book Asks. Datatype: Boolean <code>ask_strategy.order_book_min</code> Bot will scan from the top min to max Order Book Asks searching for a profitable rate. Defaults to <code>1</code>. Datatype: Positive Integer <code>ask_strategy.order_book_max</code> Bot will scan from the top min to max Order Book Asks searching for a profitable rate. Defaults to <code>1</code>. Datatype: Positive Integer <code>ask_strategy.use_sell_signal</code> Use sell signals produced by the strategy in addition to the <code>minimal_roi</code>. Strategy Override. Defaults to <code>true</code>. Datatype: Boolean <code>ask_strategy.sell_profit_only</code> Wait until the bot reaches <code>ask_strategy.sell_profit_offset</code> before taking a sell decision. Strategy Override. Defaults to <code>false</code>. Datatype: Boolean <code>ask_strategy.sell_profit_offset</code> Sell-signal is only active above this value. Strategy Override. Defaults to <code>0.0</code>. Datatype: Float (as ratio) <code>ask_strategy.ignore_roi_if_buy_signal</code> Do not sell if the buy signal is still active. This setting takes preference over <code>minimal_roi</code> and <code>use_sell_signal</code>. Strategy Override. Defaults to <code>false</code>. Datatype: Boolean <code>ask_strategy.ignore_buying_expired_candle_after</code> Specifies the number of seconds until a buy signal is no longer used. Datatype: Integer <code>order_types</code> Configure order-types depending on the action (<code>\"buy\"</code>, <code>\"sell\"</code>, <code>\"stoploss\"</code>, <code>\"stoploss_on_exchange\"</code>). More information below. Strategy Override. Datatype: Dict <code>order_time_in_force</code> Configure time in force for buy and sell orders. More information below. Strategy Override. Datatype: Dict <code>exchange.name</code> Required. Name of the exchange class to use. List below. Datatype: String <code>exchange.sandbox</code> Use the 'sandbox' version of the exchange, where the exchange provides a sandbox for risk-free integration. See here in more details. Datatype: Boolean <code>exchange.key</code> 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 <code>exchange.secret</code> 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 <code>exchange.password</code> 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 <code>exchange.pair_whitelist</code> List of pairs to use by the bot for trading and to check for potential trades during backtesting. Supports regex pairs as <code>.*/BTC</code>. Not used by VolumePairList. More information. Datatype: List <code>exchange.pair_blacklist</code> List of pairs the bot must absolutely avoid for trading and backtesting. More information. Datatype: List <code>exchange.ccxt_config</code> 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 <code>exchange.ccxt_sync_config</code> 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 <code>exchange.ccxt_async_config</code> 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 <code>exchange.markets_refresh_interval</code> The interval in minutes in which markets are reloaded. Defaults to <code>60</code> minutes. Datatype: Positive Integer <code>exchange.skip_pair_validation</code> Skip pairlist validation on startup.Defaults to <code>false</code> Datatype:* Boolean <code>exchange.skip_open_order_update</code> Skips open order updates on startup should the exchange cause problems. Only relevant in live conditions.Defaults to <code>false</code> Datatype:* Boolean <code>edge.*</code> Please refer to edge configuration document for detailed explanation. <code>experimental.block_bad_exchanges</code> Block exchanges known to not work with freqtrade. Leave on default unless you want to test if that exchange works now. Defaults to <code>true</code>. Datatype: Boolean <code>pairlists</code> Define one or more pairlists to be used. More information. Defaults to <code>StaticPairList</code>. Datatype: List of Dicts <code>protections</code> Define one or more protections to be used. More information. Strategy Override. Datatype: List of Dicts <code>telegram.enabled</code> Enable the usage of Telegram. Datatype: Boolean <code>telegram.token</code> Your Telegram bot token. Only required if <code>telegram.enabled</code> is <code>true</code>. Keep it in secret, do not disclose publicly. Datatype: String <code>telegram.chat_id</code> Your personal Telegram account id. Only required if <code>telegram.enabled</code> is <code>true</code>. Keep it in secret, do not disclose publicly. Datatype: String <code>webhook.enabled</code> Enable usage of Webhook notifications Datatype: Boolean <code>webhook.url</code> URL for the webhook. Only required if <code>webhook.enabled</code> is <code>true</code>. See the webhook documentation for more details. Datatype: String <code>webhook.webhookbuy</code> Payload to send on buy. Only required if <code>webhook.enabled</code> is <code>true</code>. See the webhook documentation for more details. Datatype: String <code>webhook.webhookbuycancel</code> Payload to send on buy order cancel. Only required if <code>webhook.enabled</code> is <code>true</code>. See the webhook documentation for more details. Datatype: String <code>webhook.webhooksell</code> Payload to send on sell. Only required if <code>webhook.enabled</code> is <code>true</code>. See the webhook documentation for more details. Datatype: String <code>webhook.webhooksellcancel</code> Payload to send on sell order cancel. Only required if <code>webhook.enabled</code> is <code>true</code>. See the webhook documentation for more details. Datatype: String <code>webhook.webhookstatus</code> Payload to send on status calls. Only required if <code>webhook.enabled</code> is <code>true</code>. See the webhook documentation for more details. Datatype: String <code>api_server.enabled</code> Enable usage of API Server. See the API Server documentation for more details. Datatype: Boolean <code>api_server.listen_ip_address</code> Bind IP address. See the API Server documentation for more details. Datatype: IPv4 <code>api_server.listen_port</code> Bind Port. See the API Server documentation for more details. Datatype: Integer between 1024 and 65535 <code>api_server.verbosity</code> Logging verbosity. <code>info</code> will print all RPC Calls, while \"error\" will only display errors. Datatype: Enum, either <code>info</code> or <code>error</code>. Defaults to <code>info</code>. <code>api_server.username</code> Username for API server. See the API Server documentation for more details. Keep it in secret, do not disclose publicly. Datatype: String <code>api_server.password</code> Password for API server. See the API Server documentation for more details. Keep it in secret, do not disclose publicly. Datatype: String <code>bot_name</code> Name of the bot. Passed via API to a client - can be shown to distinguish / name bots. Defaults to <code>freqtrade</code> Datatype: String <code>db_url</code> Declares database URL to use. NOTE: This defaults to <code>sqlite:///tradesv3.dryrun.sqlite</code> if <code>dry_run</code> is <code>true</code>, and to <code>sqlite:///tradesv3.sqlite</code> for production instances. Datatype: String, SQLAlchemy connect string <code>initial_state</code> Defines the initial application state. If set to stopped, then the bot has to be explicitly started via <code>/start</code> RPC command. Defaults to <code>stopped</code>. Datatype: Enum, either <code>stopped</code> or <code>running</code> <code>forcebuy_enable</code> Enables the RPC Commands to force a buy. More information below. Datatype: Boolean <code>disable_dataframe_checks</code> 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 <code>False</code>. Datatype: Boolean <code>strategy</code> Required Defines Strategy class to use. Recommended to be set via <code>--strategy NAME</code>. Datatype: ClassName <code>strategy_path</code> Adds an additional strategy lookup path (must be a directory). Datatype: String <code>internals.process_throttle_secs</code> Set the process throttle, or minimum loop duration for one bot iteration loop. Value in second. Defaults to <code>5</code> seconds. Datatype: Positive Integer <code>internals.heartbeat_interval</code> Print heartbeat message every N seconds. Set to 0 to disable heartbeat messages. Defaults to <code>60</code> seconds. Datatype: Positive Integer or 0 <code>internals.sd_notify</code> 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 <code>logfile</code> Specifies logfile name. Uses a rolling strategy for log file rotation for 10 files with the 1MB limit per file. Datatype: String <code>user_data_dir</code> Directory containing user data. Defaults to <code>./user_data/</code>. Datatype: String <code>dataformat_ohlcv</code> Data format to use to store historical candle (OHLCV) data. Defaults to <code>json</code>. Datatype: String <code>dataformat_trades</code> Data format to use to store historical trades data. Defaults to <code>jsongz</code>. Datatype: String"},{"location":"configuration/#parameters-in-the-strategy","title":"Parameters in the strategy","text":"<p>The following parameters can be set in either configuration file or strategy. Values set in the configuration file always overwrite values set in the strategy.</p> <ul> <li><code>minimal_roi</code></li> <li><code>timeframe</code></li> <li><code>stoploss</code></li> <li><code>trailing_stop</code></li> <li><code>trailing_stop_positive</code></li> <li><code>trailing_stop_positive_offset</code></li> <li><code>trailing_only_offset_is_reached</code></li> <li><code>use_custom_stoploss</code></li> <li><code>process_only_new_candles</code></li> <li><code>order_types</code></li> <li><code>order_time_in_force</code></li> <li><code>stake_currency</code></li> <li><code>stake_amount</code></li> <li><code>unfilledtimeout</code></li> <li><code>disable_dataframe_checks</code></li> <li><code>protections</code></li> <li><code>use_sell_signal</code> (ask_strategy)</li> <li><code>sell_profit_only</code> (ask_strategy)</li> <li><code>sell_profit_offset</code> (ask_strategy)</li> <li><code>ignore_roi_if_buy_signal</code> (ask_strategy)</li> <li><code>ignore_buying_expired_candle_after</code> (ask_strategy)</li> </ul>"},{"location":"configuration/#configuring-amount-per-trade","title":"Configuring amount per trade","text":"<p>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.</p>"},{"location":"configuration/#available-balance","title":"Available balance","text":"<p>By default, the bot assumes that the <code>complete amount - 1%</code> is at it's disposal, and when using dynamic stake amount, it will split the complete balance into <code>max_open_trades</code> buckets per trade. Freqtrade will reserve 1% for eventual fees when entering a trade and will therefore not touch that by default.</p> <p>You can configure the \"untouched\" amount by using the <code>tradable_balance_ratio</code> setting.</p> <p>For example, if you have 10 ETH available in your wallet on the exchange and <code>tradable_balance_ratio=0.5</code> (which is 50%), then the bot will use a maximum amount of 5 ETH for trading and considers this as available balance. The rest of the wallet is untouched by the trades.</p> <p>Warning</p> <p>The <code>tradable_balance_ratio</code> setting applies to the current balance (free balance + tied up in trades). Therefore, assuming the starting balance of 1000, a configuration with <code>tradable_balance_ratio=0.99</code> 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).</p>"},{"location":"configuration/#amend-last-stake-amount","title":"Amend last stake amount","text":"<p>Assuming we have the tradable balance of 1000 USDT, <code>stake_amount=400</code>, and <code>max_open_trades=3</code>. 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.</p> <p>To overcome this, the option <code>amend_last_stake_amount</code> can be set to <code>True</code>, which will enable the bot to reduce stake_amount to the available balance in order to fill the last trade slot.</p> <p>In the example above this would mean:</p> <ul> <li>Trade1: 400 USDT</li> <li>Trade2: 400 USDT</li> <li>Trade3: 200 USDT</li> </ul> <p>Note</p> <p>This option only applies with Static stake amount - since Dynamic stake amount divides the balances evenly.</p> <p>Note</p> <p>The minimum last stake amount can be configured using <code>last_stake_amount_min_ratio</code> - which defaults to 0.5 (50%). This means that the minimum stake amount that's ever used is <code>stake_amount * 0.5</code>. This avoids very low stake amounts, that are close to the minimum tradable amount for the pair and can be refused by the exchange.</p>"},{"location":"configuration/#static-stake-amount","title":"Static stake amount","text":"<p>The <code>stake_amount</code> configuration statically configures the amount of stake-currency your bot will use for each trade.</p> <p>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.</p> <p>This setting works in combination with <code>max_open_trades</code>. The maximum capital engaged in trades is <code>stake_amount * max_open_trades</code>. For example, the bot will at most use (0.05 BTC x 3) = 0.15 BTC, assuming a configuration of <code>max_open_trades=3</code> and <code>stake_amount=0.05</code>.</p> <p>Note</p> <p>This setting respects the available balance configuration.</p>"},{"location":"configuration/#dynamic-stake-amount","title":"Dynamic stake amount","text":"<p>Alternatively, you can use a dynamic stake amount, which will use the available balance on the exchange, and divide that equally by the amount of allowed trades (<code>max_open_trades</code>).</p> <p>To configure this, set <code>stake_amount=\"unlimited\"</code>. We also recommend to set <code>tradable_balance_ratio=0.99</code> (99%) - to keep a minimum balance for eventual fees.</p> <p>In this case a trade amount is calculated as:</p> <pre><code>currency_balance / (max_open_trades - current_open_trades)\n</code></pre> <p>To allow the bot to trade all the available <code>stake_currency</code> in your account (minus <code>tradable_balance_ratio</code>) set</p> <pre><code>\"stake_amount\" : \"unlimited\",\n\"tradable_balance_ratio\": 0.99,\n</code></pre> <p>Note</p> <p>This configuration will allow increasing / decreasing stakes depending on the performance of the bot (lower stake if bot is loosing, higher stakes if the bot has a winning record, since higher balances are available).</p> <p>When using Dry-Run Mode</p> <p>When using <code>\"stake_amount\" : \"unlimited\",</code> in combination with Dry-Run, the balance will be simulated starting with a stake of <code>dry_run_wallet</code> which will evolve over time. It is therefore important to set <code>dry_run_wallet</code> 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.</p>"},{"location":"configuration/#understand-minimal_roi","title":"Understand minimal_roi","text":"<p>The <code>minimal_roi</code> configuration parameter is a JSON object where the key is a duration in minutes and the value is the minimum ROI as ratio. See the example below:</p> <pre><code>\"minimal_roi\": {\n \"40\": 0.0, # Sell after 40 minutes if the profit is not negative\n \"30\": 0.01, # Sell after 30 minutes if there is at least 1% profit\n \"20\": 0.02, # Sell after 20 minutes if there is at least 2% profit\n \"0\": 0.04 # Sell immediately if there is at least 4% profit\n},\n</code></pre> <p>Most of the strategy files already include the optimal <code>minimal_roi</code> value. This parameter can be set in either Strategy or Configuration file. If you use it in the configuration file, it will override the <code>minimal_roi</code> value from the strategy file. If it is not set in either Strategy or Configuration, a default of 1000% <code>{\"0\": 10}</code> is used, and minimal roi is disabled unless your trade generates 1000% profit.</p> <p>Special case to forcesell after a specific time</p> <p>A special case presents using <code>\"<N>\": -1</code> 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.</p>"},{"location":"configuration/#understand-forcebuy_enable","title":"Understand forcebuy_enable","text":"<p>The <code>forcebuy_enable</code> 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 <code>/forcebuy ETH/BTC</code> to the bot, which will result in freqtrade buying the pair and holds it until a regular sell-signal (ROI, stoploss, /forcesell) appears.</p> <p>This can be dangerous with some strategies, so use with care.</p> <p>See the telegram documentation for details on usage.</p>"},{"location":"configuration/#ignoring-expired-candles","title":"Ignoring expired candles","text":"<p>When working with larger timeframes (for example 1h or more) and using a low <code>max_open_trades</code> 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.</p> <p>In these situations, you can enable the functionality to ignore candles that are beyond a specified period by setting <code>ask_strategy.ignore_buying_expired_candle_after</code> to a positive number, indicating the number of seconds after which the buy signal becomes expired.</p> <p>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:</p> <pre><code> \"ask_strategy\":{\n \"ignore_buying_expired_candle_after\": 300,\n \"price_side\": \"bid\",\n // ...\n },\n</code></pre>"},{"location":"configuration/#understand-order_types","title":"Understand order_types","text":"<p>The <code>order_types</code> configuration parameter maps actions (<code>buy</code>, <code>sell</code>, <code>stoploss</code>, <code>emergencysell</code>) to order-types (<code>market</code>, <code>limit</code>, ...) as well as configures stoploss to be on the exchange and defines stoploss on exchange update interval in seconds.</p> <p>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.</p> <p><code>order_types</code> set in the configuration file overwrites values set in the strategy as a whole, so you need to configure the whole <code>order_types</code> dictionary in one place.</p> <p>If this is configured, the following 4 values (<code>buy</code>, <code>sell</code>, <code>stoploss</code> and <code>stoploss_on_exchange</code>) need to be present, otherwise the bot will fail to start.</p> <p>For information on (<code>emergencysell</code>,<code>stoploss_on_exchange</code>,<code>stoploss_on_exchange_interval</code>,<code>stoploss_on_exchange_limit_ratio</code>) please see stop loss documentation stop loss on exchange</p> <p>Syntax for Strategy:</p> <pre><code>order_types = {\n \"buy\": \"limit\",\n \"sell\": \"limit\",\n \"emergencysell\": \"market\",\n \"stoploss\": \"market\",\n \"stoploss_on_exchange\": False,\n \"stoploss_on_exchange_interval\": 60,\n \"stoploss_on_exchange_limit_ratio\": 0.99,\n}\n</code></pre> <p>Configuration:</p> <pre><code>\"order_types\": {\n \"buy\": \"limit\",\n \"sell\": \"limit\",\n \"emergencysell\": \"market\",\n \"stoploss\": \"market\",\n \"stoploss_on_exchange\": false,\n \"stoploss_on_exchange_interval\": 60\n}\n</code></pre> <p>Market order support</p> <p>Not all exchanges support \"market\" orders. The following message will be shown if your exchange does not support market orders: <code>\"Exchange <yourexchange> does not support market orders.\"</code> and the bot will refuse to start.</p> <p>Using market orders</p> <p>Please carefully read the section Market order pricing section when using market orders.</p> <p>Stoploss on exchange</p> <p><code>stoploss_on_exchange_interval</code> 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.</p> <p>If <code>stoploss_on_exchange</code> is enabled and the stoploss is cancelled manually on the exchange, then the bot will create a new stoploss order.</p> <p>Warning: stoploss_on_exchange failures</p> <p>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 <code>emergencysell</code> value in the <code>order_types</code> dictionary - however this is not advised.</p>"},{"location":"configuration/#understand-order_time_in_force","title":"Understand order_time_in_force","text":"<p>The <code>order_time_in_force</code> configuration parameter defines the policy by which the order is executed on the exchange. Three commonly used time in force are:</p> <p>GTC (Good Till Canceled):</p> <p>This is most of the time the default time in force. It means the order will remain on exchange till it is canceled by user. It can be fully or partially fulfilled. If partially fulfilled, the remaining will stay on the exchange till cancelled.</p> <p>FOK (Fill Or Kill):</p> <p>It means if the order is not executed immediately AND fully then it is canceled by the exchange.</p> <p>IOC (Immediate Or Canceled):</p> <p>It is the same as FOK (above) except it can be partially fulfilled. The remaining part is automatically cancelled by the exchange.</p> <p>The <code>order_time_in_force</code> 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.</p> <p>The possible values are: <code>gtc</code> (default), <code>fok</code> or <code>ioc</code>.</p> <pre><code>\"order_time_in_force\": {\n \"buy\": \"gtc\",\n \"sell\": \"gtc\"\n},\n</code></pre> <p>Warning</p> <p>This is an ongoing work. For now it is supported only for binance and only for buy orders. Please don't change the default value unless you know what you are doing.</p>"},{"location":"configuration/#exchange-configuration","title":"Exchange configuration","text":"<p>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 the these are the only officially supported exchanges:</p> <ul> <li>Bittrex: \"bittrex\"</li> <li>Binance: \"binance\"</li> <li>Kraken: \"kraken\"</li> </ul> <p>Feel free to test other exchanges and submit your PR to improve the bot.</p> <p>Some exchanges require special configuration, which can be found on the Exchange-specific Notes documentation page.</p>"},{"location":"configuration/#sample-exchange-configuration","title":"Sample exchange configuration","text":"<p>A exchange configuration for \"binance\" would look as follows:</p> <pre><code>\"exchange\": {\n \"name\": \"binance\",\n \"key\": \"your_exchange_key\",\n \"secret\": \"your_exchange_secret\",\n \"ccxt_config\": {\"enableRateLimit\": true},\n \"ccxt_async_config\": {\n \"enableRateLimit\": true,\n \"rateLimit\": 200\n },\n</code></pre> <p>This configuration enables binance, as well as rate limiting to avoid bans from the exchange. <code>\"rateLimit\": 200</code> defines a wait-event of 0.2s between each call. This can also be completely disabled by setting <code>\"enableRateLimit\"</code> to false.</p> <p>Note</p> <p>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 <code>\"enableRateLimit\"</code> is enabled and increase the <code>\"rateLimit\"</code> parameter step by step.</p>"},{"location":"configuration/#advanced-freqtrade-exchange-configuration","title":"Advanced Freqtrade Exchange configuration","text":"<p>Advanced options can be configured using the <code>_ft_has_params</code> setting, which will override Defaults and exchange-specific behaviours.</p> <p>Available options are listed in the exchange-class as <code>_ft_has_default</code>.</p> <p>For example, to test the order type <code>FOK</code> with Kraken, and modify candle limit to 200 (so you only get 200 candles per API call):</p> <pre><code>\"exchange\": {\n \"name\": \"kraken\",\n \"_ft_has_params\": {\n \"order_time_in_force\": [\"gtc\", \"fok\"],\n \"ohlcv_candle_limit\": 200\n }\n</code></pre> <p>Warning</p> <p>Please make sure to fully understand the impacts of these settings before modifying them.</p>"},{"location":"configuration/#what-values-can-be-used-for-fiat_display_currency","title":"What values can be used for fiat_display_currency?","text":"<p>The <code>fiat_display_currency</code> configuration parameter sets the base currency to use for the conversion from coin to fiat in the bot Telegram reports.</p> <p>The valid values are:</p> <pre><code>\"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\"\n</code></pre> <p>In addition to fiat currencies, a range of cryto currencies are supported.</p> <p>The valid values are:</p> <pre><code>\"BTC\", \"ETH\", \"XRP\", \"LTC\", \"BCH\", \"USDT\"\n</code></pre>"},{"location":"configuration/#prices-used-for-orders","title":"Prices used for orders","text":"<p>Prices for regular orders can be controlled via the parameter structures <code>bid_strategy</code> for buying and <code>ask_strategy</code> for selling. Prices are always retrieved right before an order is placed, either by querying the exchange tickers or by using the orderbook data.</p> <p>Note</p> <p>Orderbook data used by Freqtrade are the data retrieved from exchange by the ccxt's function <code>fetch_order_book()</code>, i.e. are usually data from the L2-aggregated orderbook, while the ticker data are the structures returned by the ccxt's <code>fetch_ticker()</code>/<code>fetch_tickers()</code> functions. Refer to the ccxt library documentation for more details.</p> <p>Using market orders</p> <p>Please read the section Market order pricing section when using market orders.</p>"},{"location":"configuration/#buy-price","title":"Buy price","text":""},{"location":"configuration/#check-depth-of-market","title":"Check depth of market","text":"<p>When check depth of market is enabled (<code>bid_strategy.check_depth_of_market.enabled=True</code>), the buy signals are filtered based on the orderbook depth (sum of all amounts) for each orderbook side.</p> <p>Orderbook <code>bid</code> (buy) side depth is then divided by the orderbook <code>ask</code> (sell) side depth and the resulting delta is compared to the value of the <code>bid_strategy.check_depth_of_market.bids_to_ask_delta</code> parameter. The buy order is only executed if the orderbook delta is greater than or equal to the configured delta value.</p> <p>Note</p> <p>A delta value below 1 means that <code>ask</code> (sell) orderbook side depth is greater than the depth of the <code>bid</code> (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).</p>"},{"location":"configuration/#buy-price-side","title":"Buy price side","text":"<p>The configuration setting <code>bid_strategy.price_side</code> defines the side of the spread the bot looks for when buying.</p> <p>The following displays an orderbook.</p> <pre><code>...\n103\n102\n101 # ask\n-------------Current spread\n99 # bid\n98\n97\n...\n</code></pre> <p>If <code>bid_strategy.price_side</code> is set to <code>\"bid\"</code>, then the bot will use 99 as buying price. In line with that, if <code>bid_strategy.price_side</code> is set to <code>\"ask\"</code>, then the bot will use 101 as buying price.</p> <p>Using <code>ask</code> 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).</p>"},{"location":"configuration/#buy-price-with-orderbook-enabled","title":"Buy price with Orderbook enabled","text":"<p>When buying with the orderbook enabled (<code>bid_strategy.use_order_book=True</code>), Freqtrade fetches the <code>bid_strategy.order_book_top</code> entries from the orderbook and then uses the entry specified as <code>bid_strategy.order_book_top</code> on the configured side (<code>bid_strategy.price_side</code>) of the orderbook. 1 specifies the topmost entry in the orderbook, while 2 would use the 2<sup>nd</sup> entry in the orderbook, and so on.</p>"},{"location":"configuration/#buy-price-without-orderbook-enabled","title":"Buy price without Orderbook enabled","text":"<p>The following section uses <code>side</code> as the configured <code>bid_strategy.price_side</code>.</p> <p>When not using orderbook (<code>bid_strategy.use_order_book=False</code>), Freqtrade uses the best <code>side</code> price from the ticker if it's below the <code>last</code> traded price from the ticker. Otherwise (when the <code>side</code> price is above the <code>last</code> price), it calculates a rate between <code>side</code> and <code>last</code> price.</p> <p>The <code>bid_strategy.ask_last_balance</code> configuration parameter controls this. A value of <code>0.0</code> will use <code>side</code> price, while <code>1.0</code> will use the <code>last</code> price and values between those interpolate between ask and last price.</p>"},{"location":"configuration/#sell-price","title":"Sell price","text":""},{"location":"configuration/#sell-price-side","title":"Sell price side","text":"<p>The configuration setting <code>ask_strategy.price_side</code> defines the side of the spread the bot looks for when selling.</p> <p>The following displays an orderbook:</p> <pre><code>...\n103\n102\n101 # ask\n-------------Current spread\n99 # bid\n98\n97\n...\n</code></pre> <p>If <code>ask_strategy.price_side</code> is set to <code>\"ask\"</code>, then the bot will use 101 as selling price. In line with that, if <code>ask_strategy.price_side</code> is set to <code>\"bid\"</code>, then the bot will use 99 as selling price.</p>"},{"location":"configuration/#sell-price-with-orderbook-enabled","title":"Sell price with Orderbook enabled","text":"<p>When selling with the orderbook enabled (<code>ask_strategy.use_order_book=True</code>), Freqtrade fetches the <code>ask_strategy.order_book_max</code> entries in the orderbook. Then each of the orderbook steps between <code>ask_strategy.order_book_min</code> and <code>ask_strategy.order_book_max</code> on the configured orderbook side are validated for a profitable sell-possibility based on the strategy configuration (<code>minimal_roi</code> conditions) and the sell order is placed at the first profitable spot.</p> <p>Note</p> <p>Using <code>order_book_max</code> higher than <code>order_book_min</code> only makes sense when ask_strategy.price_side is set to <code>\"ask\"</code>.</p> <p>The idea here is to place the sell order early, to be ahead in the queue.</p> <p>A fixed slot (mirroring <code>bid_strategy.order_book_top</code>) can be defined by setting <code>ask_strategy.order_book_min</code> and <code>ask_strategy.order_book_max</code> to the same number.</p> <p>Order_book_max > 1 - increased risks for stoplosses!</p> <p>Using <code>ask_strategy.order_book_max</code> higher than 1 will increase the risk the stoploss on exchange is cancelled too early, since an eventual stoploss on exchange will be cancelled as soon as the order is placed. Also, the sell order will remain on the exchange for <code>unfilledtimeout.sell</code> (or until it's filled) - which can lead to missed stoplosses (with or without using stoploss on exchange).</p> <p>Order_book_max > 1 in dry-run</p> <p>Using <code>ask_strategy.order_book_max</code> higher than 1 will result in improper dry-run results (significantly better than real orders executed on exchange), since dry-run assumes orders to be filled almost instantly. It is therefore advised to not use this setting for dry-runs.</p>"},{"location":"configuration/#sell-price-without-orderbook-enabled","title":"Sell price without Orderbook enabled","text":"<p>When not using orderbook (<code>ask_strategy.use_order_book=False</code>), the price at the <code>ask_strategy.price_side</code> side (defaults to <code>\"ask\"</code>) from the ticker will be used as the sell price.</p>"},{"location":"configuration/#market-order-pricing","title":"Market order pricing","text":"<p>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</p> <pre><code> \"order_types\": {\n \"buy\": \"market\",\n \"sell\": \"market\"\n // ...\n },\n \"bid_strategy\": {\n \"price_side\": \"ask\",\n // ...\n },\n \"ask_strategy\":{\n \"price_side\": \"bid\",\n // ...\n },\n</code></pre> <p>Obviously, if only one side is using limit orders, different pricing combinations can be used.</p>"},{"location":"configuration/#using-dry-run-mode","title":"Using Dry-run mode","text":"<p>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.</p> <ol> <li>Edit your <code>config.json</code> configuration file.</li> <li>Switch <code>dry-run</code> to <code>true</code> and specify <code>db_url</code> for a persistence database.</li> </ol> <pre><code>\"dry_run\": true,\n\"db_url\": \"sqlite:///tradesv3.dryrun.sqlite\",\n</code></pre> <ol> <li>Remove your Exchange API key and secret (change them by empty values or fake credentials):</li> </ol> <pre><code>\"exchange\": {\n \"name\": \"bittrex\",\n \"key\": \"key\",\n \"secret\": \"secret\",\n ...\n}\n</code></pre> <p>Once you will be happy with your bot performance running in the Dry-run mode, you can switch it to production mode.</p> <p>Note</p> <p>A simulated wallet is available during dry-run mode, and will assume a starting capital of <code>dry_run_wallet</code> (defaults to 1000).</p>"},{"location":"configuration/#considerations-for-dry-run","title":"Considerations for dry-run","text":"<ul> <li>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.</li> <li>Wallets (<code>/balance</code>) are simulated based on <code>dry_run_wallet</code>.</li> <li>Orders are simulated, and will not be posted to the exchange.</li> <li>Orders are assumed to fill immediately, and will never time out.</li> <li>In combination with <code>stoploss_on_exchange</code>, the stop_loss price is assumed to be filled.</li> <li>Open orders (not trades, which are stored in the database) are reset on bot restart.</li> </ul>"},{"location":"configuration/#switch-to-production-mode","title":"Switch to production mode","text":"<p>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.</p>"},{"location":"configuration/#setup-your-exchange-account","title":"Setup your exchange account","text":"<p>You will need to create API Keys (usually you get <code>key</code> and <code>secret</code>, some exchanges require an additional <code>password</code>) from the Exchange website and you'll need to insert this into the appropriate fields in the configuration or when asked by the <code>freqtrade new-config</code> 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 setup the bot in dry-run mode, you may fill these fields with empty values.</p>"},{"location":"configuration/#to-switch-your-bot-in-production-mode","title":"To switch your bot in production mode","text":"<p>Edit your <code>config.json</code> file.</p> <p>Switch dry-run to false and don't forget to adapt your database URL if set:</p> <pre><code>\"dry_run\": false,\n</code></pre> <p>Insert your Exchange API key (change them by fake api keys):</p> <pre><code>\"exchange\": {\n \"name\": \"bittrex\",\n \"key\": \"af8ddd35195e9dc500b9a6f799f6f5c93d89193b\",\n \"secret\": \"08a9dc6db3d7b53e1acebd9275677f4b0a04f1a5\",\n ...\n}\n</code></pre> <p>You should also make sure to read the Exchanges section of the documentation to be aware of potential configuration details specific to your exchange.</p>"},{"location":"configuration/#using-proxy-with-freqtrade","title":"Using proxy with Freqtrade","text":"<p>To use a proxy with freqtrade, add the kwarg <code>\"aiohttp_trust_env\"=true</code> to the <code>\"ccxt_async_kwargs\"</code> dict in the exchange section of the configuration.</p> <p>An example for this can be found in <code>config_full.json.example</code></p> <pre><code>\"ccxt_async_config\": {\n \"aiohttp_trust_env\": true\n}\n</code></pre> <p>Then, export your proxy settings using the variables <code>\"HTTP_PROXY\"</code> and <code>\"HTTPS_PROXY\"</code> set to the appropriate values</p> <pre><code>export HTTP_PROXY=\"http://addr:port\"\nexport HTTPS_PROXY=\"http://addr:port\"\nfreqtrade\n</code></pre>"},{"location":"configuration/#next-step","title":"Next step","text":"<p>Now you have configured your config.json, the next step is to start your bot.</p>"},{"location":"data-analysis/","title":"Analyzing bot data with Jupyter notebooks","text":"<p>You can analyze the results of backtests and trading history easily using Jupyter notebooks. Sample notebooks are located at <code>user_data/notebooks/</code> after initializing the user directory with <code>freqtrade create-userdir --userdir user_data</code>. </p>"},{"location":"data-analysis/#quick-start-with-docker","title":"Quick start with docker","text":"<p>Freqtrade provides a docker-compose file which starts up a jupyter lab server. You can run this server using the following command: <code>docker-compose -f docker/docker-compose-jupyter.yml up</code></p> <p>This will create a dockercontainer running jupyter lab, which will be accessible using <code>https://127.0.0.1:8888/lab</code>. Please use the link that's printed in the console after startup for simplified login.</p> <p>For more information, Please visit the Data analysis with Docker section.</p>"},{"location":"data-analysis/#pro-tips","title":"Pro tips","text":"<ul> <li>See jupyter.org for usage instructions.</li> <li>Don't forget to start a Jupyter notebook server from within your conda or venv environment or use nb_conda_kernels*</li> <li>Copy the example notebook before use so your changes don't get overwritten with the next freqtrade update.</li> </ul>"},{"location":"data-analysis/#using-virtual-environment-with-system-wide-jupyter-installation","title":"Using virtual environment with system-wide Jupyter installation","text":"<p>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).</p> <p>For this to work, first activate your virtual environment and run the following commands:</p> <pre><code># Activate virtual environment\nsource .env/bin/activate\n\npip install ipykernel\nipython kernel install --user --name=freqtrade\n# Restart jupyter (lab / notebook)\n# select kernel \"freqtrade\" in the notebook\n</code></pre> <p>Note</p> <p>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.</p> <p>Warning</p> <p>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.</p>"},{"location":"data-analysis/#recommended-workflow","title":"Recommended workflow","text":"Task Tool Bot operations CLI Repetitive tasks Shell scripts Data analysis & visualization Notebook <ol> <li> <p>Use the CLI to * download historical data * run a backtest * run with real-time data * export results </p> </li> <li> <p>Collect these actions in shell scripts * save complicated commands with arguments * execute multi-step operations * automate testing strategies and preparing data for analysis</p> </li> <li> <p>Use a notebook to * visualize data * munge and plot to generate insights</p> </li> </ol>"},{"location":"data-analysis/#example-utility-snippets","title":"Example utility snippets","text":""},{"location":"data-analysis/#change-directory-to-root","title":"Change directory to root","text":"<p>Jupyter notebooks execute from the notebook directory. The following snippet searches for the project root, so relative paths remain consistent.</p> <pre><code>import os\nfrom pathlib import Path\n\n# Change directory\n# Modify this cell to insure that the output shows the correct path.\n# Define all paths relative to the project root shown in the cell output\nproject_root = \"somedir/freqtrade\"\ni=0\ntry:\n os.chdirdir(project_root)\n assert Path('LICENSE').is_file()\nexcept:\n while i<4 and (not Path('LICENSE').is_file()):\n os.chdir(Path(Path.cwd(), '../'))\n i+=1\n project_root = Path.cwd()\nprint(Path.cwd())\n</code></pre>"},{"location":"data-analysis/#load-multiple-configuration-files","title":"Load multiple configuration files","text":"<p>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.</p> <pre><code>import json\nfrom freqtrade.configuration import Configuration\n\n# Load config from multiple files\nconfig = Configuration.from_files([\"config1.json\", \"config2.json\"])\n\n# Show the config in memory\nprint(json.dumps(config['original_config'], indent=2))\n</code></pre> <p>For Interactive environments, have an additional configuration specifying <code>user_data_dir</code> 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.</p> <pre><code>{\n \"user_data_dir\": \"~/.freqtrade/\"\n}\n</code></pre>"},{"location":"data-analysis/#further-data-analysis-documentation","title":"Further Data analysis documentation","text":"<ul> <li>Strategy debugging - also available as Jupyter notebook (<code>user_data/notebooks/strategy_analysis_example.ipynb</code>)</li> <li>Plotting</li> </ul> <p>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.</p>"},{"location":"data-download/","title":"Data Downloading","text":""},{"location":"data-download/#getting-data-for-backtesting-and-hyperopt","title":"Getting data for backtesting and hyperopt","text":"<p>To download data (candles / OHLCV) needed for backtesting and hyperoptimization use the <code>freqtrade download-data</code> command.</p> <p>If no additional parameter is specified, freqtrade will download data for <code>\"1m\"</code> and <code>\"5m\"</code> timeframes for the last 30 days. Exchange and pairs will come from <code>config.json</code> (if specified using <code>-c/--config</code>). Otherwise <code>--exchange</code> becomes mandatory.</p> <p>You can use a relative timerange (<code>--days 20</code>) or an absolute starting point (<code>--timerange 20200101-</code>). For incremental downloads, the relative approach should be used.</p> <p>Tip: Updating existing data</p> <p>If you already have backtesting data available in your data-directory and would like to refresh this data up to today, use <code>--days xx</code> with a number slightly higher than the missing number of days. Freqtrade will keep the available data and only download the missing data. Be careful though: If the number is too small (which would result in a few missing days), the whole dataset will be removed and only xx days will be downloaded.</p>"},{"location":"data-download/#usage","title":"Usage","text":"<pre><code>usage: freqtrade download-data [-h] [-v] [--logfile FILE] [-V] [-c PATH]\n [-d PATH] [--userdir PATH]\n [-p PAIRS [PAIRS ...]] [--pairs-file FILE]\n [--days INT] [--timerange TIMERANGE]\n [--dl-trades] [--exchange EXCHANGE]\n [-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} ...]]\n [--erase]\n [--data-format-ohlcv {json,jsongz,hdf5}]\n [--data-format-trades {json,jsongz,hdf5}]\n\noptional arguments:\n -h, --help show this help message and exit\n -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]\n Show profits for only these pairs. Pairs are space-\n separated.\n --pairs-file FILE File containing a list of pairs to download.\n --days INT Download data for given number of days.\n --timerange TIMERANGE\n Specify what timerange of data to use.\n --dl-trades Download trades instead of OHLCV data. The bot will\n resample trades to the desired timeframe as specified\n as --timeframes/-t.\n --exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no\n config is provided.\n -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} ...]\n Specify which tickers to download. Space-separated\n list. Default: `1m 5m`.\n --erase Clean all existing data for the selected\n exchange/pairs/timeframes.\n --data-format-ohlcv {json,jsongz,hdf5}\n Storage format for downloaded candle (OHLCV) data.\n (default: `json`).\n --data-format-trades {json,jsongz,hdf5}\n Storage format for downloaded trades data. (default:\n `jsongz`).\n\nCommon arguments:\n -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).\n --logfile FILE Log to the file specified. Special values are:\n 'syslog', 'journald'. See the documentation for more\n details.\n -V, --version show program's version number and exit\n -c PATH, --config PATH\n Specify configuration file (default:\n `userdir/config.json` or `config.json` whichever\n exists). Multiple --config options may be used. Can be\n set to `-` to read config from stdin.\n -d PATH, --datadir PATH\n Path to directory with historical backtesting data.\n --userdir PATH, --user-data-dir PATH\n Path to userdata directory.\n</code></pre> <p>Startup period</p> <p><code>download-data</code> 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.</p> <p>For that reason, <code>download-data</code> 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).</p>"},{"location":"data-download/#data-format","title":"Data format","text":"<p>Freqtrade currently supports 3 data-formats for both OHLCV and trades data:</p> <ul> <li><code>json</code> (plain \"text\" json files)</li> <li><code>jsongz</code> (a gzip-zipped version of json files)</li> <li><code>hdf5</code> (a high performance datastore)</li> </ul> <p>By default, OHLCV data is stored as <code>json</code> data, while trades data is stored as <code>jsongz</code> data.</p> <p>This can be changed via the <code>--data-format-ohlcv</code> and <code>--data-format-trades</code> 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:</p> <pre><code> // ...\n \"dataformat_ohlcv\": \"hdf5\",\n \"dataformat_trades\": \"hdf5\",\n // ...\n</code></pre> <p>If the default data-format has been changed during download, then the keys <code>dataformat_ohlcv</code> and <code>dataformat_trades</code> in the configuration file need to be adjusted to the selected dataformat as well.</p> <p>Note</p> <p>You can convert between data-formats using the convert-data and convert-trade-data methods.</p>"},{"location":"data-download/#sub-command-convert-data","title":"Sub-command convert data","text":"<pre><code>usage: freqtrade convert-data [-h] [-v] [--logfile FILE] [-V] [-c PATH]\n [-d PATH] [--userdir PATH]\n [-p PAIRS [PAIRS ...]] --format-from\n {json,jsongz,hdf5} --format-to\n {json,jsongz,hdf5} [--erase]\n [-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} ...]]\n\noptional arguments:\n -h, --help show this help message and exit\n -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]\n Show profits for only these pairs. Pairs are space-\n separated.\n --format-from {json,jsongz,hdf5}\n Source format for data conversion.\n --format-to {json,jsongz,hdf5}\n Destination format for data conversion.\n --erase Clean all existing data for the selected\n exchange/pairs/timeframes.\n -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} ...]\n Specify which tickers to download. Space-separated\n list. Default: `1m 5m`.\n\nCommon arguments:\n -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).\n --logfile FILE Log to the file specified. Special values are:\n 'syslog', 'journald'. See the documentation for more\n details.\n -V, --version show program's version number and exit\n -c PATH, --config PATH\n Specify configuration file (default:\n `userdir/config.json` or `config.json` whichever\n exists). Multiple --config options may be used. Can be\n set to `-` to read config from stdin.\n -d PATH, --datadir PATH\n Path to directory with historical backtesting data.\n --userdir PATH, --user-data-dir PATH\n Path to userdata directory.\n</code></pre>"},{"location":"data-download/#example-converting-data","title":"Example converting data","text":"<p>The following command will convert all candle (OHLCV) data available in <code>~/.freqtrade/data/binance</code> from json to jsongz, saving diskspace in the process. It'll also remove original json data files (<code>--erase</code> parameter).</p> <pre><code>freqtrade convert-data --format-from json --format-to jsongz --datadir ~/.freqtrade/data/binance -t 5m 15m --erase\n</code></pre>"},{"location":"data-download/#sub-command-convert-trade-data","title":"Sub-command convert trade data","text":"<pre><code>usage: freqtrade convert-trade-data [-h] [-v] [--logfile FILE] [-V] [-c PATH]\n [-d PATH] [--userdir PATH]\n [-p PAIRS [PAIRS ...]] --format-from\n {json,jsongz,hdf5} --format-to\n {json,jsongz,hdf5} [--erase]\n\noptional arguments:\n -h, --help show this help message and exit\n -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]\n Show profits for only these pairs. Pairs are space-\n separated.\n --format-from {json,jsongz,hdf5}\n Source format for data conversion.\n --format-to {json,jsongz,hdf5}\n Destination format for data conversion.\n --erase Clean all existing data for the selected\n exchange/pairs/timeframes.\n\nCommon arguments:\n -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).\n --logfile FILE Log to the file specified. Special values are:\n 'syslog', 'journald'. See the documentation for more\n details.\n -V, --version show program's version number and exit\n -c PATH, --config PATH\n Specify configuration file (default:\n `userdir/config.json` or `config.json` whichever\n exists). Multiple --config options may be used. Can be\n set to `-` to read config from stdin.\n -d PATH, --datadir PATH\n Path to directory with historical backtesting data.\n --userdir PATH, --user-data-dir PATH\n Path to userdata directory.\n</code></pre>"},{"location":"data-download/#example-converting-trades","title":"Example converting trades","text":"<p>The following command will convert all available trade-data in <code>~/.freqtrade/data/kraken</code> from jsongz to json. It'll also remove original jsongz data files (<code>--erase</code> parameter).</p> <pre><code>freqtrade convert-trade-data --format-from jsongz --format-to json --datadir ~/.freqtrade/data/kraken --erase\n</code></pre>"},{"location":"data-download/#sub-command-list-data","title":"Sub-command list-data","text":"<p>You can get a list of downloaded data using the <code>list-data</code> sub-command.</p> <pre><code>usage: freqtrade list-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]\n [--userdir PATH] [--exchange EXCHANGE]\n [--data-format-ohlcv {json,jsongz,hdf5}]\n [-p PAIRS [PAIRS ...]]\n\noptional arguments:\n -h, --help show this help message and exit\n --exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no\n config is provided.\n --data-format-ohlcv {json,jsongz,hdf5}\n Storage format for downloaded candle (OHLCV) data.\n (default: `json`).\n -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]\n Show profits for only these pairs. Pairs are space-\n separated.\n\nCommon arguments:\n -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).\n --logfile FILE Log to the file specified. Special values are:\n 'syslog', 'journald'. See the documentation for more\n details.\n -V, --version show program's version number and exit\n -c PATH, --config PATH\n Specify configuration file (default:\n `userdir/config.json` or `config.json` whichever\n exists). Multiple --config options may be used. Can be\n set to `-` to read config from stdin.\n -d PATH, --datadir PATH\n Path to directory with historical backtesting data.\n --userdir PATH, --user-data-dir PATH\n Path to userdata directory.\n</code></pre>"},{"location":"data-download/#example-list-data","title":"Example list-data","text":"<pre><code>> freqtrade list-data --userdir ~/.freqtrade/user_data/\n\nFound 33 pair / timeframe combinations.\npairs timeframe\n---------- -----------------------------------------\nADA/BTC 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d\nADA/ETH 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d\nETH/BTC 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d\nETH/USDT 5m, 15m, 30m, 1h, 2h, 4h\n</code></pre>"},{"location":"data-download/#pairs-file","title":"Pairs file","text":"<p>In alternative to the whitelist from <code>config.json</code>, a <code>pairs.json</code> file can be used.</p> <p>If you are using Binance for example:</p> <ul> <li>create a directory <code>user_data/data/binance</code> and copy or create the <code>pairs.json</code> file in that directory.</li> <li>update the <code>pairs.json</code> file to contain the currency pairs you are interested in.</li> </ul> <pre><code>mkdir -p user_data/data/binance\ncp tests/testdata/pairs.json user_data/data/binance\n</code></pre> <p>If you your configuration directory <code>user_data</code> was made by docker, you may get the following error:</p> <pre><code>cp: cannot create regular file 'user_data/data/binance/pairs.json': Permission denied\n</code></pre> <p>You can fix the permissions of your user-data directory as follows:</p> <pre><code>sudo chown -R $UID:$GID user_data\n</code></pre> <p>The format of the <code>pairs.json</code> file is a simple json list. Mixing different stake-currencies is allowed for this file, since it's only used for downloading.</p> <pre><code>[\n \"ETH/BTC\",\n \"ETH/USDT\",\n \"BTC/USDT\",\n \"XRP/ETH\"\n]\n</code></pre>"},{"location":"data-download/#start-download","title":"Start download","text":"<p>Then run:</p> <pre><code>freqtrade download-data --exchange binance\n</code></pre> <p>This will download historical candle (OHLCV) data for all the currency pairs you defined in <code>pairs.json</code>.</p>"},{"location":"data-download/#other-notes","title":"Other Notes","text":"<ul> <li>To use a different directory than the exchange specific default, use <code>--datadir user_data/data/some_directory</code>.</li> <li>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.)</li> <li>To use <code>pairs.json</code> from some other directory, use <code>--pairs-file some_other_dir/pairs.json</code>.</li> <li>To download historical candle (OHLCV) data for only 10 days, use <code>--days 10</code> (defaults to 30 days).</li> <li>To download historical candle (OHLCV) data from a fixed starting point, use <code>--timerange 20200101-</code> - which will download all data from January 1<sup>st</sup>, 2020. Eventually set end dates are ignored.</li> <li>Use <code>--timeframes</code> to specify what timeframe download the historical candle (OHLCV) data for. Default is <code>--timeframes 1m 5m</code> which will download 1-minute and 5-minute data.</li> <li>To use exchange, timeframe and list of pairs as defined in your configuration file, use the <code>-c/--config</code> 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 <code>-c/--config</code> with most other options.</li> </ul>"},{"location":"data-download/#trades-tick-data","title":"Trades (tick) data","text":"<p>By default, <code>download-data</code> 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.</p> <p>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 <code><pair>-trades.json.gz</code> (<code>ETH_BTC-trades.json.gz</code>). Incremental mode is also supported, as for historic OHLCV data, so downloading the data once per week with <code>--days 8</code> will create an incremental data-repository.</p> <p>To use this mode, simply add <code>--dl-trades</code> to your call. This will swap the download method to download trades, and resamples the data locally.</p> <p>do not use</p> <p>You should not use this unless you're a kraken user. Most other exchanges provide OHLCV data with sufficient history.</p> <p>Example call:</p> <pre><code>freqtrade download-data --exchange kraken --pairs XRP/EUR ETH/EUR --days 20 --dl-trades\n</code></pre> <p>Note</p> <p>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.</p> <p>Warning</p> <p>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.</p> <p>Kraken user</p> <p>Kraken users should read this before starting to download data.</p>"},{"location":"data-download/#next-step","title":"Next step","text":"<p>Great, you now have backtest data downloaded, so you can now start backtesting your strategy.</p>"},{"location":"deprecated/","title":"Deprecated features","text":"<p>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.</p>"},{"location":"deprecated/#removed-features","title":"Removed features","text":""},{"location":"deprecated/#the-refresh-pairs-cached-command-line-option","title":"the <code>--refresh-pairs-cached</code> command line option","text":"<p><code>--refresh-pairs-cached</code> 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 <code>freqtrade download-data</code>.</p> <p>This command line option was deprecated in 2019.7-dev (develop branch) and removed in 2019.9.</p>"},{"location":"deprecated/#the-dynamic-whitelist-command-line-option","title":"The --dynamic-whitelist command line option","text":"<p>This command line option was deprecated in 2018 and removed freqtrade 2019.6-dev (develop branch) and in freqtrade 2019.7.</p>"},{"location":"deprecated/#the-live-command-line-option","title":"the <code>--live</code> command line option","text":"<p><code>--live</code> 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.</p>"},{"location":"deprecated/#allow-running-multiple-pairlists-in-sequence","title":"Allow running multiple pairlists in sequence","text":"<p>The former <code>\"pairlist\"</code> section in the configuration has been removed, and is replaced by <code>\"pairlists\"</code> - being a list to specify a sequence of pairlists.</p> <p>The old section of configuration parameters (<code>\"pairlist\"</code>) has been deprecated in 2019.11 and has been removed in 2020.4.</p>"},{"location":"deprecated/#deprecation-of-bidvolume-and-askvolume-from-volume-pairlist","title":"deprecation of bidVolume and askVolume from volume-pairlist","text":"<p>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.</p>"},{"location":"developer/","title":"Development Help","text":"<p>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.</p> <p>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 or slack where you can ask questions.</p>"},{"location":"developer/#documentation","title":"Documentation","text":"<p>Documentation is available at https://freqtrade.io and needs to be provided with every new feature PR.</p> <p>Special fields for the documentation (like Note boxes, ...) can be found here.</p> <p>To test the documentation locally use the following commands.</p> <pre><code>pip install -r docs/requirements-docs.txt\nmkdocs serve\n</code></pre> <p>This will spin up a local server (usually on port 8000) so you can see if everything looks as you'd like it to.</p>"},{"location":"developer/#developer-setup","title":"Developer setup","text":"<p>To configure a development environment, you can either use the provided DevContainer, or use the <code>setup.sh</code> 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 <code>pip3 install -e .[all]</code>.</p> <p>This will install all required tools for development, including <code>pytest</code>, <code>flake8</code>, <code>mypy</code>, and <code>coveralls</code>.</p>"},{"location":"developer/#devcontainer-setup","title":"Devcontainer setup","text":"<p>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.</p>"},{"location":"developer/#devcontainer-dependencies","title":"Devcontainer dependencies","text":"<ul> <li>VSCode</li> <li>docker</li> <li>Remote container extension documentation</li> </ul> <p>For more information about the Remote container extension, best consult the documentation.</p>"},{"location":"developer/#tests","title":"Tests","text":"<p>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).</p>"},{"location":"developer/#checking-log-content-in-tests","title":"Checking log content in tests","text":"<p>Freqtrade uses 2 main methods to check log content in tests, <code>log_has()</code> and <code>log_has_re()</code> (to check using regex, in case of dynamic log-messages). These are available from <code>conftest.py</code> and can be imported in any test module.</p> <p>A sample check looks as follows:</p> <pre><code>from tests.conftest import log_has, log_has_re\n\ndef test_method_to_test(caplog):\n method_to_test()\n\n assert log_has(\"This event happened\", caplog)\n # Check regex with trailing number ...\n assert log_has_re(r\"This dynamic event happened and produced \\d+\", caplog)\n</code></pre>"},{"location":"developer/#errorhandling","title":"ErrorHandling","text":"<p>Freqtrade Exceptions all inherit from <code>FreqtradeException</code>. This general class of error should however not be used directly. Instead, multiple specialized sub-Exceptions exist.</p> <p>Below is an outline of exception inheritance hierarchy:</p> <pre><code>+ FreqtradeException\n|\n+---+ OperationalException\n|\n+---+ DependencyException\n| |\n| +---+ PricingError\n| |\n| +---+ ExchangeError\n| |\n| +---+ TemporaryError\n| |\n| +---+ DDosProtection\n| |\n| +---+ InvalidOrderException\n| |\n| +---+ RetryableOrderError\n| |\n| +---+ InsufficientFundsError\n|\n+---+ StrategyError\n</code></pre>"},{"location":"developer/#plugins","title":"Plugins","text":""},{"location":"developer/#pairlists","title":"Pairlists","text":"<p>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.</p> <p>Whatever your motivations are - This should get you off the ground in trying to develop a new Pairlist Handler.</p> <p>First of all, have a look at the VolumePairList Handler, and best copy this file with a name of your new Pairlist Handler.</p> <p>This is a simple Handler, which however serves as a good example on how to start developing.</p> <p>Next, modify the class-name of the Handler (ideally align this with the module filename).</p> <p>The base-class provides an instance of the exchange (<code>self._exchange</code>) the pairlist manager (<code>self._pairlistmanager</code>), as well as the main configuration (<code>self._config</code>), the pairlist dedicated configuration (<code>self._pairlistconfig</code>) and the absolute position within the list of pairlists.</p> <pre><code> self._exchange = exchange\n self._pairlistmanager = pairlistmanager\n self._config = config\n self._pairlistconfig = pairlistconfig\n self._pairlist_pos = pairlist_pos\n</code></pre> <p>Tip</p> <p>Don't forget to register your pairlist in <code>constants.py</code> under the variable <code>AVAILABLE_PAIRLISTS</code> - otherwise it will not be selectable.</p> <p>Now, let's step through the methods which require actions:</p>"},{"location":"developer/#pairlist-configuration","title":"Pairlist configuration","text":"<p>Configuration for the chain of Pairlist Handlers is done in the bot configuration file in the element <code>\"pairlists\"</code>, an array of configuration parameters for each Pairlist Handlers in the chain.</p> <p>By convention, <code>\"number_assets\"</code> is used to specify the maximum number of pairs to keep in the pairlist. Please follow this to ensure a consistent user experience.</p> <p>Additional parameters can be configured as needed. For instance, <code>VolumePairList</code> uses <code>\"sort_key\"</code> to specify the sorting value - however feel free to specify whatever is necessary for your great algorithm to be successful and dynamic.</p>"},{"location":"developer/#short_desc","title":"short_desc","text":"<p>Returns a description used for Telegram messages.</p> <p>This should contain the name of the Pairlist Handler, as well as a short description containing the number of assets. Please follow the format <code>\"PairlistName - top/bottom X pairs\"</code>.</p>"},{"location":"developer/#gen_pairlist","title":"gen_pairlist","text":"<p>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 <code>StaticPairList</code> and <code>VolumePairList</code>.</p> <p>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.</p> <p>It must return the resulting pairlist (which may then be passed into the chain of Pairlist Handlers).</p> <p>Validations are optional, the parent class exposes a <code>_verify_blacklist(pairlist)</code> and <code>_whitelist_for_active_markets(pairlist)</code> 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.</p>"},{"location":"developer/#filter_pairlist","title":"filter_pairlist","text":"<p>This method is called for each Pairlist Handler in the chain by the pairlist manager.</p> <p>This is called with each iteration of the bot - so consider implementing caching for compute/network heavy calculations.</p> <p>It gets passed a pairlist (which can be the result of previous pairlists) as well as <code>tickers</code>, a pre-fetched version of <code>get_tickers()</code>.</p> <p>The default implementation in the base class simply calls the <code>_validate_pair()</code> method for each pair in the pairlist, but you may override it. So you should either implement the <code>_validate_pair()</code> in your Pairlist Handler or override <code>filter_pairlist()</code> to do something else.</p> <p>If overridden, it must return the resulting pairlist (which may then be passed into the next Pairlist Handler in the chain).</p> <p>Validations are optional, the parent class exposes a <code>_verify_blacklist(pairlist)</code> and <code>_whitelist_for_active_markets(pairlist)</code> 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.</p> <p>In <code>VolumePairList</code>, this implements different methods of sorting, does early validation so only the expected number of pairs is returned.</p>"},{"location":"developer/#sample","title":"sample","text":"<pre><code> def filter_pairlist(self, pairlist: List[str], tickers: Dict) -> List[str]:\n # Generate dynamic whitelist\n pairs = self._calculate_pairlist(pairlist, tickers)\n return pairs\n</code></pre>"},{"location":"developer/#protections","title":"Protections","text":"<p>Best read the Protection documentation to understand protections. This Guide is directed towards Developers who want to develop a new protection.</p> <p>No protection should use datetime directly, but use the provided <code>date_now</code> variable for date calculations. This preserves the ability to backtest protections.</p> <p>Writing a new Protection</p> <p>Best copy one of the existing Protections to have a good example. Don't forget to register your protection in <code>constants.py</code> under the variable <code>AVAILABLE_PROTECTIONS</code> - otherwise it will not be selectable.</p>"},{"location":"developer/#implementation-of-a-new-protection","title":"Implementation of a new protection","text":"<p>All Protection implementations must have <code>IProtection</code> as parent class. For that reason, they must implement the following methods:</p> <ul> <li><code>short_desc()</code></li> <li><code>global_stop()</code></li> <li><code>stop_per_pair()</code>.</li> </ul> <p><code>global_stop()</code> and <code>stop_per_pair()</code> must return a ProtectionReturn tuple, which consists of:</p> <ul> <li>lock pair - boolean</li> <li>lock until - datetime - until when should the pair be locked (will be rounded up to the next new candle)</li> <li>reason - string, used for logging and storage in the database</li> </ul> <p>The <code>until</code> portion should be calculated using the provided <code>calculate_lock_end()</code> method.</p> <p>All Protections should use <code>\"stop_duration\"</code> / <code>\"stop_duration_candles\"</code> to define how long a a pair (or all pairs) should be locked. The content of this is made available as <code>self._stop_duration</code> to the each Protection.</p> <p>If your protection requires a look-back period, please use <code>\"lookback_period\"</code> / <code>\"lockback_period_candles\"</code> to keep all protections aligned.</p>"},{"location":"developer/#global-vs-local-stops","title":"Global vs. local stops","text":"<p>Protections can have 2 different ways to stop trading for a limited :</p> <ul> <li>Per pair (local)</li> <li>For all Pairs (globally)</li> </ul>"},{"location":"developer/#protections-per-pair","title":"Protections - per pair","text":"<p>Protections that implement the per pair approach must set <code>has_local_stop=True</code>. The method <code>stop_per_pair()</code> will be called whenever a trade closed (sell order completed).</p>"},{"location":"developer/#protections-global-protection","title":"Protections - global protection","text":"<p>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 <code>has_global_stop=True</code> to be evaluated for global stops. The method <code>global_stop()</code> will be called whenever a trade closed (sell order completed).</p>"},{"location":"developer/#protections-calculating-lock-end-time","title":"Protections - calculating lock end time","text":"<p>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.</p> <p>The <code>IProtection</code> parent class provides a helper method for this in <code>calculate_lock_end()</code>.</p>"},{"location":"developer/#implement-a-new-exchange-wip","title":"Implement a new Exchange (WIP)","text":"<p>Note</p> <p>This section is a Work in Progress and is not a complete guide on how to test a new exchange with Freqtrade.</p> <p>Most exchanges supported by CCXT should work out of the box.</p> <p>To quickly test the public endpoints of an exchange, add a configuration for your exchange to <code>test_ccxt_compat.py</code> and run these tests with <code>pytest --longrun tests/exchange/test_ccxt_compat.py</code>. 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).</p>"},{"location":"developer/#stoploss-on-exchange","title":"Stoploss On Exchange","text":"<p>Check if the new exchange supports Stoploss on Exchange orders through their API.</p> <p>Since CCXT does not provide unification for Stoploss On Exchange yet, we'll need to implement the exchange-specific parameters ourselves. Best look at <code>binance.py</code> 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.</p>"},{"location":"developer/#incomplete-candles","title":"Incomplete candles","text":"<p>While fetching candle (OHLCV) data, we may end up getting incomplete candles (depending on the exchange). To demonstrate this, we'll use daily candles (<code>\"1d\"</code>) to keep things simple. We query the api (<code>ct.fetch_ohlcv()</code>) 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.</p> <p>To check how the new exchange behaves, you can use the following snippet:</p> <pre><code>import ccxt\nfrom datetime import datetime\nfrom freqtrade.data.converter import ohlcv_to_dataframe\nct = ccxt.binance()\ntimeframe = \"1d\"\npair = \"XLM/BTC\" # Make sure to use a pair that exists on that exchange!\nraw = ct.fetch_ohlcv(pair, timeframe=timeframe)\n\n# convert to dataframe\ndf1 = ohlcv_to_dataframe(raw, timeframe, pair=pair, drop_incomplete=False)\n\nprint(df1.tail(1))\nprint(datetime.utcnow())\n</code></pre> <pre><code> date open high low close volume \n499 2019-06-08 00:00:00+00:00 0.000007 0.000007 0.000007 0.000007 26264344.0 \n2019-06-09 12:30:27.873327\n</code></pre> <p>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 <code>\"ohlcv_partial_candle\"</code> from the exchange-class untouched / True). Otherwise, set <code>\"ohlcv_partial_candle\"</code> to <code>False</code> 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).</p>"},{"location":"developer/#updating-example-notebooks","title":"Updating example notebooks","text":"<p>To keep the jupyter notebooks aligned with the documentation, the following should be ran after updating a example notebook.</p> <pre><code>jupyter nbconvert --ClearOutputPreprocessor.enabled=True --inplace freqtrade/templates/strategy_analysis_example.ipynb\njupyter nbconvert --ClearOutputPreprocessor.enabled=True --to markdown freqtrade/templates/strategy_analysis_example.ipynb --stdout > docs/strategy_analysis_example.md\n</code></pre>"},{"location":"developer/#continuous-integration","title":"Continuous integration","text":"<p>This documents some decisions taken for the CI Pipeline.</p> <ul> <li>CI runs on all OS variants, Linux (ubuntu), macOS and Windows.</li> <li>Docker images are build for the branches <code>stable</code> and <code>develop</code>.</li> <li>Docker images containing Plot dependencies are also available as <code>stable_plot</code> and <code>develop_plot</code>.</li> <li>Raspberry PI Docker images are postfixed with <code>_pi</code> - so tags will be <code>:stable_pi</code> and <code>develop_pi</code>.</li> <li>Docker images contain a file, <code>/freqtrade/freqtrade_commit</code> containing the commit this image is based of.</li> <li>Full docker image rebuilds are run once a week via schedule.</li> <li>Deployments run on ubuntu.</li> <li>ta-lib binaries are contained in the build_helpers directory to avoid fails related to external unavailability.</li> <li>All tests must pass for a PR to be merged to <code>stable</code> or <code>develop</code>.</li> </ul>"},{"location":"developer/#creating-a-release","title":"Creating a release","text":"<p>This part of the documentation is aimed at maintainers, and shows how to create a release.</p>"},{"location":"developer/#create-release-branch","title":"Create release branch","text":"<p>First, pick a commit that's about one week old (to not include latest additions to releases).</p> <pre><code># create new branch\ngit checkout -b new_release <commitid>\n</code></pre> <p>Determine if crucial bugfixes have been made between this commit and the current state, and eventually cherry-pick these.</p> <ul> <li>Merge the release branch (stable) into this branch.</li> <li>Edit <code>freqtrade/__init__.py</code> and add the version matching the current date (for example <code>2019.7</code> for July 2019). Minor versions can be <code>2019.7.1</code> should we need to do a second release that month. Version numbers must follow allowed versions from PEP0440 to avoid failures pushing to pypi.</li> <li>Commit this part</li> <li>push that branch to the remote and create a PR against the stable branch</li> </ul>"},{"location":"developer/#create-changelog-from-git-commits","title":"Create changelog from git commits","text":"<p>Note</p> <p>Make sure that the <code>stable</code> branch is up-to-date!</p> <pre><code># Needs to be done before merging / pulling that branch.\ngit log --oneline --no-decorate --no-merges stable..new_release\n</code></pre> <p>To keep the release-log short, best wrap the full git changelog into a collapsible details section.</p> <pre><code><details>\n<summary>Expand full changelog</summary>\n\n... Full git changelog\n\n</details>\n</code></pre>"},{"location":"developer/#create-github-release-tag","title":"Create github release / tag","text":"<p>Once the PR against stable is merged (best right after merging):</p> <ul> <li>Use the button \"Draft a new release\" in the Github UI (subsection releases).</li> <li>Use the version-number specified as tag.</li> <li>Use \"stable\" as reference (this step comes after the above PR is merged).</li> <li>Use the above changelog as release comment (as codeblock)</li> </ul>"},{"location":"developer/#releases","title":"Releases","text":""},{"location":"developer/#pypi","title":"pypi","text":"<p>Note</p> <p>This process is now automated as part of Github Actions.</p> <p>To create a pypi release, please run the following commands:</p> <p>Additional requirement: <code>wheel</code>, <code>twine</code> (for uploading), account on pypi with proper permissions.</p> <pre><code>python setup.py sdist bdist_wheel\n\n# For pypi test (to check if some change to the installation did work)\ntwine upload --repository-url https://test.pypi.org/legacy/ dist/*\n\n# For production:\ntwine upload dist/*\n</code></pre> <p>Please don't push non-releases to the productive / real pypi instance.</p>"},{"location":"docker_quickstart/","title":"Using Freqtrade with Docker","text":""},{"location":"docker_quickstart/#install-docker","title":"Install Docker","text":"<p>Start by downloading and installing Docker CE for your platform:</p> <ul> <li>Mac</li> <li>Windows</li> <li>Linux</li> </ul> <p>To simplify running freqtrade, please install <code>docker-compose</code> should be installed and available to follow the below docker quick start guide.</p>"},{"location":"docker_quickstart/#freqtrade-with-docker-compose","title":"Freqtrade with docker-compose","text":"<p>Freqtrade provides an official Docker image on Dockerhub, as well as a docker-compose file ready for usage.</p> <p>Note</p> <ul> <li>The following section assumes that <code>docker</code> and <code>docker-compose</code> are installed and available to the logged in user.</li> <li>All below commands use relative directories and will have to be executed from the directory containing the <code>docker-compose.yml</code> file.</li> </ul>"},{"location":"docker_quickstart/#docker-quick-start","title":"Docker quick start","text":"<p>Create a new directory and place the docker-compose file in this directory.</p> PC/MAC/Linux <pre><code>mkdir ft_userdata\ncd ft_userdata/\n# Download the docker-compose file from the repository\ncurl https://raw.githubusercontent.com/freqtrade/freqtrade/stable/docker-compose.yml -o docker-compose.yml\n\n# Pull the freqtrade image\ndocker-compose pull\n\n# Create user directory structure\ndocker-compose run --rm freqtrade create-userdir --userdir user_data\n\n# Create configuration - Requires answering interactive questions\ndocker-compose run --rm freqtrade new-config --config user_data/config.json\n</code></pre> RaspberryPi <pre><code>mkdir ft_userdata\ncd ft_userdata/\n# Download the docker-compose file from the repository\ncurl https://raw.githubusercontent.com/freqtrade/freqtrade/stable/docker-compose.yml -o docker-compose.yml\n\n# Pull the freqtrade image\ndocker-compose pull\n\n# Create user directory structure\ndocker-compose run --rm freqtrade create-userdir --userdir user_data\n\n# Create configuration - Requires answering interactive questions\ndocker-compose run --rm freqtrade new-config --config user_data/config.json\n</code></pre> <p>Change your docker Image</p> <p>You have to change the docker image in the docker-compose file for your Raspberry build to work properly. <pre><code>image: freqtradeorg/freqtrade:stable_pi\n# image: freqtradeorg/freqtrade:develop_pi\n</code></pre></p> <p>The above snippet creates a new directory called <code>ft_userdata</code>, downloads the latest compose file and pulls the freqtrade image. The last 2 steps in the snippet create the directory with <code>user_data</code>, as well as (interactively) the default configuration based on your selections.</p> <p>How to edit the bot configuration?</p> <p>You can edit the configuration at any time, which is available as <code>user_data/config.json</code> (within the directory <code>ft_userdata</code>) when using the above configuration.</p> <p>You can also change the both Strategy and commands by editing the command section of your <code>docker-compose.yml</code> file.</p>"},{"location":"docker_quickstart/#adding-a-custom-strategy","title":"Adding a custom strategy","text":"<ol> <li>The configuration is now available as <code>user_data/config.json</code></li> <li>Copy a custom strategy to the directory <code>user_data/strategies/</code></li> <li>add the Strategy' class name to the <code>docker-compose.yml</code> file</li> </ol> <p>The <code>SampleStrategy</code> is run by default.</p> <p><code>SampleStrategy</code> is just a demo!</p> <p>The <code>SampleStrategy</code> 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.</p> <p>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).</p> <pre><code>docker-compose up -d\n</code></pre>"},{"location":"docker_quickstart/#monitoring-the-bot","title":"Monitoring the bot","text":"<p>You can check for running instances with <code>docker-compose ps</code>. This should list the service <code>freqtrade</code> as <code>running</code>. If that's not the case, best check the logs (see next point).</p>"},{"location":"docker_quickstart/#docker-compose-logs","title":"Docker-compose logs","text":"<p>Logs will be written to: <code>user_data/logs/freqtrade.log</code>. You can also check the latest log with the command <code>docker-compose logs -f</code>.</p>"},{"location":"docker_quickstart/#database","title":"Database","text":"<p>The database will be located at: <code>user_data/tradesv3.sqlite</code></p>"},{"location":"docker_quickstart/#updating-freqtrade-with-docker-compose","title":"Updating freqtrade with docker-compose","text":"<p>Updating freqtrade when using <code>docker-compose</code> is as simple as running the following 2 commands:</p> <pre><code># Download the latest image\ndocker-compose pull\n# Restart the image\ndocker-compose up -d\n</code></pre> <p>This will first pull the latest image, and will then restart the container with the just pulled version.</p> <p>Check the Changelog</p> <p>You should always check the changelog for breaking changes / manual interventions required and make sure the bot starts correctly after the update.</p>"},{"location":"docker_quickstart/#editing-the-docker-compose-file","title":"Editing the docker-compose file","text":"<p>Advanced users may edit the docker-compose file further to include all possible options or arguments.</p> <p>All freqtrade arguments will be available by running <code>docker-compose run --rm freqtrade <command> <optional arguments></code>.</p> <p><code>docker-compose run --rm</code></p> <p>Including <code>--rm</code> will remove the container after completion, and is highly recommended for all modes except trading mode (running with <code>freqtrade trade</code> command).</p>"},{"location":"docker_quickstart/#example-download-data-with-docker-compose","title":"Example: Download data with docker-compose","text":"<p>Download backtesting data for 5 days for the pair ETH/BTC and 1h timeframe from Binance. The data will be stored in the directory <code>user_data/data/</code> on the host.</p> <pre><code>docker-compose run --rm freqtrade download-data --pairs ETH/BTC --exchange binance --days 5 -t 1h\n</code></pre> <p>Head over to the Data Downloading Documentation for more details on downloading data.</p>"},{"location":"docker_quickstart/#example-backtest-with-docker-compose","title":"Example: Backtest with docker-compose","text":"<p>Run backtesting in docker-containers for SampleStrategy and specified timerange of historical data, on 5m timeframe:</p> <pre><code>docker-compose run --rm freqtrade backtesting --config user_data/config.json --strategy SampleStrategy --timerange 20190801-20191001 -i 5m\n</code></pre> <p>Head over to the Backtesting Documentation to learn more.</p>"},{"location":"docker_quickstart/#additional-dependencies-with-docker-compose","title":"Additional dependencies with docker-compose","text":"<p>If your strategy requires dependencies not included in the default image (like technical) - 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.technical for an example).</p> <p>You'll then also need to modify the <code>docker-compose.yml</code> file and uncomment the build step, as well as rename the image to avoid naming collisions.</p> <pre><code> image: freqtrade_custom\n build:\n context: .\n dockerfile: \"./Dockerfile.<yourextension>\"\n</code></pre> <p>You can then run <code>docker-compose build</code> to build the docker image, and run it using the commands described above.</p>"},{"location":"docker_quickstart/#plotting-with-docker-compose","title":"Plotting with docker-compose","text":"<p>Commands <code>freqtrade plot-profit</code> and <code>freqtrade plot-dataframe</code> (Documentation) are available by changing the image to <code>*_plot</code> in your docker-compose.yml file. You can then use these commands as follows:</p> <pre><code>docker-compose run --rm freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH --timerange=20180801-20180805\n</code></pre> <p>The output will be stored in the <code>user_data/plot</code> directory, and can be opened with any modern browser.</p>"},{"location":"docker_quickstart/#data-analysis-using-docker-compose","title":"Data analysis using docker compose","text":"<p>Freqtrade provides a docker-compose file which starts up a jupyter lab server. You can run this server using the following command:</p> <pre><code>docker-compose -f docker/docker-compose-jupyter.yml up\n</code></pre> <p>This will create a docker-container running jupyter lab, which will be accessible using <code>https://127.0.0.1:8888/lab</code>. Please use the link that's printed in the console after startup for simplified login.</p> <p>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.</p> <pre><code>docker-compose -f docker/docker-compose-jupyter.yml build --no-cache\n</code></pre>"},{"location":"edge/","title":"Edge positioning","text":"<p>The <code>Edge Positioning</code> 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. </p> <p>Warning</p> <p><code>Edge positioning</code> is not compatible with dynamic (volume-based) whitelist.</p> <p>Note</p> <p><code>Edge Positioning</code> only considers its own buy/sell/stoploss signals. It ignores the stoploss, trailing stoploss, and ROI settings in the strategy configuration file. <code>Edge Positioning</code> improves the performance of some trading strategies and decreases the performance of others.</p>"},{"location":"edge/#introduction","title":"Introduction","text":"<p>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.</p> <p>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. </p> <p>It doesn't matter how often, but how much!</p> <p>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.</p> <p>The Edge Positioning module seeks to improve a strategy's winning probability and the money that the strategy will make on the long run. </p> <p>We raise the following question<sup>1</sup>:</p> <p>Which trade is a better option?</p> <p>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$</p> Answer <p>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</p> <p>Another way to look at it is to ask a similar question:</p> <p>Which trade is a better option?</p> <p>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$</p> <p>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.</p>"},{"location":"edge/#trading-winning-and-losing","title":"Trading, winning and losing","text":"<p>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.</p> <p>Example</p> <p>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\\).</p> <p>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:</p> \\[ T_{win} = \\{ o \\in O | o > 0 \\} \\] <p>Similarly, we can discover the set of losing trades \\(T_{lose}\\) as follows:</p> \\[ T_{lose} = \\{o \\in O | o \\leq 0\\} \\] <p>Example</p> <p>In a section where a strategy made four transactions \\(O = \\{3.5, -1, 15, 0\\}\\): \\(T_{win} = \\{3.5, 15\\}\\) \\(T_{lose} = \\{-1, 0\\}\\)</p>"},{"location":"edge/#win-rate-and-lose-rate","title":"Win Rate and Lose Rate","text":"<p>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:</p> \\[W = \\frac{|T_{win}|}{N}\\] <p>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.</p> <p>Similarly, we can compute the rate of losing trades:</p> \\[ L = \\frac{|T_{lose}|}{N} \\] <p>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\\)</p>"},{"location":"edge/#risk-reward-ratio","title":"Risk Reward Ratio","text":"<p>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:</p> \\[ R = \\frac{\\text{potential_profit}}{\\text{potential_loss}} \\] Worked example of \\(R\\) calculation <p>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).</p> <p>Your potential profit is calculated as:</p> <p>\\(\\begin{aligned} \\text{potential_profit} &= (\\text{potential_price} - \\text{entry_price}) * \\frac{\\text{investment}}{\\text{entry_price}} \\\\ &= (15 - 10) * (100 / 10) \\\\ &= 50 \\end{aligned}\\)</p> <p>Since the price might go to 0$, the 100$ dollars invested could turn into 0.</p> <p>We do however use a stoploss of 15% - so in the worst case, we'll sell 15% below entry price (or at 8.5$).</p> <p>\\(\\begin{aligned} \\text{potential_loss} &= (\\text{entry_price} - \\text{stoploss}) * \\frac{\\text{investment}}{\\text{entry_price}} \\\\ &= (10 - 8.5) * (100 / 10)\\\\ &= 15 \\end{aligned}\\)</p> <p>We can compute the Risk Reward Ratio as follows:</p> <p>\\(\\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.</p> <p>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:</p> \\[ \\text{average_profit} = \\mu_{win} = \\frac{\\text{sum_of_profits}}{\\text{count_winning_trades}} = \\frac{\\sum^{o \\in T_{win}} o}{|T_{win}|} \\] <p>Similarly, we can calculate the average loss, \\(\\mu_{lose}\\), as follows:</p> \\[ \\text{average_loss} = \\mu_{lose} = \\frac{\\text{sum_of_losses}}{\\text{count_losing_trades}} = \\frac{\\sum^{o \\in T_{lose}} o}{|T_{lose}|} \\] <p>Finally, we can calculate the Risk Reward ratio, \\(R\\), as follows:</p> \\[ R = \\frac{\\text{average_profit}}{\\text{average_loss}} = \\frac{\\mu_{win}}{\\mu_{lose}}\\\\ \\] Worked example of \\(R\\) calculation using mean profit/loss <p>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...\\)</p>"},{"location":"edge/#expectancy","title":"Expectancy","text":"<p>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:</p> \\[E = R * W - L\\] <p>Calculating \\(E\\)</p> <p>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\\) </p> <p>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. </p> <p>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.</p> <p>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.</p> <p>You can also use this value to evaluate the effectiveness of modifications to this system.</p> <p>Note</p> <p>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.</p>"},{"location":"edge/#how-does-it-work","title":"How does it work?","text":"<p>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:</p> 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 <p>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.</p> <p>Edge module then forces stoploss value it evaluated to your strategy dynamically.</p>"},{"location":"edge/#position-size","title":"Position size","text":"<p>Edge dictates the amount at stake for each trade to the bot according to the following factors:</p> <ul> <li>Allowed capital at risk</li> <li>Stoploss</li> </ul> <p>Allowed capital at risk is calculated as follows:</p> <pre><code>Allowed capital at risk = (Capital available_percentage) X (Allowed risk per trade)\n</code></pre> <p>Stoploss is calculated as described above with respect to historical data.</p> <p>The position size is calculated as follows:</p> <pre><code>Position size = (Allowed capital at risk) / Stoploss\n</code></pre> <p>Example:</p> <p>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.</p> <ul> <li>Trade 1: The strategy detects a new buy signal in the XLM/ETH market. <code>Edge Positioning</code> 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.</li> </ul> <ul> <li>Trade 2: The strategy detects a buy signal on the BTC/ETH market while Trade 1 is still open. <code>Edge Positioning</code> calculates the stoploss of \\(4\\%\\) on this market. Thus, Trade 2 position size is \\(0.05 / 0.04 = 1.25\\) ETH.</li> </ul> <p>Available Capital \\(\\neq\\) Available in wallet</p> <p>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.</p> <ul> <li>Trade 3: The strategy detects a buy signal in the ADA/ETH market. <code>Edge Positioning</code> 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. </li> </ul> <p>Available Capital Updates</p> <p>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.</p> <ul> <li>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.</li> </ul> <ul> <li>Trade 4 The strategy detects a new buy signal int the XLM/ETH market. <code>Edge Positioning</code> calculates the stoploss of \\(2\\%\\), and the position size of \\(0.055 / 0.02 = 2.75\\) ETH.</li> </ul>"},{"location":"edge/#edge-command-reference","title":"Edge command reference","text":"<pre><code>usage: freqtrade edge [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]\n [--userdir PATH] [-s NAME] [--strategy-path PATH]\n [-i TIMEFRAME] [--timerange TIMERANGE]\n [--max-open-trades INT] [--stake-amount STAKE_AMOUNT]\n [--fee FLOAT] [--stoplosses STOPLOSS_RANGE]\n\noptional arguments:\n -h, --help show this help message and exit\n -i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME\n Specify ticker interval (`1m`, `5m`, `30m`, `1h`,\n `1d`).\n --timerange TIMERANGE\n Specify what timerange of data to use.\n --max-open-trades INT\n Override the value of the `max_open_trades`\n configuration setting.\n --stake-amount STAKE_AMOUNT\n Override the value of the `stake_amount` configuration\n setting.\n --fee FLOAT Specify fee ratio. Will be applied twice (on trade\n entry and exit).\n --stoplosses STOPLOSS_RANGE\n Defines a range of stoploss values against which edge\n will assess the strategy. The format is \"min,max,step\"\n (without any space). Example:\n `--stoplosses=-0.01,-0.1,-0.001`\n\nCommon arguments:\n -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).\n --logfile FILE Log to the file specified. Special values are:\n 'syslog', 'journald'. See the documentation for more\n details.\n -V, --version show program's version number and exit\n -c PATH, --config PATH\n Specify configuration file (default:\n `userdir/config.json` or `config.json` whichever\n exists). Multiple --config options may be used. Can be\n set to `-` to read config from stdin.\n -d PATH, --datadir PATH\n Path to directory with historical backtesting data.\n --userdir PATH, --user-data-dir PATH\n Path to userdata directory.\n\nStrategy arguments:\n -s NAME, --strategy NAME\n Specify strategy class name which will be used by the\n bot.\n --strategy-path PATH Specify additional strategy lookup path.\n</code></pre>"},{"location":"edge/#configurations","title":"Configurations","text":"<p>Edge module has following configuration options:</p> Parameter Description <code>enabled</code> If true, then Edge will run periodically. Defaults to <code>false</code>. Datatype: Boolean <code>process_throttle_secs</code> How often should Edge run in seconds. Defaults to <code>3600</code> (once per hour). Datatype: Integer <code>calculate_since_number_of_days</code> 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 <code>7</code>. Datatype: Integer <code>allowed_risk</code> Ratio of allowed risk per trade. Defaults to <code>0.01</code> (1%)). Datatype: Float <code>stoploss_range_min</code> Minimum stoploss. Defaults to <code>-0.01</code>. Datatype: Float <code>stoploss_range_max</code> Maximum stoploss. Defaults to <code>-0.10</code>. Datatype: Float <code>stoploss_range_step</code> As an example if this is set to -0.01 then Edge will test the strategy for <code>[-0.01, -0,02, -0,03 ..., -0.09, -0.10]</code> 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 <code>-0.001</code>. Datatype: Float <code>minimum_winrate</code> 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 <code>0.60</code>. Datatype: Float <code>minimum_expectancy</code> 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 <code>0.20</code>. Datatype: Float <code>min_trade_number</code> 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 <code>10</code> (it is highly recommended not to decrease this number). Datatype: Integer <code>max_trade_duration_minute</code> 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 <code>1440</code> (one day). Datatype: Integer <code>remove_pumps</code> 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 <code>false</code>. Datatype: Boolean"},{"location":"edge/#running-edge-independently","title":"Running Edge independently","text":"<p>You can run Edge independently in order to see in details the result. Here is an example:</p> <pre><code>freqtrade edge\n</code></pre> <p>An example of its output:</p> 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 <p>Edge produced the above table by comparing <code>calculate_since_number_of_days</code> to <code>minimum_expectancy</code> to find <code>min_trade_number</code> historical information based on the config file. The timerange Edge uses for its comparisons can be further limited by using the <code>--timerange</code> switch.</p> <p>In live and dry-run modes, after the <code>process_throttle_secs</code> has passed, Edge will again process <code>calculate_since_number_of_days</code> against <code>minimum_expectancy</code> to find <code>min_trade_number</code>. If no <code>min_trade_number</code> 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.</p> <p>If you encounter \"whitelist empty\" a lot, condsider tuning <code>calculate_since_number_of_days</code>, <code>minimum_expectancy</code> and <code>min_trade_number</code> to align to the trading frequency of your strategy.</p>"},{"location":"edge/#update-cached-pairs-with-the-latest-data","title":"Update cached pairs with the latest data","text":"<p>Edge requires historic data the same way as backtesting does. Please refer to the Data Downloading section of the documentation for details.</p>"},{"location":"edge/#precising-stoploss-range","title":"Precising stoploss range","text":"<pre><code>freqtrade edge --stoplosses=-0.01,-0.1,-0.001 #min,max,step\n</code></pre>"},{"location":"edge/#advanced-use-of-timerange","title":"Advanced use of timerange","text":"<pre><code>freqtrade edge --timerange=20181110-20181113\n</code></pre> <p>Doing <code>--timerange=-20190901</code> will get all available data until September 1<sup>st</sup> (excluding September 1<sup>st</sup> 2019).</p> <p>The full timerange specification:</p> <ul> <li>Use tickframes till 2018/01/31: <code>--timerange=-20180131</code></li> <li>Use tickframes since 2018/01/31: <code>--timerange=20180131-</code></li> <li>Use tickframes since 2018/01/31 till 2018/03/01 : <code>--timerange=20180131-20180301</code></li> <li>Use tickframes between POSIX timestamps 1527595200 1527618600: <code>--timerange=1527595200-1527618600</code></li> </ul> <ol> <li> <p>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</p> </li> </ol>"},{"location":"exchanges/","title":"Exchange-specific Notes","text":"<p>This page combines common gotchas and informations which are exchange-specific and most likely don't apply to other exchanges.</p>"},{"location":"exchanges/#binance","title":"Binance","text":"<p>Stoploss on Exchange</p> <p>Binance supports <code>stoploss_on_exchange</code> and uses stop-loss-limit orders. It provides great advantages, so we recommend to benefit from it.</p>"},{"location":"exchanges/#blacklists","title":"Blacklists","text":"<p>For Binance, please add <code>\"BNB/<STAKE>\"</code> to your blacklist to avoid issues. Accounts having BNB accounts use this to pay for fees - if your first trade happens to be on <code>BNB</code>, further trades will consume this position and make the initial BNB order unsellable as the expected amount is not there anymore.</p>"},{"location":"exchanges/#binance-sites","title":"Binance sites","text":"<p>Binance has been split into 3, and users must use the correct ccxt exchange ID for their exchange, otherwise API keys are not recognized.</p> <ul> <li>binance.com - International users. Use exchange id: <code>binance</code>.</li> <li>binance.us - US based users. Use exchange id: <code>binanceus</code>.</li> <li>binance.je - Binance Jersey, trading fiat currencies. Use exchange id: <code>binanceje</code>.</li> </ul>"},{"location":"exchanges/#kraken","title":"Kraken","text":"<p>Stoploss on Exchange</p> <p>Kraken supports <code>stoploss_on_exchange</code> 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 <code>\"limit\"</code> or <code>\"market\"</code> in the <code>order_types.stoploss</code> configuration setting to decide which type to use.</p>"},{"location":"exchanges/#historic-kraken-data","title":"Historic Kraken data","text":"<p>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 <code>--dl-trades</code> is mandatory, otherwise the bot will download the same 720 candles over and over, and you'll not have enough backtest data.</p> <p>Due to the heavy rate-limiting applied by Kraken, the following configuration section should be used to download data:</p> <pre><code> \"ccxt_async_config\": {\n \"enableRateLimit\": true,\n \"rateLimit\": 3100\n },\n</code></pre>"},{"location":"exchanges/#bittrex","title":"Bittrex","text":""},{"location":"exchanges/#order-types","title":"Order types","text":"<p>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 <code>\"market\"</code> to <code>\"limit\"</code>. See some more details on this here in the FAQ.</p>"},{"location":"exchanges/#restricted-markets","title":"Restricted markets","text":"<p>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.</p> <p>If you have restricted pairs in your whitelist, you'll get a warning message in the log on Freqtrade startup for each restricted pair.</p> <p>The warning message will look similar to the following:</p> <pre><code>[...] Message: bittrex {\"success\":false,\"message\":\"RESTRICTED_MARKET\",\"result\":null,\"explanation\":null}\"\n</code></pre> <p>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.</p> <p>You can get a list of restricted markets by using the following snippet:</p> <pre><code>import ccxt\nct = ccxt.bittrex()\n_ = ct.load_markets()\nres = [ f\"{x['MarketCurrency']}/{x['BaseCurrency']}\" for x in ct.publicGetMarkets()['result'] if x['IsRestricted']]\nprint(res)\n</code></pre>"},{"location":"exchanges/#ftx","title":"FTX","text":"<p>Stoploss on Exchange</p> <p>FTX supports <code>stoploss_on_exchange</code> 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 <code>\"limit\"</code> or <code>\"market\"</code> in the <code>order_types.stoploss</code> configuration setting to decide which type of stoploss shall be used.</p>"},{"location":"exchanges/#using-subaccounts","title":"Using subaccounts","text":"<p>To use subaccounts with FTX, you need to edit the configuration and add the following:</p> <pre><code>\"exchange\": {\n \"ccxt_config\": {\n \"headers\": {\n \"FTX-SUBACCOUNT\": \"name\"\n }\n },\n}\n</code></pre> <p>Note</p> <p>Older versions of freqtrade may require this key to be added to <code>\"ccxt_async_config\"</code> as well.</p>"},{"location":"exchanges/#all-exchanges","title":"All exchanges","text":"<p>Should you experience constant errors with Nonce (like <code>InvalidNonce</code>), it is best to regenerate the API keys. Resetting Nonce is difficult and it's usually easier to regenerate the API keys.</p>"},{"location":"exchanges/#random-notes-for-other-exchanges","title":"Random notes for other exchanges","text":"<ul> <li>The Ocean (exchange id: <code>theocean</code>) exchange uses Web3 functionality and requires <code>web3</code> python package to be installed:</li> </ul> <pre><code>$ pip3 install web3\n</code></pre>"},{"location":"exchanges/#getting-latest-price-incomplete-candles","title":"Getting latest price / Incomplete candles","text":"<p>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.</p> <p>Whether your exchange returns incomplete candles or not can be checked using the helper script from the Contributor documentation.</p> <p>Due to the danger of repainting, Freqtrade does not allow you to use this incomplete candle.</p> <p>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.</p>"},{"location":"faq/","title":"Freqtrade FAQ","text":""},{"location":"faq/#beginner-tips-tricks","title":"Beginner Tips & Tricks","text":"<ul> <li>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).</li> </ul>"},{"location":"faq/#freqtrade-common-issues","title":"Freqtrade common issues","text":""},{"location":"faq/#the-bot-does-not-start","title":"The bot does not start","text":"<p>Running the bot with <code>freqtrade trade --config config.json</code> shows the output <code>freqtrade: command not found</code>.</p> <p>This could be caused by the following reasons:</p> <ul> <li>The virtual environment is not active.<ul> <li>Run <code>source .env/bin/activate</code> to activate the virtual environment.</li> </ul> </li> <li>The installation did not work correctly.<ul> <li>Please check the Installation documentation.</li> </ul> </li> </ul>"},{"location":"faq/#i-have-waited-5-minutes-why-hasnt-the-bot-made-any-trades-yet","title":"I have waited 5 minutes, why hasn't the bot made any trades yet?","text":"<ul> <li>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!</li> </ul> <ul> <li>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).</li> </ul>"},{"location":"faq/#i-have-made-12-trades-already-why-is-my-total-profit-negative","title":"I have made 12 trades already, why is my total profit negative?","text":"<p>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.</p>"},{"location":"faq/#id-like-to-make-changes-to-the-config-can-i-do-that-without-having-to-kill-the-bot","title":"I\u2019d like to make changes to the config. Can I do that without having to kill the bot?","text":"<p>Yes. You can edit your config and use the <code>/reload_config</code> command to reload the configuration. The bot will stop, reload the configuration and strategy and will restart with the new configuration and strategy.</p>"},{"location":"faq/#i-want-to-improve-the-bot-with-a-new-strategy","title":"I want to improve the bot with a new strategy","text":"<p>That's great. We have a nice backtesting and hyperoptimization setup. See the tutorial here|Testing-new-strategies-with-Hyperopt.</p>"},{"location":"faq/#is-there-a-setting-to-only-sell-the-coins-being-held-and-not-perform-anymore-buys","title":"Is there a setting to only SELL the coins being held and not perform anymore BUYS?","text":"<p>You can use the <code>/stopbuy</code> command in Telegram to prevent future buys, followed by <code>/forcesell all</code> (sell all open trades).</p>"},{"location":"faq/#i-want-to-run-multiple-bots-on-the-same-machine","title":"I want to run multiple bots on the same machine","text":"<p>Please look at the advanced setup documentation Page.</p>"},{"location":"faq/#im-getting-missing-data-fillup-messages-in-the-log","title":"I'm getting \"Missing data fillup\" messages in the log","text":"<p>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.</p> <p>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.</p> <p>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 <code>_</code> - and is aligned with how exchanges usually represent 0 volume candles.</p>"},{"location":"faq/#im-getting-the-restricted_market-message-in-the-log","title":"I'm getting the \"RESTRICTED_MARKET\" message in the log","text":"<p>Currently known to happen for US Bittrex users. </p> <p>Read the Bittrex section about restricted markets for more information.</p>"},{"location":"faq/#im-getting-the-exchange-bittrex-does-not-support-market-orders-message-and-cannot-run-my-strategy","title":"I'm getting the \"Exchange Bittrex does not support market orders.\" message and cannot run my strategy","text":"<p>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).</p> <p>To fix it for Bittrex, redefine order types in the strategy to use \"limit\" instead of \"market\":</p> <pre><code> order_types = {\n ...\n 'stoploss': 'limit',\n ...\n }\n</code></pre> <p>The same fix should be applied in the configuration file, if order types are defined in your custom config rather than in the strategy.</p>"},{"location":"faq/#how-do-i-search-the-bot-logs-for-something","title":"How do I search the bot logs for something?","text":"<p>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 <code>print()</code>'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.</p> <ul> <li>In unix shells, this normally can be done as simple as: <pre><code>$ freqtrade --some-options 2>&1 >/dev/null | grep 'something'\n</code></pre> (note, <code>2>&1</code> and <code>>/dev/null</code> should be written in this order)</li> </ul> <ul> <li>Bash interpreter also supports so called process substitution syntax, you can grep the log for a string with it as: <pre><code>$ freqtrade --some-options 2> >(grep 'something') >/dev/null\n</code></pre> or <pre><code>$ freqtrade --some-options 2> >(grep -v 'something' 1>&2)\n</code></pre></li> </ul> <ul> <li>You can also write the copy of Freqtrade log messages to a file with the <code>--logfile</code> option: <pre><code>$ freqtrade --logfile /path/to/mylogfile.log --some-options\n</code></pre> and then grep it as: <pre><code>$ cat /path/to/mylogfile.log | grep 'something'\n</code></pre> or even on the fly, as the bot works and the log file grows: <pre><code>$ tail -f /path/to/mylogfile.log | grep 'something'\n</code></pre> from a separate terminal window.</li> </ul> <p>On Windows, the <code>--logfile</code> option is also supported by Freqtrade and you can use the <code>findstr</code> command to search the log for the string of interest: <pre><code>> type \\path\\to\\mylogfile.log | findstr \"something\"\n</code></pre></p>"},{"location":"faq/#hyperopt-module","title":"Hyperopt module","text":""},{"location":"faq/#how-many-epochs-do-i-need-to-get-a-good-hyperopt-result","title":"How many epochs do I need to get a good Hyperopt result?","text":"<p>Per default Hyperopt called without the <code>-e</code>/<code>--epochs</code> 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.</p> <p>Since hyperopt uses Bayesian search, running for too many epochs may not produce greater results.</p> <p>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.</p> <pre><code>freqtrade hyperopt --hyperopt SampleHyperopt --hyperopt-loss SharpeHyperOptLossDaily --strategy SampleStrategy -e 1000\n</code></pre>"},{"location":"faq/#why-does-it-take-a-long-time-to-run-hyperopt","title":"Why does it take a long time to run hyperopt?","text":"<ul> <li>Discovering a great strategy with Hyperopt takes time. Study www.freqtrade.io, the Freqtrade Documentation page, join the Freqtrade Slack community - or 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.</li> </ul> <ul> <li>If you wonder why it can take from 20 minutes to days to do 1000 epochs here are some answers:</li> </ul> <p>This answer was written during the release 0.15.1, when we had:</p> <ul> <li>8 triggers</li> <li>9 guards: let's say we evaluate even 10 values from each</li> <li>1 stoploss calculation: let's say we want 10 values from that too to be evaluated</li> </ul> <p>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.</p> <ul> <li>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. </li> </ul> <p>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. </p> <p>Example: <code>freqtrade --config config.json --strategy SampleStrategy --hyperopt SampleHyperopt -e 1000 --timerange 20190601-20200601</code></p>"},{"location":"faq/#edge-module","title":"Edge module","text":""},{"location":"faq/#edge-implements-interesting-approach-for-controlling-position-size-is-there-any-theory-behind-it","title":"Edge implements interesting approach for controlling position size, is there any theory behind it?","text":"<p>The Edge module is mostly a result of brainstorming of @mishaker and @creslinux freqtrade team members.</p> <p>You can find further info on expectancy, win rate, risk management and position size in the following sources:</p> <ul> <li>https://www.tradeciety.com/ultimate-math-guide-for-traders/</li> <li>http://www.vantharp.com/tharp-concepts/expectancy.asp</li> <li>https://samuraitradingacademy.com/trading-expectancy/</li> <li>https://www.learningmarkets.com/determining-expectancy-in-your-trading/</li> <li>http://www.lonestocktrader.com/make-money-trading-positive-expectancy/</li> <li>https://www.babypips.com/trading/trade-expectancy-matter</li> </ul>"},{"location":"hyperopt/","title":"Hyperopt","text":"<p>This page explains how to tune your strategy by finding the optimal parameters, a process called hyperparameter optimization. The bot uses several algorithms included in the <code>scikit-optimize</code> 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.</p> <p>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.</p> <p>Hyperopt requires historic data to be available, just as backtesting does. 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.</p> <p>Bug</p> <p>Hyperopt can crash when used with only 1 CPU Core as found out in Issue #1133</p>"},{"location":"hyperopt/#install-hyperopt-dependencies","title":"Install hyperopt dependencies","text":"<p>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.</p> <p>Note</p> <p>Since Hyperopt is a resource intensive process, running it on a Raspberry Pi is not recommended nor supported.</p>"},{"location":"hyperopt/#docker","title":"Docker","text":"<p>The docker-image includes hyperopt dependencies, no further action needed.</p>"},{"location":"hyperopt/#easy-installation-script-setupsh-manual-installation","title":"Easy installation script (setup.sh) / Manual installation","text":"<pre><code>source .env/bin/activate\npip install -r requirements-hyperopt.txt\n</code></pre>"},{"location":"hyperopt/#hyperopt-command-reference","title":"Hyperopt command reference","text":"<pre><code>usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]\n [--userdir PATH] [-s NAME] [--strategy-path PATH]\n [-i TIMEFRAME] [--timerange TIMERANGE]\n [--data-format-ohlcv {json,jsongz,hdf5}]\n [--max-open-trades INT]\n [--stake-amount STAKE_AMOUNT] [--fee FLOAT]\n [--hyperopt NAME] [--hyperopt-path PATH] [--eps]\n [--dmmp] [--enable-protections] [-e INT]\n [--spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...]]\n [--print-all] [--no-color] [--print-json] [-j JOBS]\n [--random-state INT] [--min-trades INT]\n [--hyperopt-loss NAME]\n\noptional arguments:\n -h, --help show this help message and exit\n -i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME\n Specify ticker interval (`1m`, `5m`, `30m`, `1h`,\n `1d`).\n --timerange TIMERANGE\n Specify what timerange of data to use.\n --data-format-ohlcv {json,jsongz,hdf5}\n Storage format for downloaded candle (OHLCV) data.\n (default: `None`).\n --max-open-trades INT\n Override the value of the `max_open_trades`\n configuration setting.\n --stake-amount STAKE_AMOUNT\n Override the value of the `stake_amount` configuration\n setting.\n --fee FLOAT Specify fee ratio. Will be applied twice (on trade\n entry and exit).\n --hyperopt NAME Specify hyperopt class name which will be used by the\n bot.\n --hyperopt-path PATH Specify additional lookup path for Hyperopt and\n Hyperopt Loss functions.\n --eps, --enable-position-stacking\n Allow buying the same pair multiple times (position\n stacking).\n --dmmp, --disable-max-market-positions\n Disable applying `max_open_trades` during backtest\n (same as setting `max_open_trades` to a very high\n number).\n --enable-protections, --enableprotections\n Enable protections for backtesting.Will slow\n backtesting down by a considerable amount, but will\n include configured protections\n -e INT, --epochs INT Specify number of epochs (default: 100).\n --spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...]\n Specify which parameters to hyperopt. Space-separated\n list.\n --print-all Print all results, not only the best ones.\n --no-color Disable colorization of hyperopt results. May be\n useful if you are redirecting output to a file.\n --print-json Print output in JSON format.\n -j JOBS, --job-workers JOBS\n The number of concurrently running jobs for\n hyperoptimization (hyperopt worker processes). If -1\n (default), all CPUs are used, for -2, all CPUs but one\n are used, etc. If 1 is given, no parallel computing\n code is used at all.\n --random-state INT Set random state to some positive integer for\n reproducible hyperopt results.\n --min-trades INT Set minimal desired number of trades for evaluations\n in the hyperopt optimization path (default: 1).\n --hyperopt-loss NAME Specify the class name of the hyperopt loss function\n class (IHyperOptLoss). Different functions can\n generate completely different results, since the\n target for optimization is different. Built-in\n Hyperopt-loss-functions are:\n ShortTradeDurHyperOptLoss, OnlyProfitHyperOptLoss,\n SharpeHyperOptLoss, SharpeHyperOptLossDaily,\n SortinoHyperOptLoss, SortinoHyperOptLossDaily\n\nCommon arguments:\n -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).\n --logfile FILE Log to the file specified. Special values are:\n 'syslog', 'journald'. See the documentation for more\n details.\n -V, --version show program's version number and exit\n -c PATH, --config PATH\n Specify configuration file (default:\n `userdir/config.json` or `config.json` whichever\n exists). Multiple --config options may be used. Can be\n set to `-` to read config from stdin.\n -d PATH, --datadir PATH\n Path to directory with historical backtesting data.\n --userdir PATH, --user-data-dir PATH\n Path to userdata directory.\n\nStrategy arguments:\n -s NAME, --strategy NAME\n Specify strategy class name which will be used by the\n bot.\n --strategy-path PATH Specify additional strategy lookup path.\n</code></pre>"},{"location":"hyperopt/#prepare-hyperopting","title":"Prepare Hyperopting","text":"<p>Before we start digging into Hyperopt, we recommend you to take a look at the sample hyperopt file located in user_data/hyperopts/.</p> <p>Configuring hyperopt is similar to writing your own strategy, and many tasks will be similar.</p> <p>About this page</p> <p>For this page, we will be using a fictional strategy called <code>AwesomeStrategy</code> - which will be optimized using the <code>AwesomeHyperopt</code> class.</p> <p>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 <code>user_data/hyperopts/AwesomeHyperopt.py</code>.</p> <pre><code>freqtrade new-hyperopt --hyperopt AwesomeHyperopt\n</code></pre>"},{"location":"hyperopt/#hyperopt-checklist","title":"Hyperopt checklist","text":"<p>Checklist on all tasks / possibilities in hyperopt</p> <p>Depending on the space you want to optimize, only some of the below are required:</p> <ul> <li>fill <code>buy_strategy_generator</code> - for buy signal optimization</li> <li>fill <code>indicator_space</code> - for buy signal optimization</li> <li>fill <code>sell_strategy_generator</code> - for sell signal optimization</li> <li>fill <code>sell_indicator_space</code> - for sell signal optimization</li> </ul> <p>Note</p> <p><code>populate_indicators</code> needs to create all indicators any of thee spaces may use, otherwise hyperopt will not work.</p> <p>Optional in hyperopt - can also be loaded from a strategy (recommended):</p> <ul> <li><code>populate_indicators</code> - fallback to create indicators</li> <li><code>populate_buy_trend</code> - fallback if not optimizing for buy space. should come from strategy</li> <li><code>populate_sell_trend</code> - fallback if not optimizing for sell space. should come from strategy</li> </ul> <p>Note</p> <p>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 <code>--strategy AweSomeStrategy</code> which contains these methods so hyperopt can use these methods instead.</p> <p>Rarely you may also need to override:</p> <ul> <li><code>roi_space</code> - for custom ROI optimization (if you need the ranges for the ROI parameters in the optimization hyperspace that differ from default)</li> <li><code>generate_roi_table</code> - 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)</li> <li><code>stoploss_space</code> - for custom stoploss optimization (if you need the range for the stoploss parameter in the optimization hyperspace that differs from default)</li> <li><code>trailing_space</code> - for custom trailing stop optimization (if you need the ranges for the trailing stop parameters in the optimization hyperspace that differ from default)</li> </ul> <p>Quickly optimize ROI, stoploss and trailing stoploss</p> <p>You can quickly optimize the spaces <code>roi</code>, <code>stoploss</code> and <code>trailing</code> without changing anything (i.e. without creation of a \"complete\" Hyperopt class with dimensions, parameters, triggers and guards, as described in this document) from the default hyperopt template by relying on your strategy to do most of the calculations.</p> <pre><code># Have a working strategy at hand.\nfreqtrade new-hyperopt --hyperopt EmptyHyperopt\n\nfreqtrade hyperopt --hyperopt EmptyHyperopt --hyperopt-loss SharpeHyperOptLossDaily --spaces roi stoploss trailing --strategy MyWorkingStrategy --config config.json -e 100\n</code></pre>"},{"location":"hyperopt/#create-a-custom-hyperopt-file","title":"Create a Custom Hyperopt File","text":"<p>Let assume you want a hyperopt file <code>AwesomeHyperopt.py</code>: </p> <pre><code>freqtrade new-hyperopt --hyperopt AwesomeHyperopt\n</code></pre> <p>This command will create a new hyperopt file from a template, allowing you to get started quickly.</p>"},{"location":"hyperopt/#configure-your-guards-and-triggers","title":"Configure your Guards and Triggers","text":"<p>There are two places you need to change in your hyperopt file to add a new buy hyperopt for testing:</p> <ul> <li>Inside <code>indicator_space()</code> - the parameters hyperopt shall be optimizing.</li> <li>Within <code>buy_strategy_generator()</code> - populate the nested <code>populate_buy_trend()</code> to apply the parameters.</li> </ul> <p>There you have two different types of indicators: 1. <code>guards</code> and 2. <code>triggers</code>.</p> <ol> <li>Guards are conditions like \"never buy if ADX < 10\", or never buy if current price is over EMA10.</li> <li>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\".</li> </ol> <p>Guards and Triggers</p> <p>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).</p> <p>Hyper-optimization will, for each epoch round, pick one trigger and possibly multiple guards. The constructed strategy will be something like \"buy exactly when close price touches lower Bollinger band, BUT only if ADX > 10\".</p> <p>If you have updated the buy strategy, i.e. changed the contents of <code>populate_buy_trend()</code> method, you have to update the <code>guards</code> and <code>triggers</code> your hyperopt must use correspondingly.</p>"},{"location":"hyperopt/#sell-optimization","title":"Sell optimization","text":"<p>Similar to the buy-signal above, sell-signals can also be optimized. Place the corresponding settings into the following methods</p> <ul> <li>Inside <code>sell_indicator_space()</code> - the parameters hyperopt shall be optimizing.</li> <li>Within <code>sell_strategy_generator()</code> - populate the nested method <code>populate_sell_trend()</code> to apply the parameters.</li> </ul> <p>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 <code>sell-</code>.</p>"},{"location":"hyperopt/#using-timeframe-as-a-part-of-the-strategy","title":"Using timeframe as a part of the Strategy","text":"<p>The Strategy class exposes the timeframe value as the <code>self.timeframe</code> attribute. The same value is available as class-attribute <code>HyperoptName.timeframe</code>. In the case of the linked sample-value this would be <code>AwesomeHyperopt.timeframe</code>.</p>"},{"location":"hyperopt/#solving-a-mystery","title":"Solving a Mystery","text":"<p>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.</p> <p>We will start by defining a search space:</p> <pre><code> def indicator_space() -> List[Dimension]:\n \"\"\"\n Define your Hyperopt space for searching strategy parameters\n \"\"\"\n return [\n Integer(20, 40, name='adx-value'),\n Integer(20, 40, name='rsi-value'),\n Categorical([True, False], name='adx-enabled'),\n Categorical([True, False], name='rsi-enabled'),\n Categorical(['bb_lower', 'macd_cross_signal'], name='trigger')\n ]\n</code></pre> <p>Above definition says: I have five parameters I want you to randomly combine to find the best combination. Two of them are integer values (<code>adx-value</code> and <code>rsi-value</code>) and I want you test in the range of values 20 to 40. Then we have three category variables. First two are either <code>True</code> or <code>False</code>. We use these to either enable or disable the ADX and RSI guards. The last one we call <code>trigger</code> and use it to decide which buy trigger we want to use.</p> <p>So let's write the buy strategy using these values:</p> <pre><code> @staticmethod\n def buy_strategy_generator(params: Dict[str, Any]) -> Callable:\n \"\"\"\n Define the buy strategy parameters to be used by Hyperopt.\n \"\"\"\n def populate_buy_trend(dataframe: DataFrame) -> DataFrame:\n conditions = []\n # GUARDS AND TRENDS\n if 'adx-enabled' in params and params['adx-enabled']:\n conditions.append(dataframe['adx'] > params['adx-value'])\n if 'rsi-enabled' in params and params['rsi-enabled']:\n conditions.append(dataframe['rsi'] < params['rsi-value'])\n\n # TRIGGERS\n if 'trigger' in params:\n if params['trigger'] == 'bb_lower':\n conditions.append(dataframe['close'] < dataframe['bb_lowerband'])\n if params['trigger'] == 'macd_cross_signal':\n conditions.append(qtpylib.crossed_above(\n dataframe['macd'], dataframe['macdsignal']\n ))\n\n # Check that volume is not 0\n conditions.append(dataframe['volume'] > 0)\n\n if conditions:\n dataframe.loc[\n reduce(lambda x, y: x & y, conditions),\n 'buy'] = 1\n\n return dataframe\n\n return populate_buy_trend\n</code></pre> <p>Hyperopt will now call <code>populate_buy_trend()</code> many times (<code>epochs</code>) 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).</p> <p>Note</p> <p>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 <code>populate_indicators()</code> method in your strategy or hyperopt file.</p>"},{"location":"hyperopt/#loss-functions","title":"Loss-functions","text":"<p>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.</p> <p>A loss function must be specified via the <code>--hyperopt-loss <Class-name></code> argument (or optionally via the configuration under the <code>\"hyperopt_loss\"</code> key). This class should be in its own file within the <code>user_data/hyperopts/</code> directory.</p> <p>Currently, the following loss functions are builtin:</p> <ul> <li><code>ShortTradeDurHyperOptLoss</code> (default legacy Freqtrade hyperoptimization loss function) - Mostly for short trade duration and avoiding losses.</li> <li><code>OnlyProfitHyperOptLoss</code> (which takes only amount of profit into consideration)</li> <li><code>SharpeHyperOptLoss</code> (optimizes Sharpe Ratio calculated on trade returns relative to standard deviation)</li> <li><code>SharpeHyperOptLossDaily</code> (optimizes Sharpe Ratio calculated on daily trade returns relative to standard deviation)</li> <li><code>SortinoHyperOptLoss</code> (optimizes Sortino Ratio calculated on trade returns relative to downside standard deviation)</li> <li><code>SortinoHyperOptLossDaily</code> (optimizes Sortino Ratio calculated on daily trade returns relative to downside standard deviation)</li> </ul> <p>Creation of a custom loss function is covered in the Advanced Hyperopt part of the documentation.</p>"},{"location":"hyperopt/#execute-hyperopt","title":"Execute Hyperopt","text":"<p>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.</p> <p>We strongly recommend to use <code>screen</code> or <code>tmux</code> to prevent any connection loss.</p> <pre><code>freqtrade hyperopt --config config.json --hyperopt <hyperoptname> --hyperopt-loss <hyperoptlossname> --strategy <strategyname> -e 500 --spaces all\n</code></pre> <p>Use <code><hyperoptname></code> as the name of the custom hyperopt used.</p> <p>The <code>-e</code> 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.</p> <p>The <code>--spaces all</code> option determines that all possible parameters should be optimized. Possibilities are listed below.</p> <p>Note</p> <p>Hyperopt will store hyperopt results with the timestamp of the hyperopt start time. Reading commands (<code>hyperopt-list</code>, <code>hyperopt-show</code>) can use <code>--hyperopt-filename <filename></code> to read and display older hyperopt results. You can find a list of filenames with <code>ls -l user_data/hyperopt_results/</code>.</p>"},{"location":"hyperopt/#execute-hyperopt-with-different-historical-data-source","title":"Execute Hyperopt with different historical data source","text":"<p>If you would like to hyperopt parameters using an alternate historical data set that you have on-disk, use the <code>--datadir PATH</code> option. By default, hyperopt uses data from directory <code>user_data/data</code>.</p>"},{"location":"hyperopt/#running-hyperopt-with-a-smaller-test-set","title":"Running Hyperopt with a smaller test-set","text":"<p>Use the <code>--timerange</code> argument to change how much of the test-set you want to use. For example, to use one month of data, pass the following parameter to the hyperopt call:</p> <pre><code>freqtrade hyperopt --hyperopt <hyperoptname> --strategy <strategyname> --timerange 20180401-20180501\n</code></pre>"},{"location":"hyperopt/#running-hyperopt-using-methods-from-a-strategy","title":"Running Hyperopt using methods from a strategy","text":"<p>Hyperopt can reuse <code>populate_indicators</code>, <code>populate_buy_trend</code>, <code>populate_sell_trend</code> from your strategy, assuming these methods are not in your custom hyperopt file, and a strategy is provided.</p> <pre><code>freqtrade hyperopt --hyperopt AwesomeHyperopt --hyperopt-loss SharpeHyperOptLossDaily --strategy AwesomeStrategy\n</code></pre>"},{"location":"hyperopt/#running-hyperopt-with-smaller-search-space","title":"Running Hyperopt with Smaller Search Space","text":"<p>Use the <code>--spaces</code> 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.</p> <p>Legal values are:</p> <ul> <li><code>all</code>: optimize everything</li> <li><code>buy</code>: just search for a new buy strategy</li> <li><code>sell</code>: just search for a new sell strategy</li> <li><code>roi</code>: just optimize the minimal profit table for your strategy</li> <li><code>stoploss</code>: search for the best stoploss value</li> <li><code>trailing</code>: search for the best trailing stop values</li> <li><code>default</code>: <code>all</code> except <code>trailing</code></li> <li>space-separated list of any of the above values for example <code>--spaces roi stoploss</code></li> </ul> <p>The default Hyperopt Search Space, used when no <code>--space</code> command line option is specified, does not include the <code>trailing</code> hyperspace. We recommend you to run optimization for the <code>trailing</code> hyperspace separately, when the best parameters for other hyperspaces were found, validated and pasted into your custom strategy.</p>"},{"location":"hyperopt/#position-stacking-and-disabling-max-market-positions","title":"Position stacking and disabling max market positions","text":"<p>In some situations, you may need to run Hyperopt (and Backtesting) with the <code>--eps</code>/<code>--enable-position-staking</code> and <code>--dmmp</code>/<code>--disable-max-market-positions</code> arguments.</p> <p>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 <code>max_open_trades</code> setting. During Hyperopt/Backtesting this may lead to some potential trades to be hidden (or masked) by previously open trades.</p> <p>The <code>--eps</code>/<code>--enable-position-stacking</code> argument allows emulation of buying the same pair multiple times, while <code>--dmmp</code>/<code>--disable-max-market-positions</code> disables applying <code>max_open_trades</code> during Hyperopt/Backtesting (which is equal to setting <code>max_open_trades</code> to a very high number).</p> <p>Note</p> <p>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.</p> <p>You can also enable position stacking in the configuration file by explicitly setting <code>\"position_stacking\"=true</code>.</p>"},{"location":"hyperopt/#reproducible-results","title":"Reproducible results","text":"<p>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 (<code>*</code>) in the first column in the Hyperopt output.</p> <p>The initial state for generation of these random values (random state) is controlled by the value of the <code>--random-state</code> command line option. You can set it to some arbitrary value of your choice to obtain reproducible results.</p> <p>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 <code>--random-state</code> command line option to repeat the set of the initial random epochs used.</p> <p>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.</p>"},{"location":"hyperopt/#understand-the-hyperopt-result","title":"Understand the Hyperopt Result","text":"<p>Once Hyperopt is completed you can use the result to create a new strategy. Given the following result from hyperopt:</p> <pre><code>Best result:\n\n 44/100: 135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722\u03a3%). Avg duration 180.4 mins. Objective: 1.94367\n\nBuy hyperspace params:\n{ 'adx-value': 44,\n 'rsi-value': 29,\n 'adx-enabled': False,\n 'rsi-enabled': True,\n 'trigger': 'bb_lower'}\n</code></pre> <p>You should understand this result like:</p> <ul> <li>The buy trigger that worked best was <code>bb_lower</code>.</li> <li>You should not use ADX because <code>adx-enabled: False</code>)</li> <li>You should consider using the RSI indicator (<code>rsi-enabled: True</code> and the best value is <code>29.0</code> (<code>rsi-value: 29.0</code>)</li> </ul> <p>You have to look inside your strategy file into <code>buy_strategy_generator()</code> method, what those values match to.</p> <p>So for example you had <code>rsi-value: 29.0</code> so we would look at <code>rsi</code>-block, that translates to the following code block:</p> <pre><code>(dataframe['rsi'] < 29.0)\n</code></pre> <p>Translating your whole hyperopt result as the new buy-signal would then look like:</p> <pre><code>def populate_buy_trend(self, dataframe: DataFrame) -> DataFrame:\n dataframe.loc[\n (\n (dataframe['rsi'] < 29.0) & # rsi-value\n dataframe['close'] < dataframe['bb_lowerband'] # trigger\n ),\n 'buy'] = 1\n return dataframe\n</code></pre> <p>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 <code>--no-color</code> option in the command line.</p> <p>You can use the <code>--print-all</code> command line option if you would like to see all results in the hyperopt output, not only the best ones. When <code>--print-all</code> 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 <code>--no-color</code> command line option.</p> <p>Windows and color output</p> <p>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.</p>"},{"location":"hyperopt/#understand-hyperopt-roi-results","title":"Understand Hyperopt ROI results","text":"<p>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:</p> <pre><code>Best result:\n\n 44/100: 135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722\u03a3%). Avg duration 180.4 mins. Objective: 1.94367\n\nROI table:\n{ 0: 0.10674,\n 21: 0.09158,\n 78: 0.03634,\n 118: 0}\n</code></pre> <p>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 <code>minimal_roi</code> attribute of your custom strategy:</p> <pre><code> # Minimal ROI designed for the strategy.\n # This attribute will be overridden if the config file contains \"minimal_roi\"\n minimal_roi = {\n 0: 0.10674,\n 21: 0.09158,\n 78: 0.03634,\n 118: 0\n }\n</code></pre> <p>As stated in the comment, you can also use it as the value of the <code>minimal_roi</code> setting in the configuration file.</p>"},{"location":"hyperopt/#default-roi-search-space","title":"Default ROI Search Space","text":"<p>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 5 digits after the decimal point):</p> # step 1m 5m 1h 1d 1 0 0.01161...0.11992 0 0.03...0.31 0 0.06883...0.71124 0 0.12178...1.25835 2 2...8 0.00774...0.04255 10...40 0.02...0.11 120...480 0.04589...0.25238 2880...11520 0.08118...0.44651 3 4...20 0.00387...0.01547 20...100 0.01...0.04 240...1200 0.02294...0.09177 5760...28800 0.04059...0.16237 4 6...44 0.0 30...220 0.0 360...2640 0.0 8640...63360 0.0 <p>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.</p> <p>If you have the <code>generate_roi_table()</code> and <code>roi_space()</code> 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.</p> <p>Override the <code>roi_space()</code> method if you need components of the ROI tables to vary in other ranges. Override the <code>generate_roi_table()</code> and <code>roi_space()</code> 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). </p> <p>A sample for these methods can be found in sample_hyperopt_advanced.py.</p>"},{"location":"hyperopt/#understand-hyperopt-stoploss-results","title":"Understand Hyperopt Stoploss results","text":"<p>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:</p> <pre><code>Best result:\n\n 44/100: 135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722\u03a3%). Avg duration 180.4 mins. Objective: 1.94367\n\nBuy hyperspace params:\n{ 'adx-value': 44,\n 'rsi-value': 29,\n 'adx-enabled': False,\n 'rsi-enabled': True,\n 'trigger': 'bb_lower'}\nStoploss: -0.27996\n</code></pre> <p>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 <code>stoploss</code> attribute of your custom strategy:</p> <pre><code> # Optimal stoploss designed for the strategy\n # This attribute will be overridden if the config file contains \"stoploss\"\n stoploss = -0.27996\n</code></pre> <p>As stated in the comment, you can also use it as the value of the <code>stoploss</code> setting in the configuration file.</p>"},{"location":"hyperopt/#default-stoploss-search-space","title":"Default Stoploss Search Space","text":"<p>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.</p> <p>If you have the <code>stoploss_space()</code> method in your custom hyperopt file, remove it in order to utilize Stoploss hyperoptimization space generated by Freqtrade by default.</p> <p>Override the <code>stoploss_space()</code> 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.</p>"},{"location":"hyperopt/#understand-hyperopt-trailing-stop-results","title":"Understand Hyperopt Trailing Stop results","text":"<p>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:</p> <pre><code>Best result:\n\n 45/100: 606 trades. Avg profit 1.04%. Total profit 0.31555614 BTC ( 630.48\u03a3%). Avg duration 150.3 mins. Objective: -1.10161\n\nTrailing stop:\n{ 'trailing_only_offset_is_reached': True,\n 'trailing_stop': True,\n 'trailing_stop_positive': 0.02001,\n 'trailing_stop_positive_offset': 0.06038}\n</code></pre> <p>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:</p> <pre><code> # Trailing stop\n # These attributes will be overridden if the config file contains corresponding values.\n trailing_stop = True\n trailing_stop_positive = 0.02001\n trailing_stop_positive_offset = 0.06038\n trailing_only_offset_is_reached = True\n</code></pre> <p>As stated in the comment, you can also use it as the values of the corresponding settings in the configuration file.</p>"},{"location":"hyperopt/#default-trailing-stop-search-space","title":"Default Trailing Stop Search Space","text":"<p>If you are optimizing trailing stop values, Freqtrade creates the 'trailing' optimization hyperspace for you. By default, the <code>trailing_stop</code> parameter is always set to True in that hyperspace, the value of the <code>trailing_only_offset_is_reached</code> vary between True and False, the values of the <code>trailing_stop_positive</code> and <code>trailing_stop_positive_offset</code> parameters vary in the ranges 0.02...0.35 and 0.01...0.1 correspondingly, which is sufficient in most cases.</p> <p>Override the <code>trailing_space()</code> 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.</p>"},{"location":"hyperopt/#show-details-of-hyperopt-results","title":"Show details of Hyperopt results","text":"<p>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 <code>hyperopt-list</code> and <code>hyperopt-show</code> sub-commands. The usage of these sub-commands is described in the Utils chapter.</p>"},{"location":"hyperopt/#validate-backtesting-results","title":"Validate backtesting results","text":"<p>Once the optimized strategy has been implemented into your strategy, you should backtest this strategy to make sure everything is working as expected.</p> <p>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 <code>--dmmp</code>/<code>--disable-max-market-positions</code> and <code>--eps</code>/<code>--enable-position-stacking</code> for Backtesting.</p> <p>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 <code>stoploss</code> or <code>trailing_stop</code>).</p>"},{"location":"installation/","title":"Installation","text":"<p>This page explains how to prepare your environment for running the bot.</p> <p>The freqtrade documentation describes various ways to install freqtrade</p> <ul> <li>Docker images (separate page)</li> <li>Script Installation</li> <li>Manual Installation</li> <li>Installation with Conda</li> </ul> <p>Please consider using the prebuilt docker images to get started quickly while evaluating how freqtrade works.</p>"},{"location":"installation/#information","title":"Information","text":"<p>For Windows installation, please use the windows installation guide.</p> <p>The easiest way to install and run Freqtrade is to clone the bot Github repository and then run the <code>./setup.sh</code> script, if it's available for your platform.</p> <p>Version considerations</p> <p>When cloning the repository the default working branch has the name <code>develop</code>. This branch contains all last features (can be considered as relatively stable, thanks to automated tests). The <code>stable</code> branch contains the code of the last release (done usually once per month on an approximately one week old snapshot of the <code>develop</code> branch to prevent packaging bugs, so potentially it's more stable).</p> <p>Note</p> <p>Python3.7 or higher and the corresponding <code>pip</code> are assumed to be available. The install-script will warn you and stop if that's not the case. <code>git</code> is also needed to clone the Freqtrade repository. Also, python headers (<code>python<yourversion>-dev</code> / <code>python<yourversion>-devel</code>) must be available for the installation to complete successfully.</p> <p>Up-to-date clock</p> <p>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.</p>"},{"location":"installation/#requirements","title":"Requirements","text":"<p>These requirements apply to both Script Installation and Manual Installation.</p>"},{"location":"installation/#install-guide","title":"Install guide","text":"<ul> <li>Python >= 3.7.x</li> <li>pip</li> <li>git</li> <li>virtualenv (Recommended)</li> <li>TA-Lib (install instructions below)</li> </ul>"},{"location":"installation/#install-code","title":"Install code","text":"<p>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.</p> <p>Note</p> <p>Python3.7 or higher and the corresponding pip are assumed to be available.</p> Debian/Ubuntu RaspberryPi/Raspbian <p>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.</p> <p>Tested using a Raspberry Pi 3 with the Raspbian Buster lite image, all updates applied.</p> <pre><code>sudo apt-get install python3-venv libatlas-base-dev cmake\n# Use pywheels.org to speed up installation\nsudo echo \"[global]\\nextra-index-url=https://www.piwheels.org/simple\" > tee /etc/pip.conf\n\ngit clone https://github.com/freqtrade/freqtrade.git\ncd freqtrade\n\nbash setup.sh -i\n</code></pre> <p>Installation duration</p> <p>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</p> <p>Note</p> <p>The above does not install hyperopt dependencies. To install these, please use <code>python3 -m pip install -e .[hyperopt]</code>. 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.</p>"},{"location":"installation/#install-necessary-dependencies","title":"Install necessary dependencies","text":"<pre><code># update repository\nsudo apt-get update\n\n# install packages\nsudo apt install -y python3-pip python3-venv python3-pandas python3-pip git\n</code></pre>"},{"location":"installation/#freqtrade-repository","title":"Freqtrade repository","text":"<p>Freqtrade is an open source crypto-currency trading bot, whose code is hosted on <code>github.com</code></p> <pre><code># Download `develop` branch of freqtrade repository\ngit clone https://github.com/freqtrade/freqtrade.git\n\n# Enter downloaded directory\ncd freqtrade\n\n# your choice (1): novice user\ngit checkout stable\n\n# your choice (2): advanced user\ngit checkout develop\n</code></pre> <p>(1) This command switches the cloned repository to the use of the <code>stable</code> branch. It's not needed, if you wish to stay on the (2) <code>develop</code> branch.</p> <p>You may later switch between branches at any time with the <code>git checkout stable</code>/<code>git checkout develop</code> commands.</p>"},{"location":"installation/#script-installation","title":"Script Installation","text":"<p>First of the ways to install Freqtrade, is to use provided the Linux/MacOS <code>./setup.sh</code> script, which install all dependencies and help you configure the bot.</p> <p>Make sure you fulfill the Requirements and have downloaded the Freqtrade repository.</p>"},{"location":"installation/#use-setupsh-install-linuxmacos","title":"Use /setup.sh -install (Linux/MacOS)","text":"<p>If you are on Debian, Ubuntu or MacOS, freqtrade provides the script to install freqtrade.</p> <pre><code># --install, Install freqtrade from scratch\n./setup.sh -i\n</code></pre>"},{"location":"installation/#activate-your-virtual-environment","title":"Activate your virtual environment","text":"<p>Each time you open a new terminal, you must run <code>source .env/bin/activate</code> to activate your virtual environment.</p> <pre><code># then activate your .env\nsource ./.env/bin/activate\n</code></pre>"},{"location":"installation/#congratulations","title":"Congratulations","text":"<p>You are ready, and run the bot</p>"},{"location":"installation/#other-options-of-setupsh-script","title":"Other options of /setup.sh script","text":"<p>You can as well update, configure and reset the codebase of your bot with <code>./script.sh</code></p> <pre><code># --update, Command git pull to update.\n./setup.sh -u\n# --reset, Hard reset your develop/stable branch.\n./setup.sh -r\n</code></pre> <pre><code>** --install **\n\nWith this option, the script will install the bot and most dependencies:\nYou will need to have git and python3.7+ installed beforehand for this to work.\n\n* Mandatory software as: `ta-lib`\n* Setup your virtualenv under `.env/`\n\nThis option is a combination of installation tasks and `--reset`\n\n** --update **\n\nThis 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.\n\n** --reset **\n\nThis option will hard reset your branch (only if you are on either `stable` or `develop`) and recreate your virtualenv.\n</code></pre>"},{"location":"installation/#manual-installation","title":"Manual Installation","text":"<p>Make sure you fulfill the Requirements and have downloaded the Freqtrade repository.</p>"},{"location":"installation/#install-ta-lib","title":"Install TA-Lib","text":""},{"location":"installation/#ta-lib-script-installation","title":"TA-Lib script installation","text":"<pre><code>sudo ./build_helpers/install_ta-lib.sh\n</code></pre> <p>Note</p> <p>This will use the ta-lib tar.gz included in this repository.</p>"},{"location":"installation/#ta-lib-manual-installation","title":"TA-Lib manual installation","text":"<p>Official webpage: https://mrjbq7.github.io/ta-lib/install.html</p> <pre><code>wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz\ntar xvzf ta-lib-0.4.0-src.tar.gz\ncd ta-lib\nsed -i.bak \"s|0.00000001|0.000000000000000001 |g\" src/ta_func/ta_utility.h\n./configure --prefix=/usr/local\nmake\nsudo make install\ncd ..\nrm -rf ./ta-lib*\n</code></pre>"},{"location":"installation/#setup-python-virtual-environment-virtualenv","title":"Setup Python virtual environment (virtualenv)","text":"<p>You will run freqtrade in separated <code>virtual environment</code></p> <pre><code># create virtualenv in directory /freqtrade/.env\npython3 -m venv .env\n\n# run virtualenv\nsource .env/bin/activate\n</code></pre>"},{"location":"installation/#install-python-dependencies","title":"Install python dependencies","text":"<pre><code>python3 -m pip install --upgrade pip\npython3 -m pip install -e .\n</code></pre>"},{"location":"installation/#congratulations_1","title":"Congratulations","text":"<p>You are ready, and run the bot</p>"},{"location":"installation/#optional-post-installation-tasks","title":"(Optional) Post-installation Tasks","text":"<p>Note</p> <p>If you run the bot on a server, you should consider using Docker or a terminal multiplexer like <code>screen</code> or <code>tmux</code> to avoid that the bot is stopped on logout.</p> <p>On Linux with software suite <code>systemd</code>, as an optional post-installation task, you may wish to setup the bot to run as a <code>systemd service</code> or configure it to send the log messages to the <code>syslog</code>/<code>rsyslog</code> or <code>journald</code> daemons. See Advanced Logging for details.</p>"},{"location":"installation/#installation-with-conda","title":"Installation with Conda","text":"<p>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.</p>"},{"location":"installation/#what-is-conda","title":"What is Conda?","text":"<p>Conda is a package, dependency and environment manager for multiple programming languages: conda docs</p>"},{"location":"installation/#installation-with-conda_1","title":"Installation with conda","text":""},{"location":"installation/#install-conda","title":"Install Conda","text":"<p>Installing on linux</p> <p>Installing on windows</p> <p>Answer all questions. After installation, it is mandatory to turn your terminal OFF and ON again.</p>"},{"location":"installation/#freqtrade-download","title":"Freqtrade download","text":"<p>Download and install freqtrade.</p> <pre><code># download freqtrade\ngit clone https://github.com/freqtrade/freqtrade.git\n\n# enter downloaded directory 'freqtrade'\ncd freqtrade \n</code></pre>"},{"location":"installation/#freqtrade-instal-conda-environment","title":"Freqtrade instal: Conda Environment","text":"<p>Prepare conda-freqtrade environment, using file <code>environment.yml</code>, which exist in main freqtrade directory</p> <pre><code>conda env create -n freqtrade-conda -f environment.yml\n</code></pre> <p>Creating Conda Environment</p> <p>The conda command <code>create -n</code> automatically installs all nested dependencies for the selected libraries, general structure of installation command is:</p> <pre><code># choose your own packages\nconda env create -n [name of the environment] [python version] [packages]\n\n# point to file with packages\nconda env create -n [name of the environment] -f [file]\n</code></pre>"},{"location":"installation/#enterexit-freqtrade-conda-environment","title":"Enter/exit freqtrade-conda environment","text":"<p>To check available environments, type</p> <pre><code>conda env list\n</code></pre> <p>Enter installed environment</p> <pre><code># enter conda environment\nconda activate freqtrade-conda\n\n# exit conda environment - don't do it now\nconda deactivate\n</code></pre> <p>Install last python dependencies with pip</p> <pre><code>python3 -m pip install --upgrade pip\npython3 -m pip install -e .\n</code></pre>"},{"location":"installation/#congratulations_2","title":"Congratulations","text":"<p>You are ready, and run the bot</p>"},{"location":"installation/#important-shortcuts","title":"Important shortcuts","text":"<pre><code># list installed conda environments\nconda env list\n\n# activate base environment\nconda activate\n\n# activate freqtrade-conda environment\nconda activate freqtrade-conda\n\n#deactivate any conda environments\nconda deactivate \n</code></pre>"},{"location":"installation/#further-info-on-anaconda","title":"Further info on anaconda","text":"<p>New heavy packages</p> <p>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.</p> <p>pip install within conda</p> <p>The documentation of conda says that pip should NOT be used within conda, because internal problems can occur. However, they are rare. Anaconda Blogpost</p> <p>Nevertheless, that is why, the <code>conda-forge</code> channel is preferred:</p> <ul> <li>more libraries are available (less need for <code>pip</code>)</li> <li><code>conda-forge</code> works better with <code>pip</code></li> <li>the libraries are newer</li> </ul> <p>Happy trading!</p>"},{"location":"installation/#you-are-ready","title":"You are ready","text":"<p>You've made it this far, so you have successfully installed freqtrade.</p>"},{"location":"installation/#initialize-the-configuration","title":"Initialize the configuration","text":"<pre><code># Step 1 - Initialize user folder\nfreqtrade create-userdir --userdir user_data\n\n# Step 2 - Create a new configuration file\nfreqtrade new-config --config config.json\n</code></pre> <p>You are ready to run, read Bot Configuration, remember to start with <code>dry_run: True</code> and verify that everything is working.</p> <p>To learn how to setup your configuration, please refer to the Bot Configuration documentation page.</p>"},{"location":"installation/#start-the-bot","title":"Start the Bot","text":"<pre><code>freqtrade trade --config config.json --strategy SampleStrategy\n</code></pre> <p>Warning</p> <p>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.</p>"},{"location":"installation/#troubleshooting","title":"Troubleshooting","text":""},{"location":"installation/#common-problem-command-not-found","title":"Common problem: \"command not found\"","text":"<p>If you used (1)<code>Script</code> or (2)<code>Manual</code> installation, you need to run the bot in virtual environment. If you get error as below, make sure venv is active.</p> <pre><code># if:\nbash: freqtrade: command not found\n\n# then activate your .env\nsource ./.env/bin/activate\n</code></pre>"},{"location":"installation/#macos-installation-error","title":"MacOS installation error","text":"<p>Newer versions of MacOS may have installation failed with errors like <code>error: command 'g++' failed with exit status 1</code>.</p> <p>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.</p> <pre><code>open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg\n</code></pre> <p>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.</p>"},{"location":"installation/#macos-installation-error-with-python-39","title":"MacOS installation error with python 3.9","text":"<p>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 <code>tables</code> or <code>blosc</code>.</p> <p>You can install the necessary libraries with the following command:</p> <pre><code>brew install hdf5 c-blosc\n</code></pre> <p>After this, please run the installation (script) again.</p>"},{"location":"plotting/","title":"Plotting","text":"<p>This page explains how to plot prices, indicators and profits.</p>"},{"location":"plotting/#installation-setup","title":"Installation / Setup","text":"<p>Plotting modules use the Plotly library. You can install / upgrade this by running the following command:</p> <pre><code>pip install -U -r requirements-plot.txt\n</code></pre>"},{"location":"plotting/#plot-price-and-indicators","title":"Plot price and indicators","text":"<p>The <code>freqtrade plot-dataframe</code> subcommand shows an interactive graph with three subplots:</p> <ul> <li>Main plot with candlestics and indicators following price (sma/ema)</li> <li>Volume bars</li> <li>Additional indicators as specified by <code>--indicators2</code></li> </ul> <p></p> <p>Possible arguments:</p> <pre><code>usage: freqtrade plot-dataframe [-h] [-v] [--logfile FILE] [-V] [-c PATH]\n [-d PATH] [--userdir PATH] [-s NAME]\n [--strategy-path PATH] [-p PAIRS [PAIRS ...]]\n [--indicators1 INDICATORS1 [INDICATORS1 ...]]\n [--indicators2 INDICATORS2 [INDICATORS2 ...]]\n [--plot-limit INT] [--db-url PATH]\n [--trade-source {DB,file}] [--export EXPORT]\n [--export-filename PATH]\n [--timerange TIMERANGE] [-i TIMEFRAME]\n [--no-trades]\n\noptional arguments:\n -h, --help show this help message and exit\n -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]\n Show profits for only these pairs. Pairs are space-\n separated.\n --indicators1 INDICATORS1 [INDICATORS1 ...]\n Set indicators from your strategy you want in the\n first row of the graph. Space-separated list. Example:\n `ema3 ema5`. Default: `['sma', 'ema3', 'ema5']`.\n --indicators2 INDICATORS2 [INDICATORS2 ...]\n Set indicators from your strategy you want in the\n third row of the graph. Space-separated list. Example:\n `fastd fastk`. Default: `['macd', 'macdsignal']`.\n --plot-limit INT Specify tick limit for plotting. Notice: too high\n values cause huge files. Default: 750.\n --db-url PATH Override trades database URL, this is useful in custom\n deployments (default: `sqlite:///tradesv3.sqlite` for\n Live Run mode, `sqlite:///tradesv3.dryrun.sqlite` for\n Dry Run).\n --trade-source {DB,file}\n Specify the source for trades (Can be DB or file\n (backtest file)) Default: file\n --export EXPORT Export backtest results, argument are: trades.\n Example: `--export=trades`\n --export-filename PATH\n Save backtest results to the file with this filename.\n Requires `--export` to be set as well. Example:\n `--export-filename=user_data/backtest_results/backtest\n _today.json`\n --timerange TIMERANGE\n Specify what timerange of data to use.\n -i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME\n Specify ticker interval (`1m`, `5m`, `30m`, `1h`,\n `1d`).\n --no-trades Skip using trades from backtesting file and DB.\n\nCommon arguments:\n -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).\n --logfile FILE Log to the file specified. Special values are:\n 'syslog', 'journald'. See the documentation for more\n details.\n -V, --version show program's version number and exit\n -c PATH, --config PATH\n Specify configuration file (default:\n `userdir/config.json` or `config.json` whichever\n exists). Multiple --config options may be used. Can be\n set to `-` to read config from stdin.\n -d PATH, --datadir PATH\n Path to directory with historical backtesting data.\n --userdir PATH, --user-data-dir PATH\n Path to userdata directory.\n\nStrategy arguments:\n -s NAME, --strategy NAME\n Specify strategy class name which will be used by the\n bot.\n --strategy-path PATH Specify additional strategy lookup path.\n</code></pre> <p>Example:</p> <pre><code>freqtrade plot-dataframe -p BTC/ETH\n</code></pre> <p>The <code>-p/--pairs</code> argument can be used to specify pairs you would like to plot.</p> <p>Note</p> <p>The <code>freqtrade plot-dataframe</code> subcommand generates one plot-file per pair.</p> <p>Specify custom indicators. Use <code>--indicators1</code> for the main plot and <code>--indicators2</code> for the subplot below (if values are in a different range than prices).</p> <p>Tip</p> <p>You will almost certainly want to specify a custom strategy! This can be done by adding <code>-s Classname</code> / <code>--strategy ClassName</code> to the command.</p> <pre><code>freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH --indicators1 sma ema --indicators2 macd\n</code></pre>"},{"location":"plotting/#further-usage-examples","title":"Further usage examples","text":"<p>To plot multiple pairs, separate them with a space:</p> <pre><code>freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH XRP/ETH\n</code></pre> <p>To plot a timerange (to zoom in)</p> <pre><code>freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH --timerange=20180801-20180805\n</code></pre> <p>To plot trades stored in a database use <code>--db-url</code> in combination with <code>--trade-source DB</code>:</p> <pre><code>freqtrade plot-dataframe --strategy AwesomeStrategy --db-url sqlite:///tradesv3.dry_run.sqlite -p BTC/ETH --trade-source DB\n</code></pre> <p>To plot trades from a backtesting result, use <code>--export-filename <filename></code></p> <pre><code>freqtrade plot-dataframe --strategy AwesomeStrategy --export-filename user_data/backtest_results/backtest-result.json -p BTC/ETH\n</code></pre>"},{"location":"plotting/#plot-dataframe-basics","title":"Plot dataframe basics","text":"<p>The <code>plot-dataframe</code> subcommand requires backtesting data, a strategy and either a backtesting-results file or a database, containing trades corresponding to the strategy.</p> <p>The resulting plot will have the following elements:</p> <ul> <li>Green triangles: Buy signals from the strategy. (Note: not every buy signal generates a trade, compare to cyan circles.)</li> <li>Red triangles: Sell signals from the strategy. (Also, not every sell signal terminates a trade, compare to red and green squares.)</li> <li>Cyan circles: Trade entry points.</li> <li>Red squares: Trade exit points for trades with loss or 0% profit.</li> <li>Green squares: Trade exit points for profitable trades.</li> <li>Indicators with values corresponding to the candle scale (e.g. SMA/EMA), as specified with <code>--indicators1</code>.</li> <li>Volume (bar chart at the bottom of the main chart).</li> <li>Indicators with values in different scales (e.g. MACD, RSI) below the volume bars, as specified with <code>--indicators2</code>.</li> </ul> <p>Bollinger Bands</p> <p>Bollinger bands are automatically added to the plot if the columns <code>bb_lowerband</code> and <code>bb_upperband</code> exist, and are painted as a light blue area spanning from the lower band to the upper band.</p>"},{"location":"plotting/#advanced-plot-configuration","title":"Advanced plot configuration","text":"<p>An advanced plot configuration can be specified in the strategy in the <code>plot_config</code> parameter.</p> <p>Additional features when using plot_config include:</p> <ul> <li>Specify colors per indicator</li> <li>Specify additional subplots</li> <li>Specify indicator pairs to fill area in between </li> </ul> <p>The sample plot configuration below specifies fixed colors for the indicators. Otherwise consecutive plots may produce different colorschemes each time, making comparisons difficult. It also allows multiple subplots to display both MACD and RSI at the same time.</p> <p>Sample configuration with inline comments explaining the process:</p> <pre><code> plot_config = {\n 'main_plot': {\n # Configuration for main plot indicators.\n # Specifies `ema10` to be red, and `ema50` to be a shade of gray\n 'ema10': {'color': 'red'},\n 'ema50': {'color': '#CCCCCC'},\n # By omitting color, a random color is selected.\n 'sar': {},\n # fill area between senkou_a and senkou_b\n 'senkou_a': {\n 'color': 'green', #optional\n 'fill_to': 'senkou_b',\n 'fill_label': 'Ichimoku Cloud', #optional\n 'fill_color': 'rgba(255,76,46,0.2)', #optional\n },\n # plot senkou_b, too. Not only the area to it.\n 'senkou_b': {}\n },\n 'subplots': {\n # Create subplot MACD\n \"MACD\": {\n 'macd': {'color': 'blue', 'fill_to': 'macdhist'},\n 'macdsignal': {'color': 'orange'}\n },\n # Additional subplot RSI\n \"RSI\": {\n 'rsi': {'color': 'red'}\n }\n }\n }\n</code></pre> <p>Note</p> <p>The above configuration assumes that <code>ema10</code>, <code>ema50</code>, <code>senkou_a</code>, <code>senkou_b</code>, <code>macd</code>, <code>macdsignal</code>, <code>macdhist</code> and <code>rsi</code> are columns in the DataFrame created by the strategy.</p>"},{"location":"plotting/#plot-profit","title":"Plot profit","text":"<p>The <code>plot-profit</code> subcommand shows an interactive graph with three plots:</p> <ul> <li>Average closing price for all pairs.</li> <li>The summarized profit made by backtesting. Note that this is not the real-world profit, but more of an estimate.</li> <li>Profit for each individual pair.</li> </ul> <p>The first graph is good to get a grip of how the overall market progresses.</p> <p>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.</p> <p>The third graph can be useful to spot outliers, events in pairs that cause profit spikes.</p> <p>Possible options for the <code>freqtrade plot-profit</code> subcommand:</p> <pre><code>usage: freqtrade plot-profit [-h] [-v] [--logfile FILE] [-V] [-c PATH]\n [-d PATH] [--userdir PATH] [-s NAME]\n [--strategy-path PATH] [-p PAIRS [PAIRS ...]]\n [--timerange TIMERANGE] [--export EXPORT]\n [--export-filename PATH] [--db-url PATH]\n [--trade-source {DB,file}] [-i TIMEFRAME]\n\noptional arguments:\n -h, --help show this help message and exit\n -p PAIRS [PAIRS ...], --pairs PAIRS [PAIRS ...]\n Show profits for only these pairs. Pairs are space-\n separated.\n --timerange TIMERANGE\n Specify what timerange of data to use.\n --export EXPORT Export backtest results, argument are: trades.\n Example: `--export=trades`\n --export-filename PATH\n Save backtest results to the file with this filename.\n Requires `--export` to be set as well. Example:\n `--export-filename=user_data/backtest_results/backtest\n _today.json`\n --db-url PATH Override trades database URL, this is useful in custom\n deployments (default: `sqlite:///tradesv3.sqlite` for\n Live Run mode, `sqlite:///tradesv3.dryrun.sqlite` for\n Dry Run).\n --trade-source {DB,file}\n Specify the source for trades (Can be DB or file\n (backtest file)) Default: file\n -i TIMEFRAME, --timeframe TIMEFRAME, --ticker-interval TIMEFRAME\n Specify ticker interval (`1m`, `5m`, `30m`, `1h`,\n `1d`).\n\nCommon arguments:\n -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).\n --logfile FILE Log to the file specified. Special values are:\n 'syslog', 'journald'. See the documentation for more\n details.\n -V, --version show program's version number and exit\n -c PATH, --config PATH\n Specify configuration file (default:\n `userdir/config.json` or `config.json` whichever\n exists). Multiple --config options may be used. Can be\n set to `-` to read config from stdin.\n -d PATH, --datadir PATH\n Path to directory with historical backtesting data.\n --userdir PATH, --user-data-dir PATH\n Path to userdata directory.\n\nStrategy arguments:\n -s NAME, --strategy NAME\n Specify strategy class name which will be used by the\n bot.\n --strategy-path PATH Specify additional strategy lookup path.\n</code></pre> <p>The <code>-p/--pairs</code> argument, can be used to limit the pairs that are considered for this calculation.</p> <p>Examples:</p> <p>Use custom backtest-export file</p> <pre><code>freqtrade plot-profit -p LTC/BTC --export-filename user_data/backtest_results/backtest-result.json\n</code></pre> <p>Use custom database</p> <pre><code>freqtrade plot-profit -p LTC/BTC --db-url sqlite:///tradesv3.sqlite --trade-source DB\n</code></pre> <pre><code>freqtrade --datadir user_data/data/binance_save/ plot-profit -p LTC/BTC\n</code></pre>"},{"location":"plugins/","title":"Plugins","text":""},{"location":"plugins/#pairlists-and-pairlist-handlers","title":"Pairlists and Pairlist Handlers","text":"<p>Pairlist Handlers define the list of pairs (pairlist) that the bot should trade. They are configured in the <code>pairlists</code> section of the configuration settings.</p> <p>In your configuration, you can use Static Pairlist (defined by the <code>StaticPairList</code> Pairlist Handler) and Dynamic Pairlist (defined by the <code>VolumePairList</code> Pairlist Handler).</p> <p>Additionally, <code>AgeFilter</code>, <code>PrecisionFilter</code>, <code>PriceFilter</code>, <code>ShuffleFilter</code> and <code>SpreadFilter</code> act as Pairlist Filters, removing certain pairs and/or moving their positions in the pairlist.</p> <p>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 <code>StaticPairList</code> or <code>VolumePairList</code> as the starting Pairlist Handler.</p> <p>Inactive markets are always removed from the resulting pairlist. Explicitly blacklisted pairs (those in the <code>pair_blacklist</code> configuration setting) are also always removed from the resulting pairlist.</p>"},{"location":"plugins/#pair-blacklist","title":"Pair blacklist","text":"<p>The pair blacklist (configured via <code>exchange.pair_blacklist</code> in the configuration) disallows certain pairs from trading. This can be as simple as excluding <code>DOGE/BTC</code> - which will remove exactly this pair.</p> <p>The pair-blacklist does also support wildcards (in regex-style) - so <code>BNB/.*</code> will exclude ALL pairs that start with BNB. You may also use something like <code>.*DOWN/BTC</code> or <code>.*UP/BTC</code> to exclude leveraged tokens (check Pair naming conventions for your exchange!)</p>"},{"location":"plugins/#available-pairlist-handlers","title":"Available Pairlist Handlers","text":"<ul> <li><code>StaticPairList</code> (default, if not configured differently)</li> <li><code>VolumePairList</code></li> <li><code>AgeFilter</code></li> <li><code>PerformanceFilter</code></li> <li><code>PrecisionFilter</code></li> <li><code>PriceFilter</code></li> <li><code>ShuffleFilter</code></li> <li><code>SpreadFilter</code></li> <li><code>RangeStabilityFilter</code></li> </ul> <p>Testing pairlists</p> <p>Pairlist configurations can be quite tricky to get right. Best use the <code>test-pairlist</code> utility sub-command to test your configuration quickly.</p>"},{"location":"plugins/#static-pair-list","title":"Static Pair List","text":"<p>By default, the <code>StaticPairList</code> method is used, which uses a statically defined pair whitelist from the configuration. The pairlist also supports wildcards (in regex-style) - so <code>.*/BTC</code> will include all pairs with BTC as a stake.</p> <p>It uses configuration from <code>exchange.pair_whitelist</code> and <code>exchange.pair_blacklist</code>.</p> <pre><code>\"pairlists\": [\n {\"method\": \"StaticPairList\"}\n ],\n</code></pre> <p>By default, only currently enabled pairs are allowed. To skip pair validation against active markets, set <code>\"allow_inactive\": true</code> within the <code>StaticPairList</code> configuration. This can be useful for backtesting expired pairs (like quarterly spot-markets). This option must be configured along with <code>exchange.skip_pair_validation</code> in the exchange configuration.</p>"},{"location":"plugins/#volume-pair-list","title":"Volume Pair List","text":"<p><code>VolumePairList</code> employs sorting/filtering of pairs by their trading volume. It selects <code>number_assets</code> top pairs with sorting based on the <code>sort_key</code> (which can only be <code>quoteVolume</code>).</p> <p>When used in the chain of Pairlist Handlers in a non-leading position (after StaticPairList and other Pairlist Filters), <code>VolumePairList</code> considers outputs of previous Pairlist Handlers, adding its sorting/selection of the pairs by the trading volume.</p> <p>When used on the leading position of the chain of Pairlist Handlers, it does not consider <code>pair_whitelist</code> configuration setting, but selects the top assets from all available markets (with matching stake-currency) on the exchange.</p> <p>The <code>refresh_period</code> setting allows to define the period (in seconds), at which the pairlist will be refreshed. Defaults to 1800s (30 minutes).</p> <p><code>VolumePairList</code> is based on the ticker data from exchange, as reported by the ccxt library:</p> <ul> <li>The <code>quoteVolume</code> is the amount of quote (stake) currency traded (bought or sold) in last 24 hours.</li> </ul> <pre><code>\"pairlists\": [{\n \"method\": \"VolumePairList\",\n \"number_assets\": 20,\n \"sort_key\": \"quoteVolume\",\n \"refresh_period\": 1800\n}],\n</code></pre> <p>Note</p> <p><code>VolumePairList</code> does not support backtesting mode.</p>"},{"location":"plugins/#agefilter","title":"AgeFilter","text":"<p>Removes pairs that have been listed on the exchange for less than <code>min_days_listed</code> days (defaults to <code>10</code>).</p> <p>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.</p> <p>This filter allows freqtrade to ignore pairs until they have been listed for at least <code>min_days_listed</code> days.</p>"},{"location":"plugins/#performancefilter","title":"PerformanceFilter","text":"<p>Sorts pairs by past trade performance, as follows: 1. Positive performance. 2. No closed trades yet. 3. Negative performance.</p> <p>Trade count is used as a tie breaker.</p> <p>Note</p> <p><code>PerformanceFilter</code> does not support backtesting mode.</p>"},{"location":"plugins/#precisionfilter","title":"PrecisionFilter","text":"<p>Filters low-value coins which would not allow setting stoplosses.</p>"},{"location":"plugins/#pricefilter","title":"PriceFilter","text":"<p>The <code>PriceFilter</code> allows filtering of pairs by price. Currently the following price filters are supported:</p> <ul> <li><code>min_price</code></li> <li><code>max_price</code></li> <li><code>low_price_ratio</code></li> </ul> <p>The <code>min_price</code> 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.</p> <p>The <code>max_price</code> 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.</p> <p>The <code>low_price_ratio</code> setting removes pairs where a raise of 1 price unit (pip) is above the <code>low_price_ratio</code> ratio. This option is disabled by default, and will only apply if set to > 0.</p> <p>For <code>PriceFiler</code> at least one of its <code>min_price</code>, <code>max_price</code> or <code>low_price_ratio</code> settings must be applied.</p> <p>Calculation example:</p> <p>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 <code>low_price_ratio</code> set to 0.09 (9%) or with <code>min_price</code> set to 0.00000011, correspondingly.</p> <p>Low priced pairs</p> <p>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.</p>"},{"location":"plugins/#shufflefilter","title":"ShuffleFilter","text":"<p>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.</p> <p>Tip</p> <p>You may set the <code>seed</code> value for this Pairlist to obtain reproducible results, which can be useful for repeated backtesting sessions. If <code>seed</code> is not set, the pairs are shuffled in the non-repeatable random order.</p>"},{"location":"plugins/#spreadfilter","title":"SpreadFilter","text":"<p>Removes pairs that have a difference between asks and bids above the specified ratio, <code>max_spread_ratio</code> (defaults to <code>0.005</code>).</p> <p>Example:</p> <p>If <code>DOGE/BTC</code> maximum bid is 0.00000026 and minimum ask is 0.00000027, the ratio is calculated as: <code>1 - bid/ask ~= 0.037</code> which is <code>> 0.005</code> and this pair will be filtered out.</p>"},{"location":"plugins/#rangestabilityfilter","title":"RangeStabilityFilter","text":"<p>Removes pairs where the difference between lowest low and highest high over <code>lookback_days</code> days is below <code>min_rate_of_change</code>. Since this is a filter that requires additional data, the results are cached for <code>refresh_period</code>.</p> <p>In the below example: If the trading range over the last 10 days is <1%, remove the pair from the whitelist.</p> <pre><code>\"pairlists\": [\n {\n \"method\": \"RangeStabilityFilter\",\n \"lookback_days\": 10,\n \"min_rate_of_change\": 0.01,\n \"refresh_period\": 1440\n }\n]\n</code></pre> <p>Tip</p> <p>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.</p>"},{"location":"plugins/#full-example-of-pairlist-handlers","title":"Full example of Pairlist Handlers","text":"<p>The below example blacklists <code>BNB/BTC</code>, uses <code>VolumePairList</code> with <code>20</code> assets, sorting pairs by <code>quoteVolume</code> and applies both <code>PrecisionFilter</code> and <code>PriceFilter</code>, filtering all assets where 1 price unit is > 1%. Then the <code>SpreadFilter</code> is applied and pairs are finally shuffled with the random seed set to some predefined value.</p> <pre><code>\"exchange\": {\n \"pair_whitelist\": [],\n \"pair_blacklist\": [\"BNB/BTC\"]\n},\n\"pairlists\": [\n {\n \"method\": \"VolumePairList\",\n \"number_assets\": 20,\n \"sort_key\": \"quoteVolume\",\n },\n {\"method\": \"AgeFilter\", \"min_days_listed\": 10},\n {\"method\": \"PrecisionFilter\"},\n {\"method\": \"PriceFilter\", \"low_price_ratio\": 0.01},\n {\"method\": \"SpreadFilter\", \"max_spread_ratio\": 0.005},\n {\n \"method\": \"RangeStabilityFilter\",\n \"lookback_days\": 10,\n \"min_rate_of_change\": 0.01,\n \"refresh_period\": 1440\n },\n {\"method\": \"ShuffleFilter\", \"seed\": 42}\n ],\n</code></pre>"},{"location":"plugins/#protections","title":"Protections","text":"<p>Beta feature</p> <p>This feature is still in it's testing phase. Should you notice something you think is wrong please let us know via Discord, Slack or via Github Issue.</p> <p>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.</p> <p>Note</p> <p>Not all Protections will work for all strategies, and parameters will need to be tuned for your strategy to improve performance. To align your protection with your strategy, you can define protections in the strategy.</p> <p>Tip</p> <p>Each Protection can be configured multiple times with different parameters, to allow different levels of protection (short-term / long-term).</p> <p>Backtesting</p> <p>Protections are supported by backtesting and hyperopt, but must be explicitly enabled by using the <code>--enable-protections</code> flag.</p>"},{"location":"plugins/#available-protections","title":"Available Protections","text":"<ul> <li><code>StoplossGuard</code> Stop trading if a certain amount of stoploss occurred within a certain time window.</li> <li><code>MaxDrawdown</code> Stop trading if max-drawdown is reached.</li> <li><code>LowProfitPairs</code> Lock pairs with low profits</li> <li><code>CooldownPeriod</code> Don't enter a trade right after selling a trade.</li> </ul>"},{"location":"plugins/#common-settings-to-all-protections","title":"Common settings to all Protections","text":"Parameter Description <code>method</code> Protection name to use. Datatype: String, selected from available Protections <code>stop_duration_candles</code> For how many candles should the lock be set? Datatype: Positive integer (in candles) <code>stop_duration</code> how many minutes should protections be locked. Cannot be used together with <code>stop_duration_candles</code>. Datatype: Float (in minutes) <code>lookback_period_candles</code> Only trades that completed within the last <code>lookback_period_candles</code> candles will be considered. This setting may be ignored by some Protections. Datatype: Positive integer (in candles). <code>lookback_period</code> Only trades that completed after <code>current_time - lookback_period</code> will be considered. Cannot be used together with <code>lookback_period_candles</code>. This setting may be ignored by some Protections. Datatype: Float (in minutes) <code>trade_limit</code> Number of trades required at minimum (not used by all Protections). Datatype: Positive integer <p>Durations</p> <p>Durations (<code>stop_duration*</code> and <code>lookback_period*</code> can be defined in either minutes or candles). For more flexibility when testing different timeframes, all below examples will use the \"candle\" definition.</p>"},{"location":"plugins/#stoploss-guard","title":"Stoploss Guard","text":"<p><code>StoplossGuard</code> selects all trades within <code>lookback_period</code> in minutes (or in candles when using <code>lookback_period_candles</code>). If <code>trade_limit</code> or more trades resulted in stoploss, trading will stop for <code>stop_duration</code> in minutes (or in candles when using <code>stop_duration_candles</code>).</p> <p>This applies across all pairs, unless <code>only_per_pair</code> is set to true, which will then only look at one pair at a time.</p> <p>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.</p> <pre><code>\"protections\": [\n {\n \"method\": \"StoplossGuard\",\n \"lookback_period_candles\": 24,\n \"trade_limit\": 4,\n \"stop_duration_candles\": 4,\n \"only_per_pair\": false\n }\n],\n</code></pre> <p>Note</p> <p><code>StoplossGuard</code> considers all trades with the results <code>\"stop_loss\"</code>, <code>\"stoploss_on_exchange\"</code> and <code>\"trailing_stop_loss\"</code> if the resulting profit was negative. <code>trade_limit</code> and <code>lookback_period</code> will need to be tuned for your strategy.</p>"},{"location":"plugins/#maxdrawdown","title":"MaxDrawdown","text":"<p><code>MaxDrawdown</code> uses all trades within <code>lookback_period</code> in minutes (or in candles when using <code>lookback_period_candles</code>) to determine the maximum drawdown. If the drawdown is below <code>max_allowed_drawdown</code>, trading will stop for <code>stop_duration</code> in minutes (or in candles when using <code>stop_duration_candles</code>) after the last trade - assuming that the bot needs some time to let markets recover.</p> <p>The below sample stops trading for 12 candles if max-drawdown is > 20% considering all pairs - with a minimum of <code>trade_limit</code> trades - within the last 48 candles. If desired, <code>lookback_period</code> and/or <code>stop_duration</code> can be used.</p> <pre><code>\"protections\": [\n {\n \"method\": \"MaxDrawdown\",\n \"lookback_period_candles\": 48,\n \"trade_limit\": 20,\n \"stop_duration_candles\": 12,\n \"max_allowed_drawdown\": 0.2\n },\n],\n</code></pre>"},{"location":"plugins/#low-profit-pairs","title":"Low Profit Pairs","text":"<p><code>LowProfitPairs</code> uses all trades for a pair within <code>lookback_period</code> in minutes (or in candles when using <code>lookback_period_candles</code>) to determine the overall profit ratio. If that ratio is below <code>required_profit</code>, that pair will be locked for <code>stop_duration</code> in minutes (or in candles when using <code>stop_duration_candles</code>).</p> <p>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.</p> <pre><code>\"protections\": [\n {\n \"method\": \"LowProfitPairs\",\n \"lookback_period_candles\": 6,\n \"trade_limit\": 2,\n \"stop_duration\": 60,\n \"required_profit\": 0.02\n }\n],\n</code></pre>"},{"location":"plugins/#cooldown-period","title":"Cooldown Period","text":"<p><code>CooldownPeriod</code> locks a pair for <code>stop_duration</code> in minutes (or in candles when using <code>stop_duration_candles</code>) after selling, avoiding a re-entry for this pair for <code>stop_duration</code> minutes.</p> <p>The below example will stop trading a pair for 2 candles after closing a trade, allowing this pair to \"cool down\".</p> <pre><code>\"protections\": [\n {\n \"method\": \"CooldownPeriod\",\n \"stop_duration_candles\": 2\n }\n],\n</code></pre> <p>Note</p> <p>This Protection applies only at pair-level, and will never lock all pairs globally. This Protection does not consider <code>lookback_period</code> as it only looks at the latest trade.</p>"},{"location":"plugins/#full-example-of-protections","title":"Full example of Protections","text":"<p>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.</p> <p>The below example assumes a timeframe of 1 hour:</p> <ul> <li>Locks each pair after selling for an additional 5 candles (<code>CooldownPeriod</code>), giving other pairs a chance to get filled.</li> <li>Stops trading for 4 hours (<code>4 * 1h candles</code>) if the last 2 days (<code>48 * 1h candles</code>) had 20 trades, which caused a max-drawdown of more than 20%. (<code>MaxDrawdown</code>).</li> <li>Stops trading if more than 4 stoploss occur for all pairs within a 1 day (<code>24 * 1h candles</code>) limit (<code>StoplossGuard</code>).</li> <li>Locks all pairs that had 4 Trades within the last 6 hours (<code>6 * 1h candles</code>) with a combined profit ratio of below 0.02 (<2%) (<code>LowProfitPairs</code>).</li> <li>Locks all pairs for 2 candles that had a profit of below 0.01 (<1%) within the last 24h (<code>24 * 1h candles</code>), a minimum of 4 trades.</li> </ul> <pre><code>\"timeframe\": \"1h\",\n\"protections\": [\n {\n \"method\": \"CooldownPeriod\",\n \"stop_duration_candles\": 5\n },\n {\n \"method\": \"MaxDrawdown\",\n \"lookback_period_candles\": 48,\n \"trade_limit\": 20,\n \"stop_duration_candles\": 4,\n \"max_allowed_drawdown\": 0.2\n },\n {\n \"method\": \"StoplossGuard\",\n \"lookback_period_candles\": 24,\n \"trade_limit\": 4,\n \"stop_duration_candles\": 2,\n \"only_per_pair\": false\n },\n {\n \"method\": \"LowProfitPairs\",\n \"lookback_period_candles\": 6,\n \"trade_limit\": 2,\n \"stop_duration_candles\": 60,\n \"required_profit\": 0.02\n },\n {\n \"method\": \"LowProfitPairs\",\n \"lookback_period_candles\": 24,\n \"trade_limit\": 4,\n \"stop_duration_candles\": 2,\n \"required_profit\": 0.01\n }\n ],\n</code></pre> <p>You can use the same in your strategy, the syntax is only slightly different:</p> <pre><code>from freqtrade.strategy import IStrategy\n\nclass AwesomeStrategy(IStrategy)\n timeframe = '1h'\n protections = [\n {\n \"method\": \"CooldownPeriod\",\n \"stop_duration_candles\": 5\n },\n {\n \"method\": \"MaxDrawdown\",\n \"lookback_period_candles\": 48,\n \"trade_limit\": 20,\n \"stop_duration_candles\": 4,\n \"max_allowed_drawdown\": 0.2\n },\n {\n \"method\": \"StoplossGuard\",\n \"lookback_period_candles\": 24,\n \"trade_limit\": 4,\n \"stop_duration_candles\": 2,\n \"only_per_pair\": False\n },\n {\n \"method\": \"LowProfitPairs\",\n \"lookback_period_candles\": 6,\n \"trade_limit\": 2,\n \"stop_duration_candles\": 60,\n \"required_profit\": 0.02\n },\n {\n \"method\": \"LowProfitPairs\",\n \"lookback_period_candles\": 24,\n \"trade_limit\": 4,\n \"stop_duration_candles\": 2,\n \"required_profit\": 0.01\n }\n ]\n # ...\n</code></pre>"},{"location":"rest-api/","title":"REST API & FreqUI","text":""},{"location":"rest-api/#frequi","title":"FreqUI","text":"<p>Freqtrade provides a builtin webserver, which can serve FreqUI, the freqtrade UI.</p> <p>By default, the UI is not included in the installation (except for docker images), and must be installed explicitly with <code>freqtrade install-ui</code>. This same command can also be used to update freqUI, should there be a new release.</p> <p>Once the bot is started in trade / dry-run mode (with <code>freqtrade trade</code>) - the UI will be available under the configured port below (usually <code>http://127.0.0.1:8080</code>).</p> <p>Alpha release</p> <p>FreqUI is still considered an alpha release - if you encounter bugs or inconsistencies please open a FreqUI issue.</p> <p>developers</p> <p>Developers should not use this method, but instead use the method described in the freqUI repository to get the source-code of freqUI.</p>"},{"location":"rest-api/#configuration","title":"Configuration","text":"<p>Enable the rest API by adding the api_server section to your configuration and setting <code>api_server.enabled</code> to <code>true</code>.</p> <p>Sample configuration:</p> <pre><code> \"api_server\": {\n \"enabled\": true,\n \"listen_ip_address\": \"127.0.0.1\",\n \"listen_port\": 8080,\n \"verbosity\": \"error\",\n \"enable_openapi\": false,\n \"jwt_secret_key\": \"somethingrandom\",\n \"CORS_origins\": [],\n \"username\": \"Freqtrader\",\n \"password\": \"SuperSecret1!\"\n },\n</code></pre> <p>Security warning</p> <p>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.</p> <p>You can then access the API by going to <code>http://127.0.0.1:8080/api/v1/ping</code> in a browser to check if the API is running correctly. This should return the response:</p> <pre><code>{\"status\":\"pong\"}\n</code></pre> <p>All other endpoints return sensitive info and require authentication and are therefore not available through a web browser.</p>"},{"location":"rest-api/#security","title":"Security","text":"<p>To generate a secure password, best use a password manager, or use the below code.</p> <pre><code>import secrets\nsecrets.token_hex()\n</code></pre> <p>JWT token</p> <p>Use the same method to also generate a JWT secret key (<code>jwt_secret_key</code>).</p> <p>Password selection</p> <p>Please make sure to select a very strong, unique password to protect your bot from unauthorized access. Also change <code>jwt_secret_key</code> to something random (no need to remember this, but it'll be used to encrypt your session, so it better be something unique!). </p>"},{"location":"rest-api/#configuration-with-docker","title":"Configuration with docker","text":"<p>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.</p> <pre><code> \"api_server\": {\n \"enabled\": true,\n \"listen_ip_address\": \"0.0.0.0\",\n \"listen_port\": 8080\n },\n</code></pre> <p>Uncomment the following from your docker-compose file:</p> <pre><code> ports:\n - \"127.0.0.1:8080:8080\"\n</code></pre> <p>Security warning</p> <p>By using <code>8080:8080</code> 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.</p>"},{"location":"rest-api/#rest-api","title":"Rest API","text":""},{"location":"rest-api/#consuming-the-api","title":"Consuming the API","text":"<p>You can consume the API by using the script <code>scripts/rest_client.py</code>. The client script only requires the <code>requests</code> module, so Freqtrade does not need to be installed on the system.</p> <pre><code>python3 scripts/rest_client.py <command> [optional parameters]\n</code></pre> <p>By default, the script assumes <code>127.0.0.1</code> (localhost) and port <code>8080</code> to be used, however you can specify a configuration file to override this behaviour.</p>"},{"location":"rest-api/#minimalistic-client-config","title":"Minimalistic client config","text":"<pre><code>{\n \"api_server\": {\n \"enabled\": true,\n \"listen_ip_address\": \"0.0.0.0\",\n \"listen_port\": 8080\n }\n}\n</code></pre> <pre><code>python3 scripts/rest_client.py --config rest_config.json <command> [optional parameters]\n</code></pre>"},{"location":"rest-api/#available-endpoints","title":"Available endpoints","text":"Command Description <code>ping</code> Simple command testing the API Readiness - requires no authentication. <code>start</code> Starts the trader. <code>stop</code> Stops the trader. <code>stopbuy</code> Stops the trader from opening new trades. Gracefully closes open trades according to their rules. <code>reload_config</code> Reloads the configuration file. <code>trades</code> List last trades. <code>delete_trade <trade_id></code> Remove trade from the database. Tries to close open orders. Requires manual handling of this trade on the exchange. <code>show_config</code> Shows part of the current configuration with relevant settings to operation. <code>logs</code> Shows last log messages. <code>status</code> Lists all open trades. <code>count</code> Displays number of trades used and available. <code>locks</code> Displays currently locked pairs. <code>profit</code> Display a summary of your profit/loss from close trades and some stats about your performance. <code>forcesell <trade_id></code> Instantly sells the given trade (Ignoring <code>minimum_roi</code>). <code>forcesell all</code> Instantly sells all open trades (Ignoring <code>minimum_roi</code>). <code>forcebuy <pair> [rate]</code> Instantly buys the given pair. Rate is optional. (<code>forcebuy_enable</code> must be set to True) <code>performance</code> Show performance of each finished trade grouped by pair. <code>balance</code> Show account balance per currency. <code>daily <n></code> Shows profit or loss per day, over the last n days (n defaults to 7). <code>stats</code> Display a summary of profit / loss reasons as well as average holding times. <code>whitelist</code> Show the current whitelist. <code>blacklist [pair]</code> Show the current blacklist, or adds a pair to the blacklist. <code>edge</code> Show validated pairs by Edge if it is enabled. <code>pair_candles</code> Returns dataframe for a pair / timeframe combination while the bot is running. Alpha <code>pair_history</code> Returns an analyzed dataframe for a given timerange, analyzed by a given strategy. Alpha <code>plot_config</code> Get plot config from the strategy (or nothing if not configured). Alpha <code>strategies</code> List strategies in strategy directory. Alpha <code>strategy <strategy></code> Get specific Strategy content. Alpha <code>available_pairs</code> List available backtest data. Alpha <code>version</code> Show version. <p>Alpha status</p> <p>Endpoints labeled with Alpha status above may change at any time without notice.</p> <p>Possible commands can be listed from the rest-client script using the <code>help</code> command.</p> <pre><code>python3 scripts/rest_client.py help\n</code></pre> <pre><code>Possible commands:\n\navailable_pairs\n Return available pair (backtest data) based on timeframe / stake_currency selection\n\n :param timeframe: Only pairs with this timeframe available.\n :param stake_currency: Only pairs that include this timeframe\n\nbalance\n Get the account balance.\n\nblacklist\n Show the current blacklist.\n\n :param add: List of coins to add (example: \"BNB/BTC\")\n\ncount\n Return the amount of open trades.\n\ndaily\n Return the amount of open trades.\n\ndelete_trade\n Delete trade from the database.\n Tries to close open orders. Requires manual handling of this asset on the exchange.\n\n :param trade_id: Deletes the trade with this ID from the database.\n\nedge\n Return information about edge.\n\nforcebuy\n Buy an asset.\n\n :param pair: Pair to buy (ETH/BTC)\n :param price: Optional - price to buy\n\nforcesell\n Force-sell a trade.\n\n :param tradeid: Id of the trade (can be received via status command)\n\nlogs\n Show latest logs.\n\n :param limit: Limits log messages to the last <limit> logs. No limit to get all the trades.\n\npair_candles\n Return live dataframe for <pair><timeframe>.\n\n :param pair: Pair to get data for\n :param timeframe: Only pairs with this timeframe available.\n :param limit: Limit result to the last n candles.\n\npair_history\n Return historic, analyzed dataframe\n\n :param pair: Pair to get data for\n :param timeframe: Only pairs with this timeframe available.\n :param strategy: Strategy to analyze and get values for\n :param timerange: Timerange to get data for (same format than --timerange endpoints)\n\nperformance\n Return the performance of the different coins.\n\nplot_config\n Return plot configuration if the strategy defines one.\n\nprofit\n Return the profit summary.\n\nreload_config\n Reload configuration.\n\nshow_config\n\n Returns part of the configuration, relevant for trading operations.\n\nstart\n Start the bot if it's in the stopped state.\n\nstats\n Return the stats report (durations, sell-reasons).\n\nstatus\n Get the status of open trades.\n\nstop\n Stop the bot. Use `start` to restart.\n\nstopbuy\n Stop buying (but handle sells gracefully). Use `reload_config` to reset.\n\nstrategies\n Lists available strategies\n\nstrategy\n Get strategy details\n\n :param strategy: Strategy class name\n\ntrades\n Return trades history.\n\n :param limit: Limits trades to the X last trades. No limit to get all the trades.\n\nversion\n Return the version of the bot.\n\nwhitelist\n Show the current whitelist.\n</code></pre>"},{"location":"rest-api/#openapi-interface","title":"OpenAPI interface","text":"<p>To enable the builtin openAPI interface (Swagger UI), specify <code>\"enable_openapi\": true</code> in the api_server configuration. This will enable the Swagger UI at the <code>/docs</code> endpoint. By default, that's running at http://localhost:8080/docs/ - but it'll depend on your settings.</p>"},{"location":"rest-api/#advanced-api-usage-using-jwt-tokens","title":"Advanced API usage using JWT tokens","text":"<p>Note</p> <p>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.</p> <p>Freqtrade's REST API also offers JWT (JSON Web Tokens). You can login using the following command, and subsequently use the resulting access_token.</p> <pre><code>> curl -X POST --user Freqtrader http://localhost:8080/api/v1/token/login\n{\"access_token\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1ODkxMTk2ODEsIm5iZiI6MTU4OTExOTY4MSwianRpIjoiMmEwYmY0NWUtMjhmOS00YTUzLTlmNzItMmM5ZWVlYThkNzc2IiwiZXhwIjoxNTg5MTIwNTgxLCJpZGVudGl0eSI6eyJ1IjoiRnJlcXRyYWRlciJ9LCJmcmVzaCI6ZmFsc2UsInR5cGUiOiJhY2Nlc3MifQ.qt6MAXYIa-l556OM7arBvYJ0SDI9J8bIk3_glDujF5g\",\"refresh_token\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1ODkxMTk2ODEsIm5iZiI6MTU4OTExOTY4MSwianRpIjoiZWQ1ZWI3YjAtYjMwMy00YzAyLTg2N2MtNWViMjIxNWQ2YTMxIiwiZXhwIjoxNTkxNzExNjgxLCJpZGVudGl0eSI6eyJ1IjoiRnJlcXRyYWRlciJ9LCJ0eXBlIjoicmVmcmVzaCJ9.d1AT_jYICyTAjD0fiQAr52rkRqtxCjUGEMwlNuuzgNQ\"}\n\n> access_token=\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1ODkxMTk2ODEsIm5iZiI6MTU4OTExOTY4MSwianRpIjoiMmEwYmY0NWUtMjhmOS00YTUzLTlmNzItMmM5ZWVlYThkNzc2IiwiZXhwIjoxNTg5MTIwNTgxLCJpZGVudGl0eSI6eyJ1IjoiRnJlcXRyYWRlciJ9LCJmcmVzaCI6ZmFsc2UsInR5cGUiOiJhY2Nlc3MifQ.qt6MAXYIa-l556OM7arBvYJ0SDI9J8bIk3_glDujF5g\"\n# Use access_token for authentication\n> curl -X GET --header \"Authorization: Bearer ${access_token}\" http://localhost:8080/api/v1/count\n</code></pre> <p>Since the access token has a short timeout (15 min) - the <code>token/refresh</code> request should be used periodically to get a fresh access token:</p> <pre><code>> curl -X POST --header \"Authorization: Bearer ${refresh_token}\"http://localhost:8080/api/v1/token/refresh\n{\"access_token\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1ODkxMTk5NzQsIm5iZiI6MTU4OTExOTk3NCwianRpIjoiMDBjNTlhMWUtMjBmYS00ZTk0LTliZjAtNWQwNTg2MTdiZDIyIiwiZXhwIjoxNTg5MTIwODc0LCJpZGVudGl0eSI6eyJ1IjoiRnJlcXRyYWRlciJ9LCJmcmVzaCI6ZmFsc2UsInR5cGUiOiJhY2Nlc3MifQ.1seHlII3WprjjclY6DpRhen0rqdF4j6jbvxIhUFaSbs\"}\n</code></pre>"},{"location":"rest-api/#cors","title":"CORS","text":"<p>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 <code>*</code> CORS policies for requests with credentials, so this setting must be set appropriately.</p> <p>Users can configure this themselves via the <code>CORS_origins</code> configuration setting. It consists of a list of allowed sites that are allowed to consume resources from the bot's API.</p> <p>Assuming your application is deployed as <code>https://frequi.freqtrade.io/home/</code> - this would mean that the following configuration becomes necessary:</p> <pre><code>{\n //...\n \"jwt_secret_key\": \"somethingrandom\",\n \"CORS_origins\": [\"https://frequi.freqtrade.io\"],\n //...\n}\n</code></pre> <p>Note</p> <p>We strongly recommend to also set <code>jwt_secret_key</code> to something random and known only to yourself to avoid unauthorized access to your bot.</p>"},{"location":"sandbox-testing/","title":"Sandbox API testing","text":"<p>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.</p> <p>This document is an overview to configure Freqtrade to be used with sandboxes. This can be useful to developers and trader alike.</p>"},{"location":"sandbox-testing/#exchanges-known-to-have-a-sandbox-testnet","title":"Exchanges known to have a sandbox / testnet","text":"<ul> <li>binance</li> <li>coinbasepro</li> <li>gemini</li> <li>huobipro</li> <li>kucoin</li> <li>phemex </li> </ul> <p>Note</p> <p>We did not test correct functioning of all of the above testnets. Please report your experiences with each sandbox.</p>"},{"location":"sandbox-testing/#configure-a-sandbox-account","title":"Configure a Sandbox account","text":"<p>When testing your API connectivity, make sure to use the appropriate sandbox / testnet URL.</p> <p>In general, you should follow these steps to enable an exchange's sandbox:</p> <ul> <li>Figure out if an exchange has a sandbox (most likely by using google or the exchange's support documents)</li> <li>Create a sandbox account (often the sandbox-account requires separate registration)</li> <li>Add some test assets to account</li> <li>Create API keys</li> </ul>"},{"location":"sandbox-testing/#add-test-funds","title":"Add test funds","text":"<p>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.</p> <p>Warning</p> <p>Test exchanges will NEVER require your real credit card or banking details!</p>"},{"location":"sandbox-testing/#configure-freqtrade-to-use-a-exchanges-sandbox","title":"Configure freqtrade to use a exchange's sandbox","text":""},{"location":"sandbox-testing/#sandbox-urls","title":"Sandbox URLs","text":"<p>Freqtrade makes use of CCXT which in turn provides a list of URLs to Freqtrade. These include <code>['test']</code> and <code>['api']</code>.</p> <ul> <li><code>[Test]</code> if available will point to an Exchanges sandbox.</li> <li><code>[Api]</code> normally used, and resolves to live API target on the exchange.</li> </ul> <p>To make use of sandbox / test add \"sandbox\": true, to your config.json</p> <pre><code> \"exchange\": {\n \"name\": \"coinbasepro\",\n \"sandbox\": true,\n \"key\": \"5wowfxemogxeowo;heiohgmd\",\n \"secret\": \"/ZMH1P62rCVmwefewrgcewX8nh4gob+lywxfwfxwwfxwfNsH1ySgvWCUR/w==\",\n \"password\": \"1bkjfkhfhfu6sr\",\n \"outdated_offset\": 5\n \"pair_whitelist\": [\n \"BTC/USD\"\n ]\n },\n \"datadir\": \"user_data/data/coinbasepro_sandbox\"\n</code></pre> <p>Also the following information:</p> <ul> <li>api-key (created for the sandbox webpage)</li> <li>api-secret (noted earlier)</li> <li>password (the passphrase - noted earlier)</li> </ul> <p>Different data directory</p> <p>We also recommend to set <code>datadir</code> 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 <code>\"datadir\"</code> key to the configuration. Now, whenever you use this configuration, your data directory will be set to this directory.</p>"},{"location":"sandbox-testing/#you-should-now-be-ready-to-test-your-sandbox","title":"You should now be ready to test your sandbox","text":"<p>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/)."},{"location":"sandbox-testing/#common-problems-with-sandbox-exchanges","title":"Common problems with sandbox exchanges","text":"<p>Sandbox exchange instances often have very low volume, which can cause some problems which usually are not seen on a real exchange instance.</p>"},{"location":"sandbox-testing/#old-candles-problem","title":"Old Candles problem","text":"<p>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 <code>\"outdated_offset\"</code> to a number that seems realistic for the sandbox you're using.</p>"},{"location":"sandbox-testing/#unfilled-orders","title":"Unfilled orders","text":"<p>Sandboxes often have very low volumes - which means that many trades can go unfilled, or can go unfilled for a very long time.</p> <p>To mitigate this, you can try to match the first order on the opposite orderbook side using the following configuration:</p> <p><code>jsonc \"order_types\": { \"buy\": \"limit\", \"sell\": \"limit\" // ... }, \"bid_strategy\": { \"price_side\": \"ask\", // ... }, \"ask_strategy\":{ \"price_side\": \"bid\", // ... },</code></p> <p>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.</p>"},{"location":"sql_cheatsheet/","title":"SQL Helper","text":"<p>This page contains some help if you want to edit your sqlite db.</p>"},{"location":"sql_cheatsheet/#install-sqlite3","title":"Install sqlite3","text":"<p>Sqlite3 is a terminal based sqlite application. Feel free to use a visual Database editor like SqliteBrowser if you feel more comfortable with that.</p>"},{"location":"sql_cheatsheet/#ubuntudebian-installation","title":"Ubuntu/Debian installation","text":"<pre><code>sudo apt-get install sqlite3\n</code></pre>"},{"location":"sql_cheatsheet/#using-sqlite3-via-docker-compose","title":"Using sqlite3 via docker-compose","text":"<p>The freqtrade docker image does contain sqlite3, so you can edit the database without having to install anything on the host system.</p> <pre><code>docker-compose exec freqtrade /bin/bash\nsqlite3 <databasefile>.sqlite\n</code></pre>"},{"location":"sql_cheatsheet/#open-the-db","title":"Open the DB","text":"<pre><code>sqlite3\n.open <filepath>\n</code></pre>"},{"location":"sql_cheatsheet/#table-structure","title":"Table structure","text":""},{"location":"sql_cheatsheet/#list-tables","title":"List tables","text":"<pre><code>.tables\n</code></pre>"},{"location":"sql_cheatsheet/#display-table-structure","title":"Display table structure","text":"<pre><code>.schema <table_name>\n</code></pre>"},{"location":"sql_cheatsheet/#get-all-trades-in-the-table","title":"Get all trades in the table","text":"<pre><code>SELECT * FROM trades;\n</code></pre>"},{"location":"sql_cheatsheet/#fix-trade-still-open-after-a-manual-sell-on-the-exchange","title":"Fix trade still open after a manual sell on the exchange","text":"<p>Warning</p> <p>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. <p>Note</p> <p>This should not be necessary after /forcesell, as forcesell orders are closed automatically by the bot on the next iteration.</p> <pre><code>UPDATE trades\nSET is_open=0,\n close_date=<close_date>,\n close_rate=<close_rate>,\n close_profit = close_rate / open_rate - 1,\n close_profit_abs = (amount * <close_rate> * (1 - fee_close) - (amount * (open_rate * (1 - fee_open)))),\n sell_reason=<sell_reason>\nWHERE id=<trade_ID_to_update>;\n</code></pre>"},{"location":"sql_cheatsheet/#example","title":"Example","text":"<pre><code>UPDATE trades\nSET is_open=0,\n close_date='2020-06-20 03:08:45.103418',\n close_rate=0.19638016,\n close_profit=0.0496,\n close_profit_abs = (amount * 0.19638016 * (1 - fee_close) - (amount * (open_rate * (1 - fee_open)))),\n sell_reason='force_sell' \nWHERE id=31;\n</code></pre>"},{"location":"sql_cheatsheet/#remove-trade-from-the-database","title":"Remove trade from the database","text":"<p>Use RPC Methods to delete trades</p> <p>Consider using <code>/delete <tradeid></code> via telegram or rest API. That's the recommended way to deleting trades.</p> <p>If you'd still like to remove a trade from the database directly, you can use the below query.</p> <pre><code>DELETE FROM trades WHERE id = <tradeid>;\n</code></pre> <pre><code>DELETE FROM trades WHERE id = 31;\n</code></pre> <p>Warning</p> <p>This will remove this trade from the database. Please make sure you got the correct id and NEVER run this query without the <code>where</code> clause.</p>"},{"location":"stoploss/","title":"Stop Loss","text":"<p>The <code>stoploss</code> configuration parameter is loss as ratio that should trigger a sale. For example, value <code>-0.10</code> will cause immediate sell if the profit dips below -10% for a given trade. This parameter is optional.</p> <p>Most of the strategy files already include the optimal <code>stoploss</code> value.</p> <p>Info</p> <p>All stoploss properties mentioned in this file can be set in the Strategy, or in the configuration. Configuration values will override the strategy values.</p>"},{"location":"stoploss/#stop-loss-on-exchangefreqtrade","title":"Stop Loss On-Exchange/Freqtrade","text":"<p>Those stoploss modes can be on exchange or off exchange.</p> <p>These modes can be configured with these values:</p> <pre><code> 'emergencysell': 'market',\n 'stoploss_on_exchange': False\n 'stoploss_on_exchange_interval': 60,\n 'stoploss_on_exchange_limit_ratio': 0.99\n</code></pre> <p>Note</p> <p>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.</p>"},{"location":"stoploss/#stoploss_on_exchange-and-stoploss_on_exchange_limit_ratio","title":"stoploss_on_exchange and stoploss_on_exchange_limit_ratio","text":"<p>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.</p> <p>If <code>stoploss_on_exchange</code> uses limit orders, the exchange needs 2 prices, the stoploss_price and the Limit price. <code>stoploss</code> 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 <code>stoploss</code> will be used to determine the stoploss type. </p> <p>Calculation example: we bought the asset at 100$. Stop-price is 95$, then limit would be <code>95 * 0.99 = 94.05$</code> - so the limit order fill can happen between 95$ and 94.05$. </p> <p>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.</p> <p>Note</p> <p>If <code>stoploss_on_exchange</code> is enabled and the stoploss is cancelled manually on the exchange, then the bot will create a new stoploss order.</p>"},{"location":"stoploss/#stoploss_on_exchange_interval","title":"stoploss_on_exchange_interval","text":"<p>In case of stoploss on exchange there is another parameter called <code>stoploss_on_exchange_interval</code>. 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.</p>"},{"location":"stoploss/#emergencysell","title":"emergencysell","text":"<p><code>emergencysell</code> is an optional value, which defaults to <code>market</code> 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.</p> <p>Example from strategy file:</p> <pre><code>order_types = {\n 'buy': 'limit',\n 'sell': 'limit',\n 'emergencysell': 'market',\n 'stoploss': 'market',\n 'stoploss_on_exchange': True,\n 'stoploss_on_exchange_interval': 60,\n 'stoploss_on_exchange_limit_ratio': 0.99\n}\n</code></pre>"},{"location":"stoploss/#stop-loss-types","title":"Stop Loss Types","text":"<p>At this stage the bot contains the following stoploss support modes:</p> <ol> <li>Static stop loss.</li> <li>Trailing stop loss.</li> <li>Trailing stop loss, custom positive loss.</li> <li>Trailing stop loss only once the trade has reached a certain offset.</li> <li>Custom stoploss function</li> </ol>"},{"location":"stoploss/#static-stop-loss","title":"Static Stop Loss","text":"<p>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.</p> <p>Example of stop loss:</p> <pre><code> stoploss = -0.10\n</code></pre> <p>For example, simplified math:</p> <ul> <li>the bot buys an asset at a price of 100$</li> <li>the stop loss is defined at -10%</li> <li>the stop loss would get triggered once the asset drops below 90$</li> </ul>"},{"location":"stoploss/#trailing-stop-loss","title":"Trailing Stop Loss","text":"<p>The initial value for this is <code>stoploss</code>, just as you would define your static Stop loss. To enable trailing stoploss:</p> <pre><code> stoploss = -0.10\n trailing_stop = True\n</code></pre> <p>This will now activate an algorithm, which automatically moves the stop loss up every time the price of your asset increases.</p> <p>For example, simplified math:</p> <ul> <li>the bot buys an asset at a price of 100$</li> <li>the stop loss is defined at -10%</li> <li>the stop loss would get triggered once the asset drops below 90$</li> <li>assuming the asset now increases to 102$</li> <li>the stop loss will now be -10% of 102$ = 91.8$</li> <li>now the asset drops in value to 101$, the stop loss will still be 91.8$ and would trigger at 91.8$.</li> </ul> <p>In summary: The stoploss will be adjusted to be always be -10% of the highest observed price.</p>"},{"location":"stoploss/#trailing-stop-loss-custom-positive-loss","title":"Trailing stop loss, custom positive loss","text":"<p>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.</p> <p>Note</p> <p>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.</p> <p>Both values require <code>trailing_stop</code> to be set to true and <code>trailing_stop_positive</code> with a value.</p> <pre><code> stoploss = -0.10\n trailing_stop = True\n trailing_stop_positive = 0.02\n</code></pre> <p>For example, simplified math:</p> <ul> <li>the bot buys an asset at a price of 100$</li> <li>the stop loss is defined at -10%</li> <li>the stop loss would get triggered once the asset drops below 90$</li> <li>assuming the asset now increases to 102$</li> <li>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%)</li> <li>now the asset drops in value to 101$, the stop loss will still be 99.96$ and would trigger at 99.96$</li> </ul> <p>The 0.02 would translate to a -2% stop loss. Before this, <code>stoploss</code> is used for the trailing stoploss.</p>"},{"location":"stoploss/#trailing-stop-loss-only-once-the-trade-has-reached-a-certain-offset","title":"Trailing stop loss only once the trade has reached a certain offset","text":"<p>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.</p> <p>If <code>\"trailing_only_offset_is_reached\": true</code> then the trailing stoploss is only activated once the offset is reached. Until then, the stoploss remains at the configured <code>stoploss</code>. This option can be used with or without <code>trailing_stop_positive</code>, but uses <code>trailing_stop_positive_offset</code> as offset.</p> <pre><code> trailing_stop_positive_offset = 0.011\n trailing_only_offset_is_reached = True\n</code></pre> <p>Configuration (offset is buy-price + 3%):</p> <pre><code> stoploss = -0.10\n trailing_stop = True\n trailing_stop_positive = 0.02\n trailing_stop_positive_offset = 0.03\n trailing_only_offset_is_reached = True\n</code></pre> <p>For example, simplified math:</p> <ul> <li>the bot buys an asset at a price of 100$</li> <li>the stop loss is defined at -10%</li> <li>the stop loss would get triggered once the asset drops below 90$</li> <li>stoploss will remain at 90$ unless asset increases to or above our configured offset</li> <li>assuming the asset now increases to 103$ (where we have the offset configured)</li> <li>the stop loss will now be -2% of 103$ = 100.94$</li> <li>now the asset drops in value to 101$, the stop loss will still be 100.94$ and would trigger at 100.94$</li> </ul> <p>Tip</p> <p>Make sure to have this value (<code>trailing_stop_positive_offset</code>) lower than minimal ROI, otherwise minimal ROI will apply first and sell the trade.</p>"},{"location":"stoploss/#changing-stoploss-on-open-trades","title":"Changing stoploss on open trades","text":"<p>A stoploss on an open trade can be changed by changing the value in the configuration or strategy and use the <code>/reload_config</code> command (alternatively, completely stopping and restarting the bot also works).</p> <p>The new stoploss value will be applied to open trades (and corresponding log-messages will be generated).</p>"},{"location":"stoploss/#limitations","title":"Limitations","text":"<p>Stoploss values cannot be changed if <code>trailing_stop</code> 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).</p>"},{"location":"strategy-advanced/","title":"Advanced Strategies","text":"<p>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.</p> <p>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.</p> <p>Note</p> <p>All callback methods described below should only be implemented in a strategy if they are actually used.</p> <p>Tip</p> <p>You can get a strategy template containing all below methods by running <code>freqtrade new-strategy --strategy MyAwesomeStrategy --template advanced</code></p>"},{"location":"strategy-advanced/#custom-stoploss","title":"Custom stoploss","text":"<p>A stoploss can only ever move upwards - so if you set it to an absolute profit of 2%, you can never move it below this price. Also, the traditional <code>stoploss</code> value serves as an absolute lower level and will be instated as the initial stoploss.</p> <p>The usage of the custom stoploss method must be enabled by setting <code>use_custom_stoploss=True</code> on the strategy object. The method must return a stoploss value (float / number) with a relative ratio below the current price. E.g. <code>current_profit = 0.05</code> (5% profit) - stoploss returns <code>0.02</code> - then you \"locked in\" a profit of 3% (<code>0.05 - 0.02 = 0.03</code>).</p> <p>To simulate a regular trailing stoploss of 4% (trailing 4% behind the maximum reached price) you would use the following very simple method:</p> <pre><code># additional imports required\nfrom datetime import datetime\nfrom freqtrade.persistence import Trade\n\nclass AwesomeStrategy(IStrategy):\n\n # ... populate_* methods\n\n use_custom_stoploss = True\n\n def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,\n current_rate: float, current_profit: float, **kwargs) -> float:\n \"\"\"\n Custom stoploss logic, returning the new distance relative to current_rate (as ratio).\n e.g. returning -0.05 would create a stoploss 5% below current_rate.\n The custom stoploss can never be below self.stoploss, which serves as a hard maximum loss.\n\n For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/\n\n When not implemented by a strategy, returns the initial stoploss value\n Only called when use_custom_stoploss is set to True.\n\n :param pair: Pair that's currently analyzed\n :param trade: trade object.\n :param current_time: datetime object, containing the current datetime\n :param current_rate: Rate, calculated based on pricing settings in ask_strategy.\n :param current_profit: Current profit (as ratio), calculated based on current_rate.\n :param **kwargs: Ensure to keep this here so updates to this won't break your strategy.\n :return float: New stoploss value, relative to the currentrate\n \"\"\"\n return -0.04\n</code></pre> <p>Stoploss on exchange works similar to <code>trailing_stop</code>, and the stoploss on exchange is updated as configured in <code>stoploss_on_exchange_interval</code> (More details about stoploss on exchange).</p> <p>Use of dates</p> <p>All time-based calculations should be done based on <code>current_time</code> - using <code>datetime.now()</code> or <code>datetime.utcnow()</code> is discouraged, as this will break backtesting support.</p> <p>Trailing stoploss</p> <p>It's recommended to disable <code>trailing_stop</code> 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.</p>"},{"location":"strategy-advanced/#custom-stoploss-examples","title":"Custom stoploss examples","text":"<p>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.</p>"},{"location":"strategy-advanced/#time-based-trailing-stop","title":"Time based trailing stop","text":"<p>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.</p> <pre><code>from datetime import datetime, timedelta\nfrom freqtrade.persistence import Trade\n\nclass AwesomeStrategy(IStrategy):\n\n # ... populate_* methods\n\n use_custom_stoploss = True\n\n def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,\n current_rate: float, current_profit: float, **kwargs) -> float:\n\n # Make sure you have the longest interval first - these conditions are evaluated from top to bottom.\n if current_time - timedelta(minutes=120) > trade.open_date:\n return -0.05\n elif current_time - timedelta(minutes=60) > trade.open_date:\n return -0.10\n return 1\n</code></pre>"},{"location":"strategy-advanced/#different-stoploss-per-pair","title":"Different stoploss per pair","text":"<p>Use a different stoploss depending on the pair. In this example, we'll trail the highest price with 10% trailing stoploss for <code>ETH/BTC</code> and <code>XRP/BTC</code>, with 5% trailing stoploss for <code>LTC/BTC</code> and with 15% for all other pairs.</p> <pre><code>from datetime import datetime\nfrom freqtrade.persistence import Trade\n\nclass AwesomeStrategy(IStrategy):\n\n # ... populate_* methods\n\n use_custom_stoploss = True\n\n def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,\n current_rate: float, current_profit: float, **kwargs) -> float:\n\n if pair in ('ETH/BTC', 'XRP/BTC'):\n return -0.10\n elif pair in ('LTC/BTC'):\n return -0.05\n return -0.15\n</code></pre>"},{"location":"strategy-advanced/#trailing-stoploss-with-positive-offset","title":"Trailing stoploss with positive offset","text":"<p>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%.</p> <p>Please note that the stoploss can only increase, values lower than the current stoploss are ignored.</p> <pre><code>from datetime import datetime, timedelta\nfrom freqtrade.persistence import Trade\n\nclass AwesomeStrategy(IStrategy):\n\n # ... populate_* methods\n\n use_custom_stoploss = True\n\n def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,\n current_rate: float, current_profit: float, **kwargs) -> float:\n\n if current_profit < 0.04:\n return -1 # return a value bigger than the inital stoploss to keep using the inital stoploss\n\n # After reaching the desired offset, allow the stoploss to trail by half the profit\n desired_stoploss = current_profit / 2 \n\n # Use a minimum of 2.5% and a maximum of 5%\n return max(min(desired_stoploss, 0.05), 0.025)\n</code></pre>"},{"location":"strategy-advanced/#absolute-stoploss","title":"Absolute stoploss","text":"<p>The below example sets absolute profit levels based on the current profit.</p> <ul> <li>Use the regular stoploss until 20% profit is reached</li> <li>Once profit is > 40%, stoploss will be at 25%, locking in at least 25% of the profit.</li> <li>Once profit is > 25% - stoploss will be 15%.</li> <li>Once profit is > 20% - stoploss will be set to 7%.</li> </ul> <pre><code>from datetime import datetime\nfrom freqtrade.persistence import Trade\n\nclass AwesomeStrategy(IStrategy):\n\n # ... populate_* methods\n\n use_custom_stoploss = True\n\n def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,\n current_rate: float, current_profit: float, **kwargs) -> float:\n\n # Calculate as `-desired_stop_from_open + current_profit` to get the distance between current_profit and initial price\n if current_profit > 0.40:\n return (-0.25 + current_profit)\n if current_profit > 0.25:\n return (-0.15 + current_profit)\n if current_profit > 0.20:\n return (-0.7 + current_profit)\n return 1\n</code></pre>"},{"location":"strategy-advanced/#custom-order-timeout-rules","title":"Custom order timeout rules","text":"<p>Simple, time-based order-timeouts can be configured either via strategy or in the configuration in the <code>unfilledtimeout</code> section.</p> <p>However, freqtrade also offers a custom callback for both order types, which allows you to decide based on custom criteria if a order did time out or not.</p> <p>Note</p> <p>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.</p>"},{"location":"strategy-advanced/#custom-order-timeout-example","title":"Custom order timeout example","text":"<p>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.</p> <p>The function must return either <code>True</code> (cancel order) or <code>False</code> (keep order alive).</p> <pre><code>from datetime import datetime, timedelta\nfrom freqtrade.persistence import Trade\n\nclass AwesomeStrategy(IStrategy):\n\n # ... populate_* methods\n\n # Set unfilledtimeout to 25 hours, since our maximum timeout from below is 24 hours.\n unfilledtimeout = {\n 'buy': 60 * 25,\n 'sell': 60 * 25\n }\n\n def check_buy_timeout(self, pair: str, trade: 'Trade', order: dict, **kwargs) -> bool:\n if trade.open_rate > 100 and trade.open_date < datetime.utcnow() - timedelta(minutes=5):\n return True\n elif trade.open_rate > 10 and trade.open_date < datetime.utcnow() - timedelta(minutes=3):\n return True\n elif trade.open_rate < 1 and trade.open_date < datetime.utcnow() - timedelta(hours=24):\n return True\n return False\n\n\n def check_sell_timeout(self, pair: str, trade: 'Trade', order: dict, **kwargs) -> bool:\n if trade.open_rate > 100 and trade.open_date < datetime.utcnow() - timedelta(minutes=5):\n return True\n elif trade.open_rate > 10 and trade.open_date < datetime.utcnow() - timedelta(minutes=3):\n return True\n elif trade.open_rate < 1 and trade.open_date < datetime.utcnow() - timedelta(hours=24):\n return True\n return False\n</code></pre> <p>Note</p> <p>For the above example, <code>unfilledtimeout</code> must be set to something bigger than 24h, otherwise that type of timeout will apply first.</p>"},{"location":"strategy-advanced/#custom-order-timeout-example-using-additional-data","title":"Custom order timeout example (using additional data)","text":"<pre><code>from datetime import datetime\nfrom freqtrade.persistence import Trade\n\nclass AwesomeStrategy(IStrategy):\n\n # ... populate_* methods\n\n # Set unfilledtimeout to 25 hours, since our maximum timeout from below is 24 hours.\n unfilledtimeout = {\n 'buy': 60 * 25,\n 'sell': 60 * 25\n }\n\n def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool:\n ob = self.dp.orderbook(pair, 1)\n current_price = ob['bids'][0][0]\n # Cancel buy order if price is more than 2% above the order.\n if current_price > order['price'] * 1.02:\n return True\n return False\n\n\n def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool:\n ob = self.dp.orderbook(pair, 1)\n current_price = ob['asks'][0][0]\n # Cancel sell order if price is more than 2% below the order.\n if current_price < order['price'] * 0.98:\n return True\n return False\n</code></pre>"},{"location":"strategy-advanced/#bot-loop-start-callback","title":"Bot loop start callback","text":"<p>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.</p> <pre><code>import requests\n\nclass AwesomeStrategy(IStrategy):\n\n # ... populate_* methods\n\n def bot_loop_start(self, **kwargs) -> None:\n \"\"\"\n Called at the start of the bot iteration (one loop).\n Might be used to perform pair-independent tasks\n (e.g. gather some remote resource for comparison)\n :param **kwargs: Ensure to keep this here so updates to this won't break your strategy.\n \"\"\"\n if self.config['runmode'].value in ('live', 'dry_run'):\n # Assign this to the class by using self.*\n # can then be used by populate_* methods\n self.remote_data = requests.get('https://some_remote_source.example.com')\n</code></pre>"},{"location":"strategy-advanced/#bot-order-confirmation","title":"Bot order confirmation","text":""},{"location":"strategy-advanced/#trade-entry-buy-order-confirmation","title":"Trade entry (buy order) confirmation","text":"<p><code>confirm_trade_entry()</code> can be used to abort a trade entry at the latest second (maybe because the price is not what we expect).</p> <pre><code>class AwesomeStrategy(IStrategy):\n\n # ... populate_* methods\n\n def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float,\n time_in_force: str, **kwargs) -> bool:\n \"\"\"\n Called right before placing a buy order.\n Timing for this function is critical, so avoid doing heavy computations or\n network requests in this method.\n\n For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/\n\n When not implemented by a strategy, returns True (always confirming).\n\n :param pair: Pair that's about to be bought.\n :param order_type: Order type (as configured in order_types). usually limit or market.\n :param amount: Amount in target (quote) currency that's going to be traded.\n :param rate: Rate that's going to be used when using limit orders\n :param time_in_force: Time in force. Defaults to GTC (Good-til-cancelled).\n :param **kwargs: Ensure to keep this here so updates to this won't break your strategy.\n :return bool: When True is returned, then the buy-order is placed on the exchange.\n False aborts the process\n \"\"\"\n return True\n</code></pre>"},{"location":"strategy-advanced/#trade-exit-sell-order-confirmation","title":"Trade exit (sell order) confirmation","text":"<p><code>confirm_trade_exit()</code> can be used to abort a trade exit (sell) at the latest second (maybe because the price is not what we expect).</p> <pre><code>from freqtrade.persistence import Trade\n\n\nclass AwesomeStrategy(IStrategy):\n\n # ... populate_* methods\n\n def confirm_trade_exit(self, pair: str, trade: Trade, order_type: str, amount: float,\n rate: float, time_in_force: str, sell_reason: str, **kwargs) -> bool:\n \"\"\"\n Called right before placing a regular sell order.\n Timing for this function is critical, so avoid doing heavy computations or\n network requests in this method.\n\n For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/\n\n When not implemented by a strategy, returns True (always confirming).\n\n :param pair: Pair that's about to be sold.\n :param order_type: Order type (as configured in order_types). usually limit or market.\n :param amount: Amount in quote currency.\n :param rate: Rate that's going to be used when using limit orders\n :param time_in_force: Time in force. Defaults to GTC (Good-til-cancelled).\n :param sell_reason: Sell reason.\n Can be any of ['roi', 'stop_loss', 'stoploss_on_exchange', 'trailing_stop_loss',\n 'sell_signal', 'force_sell', 'emergency_sell']\n :param **kwargs: Ensure to keep this here so updates to this won't break your strategy.\n :return bool: When True is returned, then the sell-order is placed on the exchange.\n False aborts the process\n \"\"\"\n if sell_reason == 'force_sell' and trade.calc_profit_ratio(rate) < 0:\n # Reject force-sells with negative profit\n # This is just a sample, please adjust to your needs\n # (this does not necessarily make sense, assuming you know when you're force-selling)\n return False\n return True\n</code></pre>"},{"location":"strategy-advanced/#derived-strategies","title":"Derived strategies","text":"<p>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:</p> <pre><code>class MyAwesomeStrategy(IStrategy):\n ...\n stoploss = 0.13\n trailing_stop = False\n # All other attributes and methods are here as they\n # should be in any custom strategy...\n ...\n\nclass MyAwesomeStrategy2(MyAwesomeStrategy):\n # Override something\n stoploss = 0.08\n trailing_stop = True\n</code></pre> <p>Both attributes and methods may be overridden, altering behavior of the original strategy in a way you need.</p> <p>Parent-strategy in different files</p> <p>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.</p> <pre><code>import sys\nfrom pathlib import Path\nsys.path.append(str(Path(__file__).parent))\n\nfrom myawesomestrategy import MyAwesomeStrategy\n</code></pre>"},{"location":"strategy-advanced/#embedding-strategies","title":"Embedding Strategies","text":"<p>Freqtrade provides you with 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.</p>"},{"location":"strategy-advanced/#encoding-a-string-as-base64","title":"Encoding a string as BASE64","text":"<p>This is a quick example, how to generate the BASE64 string in python</p> <pre><code>from base64 import urlsafe_b64encode\n\nwith open(file, 'r') as f:\n content = f.read()\ncontent = urlsafe_b64encode(content.encode('utf-8'))\n</code></pre> <p>The variable 'content', will contain the strategy file in a BASE64 encoded form. Which can now be set in your configurations file as following</p> <pre><code>\"strategy\": \"NameOfStrategy:BASE64String\"\n</code></pre> <p>Please ensure that 'NameOfStrategy' is identical to the strategy name!</p>"},{"location":"strategy-customization/","title":"Strategy Customization","text":"<p>This page explains how to customize your strategies, add new indicators and set up trading rules.</p> <p>Please familiarize yourself with Freqtrade basics first, which provides overall info on how the bot operates.</p>"},{"location":"strategy-customization/#install-a-custom-strategy-file","title":"Install a custom strategy file","text":"<p>This is very simple. Copy paste your strategy file into the directory <code>user_data/strategies</code>.</p> <p>Let assume you have a class called <code>AwesomeStrategy</code> in the file <code>AwesomeStrategy.py</code>:</p> <ol> <li>Move your file into <code>user_data/strategies</code> (you should have <code>user_data/strategies/AwesomeStrategy.py</code></li> <li>Start the bot with the param <code>--strategy AwesomeStrategy</code> (the parameter is the class name)</li> </ol> <pre><code>freqtrade trade --strategy AwesomeStrategy\n</code></pre>"},{"location":"strategy-customization/#develop-your-own-strategy","title":"Develop your own strategy","text":"<p>The bot includes a default strategy file. Also, several other strategies are available in the strategy repository.</p> <p>You will however most likely have your own idea for a strategy. This document intends to help you develop one for yourself.</p> <p>To get started, use <code>freqtrade new-strategy --strategy AwesomeStrategy</code>. This will create a new strategy file from a template, which will be located under <code>user_data/strategies/AwesomeStrategy.py</code>.</p> <p>Note</p> <p>This is just a template file, which will most likely not be profitable out of the box.</p>"},{"location":"strategy-customization/#anatomy-of-a-strategy","title":"Anatomy of a strategy","text":"<p>A strategy file contains all the information needed to build a good strategy:</p> <ul> <li>Indicators</li> <li>Buy strategy rules</li> <li>Sell strategy rules</li> <li>Minimal ROI recommended</li> <li>Stoploss strongly recommended</li> </ul> <p>The bot also include a sample strategy called <code>SampleStrategy</code> you can update: <code>user_data/strategies/sample_strategy.py</code>. You can test it with the parameter: <code>--strategy SampleStrategy</code></p> <p>Additionally, there is an attribute called <code>INTERFACE_VERSION</code>, 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.</p> <p>Future versions will require this to be set.</p> <pre><code>freqtrade trade --strategy AwesomeStrategy\n</code></pre> <p>For the following section we will use the user_data/strategies/sample_strategy.py file as reference.</p> <p>Strategies and Backtesting</p> <p>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 <code>populate_*()</code> methods at once. It is therefore best to use vectorized operations (across the whole dataframe, not loops) and avoid index referencing (<code>df.iloc[-1]</code>), but instead use <code>df.shift()</code> to get to the previous candle.</p> <p>Warning: Using future data</p> <p>Since backtesting passes the full time range to the <code>populate_*()</code> 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.</p>"},{"location":"strategy-customization/#customize-indicators","title":"Customize Indicators","text":"<p>Buy and sell strategies need indicators. You can add more indicators by extending the list contained in the method <code>populate_indicators()</code> from your strategy file.</p> <p>You should only add the indicators used in either <code>populate_buy_trend()</code>, <code>populate_sell_trend()</code>, or to populate another indicator, otherwise performance may suffer.</p> <p>It's important to always return the dataframe without removing/modifying the columns <code>\"open\", \"high\", \"low\", \"close\", \"volume\"</code>, otherwise these fields would contain something unexpected.</p> <p>Sample:</p> <pre><code>def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n \"\"\"\n Adds several different TA indicators to the given DataFrame\n\n Performance Note: For the best performance be frugal on the number of indicators\n you are using. Let uncomment only the indicator you are using in your strategies\n or your hyperopt configuration, otherwise you will waste your memory and CPU usage.\n :param dataframe: Dataframe with data from the exchange\n :param metadata: Additional information, like the currently traded pair\n :return: a Dataframe with all mandatory indicators for the strategies\n \"\"\"\n dataframe['sar'] = ta.SAR(dataframe)\n dataframe['adx'] = ta.ADX(dataframe)\n stoch = ta.STOCHF(dataframe)\n dataframe['fastd'] = stoch['fastd']\n dataframe['fastk'] = stoch['fastk']\n dataframe['blower'] = ta.BBANDS(dataframe, nbdevup=2, nbdevdn=2)['lowerband']\n dataframe['sma'] = ta.SMA(dataframe, timeperiod=40)\n dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9)\n dataframe['mfi'] = ta.MFI(dataframe)\n dataframe['rsi'] = ta.RSI(dataframe)\n dataframe['ema5'] = ta.EMA(dataframe, timeperiod=5)\n dataframe['ema10'] = ta.EMA(dataframe, timeperiod=10)\n dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50)\n dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100)\n dataframe['ao'] = awesome_oscillator(dataframe)\n macd = ta.MACD(dataframe)\n dataframe['macd'] = macd['macd']\n dataframe['macdsignal'] = macd['macdsignal']\n dataframe['macdhist'] = macd['macdhist']\n hilbert = ta.HT_SINE(dataframe)\n dataframe['htsine'] = hilbert['sine']\n dataframe['htleadsine'] = hilbert['leadsine']\n dataframe['plus_dm'] = ta.PLUS_DM(dataframe)\n dataframe['plus_di'] = ta.PLUS_DI(dataframe)\n dataframe['minus_dm'] = ta.MINUS_DM(dataframe)\n dataframe['minus_di'] = ta.MINUS_DI(dataframe)\n return dataframe\n</code></pre> <p>Want more indicator examples?</p> <p>Look into the user_data/strategies/sample_strategy.py. Then uncomment indicators you need.</p>"},{"location":"strategy-customization/#strategy-startup-period","title":"Strategy startup period","text":"<p>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 <code>startup_candle_count</code> attribute. This should be set to the maximum number of candles that the strategy requires to calculate stable indicators.</p> <p>In this example strategy, this should be set to 100 (<code>startup_candle_count = 100</code>), since the longest needed history is 100 candles.</p> <pre><code> dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100)\n</code></pre> <p>By letting the bot know how much history is needed, backtest trades can start at the specified timerange during backtesting and hyperopt.</p> <p>Warning</p> <p><code>startup_candle_count</code> should be below <code>ohlcv_candle_limit</code> (which is 500 for most exchanges) - since only this amount of candles will be available during Dry-Run/Live Trade operations.</p>"},{"location":"strategy-customization/#example","title":"Example","text":"<p>Let's try to backtest 1 month (January 2019) of 5m candles using an example strategy with EMA100, as above.</p> <pre><code>freqtrade backtesting --timerange 20190101-20190201 --timeframe 5m\n</code></pre> <p>Assuming <code>startup_candle_count</code> is set to 100, backtesting knows it needs 100 candles to generate valid buy signals. It will load data from <code>20190101 - (100 * 5m)</code> - 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.</p> <p>Note</p> <p>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.</p>"},{"location":"strategy-customization/#buy-signal-rules","title":"Buy signal rules","text":"<p>Edit the method <code>populate_buy_trend()</code> in your strategy file to update your buy strategy.</p> <p>It's important to always return the dataframe without removing/modifying the columns <code>\"open\", \"high\", \"low\", \"close\", \"volume\"</code>, otherwise these fields would contain something unexpected.</p> <p>This will method will also define a new column, <code>\"buy\"</code>, which needs to contain 1 for buys, and 0 for \"no action\".</p> <p>Sample from <code>user_data/strategies/sample_strategy.py</code>:</p> <pre><code>def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n \"\"\"\n Based on TA indicators, populates the buy signal for the given dataframe\n :param dataframe: DataFrame populated with indicators\n :param metadata: Additional information, like the currently traded pair\n :return: DataFrame with buy column\n \"\"\"\n dataframe.loc[\n (\n (qtpylib.crossed_above(dataframe['rsi'], 30)) & # Signal: RSI crosses above 30\n (dataframe['tema'] <= dataframe['bb_middleband']) & # Guard\n (dataframe['tema'] > dataframe['tema'].shift(1)) & # Guard\n (dataframe['volume'] > 0) # Make sure Volume is not 0\n ),\n 'buy'] = 1\n\n return dataframe\n</code></pre> <p>Note</p> <p>Buying requires sellers to buy from - therefore volume needs to be > 0 (<code>dataframe['volume'] > 0</code>) to make sure that the bot does not buy/sell in no-activity periods.</p>"},{"location":"strategy-customization/#sell-signal-rules","title":"Sell signal rules","text":"<p>Edit the method <code>populate_sell_trend()</code> into your strategy file to update your sell strategy. Please note that the sell-signal is only used if <code>use_sell_signal</code> is set to true in the configuration.</p> <p>It's important to always return the dataframe without removing/modifying the columns <code>\"open\", \"high\", \"low\", \"close\", \"volume\"</code>, otherwise these fields would contain something unexpected.</p> <p>This will method will also define a new column, <code>\"sell\"</code>, which needs to contain 1 for sells, and 0 for \"no action\".</p> <p>Sample from <code>user_data/strategies/sample_strategy.py</code>:</p> <pre><code>def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n \"\"\"\n Based on TA indicators, populates the sell signal for the given dataframe\n :param dataframe: DataFrame populated with indicators\n :param metadata: Additional information, like the currently traded pair\n :return: DataFrame with buy column\n \"\"\"\n dataframe.loc[\n (\n (qtpylib.crossed_above(dataframe['rsi'], 70)) & # Signal: RSI crosses above 70\n (dataframe['tema'] > dataframe['bb_middleband']) & # Guard\n (dataframe['tema'] < dataframe['tema'].shift(1)) & # Guard\n (dataframe['volume'] > 0) # Make sure Volume is not 0\n ),\n 'sell'] = 1\n return dataframe\n</code></pre>"},{"location":"strategy-customization/#minimal-roi","title":"Minimal ROI","text":"<p>This dict defines the minimal Return On Investment (ROI) a trade should reach before selling, independent from the sell signal.</p> <p>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.</p> <pre><code>minimal_roi = {\n \"40\": 0.0,\n \"30\": 0.01,\n \"20\": 0.02,\n \"0\": 0.04\n}\n</code></pre> <p>The above configuration would therefore mean:</p> <ul> <li>Sell whenever 4% profit was reached</li> <li>Sell when 2% profit was reached (in effect after 20 minutes)</li> <li>Sell when 1% profit was reached (in effect after 30 minutes)</li> <li>Sell when trade is non-loosing (in effect after 40 minutes)</li> </ul> <p>The calculation does include fees.</p> <p>To disable ROI completely, set it to an insanely high number:</p> <pre><code>minimal_roi = {\n \"0\": 100\n}\n</code></pre> <p>While technically not completely disabled, this would sell once the trade reaches 10000% Profit.</p> <p>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 ...)</p> <pre><code>from freqtrade.exchange import timeframe_to_minutes\n\nclass AwesomeStrategy(IStrategy):\n\n timeframe = \"1d\"\n timeframe_mins = timeframe_to_minutes(timeframe)\n minimal_roi = {\n \"0\": 0.05, # 5% for the first 3 candles\n str(timeframe_mins * 3)): 0.02, # 2% after 3 candles\n str(timeframe_mins * 6)): 0.01, # 1% After 6 candles\n }\n</code></pre>"},{"location":"strategy-customization/#stoploss","title":"Stoploss","text":"<p>Setting a stoploss is highly recommended to protect your capital from strong moves against you.</p> <p>Sample:</p> <pre><code>stoploss = -0.10\n</code></pre> <p>This would signify a stoploss of -10%.</p> <p>For the full documentation on stoploss features, look at the dedicated stoploss page.</p> <p>If your exchange supports it, it's recommended to also set <code>\"stoploss_on_exchange\"</code> 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.</p> <p>For more information on order_types please look here.</p>"},{"location":"strategy-customization/#timeframe-formerly-ticker-interval","title":"Timeframe (formerly ticker interval)","text":"<p>This is the set of candles the bot should download and use for the analysis. Common values are <code>\"1m\"</code>, <code>\"5m\"</code>, <code>\"15m\"</code>, <code>\"1h\"</code>, however all values supported by your exchange should work.</p> <p>Please note that the same buy/sell signals may work well with one timeframe, but not with the others.</p> <p>This setting is accessible within the strategy methods as the <code>self.timeframe</code> attribute.</p>"},{"location":"strategy-customization/#metadata-dict","title":"Metadata dict","text":"<p>The metadata-dict (available for <code>populate_buy_trend</code>, <code>populate_sell_trend</code>, <code>populate_indicators</code>) contains additional information. Currently this is <code>pair</code>, which can be accessed using <code>metadata['pair']</code> - and will return a pair in the format <code>XRP/BTC</code>.</p> <p>The Metadata-dict should not be modified and does not persist information across multiple calls. Instead, have a look at the section Storing information</p>"},{"location":"strategy-customization/#storing-information","title":"Storing information","text":"<p>Storing information can be accomplished by creating a new dictionary within the strategy class.</p> <p>The name of the variable can be chosen at will, but should be prefixed with <code>cust_</code> to avoid naming collisions with predefined strategy variables.</p> <pre><code>class AwesomeStrategy(IStrategy):\n # Create custom dictionary\n cust_info = {}\n\n def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n # Check if the entry already exists\n if not metadata[\"pair\"] in self.cust_info:\n # Create empty entry for this pair\n self.cust_info[metadata[\"pair\"]] = {}\n\n if \"crosstime\" in self.cust_info[metadata[\"pair\"]]:\n self.cust_info[metadata[\"pair\"]][\"crosstime\"] += 1\n else:\n self.cust_info[metadata[\"pair\"]][\"crosstime\"] = 1\n</code></pre> <p>Warning</p> <p>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.</p> <p>Note</p> <p>If the data is pair-specific, make sure to use pair as one of the keys in the dictionary.</p>"},{"location":"strategy-customization/#additional-data-informative_pairs","title":"Additional data (informative_pairs)","text":""},{"location":"strategy-customization/#get-data-for-non-tradeable-pairs","title":"Get data for non-tradeable pairs","text":"<p>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 <code>DataProvider</code> 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.</p> <p>The pairs need to be specified as tuples in the format <code>(\"pair\", \"timeframe\")</code>, with pair as the first and timeframe as the second argument.</p> <p>Sample:</p> <pre><code>def informative_pairs(self):\n return [(\"ETH/USDT\", \"5m\"),\n (\"BTC/TUSD\", \"15m\"),\n ]\n</code></pre> <p>A full sample can be found in the DataProvider section.</p> <p>Warning</p> <p>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.</p>"},{"location":"strategy-customization/#additional-data-dataprovider","title":"Additional data (DataProvider)","text":"<p>The strategy provides access to the <code>DataProvider</code>. This allows you to get additional data to use in your strategy.</p> <p>All methods return <code>None</code> in case of failure (do not raise an exception).</p> <p>Please always check the mode of operation to select the correct method to get data (samples see below).</p> <p>Hyperopt</p> <p>Dataprovider is available during hyperopt, however it can only be used in <code>populate_indicators()</code> within a strategy. It is not available in <code>populate_buy()</code> and <code>populate_sell()</code> methods, nor in <code>populate_indicators()</code>, if this method located in the hyperopt file.</p>"},{"location":"strategy-customization/#possible-options-for-dataprovider","title":"Possible options for DataProvider","text":"<ul> <li><code>available_pairs</code> - Property with tuples listing cached pairs with their timeframe (pair, timeframe).</li> <li><code>current_whitelist()</code> - Returns a current list of whitelisted pairs. Useful for accessing dynamic whitelists (i.e. VolumePairlist)</li> <li><code>get_pair_dataframe(pair, timeframe)</code> - This is a universal method, which returns either historical data (for backtesting) or cached live data (for the Dry-Run and Live-Run modes).</li> <li><code>get_analyzed_dataframe(pair, timeframe)</code> - Returns the analyzed dataframe (after calling <code>populate_indicators()</code>, <code>populate_buy()</code>, <code>populate_sell()</code>) and the time of the latest analysis.</li> <li><code>historic_ohlcv(pair, timeframe)</code> - Returns historical data stored on disk.</li> <li><code>market(pair)</code> - Returns market data for the pair: fees, limits, precisions, activity flag, etc. See ccxt documentation for more details on the Market data structure.</li> <li><code>ohlcv(pair, timeframe)</code> - Currently cached candle (OHLCV) data for the pair, returns DataFrame or empty DataFrame.</li> <li><code>orderbook(pair, maximum)</code> - Returns latest orderbook data for the pair, a dict with bids/asks with a total of <code>maximum</code> entries.</li> <li><code>ticker(pair)</code> - Returns current ticker data for the pair. See ccxt documentation for more details on the Ticker data structure.</li> <li><code>runmode</code> - Property containing the current runmode.</li> </ul>"},{"location":"strategy-customization/#example-usages","title":"Example Usages","text":""},{"location":"strategy-customization/#available_pairs","title":"available_pairs","text":"<pre><code>if self.dp:\n for pair, timeframe in self.dp.available_pairs:\n print(f\"available {pair}, {timeframe}\")\n</code></pre>"},{"location":"strategy-customization/#current_whitelist","title":"current_whitelist()","text":"<p>Imagine you've developed a strategy that trades the <code>5m</code> timeframe using signals generated from a <code>1d</code> timeframe on the top 10 volume pairs by volume. </p> <p>The strategy might look something like this:</p> <p>Scan through the top 10 pairs by volume using the <code>VolumePairList</code> every 5 minutes and use a 14 day RSI to buy and sell.</p> <p>Due to the limited available data, it's very difficult to resample our <code>5m</code> 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!</p> <p>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.</p> <p>This is where calling <code>self.dp.current_whitelist()</code> comes in handy.</p> <pre><code> def informative_pairs(self):\n\n # get access to all pairs available in whitelist.\n pairs = self.dp.current_whitelist()\n # Assign tf to each pair so they can be downloaded and cached for strategy.\n informative_pairs = [(pair, '1d') for pair in pairs]\n return informative_pairs \n</code></pre>"},{"location":"strategy-customization/#get_pair_dataframepair-timeframe","title":"get_pair_dataframe(pair, timeframe)","text":"<pre><code># fetch live / historical candle (OHLCV) data for the first informative pair\nif self.dp:\n inf_pair, inf_timeframe = self.informative_pairs()[0]\n informative = self.dp.get_pair_dataframe(pair=inf_pair,\n timeframe=inf_timeframe)\n</code></pre> <p>Warning about backtesting</p> <p>Be careful when using dataprovider in backtesting. <code>historic_ohlcv()</code> (and <code>get_pair_dataframe()</code> 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.</p>"},{"location":"strategy-customization/#get_analyzed_dataframepair-timeframe","title":"get_analyzed_dataframe(pair, timeframe)","text":"<p>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).</p> <pre><code># fetch current dataframe\nif self.dp:\n if self.dp.runmode.value in ('live', 'dry_run'):\n dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=metadata['pair'],\n timeframe=self.timeframe)\n</code></pre> <p>No data available</p> <p>Returns an empty dataframe if the requested pair was not cached. This should not happen when using whitelisted pairs.</p> <p>Warning about backtesting</p> <p>This method will return an empty dataframe during backtesting.</p>"},{"location":"strategy-customization/#orderbookpair-maximum","title":"orderbook(pair, maximum)","text":"<pre><code>if self.dp:\n if self.dp.runmode.value in ('live', 'dry_run'):\n ob = self.dp.orderbook(metadata['pair'], 1)\n dataframe['best_bid'] = ob['bids'][0][0]\n dataframe['best_ask'] = ob['asks'][0][0]\n</code></pre> <p>Warning about backtesting</p> <p>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.</p>"},{"location":"strategy-customization/#tickerpair","title":"ticker(pair)","text":"<pre><code>if self.dp:\n if self.dp.runmode.value in ('live', 'dry_run'):\n ticker = self.dp.ticker(metadata['pair'])\n dataframe['last_price'] = ticker['last']\n dataframe['volume24h'] = ticker['quoteVolume']\n dataframe['vwap'] = ticker['vwap']\n</code></pre> <p>Warning</p> <p>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 <code>vwap</code> values, the FTX exchange does not always fills in the <code>last</code> 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.</p> <p>Warning about backtesting</p> <p>This method will always return up-to-date values - so usage during backtesting / hyperopt will lead to wrong results.</p>"},{"location":"strategy-customization/#complete-data-provider-sample","title":"Complete Data-provider sample","text":"<pre><code>from freqtrade.strategy import IStrategy, merge_informative_pair\nfrom pandas import DataFrame\n\nclass SampleStrategy(IStrategy):\n # strategy init stuff...\n\n timeframe = '5m'\n\n # more strategy init stuff..\n\n def informative_pairs(self):\n\n # get access to all pairs available in whitelist.\n pairs = self.dp.current_whitelist()\n # Assign tf to each pair so they can be downloaded and cached for strategy.\n informative_pairs = [(pair, '1d') for pair in pairs]\n # Optionally Add additional \"static\" pairs\n informative_pairs += [(\"ETH/USDT\", \"5m\"),\n (\"BTC/TUSD\", \"15m\"),\n ]\n return informative_pairs\n\n def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n if not self.dp:\n # Don't do anything if DataProvider is not available.\n return dataframe\n\n inf_tf = '1d'\n # Get the informative pair\n informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=inf_tf)\n # Get the 14 day rsi\n informative['rsi'] = ta.RSI(informative, timeperiod=14)\n\n # Use the helper function merge_informative_pair to safely merge the pair\n # Automatically renames the columns and merges a shorter timeframe dataframe and a longer timeframe informative pair\n # use ffill to have the 1d value available in every row throughout the day.\n # Without this, comparisons between columns of the original and the informative pair would only work once per day.\n # Full documentation of this method, see below\n dataframe = merge_informative_pair(dataframe, informative, self.timeframe, inf_tf, ffill=True)\n\n # Calculate rsi of the original dataframe (5m timeframe)\n dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)\n\n # Do other stuff\n # ...\n\n return dataframe\n\n def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n\n dataframe.loc[\n (\n (qtpylib.crossed_above(dataframe['rsi'], 30)) & # Signal: RSI crosses above 30\n (dataframe['rsi_1d'] < 30) & # Ensure daily RSI is < 30\n (dataframe['volume'] > 0) # Ensure this candle had volume (important for backtesting)\n ),\n 'buy'] = 1\n</code></pre>"},{"location":"strategy-customization/#helper-functions","title":"Helper functions","text":""},{"location":"strategy-customization/#merge_informative_pair","title":"merge_informative_pair()","text":"<p>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.</p> <p>Options:</p> <ul> <li>Rename the columns for you to create unique columns</li> <li>Merge the dataframe without lookahead bias</li> <li>Forward-fill (optional)</li> </ul> <p>All columns of the informative dataframe will be available on the returning dataframe in a renamed fashion:</p> <p>Column renaming</p> <p>Assuming <code>inf_tf = '1d'</code> the resulting columns will be:</p> <pre><code>'date', 'open', 'high', 'low', 'close', 'rsi' # from the original dataframe\n'date_1d', 'open_1d', 'high_1d', 'low_1d', 'close_1d', 'rsi_1d' # from the informative dataframe\n</code></pre> Column renaming - 1h <p>Assuming <code>inf_tf = '1h'</code> the resulting columns will be:</p> <pre><code>'date', 'open', 'high', 'low', 'close', 'rsi' # from the original dataframe\n'date_1h', 'open_1h', 'high_1h', 'low_1h', 'close_1h', 'rsi_1h' # from the informative dataframe \n</code></pre> Custom implementation <p>A custom implementation for this is possible, and can be done as follows:</p> <pre><code># Shift date by 1 candle\n# This is necessary since the data is always the \"open date\"\n# and a 15m candle starting at 12:15 should not know the close of the 1h candle from 12:00 to 13:00\nminutes = timeframe_to_minutes(inf_tf)\n# Only do this if the timeframes are different:\ninformative['date_merge'] = informative[\"date\"] + pd.to_timedelta(minutes, 'm')\n\n# Rename columns to be unique\ninformative.columns = [f\"{col}_{inf_tf}\" for col in informative.columns]\n# Assuming inf_tf = '1d' - then the columns will now be:\n# date_1d, open_1d, high_1d, low_1d, close_1d, rsi_1d\n\n# Combine the 2 dataframes\n# all indicators on the informative sample MUST be calculated before this point\ndataframe = pd.merge(dataframe, informative, left_on='date', right_on=f'date_merge_{inf_tf}', how='left')\n# FFill to have the 1d value available in every row throughout the day.\n# Without this, comparisons would only work once per day.\ndataframe = dataframe.ffill()\n</code></pre> <p>Informative timeframe < timeframe</p> <p>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).</p>"},{"location":"strategy-customization/#additional-data-wallets","title":"Additional data (Wallets)","text":"<p>The strategy provides access to the <code>Wallets</code> object. This contains the current balances on the exchange.</p> <p>Note</p> <p>Wallets is not available during backtesting / hyperopt.</p> <p>Please always check if <code>Wallets</code> is available to avoid failures during backtesting.</p> <pre><code>if self.wallets:\n free_eth = self.wallets.get_free('ETH')\n used_eth = self.wallets.get_used('ETH')\n total_eth = self.wallets.get_total('ETH')\n</code></pre>"},{"location":"strategy-customization/#possible-options-for-wallets","title":"Possible options for Wallets","text":"<ul> <li><code>get_free(asset)</code> - currently available balance to trade</li> <li><code>get_used(asset)</code> - currently tied up balance (open orders)</li> <li><code>get_total(asset)</code> - total available balance - sum of the 2 above</li> </ul>"},{"location":"strategy-customization/#additional-data-trades","title":"Additional data (Trades)","text":"<p>A history of Trades can be retrieved in the strategy by querying the database.</p> <p>At the top of the file, import Trade.</p> <pre><code>from freqtrade.persistence import Trade\n</code></pre> <p>The following example queries for the current pair and trades from today, however other filters can easily be added.</p> <pre><code>if self.config['runmode'].value in ('live', 'dry_run'):\n trades = Trade.get_trades([Trade.pair == metadata['pair'],\n Trade.open_date > datetime.utcnow() - timedelta(days=1),\n Trade.is_open.is_(False),\n ]).order_by(Trade.close_date).all()\n # Summarize profit for this pair.\n curdayprofit = sum(trade.close_profit for trade in trades)\n</code></pre> <p>Get amount of stake_currency currently invested in Trades:</p> <pre><code>if self.config['runmode'].value in ('live', 'dry_run'):\n total_stakes = Trade.total_open_trades_stakes()\n</code></pre> <p>Retrieve performance per pair. Returns a List of dicts per pair.</p> <pre><code>if self.config['runmode'].value in ('live', 'dry_run'):\n performance = Trade.get_overall_performance()\n</code></pre> <p>Sample return value: ETH/BTC had 5 trades, with a total profit of 1.5% (ratio of 0.015).</p> <pre><code>{'pair': \"ETH/BTC\", 'profit': 0.015, 'count': 5}\n</code></pre> <p>Warning</p> <p>Trade history is not available during backtesting or hyperopt.</p>"},{"location":"strategy-customization/#prevent-trades-from-happening-for-a-specific-pair","title":"Prevent trades from happening for a specific pair","text":"<p>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.</p> <p>Locked pairs will show the message <code>Pair <pair> is currently locked.</code>.</p>"},{"location":"strategy-customization/#locking-pairs-from-within-the-strategy","title":"Locking pairs from within the strategy","text":"<p>Sometimes it may be desired to lock a pair after certain events happen (e.g. multiple losing trades in a row).</p> <p>Freqtrade has an easy method to do this from within the strategy, by calling <code>self.lock_pair(pair, until, [reason])</code>. <code>until</code> must be a datetime object in the future, after which trading will be re-enabled for that pair, while <code>reason</code> is an optional string detailing why the pair was locked.</p> <p>Locks can also be lifted manually, by calling <code>self.unlock_pair(pair)</code>.</p> <p>To verify if a pair is currently locked, use <code>self.is_pair_locked(pair)</code>.</p> <p>Note</p> <p>Locked pairs will always be rounded up to the next candle. So assuming a <code>5m</code> timeframe, a lock with <code>until</code> set to 10:18 will lock the pair until the candle from 10:15-10:20 will be finished.</p> <p>Warning</p> <p>Locking pairs is not available during backtesting.</p>"},{"location":"strategy-customization/#pair-locking-example","title":"Pair locking example","text":"<pre><code>from freqtrade.persistence import Trade\nfrom datetime import timedelta, datetime, timezone\n# Put the above lines a the top of the strategy file, next to all the other imports\n# --------\n\n# Within populate indicators (or populate_buy):\nif self.config['runmode'].value in ('live', 'dry_run'):\n # fetch closed trades for the last 2 days\n trades = Trade.get_trades([Trade.pair == metadata['pair'],\n Trade.open_date > datetime.utcnow() - timedelta(days=2),\n Trade.is_open.is_(False),\n ]).all()\n # Analyze the conditions you'd like to lock the pair .... will probably be different for every strategy\n sumprofit = sum(trade.close_profit for trade in trades)\n if sumprofit < 0:\n # Lock pair for 12 hours\n self.lock_pair(metadata['pair'], until=datetime.now(timezone.utc) + timedelta(hours=12))\n</code></pre>"},{"location":"strategy-customization/#print-created-dataframe","title":"Print created dataframe","text":"<p>To inspect the created dataframe, you can issue a print-statement in either <code>populate_buy_trend()</code> or <code>populate_sell_trend()</code>. You may also want to print the pair so it's clear what data is currently shown.</p> <pre><code>def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n dataframe.loc[\n (\n #>> whatever condition<<<\n ),\n 'buy'] = 1\n\n # Print the Analyzed pair\n print(f\"result for {metadata['pair']}\")\n\n # Inspect the last 5 rows\n print(dataframe.tail())\n\n return dataframe\n</code></pre> <p>Printing more than a few rows is also possible (simply use <code>print(dataframe)</code> instead of <code>print(dataframe.tail())</code>), however not recommended, as that will be very verbose (~500 lines per pair every 5 seconds).</p>"},{"location":"strategy-customization/#common-mistakes-when-developing-strategies","title":"Common mistakes when developing strategies","text":"<p>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.</p> <p>The following lists some common patterns which should be avoided to prevent frustration:</p> <ul> <li>don't use <code>shift(-1)</code>. This uses data from the future, which is not available.</li> <li>don't use <code>.iloc[-1]</code> or any other absolute position in the dataframe, this will be different between dry-run and backtesting.</li> <li>don't use <code>dataframe['volume'].mean()</code>. This uses the full DataFrame for backtesting, including data from the future. Use <code>dataframe['volume'].rolling(<window>).mean()</code> instead</li> <li>don't use <code>.resample('1h')</code>. This uses the left border of the interval, so moves data from an hour to the start of the hour. Use <code>.resample('1h', label='right')</code> instead.</li> </ul>"},{"location":"strategy-customization/#further-strategy-ideas","title":"Further strategy ideas","text":"<p>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.</p>"},{"location":"strategy-customization/#next-step","title":"Next step","text":"<p>Now you have a perfect strategy you probably want to backtest it. Your next step is to learn How to use the Backtesting.</p>"},{"location":"strategy_analysis_example/","title":"Strategy analysis example","text":"<p>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.</p>"},{"location":"strategy_analysis_example/#setup","title":"Setup","text":"<pre><code>from pathlib import Path\nfrom freqtrade.configuration import Configuration\n\n# Customize these according to your needs.\n\n# Initialize empty configuration object\nconfig = Configuration.from_files([])\n# Optionally, use existing configuration file\n# config = Configuration.from_files([\"config.json\"])\n\n# Define some constants\nconfig[\"timeframe\"] = \"5m\"\n# Name of the strategy class\nconfig[\"strategy\"] = \"SampleStrategy\"\n# Location of the data\ndata_location = Path(config['user_data_dir'], 'data', 'binance')\n# Pair to analyze - Only use one pair here\npair = \"BTC/USDT\"\n</code></pre> <pre><code># Load data using values set above\nfrom freqtrade.data.history import load_pair_history\n\ncandles = load_pair_history(datadir=data_location,\n timeframe=config[\"timeframe\"],\n pair=pair,\n data_format = \"hdf5\",\n )\n\n# Confirm success\nprint(\"Loaded \" + str(len(candles)) + f\" rows of data for {pair} from {data_location}\")\ncandles.head()\n</code></pre>"},{"location":"strategy_analysis_example/#load-and-run-strategy","title":"Load and run strategy","text":"<ul> <li>Rerun each time the strategy file is changed</li> </ul> <pre><code># Load strategy using values set above\nfrom freqtrade.resolvers import StrategyResolver\nstrategy = StrategyResolver.load_strategy(config)\n\n# Generate buy/sell signals using strategy\ndf = strategy.analyze_ticker(candles, {'pair': pair})\ndf.tail()\n</code></pre>"},{"location":"strategy_analysis_example/#display-the-trade-details","title":"Display the trade details","text":"<ul> <li>Note that using <code>data.head()</code> would also work, however most indicators have some \"startup\" data at the top of the dataframe.</li> <li>Some possible problems * Columns with NaN values at the end of the dataframe * Columns used in <code>crossed*()</code> functions with completely different units</li> <li>Comparison with full backtest * having 200 buy signals as output for one pair from <code>analyze_ticker()</code> does not necessarily mean that 200 trades will be made during backtesting. * Assuming you use only one condition such as, <code>df['rsi'] < 30</code> 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. </li> </ul> <pre><code># Report results\nprint(f\"Generated {df['buy'].sum()} buy signals\")\ndata = df.set_index('date', drop=False)\ndata.tail()\n</code></pre>"},{"location":"strategy_analysis_example/#load-existing-objects-into-a-jupyter-notebook","title":"Load existing objects into a Jupyter notebook","text":"<p>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.</p>"},{"location":"strategy_analysis_example/#load-backtest-results-to-pandas-dataframe","title":"Load backtest results to pandas dataframe","text":"<p>Analyze a trades dataframe (also used below for plotting)</p> <pre><code>from freqtrade.data.btanalysis import load_backtest_data, load_backtest_stats\n\n# if backtest_dir points to a directory, it'll automatically load the last backtest file.\nbacktest_dir = config[\"user_data_dir\"] / \"backtest_results\"\n# backtest_dir can also point to a specific file \n# backtest_dir = config[\"user_data_dir\"] / \"backtest_results/backtest-result-2020-07-01_20-04-22.json\"\n</code></pre> <pre><code># You can get the full backtest statistics by using the following command.\n# This contains all information used to generate the backtest result.\nstats = load_backtest_stats(backtest_dir)\n\nstrategy = 'SampleStrategy'\n# All statistics are available per strategy, so if `--strategy-list` was used during backtest, this will be reflected here as well.\n# Example usages:\nprint(stats['strategy'][strategy]['results_per_pair'])\n# Get pairlist used for this backtest\nprint(stats['strategy'][strategy]['pairlist'])\n# Get market change (average change of all pairs from start to end of the backtest period)\nprint(stats['strategy'][strategy]['market_change'])\n# Maximum drawdown ()\nprint(stats['strategy'][strategy]['max_drawdown'])\n# Maximum drawdown start and end\nprint(stats['strategy'][strategy]['drawdown_start'])\nprint(stats['strategy'][strategy]['drawdown_end'])\n\n\n# Get strategy comparison (only relevant if multiple strategies were compared)\nprint(stats['strategy_comparison'])\n</code></pre> <pre><code># Load backtested trades as dataframe\ntrades = load_backtest_data(backtest_dir)\n\n# Show value-counts per pair\ntrades.groupby(\"pair\")[\"sell_reason\"].value_counts()\n</code></pre>"},{"location":"strategy_analysis_example/#load-live-trading-results-into-a-pandas-dataframe","title":"Load live trading results into a pandas dataframe","text":"<p>In case you did already some trading and want to analyze your performance</p> <pre><code>from freqtrade.data.btanalysis import load_trades_from_db\n\n# Fetch trades from database\ntrades = load_trades_from_db(\"sqlite:///tradesv3.sqlite\")\n\n# Display results\ntrades.groupby(\"pair\")[\"sell_reason\"].value_counts()\n</code></pre>"},{"location":"strategy_analysis_example/#analyze-the-loaded-trades-for-trade-parallelism","title":"Analyze the loaded trades for trade parallelism","text":"<p>This can be useful to find the best <code>max_open_trades</code> parameter, when used with backtesting in conjunction with <code>--disable-max-market-positions</code>.</p> <p><code>analyze_trade_parallelism()</code> returns a timeseries dataframe with an \"open_trades\" column, specifying the number of open trades for each candle.</p> <pre><code>from freqtrade.data.btanalysis import analyze_trade_parallelism\n\n# Analyze the above\nparallel_trades = analyze_trade_parallelism(trades, '5m')\n\nparallel_trades.plot()\n</code></pre>"},{"location":"strategy_analysis_example/#plot-results","title":"Plot results","text":"<p>Freqtrade offers interactive plotting capabilities based on plotly.</p> <pre><code>from freqtrade.plot.plotting import generate_candlestick_graph\n# Limit graph period to keep plotly quick and reactive\n\n# Filter trades to one pair\ntrades_red = trades.loc[trades['pair'] == pair]\n\ndata_red = data['2019-06-01':'2019-06-10']\n# Generate candlestick graph\ngraph = generate_candlestick_graph(pair=pair,\n data=data_red,\n trades=trades_red,\n indicators1=['sma20', 'ema50', 'ema55'],\n indicators2=['rsi', 'macd', 'macdsignal', 'macdhist']\n )\n</code></pre> <pre><code># Show graph inline\n# graph.show()\n\n# Render graph in a seperate window\ngraph.show(renderer=\"browser\")\n</code></pre> <p>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.</p>"},{"location":"telegram-usage/","title":"Telegram usage","text":""},{"location":"telegram-usage/#setup-your-telegram-bot","title":"Setup your Telegram bot","text":"<p>Below we explain how to create your Telegram Bot, and how to get your Telegram user id.</p>"},{"location":"telegram-usage/#1-create-your-telegram-bot","title":"1. Create your Telegram bot","text":"<p>Start a chat with the Telegram BotFather</p> <p>Send the message <code>/newbot</code>.</p> <p>BotFather response:</p> <p>Alright, a new bot. How are we going to call it? Please choose a name for your bot.</p> <p>Choose the public name of your bot (e.x. <code>Freqtrade bot</code>)</p> <p>BotFather response:</p> <p>Good. Now let's choose a username for your bot. It must end in <code>bot</code>. Like this, for example: TetrisBot or tetris_bot.</p> <p>Choose the name id of your bot and send it to the BotFather (e.g. \"<code>My_own_freqtrade_bot</code>\")</p> <p>BotFather response:</p> <p>Done! Congratulations on your new bot. You will find it at <code>t.me/yourbots_name_bot</code>. 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.</p> <p>Use this token to access the HTTP API: <code>22222222:APITOKEN</code></p> <p>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)</p> <p>Copy the API Token (<code>22222222:APITOKEN</code> in the above example) and keep use it for the config parameter <code>token</code>.</p> <p>Don't forget to start the conversation with your bot, by clicking <code>/START</code> button</p>"},{"location":"telegram-usage/#2-telegram-user_id","title":"2. Telegram user_id","text":""},{"location":"telegram-usage/#get-your-user-id","title":"Get your user id","text":"<p>Talk to the userinfobot</p> <p>Get your \"Id\", you will use it for the config parameter <code>chat_id</code>.</p>"},{"location":"telegram-usage/#use-group-id","title":"Use Group id","text":"<p>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 <code>\"chat\"</code> section, which the RawDataBot will send to you:</p> <pre><code>\"chat\":{\n \"id\":-1001332619709\n}\n</code></pre> <p>For the Freqtrade configuration, you can then use the the full value (including <code>-</code> if it's there) as string:</p> <pre><code> \"chat_id\": \"-1001332619709\"\n</code></pre>"},{"location":"telegram-usage/#control-telegram-noise","title":"Control telegram noise","text":"<p>Freqtrade provides means to control the verbosity of your telegram bot. Each setting has the following possible values:</p> <ul> <li><code>on</code> - Messages will be sent, and user will be notified.</li> <li><code>silent</code> - Message will be sent, Notification will be without sound / vibration.</li> <li><code>off</code> - Skip sending a message-type all together.</li> </ul> <p>Example configuration showing the different settings:</p> <pre><code>\"telegram\": {\n \"enabled\": true,\n \"token\": \"your_telegram_token\",\n \"chat_id\": \"your_telegram_chat_id\",\n \"notification_settings\": {\n \"status\": \"silent\",\n \"warning\": \"on\",\n \"startup\": \"off\",\n \"buy\": \"silent\",\n \"sell\": \"on\",\n \"buy_cancel\": \"silent\",\n \"sell_cancel\": \"on\"\n }\n },\n</code></pre>"},{"location":"telegram-usage/#create-a-custom-keyboard-command-shortcut-buttons","title":"Create a custom keyboard (command shortcut buttons)","text":"<p>Telegram allows us to create a custom keyboard with buttons for commands. The default custom keyboard looks like this.</p> <pre><code>[\n [\"/daily\", \"/profit\", \"/balance\"], # row 1, 3 commands\n [\"/status\", \"/status table\", \"/performance\"], # row 2, 3 commands\n [\"/count\", \"/start\", \"/stop\", \"/help\"] # row 3, 4 commands\n]\n</code></pre>"},{"location":"telegram-usage/#usage","title":"Usage","text":"<p>You can create your own keyboard in <code>config.json</code>:</p> <pre><code>\"telegram\": {\n \"enabled\": true,\n \"token\": \"your_telegram_token\",\n \"chat_id\": \"your_telegram_chat_id\",\n \"keyboard\": [ \n [\"/daily\", \"/stats\", \"/balance\", \"/profit\"],\n [\"/status table\", \"/performance\"],\n [\"/reload_config\", \"/count\", \"/logs\"]\n ]\n },\n</code></pre> <p>Supported Commands</p> <p>Only the following commands are allowed. Command arguments are not supported!</p> <p><code>/start</code>, <code>/stop</code>, <code>/status</code>, <code>/status table</code>, <code>/trades</code>, <code>/profit</code>, <code>/performance</code>, <code>/daily</code>, <code>/stats</code>, <code>/count</code>, <code>/locks</code>, <code>/balance</code>, <code>/stopbuy</code>, <code>/reload_config</code>, <code>/show_config</code>, <code>/logs</code>, <code>/whitelist</code>, <code>/blacklist</code>, <code>/edge</code>, <code>/help</code>, <code>/version</code></p>"},{"location":"telegram-usage/#telegram-commands","title":"Telegram commands","text":"<p>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 <code>/help</code>.</p> Command Description <code>/start</code> Starts the trader <code>/stop</code> Stops the trader <code>/stopbuy</code> Stops the trader from opening new trades. Gracefully closes open trades according to their rules. <code>/reload_config</code> Reloads the configuration file <code>/show_config</code> Shows part of the current configuration with relevant settings to operation <code>/logs [limit]</code> Show last log messages. <code>/status</code> Lists all open trades <code>/status <trade_id></code> Lists one or more specific trade. Separate multiple with a blank space. <code>/status table</code> 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 (*) <code>/trades [limit]</code> List all recently closed trades in a table format. <code>/delete <trade_id></code> Delete a specific trade from the Database. Tries to close open orders. Requires manual handling of this trade on the exchange. <code>/count</code> Displays number of trades used and available <code>/locks</code> Show currently locked pairs. <code>/profit</code> Display a summary of your profit/loss from close trades and some stats about your performance <code>/forcesell <trade_id></code> Instantly sells the given trade (Ignoring <code>minimum_roi</code>). <code>/forcesell all</code> Instantly sells all open trades (Ignoring <code>minimum_roi</code>). <code>/forcebuy <pair> [rate]</code> Instantly buys the given pair. Rate is optional. (<code>forcebuy_enable</code> must be set to True) <code>/performance</code> Show performance of each finished trade grouped by pair <code>/balance</code> Show account balance per currency <code>/daily <n></code> Shows profit or loss per day, over the last n days (n defaults to 7) <code>/stats</code> Shows Wins / losses by Sell reason as well as Avg. holding durations for buys and sells <code>/whitelist</code> Show the current whitelist <code>/blacklist [pair]</code> Show the current blacklist, or adds a pair to the blacklist. <code>/edge</code> Show validated pairs by Edge if it is enabled. <code>/help</code> Show help message <code>/version</code> Show version"},{"location":"telegram-usage/#telegram-commands-in-action","title":"Telegram commands in action","text":"<p>Below, example of Telegram message you will receive for each command.</p>"},{"location":"telegram-usage/#start","title":"/start","text":"<p>Status: <code>running</code></p>"},{"location":"telegram-usage/#stop","title":"/stop","text":"<p><code>Stopping trader ...</code> Status: <code>stopped</code></p>"},{"location":"telegram-usage/#stopbuy","title":"/stopbuy","text":"<p>status: <code>Setting max_open_trades to 0. Run /reload_config to reset.</code></p> <p>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, ...).</p> <p>After this, give the bot time to close off open trades (can be checked via <code>/status table</code>). Once all positions are sold, run <code>/stop</code> to completely stop the bot.</p> <p><code>/reload_config</code> resets \"max_open_trades\" to the value set in the configuration and resets this command.</p> <p>Warning</p> <p>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.</p>"},{"location":"telegram-usage/#status","title":"/status","text":"<p>For each open trade, the bot will send you the following message.</p> <p>Trade ID: <code>123</code> <code>(since 1 days ago)</code> Current Pair: CVC/BTC Open Since: <code>1 days ago</code> Amount: <code>26.64180098</code> Open Rate: <code>0.00007489</code> Current Rate: <code>0.00007489</code> Current Profit: <code>12.95%</code> Stoploss: <code>0.00007389 (-0.02%)</code> </p>"},{"location":"telegram-usage/#status-table","title":"/status table","text":"<p>Return the status of all open trades in a table format.</p> <pre><code> ID Pair Since Profit\n---- -------- ------- --------\n 67 SC/BTC 1 d 13.33%\n 123 CVC/BTC 1 h 12.95%\n</code></pre>"},{"location":"telegram-usage/#count","title":"/count","text":"<p>Return the number of trades used and available.</p> <pre><code>current max\n--------- -----\n 2 10\n</code></pre>"},{"location":"telegram-usage/#profit","title":"/profit","text":"<p>Return a summary of your profit/loss and performance.</p> <p>ROI: Close trades \u2219 <code>0.00485701 BTC (258.45%)</code> \u2219 <code>62.968 USD</code> ROI: All trades \u2219 <code>0.00255280 BTC (143.43%)</code> \u2219 <code>33.095 EUR</code> </p> <p>Total Trade Count: <code>138</code> First Trade opened: <code>3 days ago</code> Latest Trade opened: <code>2 minutes ago</code> Avg. Duration: <code>2:33:45</code> Best Performing: <code>PAY/BTC: 50.23%</code> </p>"},{"location":"telegram-usage/#forcesell","title":"/forcesell <p>BITTREX: Selling BTC/LTC with limit <code>0.01650000 (profit: ~-4.07%, -0.00008168)</code></p>","text":""},{"location":"telegram-usage/#forcebuy","title":"/forcebuy <p>BITTREX: Buying ETH/BTC with limit <code>0.03400000</code> (<code>1.000000 ETH</code>, <code>225.290 USD</code>)</p> <p>Note that for this to work, <code>forcebuy_enable</code> needs to be set to true.</p> <p>More details</p>","text":""},{"location":"telegram-usage/#performance","title":"/performance <p>Return the performance of each crypto-currency the bot has sold.</p> <p>Performance: 1. <code>RCN/BTC 57.77%</code> 2. <code>PAY/BTC 56.91%</code> 3. <code>VIB/BTC 47.07%</code> 4. <code>SALT/BTC 30.24%</code> 5. <code>STORJ/BTC 27.24%</code> ... </p>","text":""},{"location":"telegram-usage/#balance","title":"/balance <p>Return the balance of all crypto-currency your have on the exchange.</p> <p>Currency: BTC Available: 3.05890234 Balance: 3.05890234 Pending: 0.0 </p> <p>Currency: CVC Available: 86.64180098 Balance: 86.64180098 Pending: 0.0 </p>","text":""},{"location":"telegram-usage/#daily","title":"/daily <p>Per default <code>/daily</code> will return the 7 last days. The example below if for <code>/daily 3</code>:</p> <p>Daily Profit over the last 3 days: <pre><code>Day Profit BTC Profit USD\n---------- -------------- ------------\n2018-01-03 0.00224175 BTC 29,142 USD\n2018-01-02 0.00033131 BTC 4,307 USD\n2018-01-01 0.00269130 BTC 34.986 USD\n</code></pre></p>","text":""},{"location":"telegram-usage/#whitelist","title":"/whitelist <p>Shows the current whitelist</p> <p>Using whitelist <code>StaticPairList</code> with 22 pairs <code>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</code></p>","text":""},{"location":"telegram-usage/#blacklist-pair","title":"/blacklist [pair] <p>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 <code>/reload_config</code> to reset the blacklist.</p> <p>Using blacklist <code>StaticPairList</code> with 2 pairs <code>DODGE/BTC</code>, <code>HOT/BTC</code>.</p>","text":""},{"location":"telegram-usage/#edge","title":"/edge <p>Shows pairs validated by Edge along with their corresponding win-rate, expectancy and stoploss values.</p> <p>Edge only validated following pairs: <pre><code>Pair Winrate Expectancy Stoploss\n-------- --------- ------------ ----------\nDOCK/ETH 0.522727 0.881821 -0.03\nPHX/ETH 0.677419 0.560488 -0.03\nHOT/ETH 0.733333 0.490492 -0.03\nHC/ETH 0.588235 0.280988 -0.02\nARDR/ETH 0.366667 0.143059 -0.01\n</code></pre></p>","text":""},{"location":"telegram-usage/#version","title":"/version <p>Version: <code>0.14.3</code></p>","text":""},{"location":"updating/","title":"How to update","text":"<p>To update your freqtrade installation, please use one of the below methods, corresponding to your installation method.</p>"},{"location":"updating/#docker-compose","title":"docker-compose","text":"<p>Legacy installations using the <code>master</code> image</p> <p>We're switching from master to stable for the release Images - please adjust your docker-file and replace <code>freqtradeorg/freqtrade:master</code> with <code>freqtradeorg/freqtrade:stable</code></p> <pre><code>docker-compose pull\ndocker-compose up -d\n</code></pre>"},{"location":"updating/#installation-via-setup-script","title":"Installation via setup script","text":"<pre><code>./setup.sh --update\n</code></pre> <p>Note</p> <p>Make sure to run this command with your virtual environment disabled!</p>"},{"location":"updating/#plain-native-installation","title":"Plain native installation","text":"<p>Please ensure that you're also updating dependencies - otherwise things might break without you noticing.</p> <pre><code>git pull\npip install -U -r requirements.txt\n</code></pre>"},{"location":"utils/","title":"Utility Subcommands","text":"<p>Besides the Live-Trade and Dry-Run run modes, the <code>backtesting</code>, <code>edge</code> and <code>hyperopt</code> optimization subcommands, and the <code>download-data</code> subcommand which prepares historical data, the bot contains a number of utility subcommands. They are described in this section.</p>"},{"location":"utils/#create-userdir","title":"Create userdir","text":"<p>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 <code>--reset</code> will reset the sample strategy and hyperopt files to their default state. </p> <pre><code>usage: freqtrade create-userdir [-h] [--userdir PATH] [--reset]\n\noptional arguments:\n -h, --help show this help message and exit\n --userdir PATH, --user-data-dir PATH\n Path to userdata directory.\n --reset Reset sample files to their original state.\n</code></pre> <p>Warning</p> <p>Using <code>--reset</code> may result in loss of data, since this will overwrite all sample files without asking again.</p> <pre><code>\u251c\u2500\u2500 backtest_results\n\u251c\u2500\u2500 data\n\u251c\u2500\u2500 hyperopt_results\n\u251c\u2500\u2500 hyperopts\n\u2502\u00a0\u00a0 \u251c\u2500\u2500 sample_hyperopt_advanced.py\n\u2502\u00a0\u00a0 \u251c\u2500\u2500 sample_hyperopt_loss.py\n\u2502\u00a0\u00a0 \u2514\u2500\u2500 sample_hyperopt.py\n\u251c\u2500\u2500 notebooks\n\u2502\u00a0\u00a0 \u2514\u2500\u2500 strategy_analysis_example.ipynb\n\u251c\u2500\u2500 plot\n\u2514\u2500\u2500 strategies\n \u2514\u2500\u2500 sample_strategy.py\n</code></pre>"},{"location":"utils/#create-new-config","title":"Create new config","text":"<p>Creates a new configuration file, asking some questions which are important selections for a configuration.</p> <pre><code>usage: freqtrade new-config [-h] [-c PATH]\n\noptional arguments:\n -h, --help show this help message and exit\n -c PATH, --config PATH\n Specify configuration file (default: `config.json`). Multiple --config options may be used. Can be set to `-`\n to read config from stdin.\n</code></pre> <p>Warning</p> <p>Only vital questions are asked. Freqtrade offers a lot more configuration possibilities, which are listed in the Configuration documentation</p>"},{"location":"utils/#create-config-examples","title":"Create config examples","text":"<pre><code>$ freqtrade new-config --config config_binance.json\n\n? Do you want to enable Dry-run (simulated trades)? Yes\n? Please insert your stake currency: BTC\n? Please insert your stake amount: 0.05\n? Please insert max_open_trades (Integer or 'unlimited'): 3\n? Please insert your desired timeframe (e.g. 5m): 5m\n? Please insert your display Currency (for reporting): USD\n? Select exchange binance\n? Do you want to enable Telegram? No\n</code></pre>"},{"location":"utils/#create-new-strategy","title":"Create new strategy","text":"<p>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.</p> <p>Results will be located in <code>user_data/strategies/<strategyclassname>.py</code>.</p> <pre><code>usage: freqtrade new-strategy [-h] [--userdir PATH] [-s NAME]\n [--template {full,minimal,advanced}]\n\noptional arguments:\n -h, --help show this help message and exit\n --userdir PATH, --user-data-dir PATH\n Path to userdata directory.\n -s NAME, --strategy NAME\n Specify strategy class name which will be used by the\n bot.\n --template {full,minimal,advanced}\n Use a template which is either `minimal`, `full`\n (containing multiple sample indicators) or `advanced`.\n Default: `full`.\n</code></pre>"},{"location":"utils/#sample-usage-of-new-strategy","title":"Sample usage of new-strategy","text":"<pre><code>freqtrade new-strategy --strategy AwesomeStrategy\n</code></pre> <p>With custom user directory</p> <pre><code>freqtrade new-strategy --userdir ~/.freqtrade/ --strategy AwesomeStrategy\n</code></pre> <p>Using the advanced template (populates all optional functions and methods)</p> <pre><code>freqtrade new-strategy --strategy AwesomeStrategy --template advanced\n</code></pre>"},{"location":"utils/#create-new-hyperopt","title":"Create new hyperopt","text":"<p>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.</p> <p>Results will be located in <code>user_data/hyperopts/<classname>.py</code>.</p> <pre><code>usage: freqtrade new-hyperopt [-h] [--userdir PATH] [--hyperopt NAME]\n [--template {full,minimal,advanced}]\n\noptional arguments:\n -h, --help show this help message and exit\n --userdir PATH, --user-data-dir PATH\n Path to userdata directory.\n --hyperopt NAME Specify hyperopt class name which will be used by the\n bot.\n --template {full,minimal,advanced}\n Use a template which is either `minimal`, `full`\n (containing multiple sample indicators) or `advanced`.\n Default: `full`.\n</code></pre>"},{"location":"utils/#sample-usage-of-new-hyperopt","title":"Sample usage of new-hyperopt","text":"<pre><code>freqtrade new-hyperopt --hyperopt AwesomeHyperopt\n</code></pre> <p>With custom user directory</p> <pre><code>freqtrade new-hyperopt --userdir ~/.freqtrade/ --hyperopt AwesomeHyperopt\n</code></pre>"},{"location":"utils/#list-strategies-and-list-hyperopts","title":"List Strategies and List Hyperopts","text":"<p>Use the <code>list-strategies</code> subcommand to see all strategies in one particular directory and the <code>list-hyperopts</code> subcommand to list custom Hyperopts.</p> <p>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).</p> <p><pre><code>usage: freqtrade list-strategies [-h] [-v] [--logfile FILE] [-V] [-c PATH]\n [-d PATH] [--userdir PATH]\n [--strategy-path PATH] [-1] [--no-color]\n\noptional arguments:\n -h, --help show this help message and exit\n --strategy-path PATH Specify additional strategy lookup path.\n -1, --one-column Print output in one column.\n --no-color Disable colorization of hyperopt results. May be\n useful if you are redirecting output to a file.\n\nCommon arguments:\n -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).\n --logfile FILE Log to the file specified. Special values are:\n 'syslog', 'journald'. See the documentation for more\n details.\n -V, --version show program's version number and exit\n -c PATH, --config PATH\n Specify configuration file (default: `config.json`).\n Multiple --config options may be used. Can be set to\n `-` to read config from stdin.\n -d PATH, --datadir PATH\n Path to directory with historical backtesting data.\n --userdir PATH, --user-data-dir PATH\n Path to userdata directory.\n</code></pre> <pre><code>usage: freqtrade list-hyperopts [-h] [-v] [--logfile FILE] [-V] [-c PATH]\n [-d PATH] [--userdir PATH]\n [--hyperopt-path PATH] [-1] [--no-color]\n\noptional arguments:\n -h, --help show this help message and exit\n --hyperopt-path PATH Specify additional lookup path for Hyperopt and\n Hyperopt Loss functions.\n -1, --one-column Print output in one column.\n --no-color Disable colorization of hyperopt results. May be\n useful if you are redirecting output to a file.\n\nCommon arguments:\n -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).\n --logfile FILE Log to the file specified. Special values are:\n 'syslog', 'journald'. See the documentation for more\n details.\n -V, --version show program's version number and exit\n -c PATH, --config PATH\n Specify configuration file (default: `config.json`).\n Multiple --config options may be used. Can be set to\n `-` to read config from stdin.\n -d PATH, --datadir PATH\n Path to directory with historical backtesting data.\n --userdir PATH, --user-data-dir PATH\n Path to userdata directory.\n</code></pre></p> <p>Warning</p> <p>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.</p> <p>Example: Search default strategies and hyperopts directories (within the default userdir).</p> <pre><code>freqtrade list-strategies\nfreqtrade list-hyperopts\n</code></pre> <p>Example: Search strategies and hyperopts directory within the userdir.</p> <pre><code>freqtrade list-strategies --userdir ~/.freqtrade/\nfreqtrade list-hyperopts --userdir ~/.freqtrade/\n</code></pre> <p>Example: Search dedicated strategy path.</p> <pre><code>freqtrade list-strategies --strategy-path ~/.freqtrade/strategies/\n</code></pre> <p>Example: Search dedicated hyperopt path.</p> <pre><code>freqtrade list-hyperopt --hyperopt-path ~/.freqtrade/hyperopts/\n</code></pre>"},{"location":"utils/#list-exchanges","title":"List Exchanges","text":"<p>Use the <code>list-exchanges</code> subcommand to see the exchanges available for the bot.</p> <pre><code>usage: freqtrade list-exchanges [-h] [-1] [-a]\n\noptional arguments:\n -h, --help show this help message and exit\n -1, --one-column Print output in one column.\n -a, --all Print all exchanges known to the ccxt library.\n</code></pre> <ul> <li>Example: see exchanges available for the bot: <pre><code>$ freqtrade list-exchanges\nExchanges available for Freqtrade: _1btcxe, acx, allcoin, bequant, bibox, binance, binanceje, binanceus, bitbank, bitfinex, bitfinex2, bitkk, bitlish, bitmart, bittrex, bitz, bleutrade, btcalpha, btcmarkets, btcturk, buda, cex, cobinhood, coinbaseprime, coinbasepro, coinex, cointiger, coss, crex24, digifinex, dsx, dx, ethfinex, fcoin, fcoinjp, gateio, gdax, gemini, hitbtc2, huobipro, huobiru, idex, kkex, kraken, kucoin, kucoin2, kuna, lbank, mandala, mercado, oceanex, okcoincny, okcoinusd, okex, okex3, poloniex, rightbtc, theocean, tidebit, upbit, zb\n</code></pre></li> </ul> <ul> <li>Example: see all exchanges supported by the ccxt library (including 'bad' ones, i.e. those that are known to not work with Freqtrade): <pre><code>$ freqtrade list-exchanges -a\nAll exchanges supported by the ccxt library: _1btcxe, acx, adara, allcoin, anxpro, bcex, bequant, bibox, bigone, binance, binanceje, binanceus, bit2c, bitbank, bitbay, bitfinex, bitfinex2, bitflyer, bitforex, bithumb, bitkk, bitlish, bitmart, bitmex, bitso, bitstamp, bitstamp1, bittrex, bitz, bl3p, bleutrade, braziliex, btcalpha, btcbox, btcchina, btcmarkets, btctradeim, btctradeua, btcturk, buda, bxinth, cex, chilebit, cobinhood, coinbase, coinbaseprime, coinbasepro, coincheck, coinegg, coinex, coinexchange, coinfalcon, coinfloor, coingi, coinmarketcap, coinmate, coinone, coinspot, cointiger, coolcoin, coss, crex24, crypton, deribit, digifinex, dsx, dx, ethfinex, exmo, exx, fcoin, fcoinjp, flowbtc, foxbit, fybse, gateio, gdax, gemini, hitbtc, hitbtc2, huobipro, huobiru, ice3x, idex, independentreserve, indodax, itbit, kkex, kraken, kucoin, kucoin2, kuna, lakebtc, latoken, lbank, liquid, livecoin, luno, lykke, mandala, mercado, mixcoins, negociecoins, nova, oceanex, okcoincny, okcoinusd, okex, okex3, paymium, poloniex, rightbtc, southxchange, stronghold, surbitcoin, theocean, therock, tidebit, tidex, upbit, vaultoro, vbtc, virwox, xbtce, yobit, zaif, zb\n</code></pre></li> </ul>"},{"location":"utils/#list-timeframes","title":"List Timeframes","text":"<p>Use the <code>list-timeframes</code> subcommand to see the list of timeframes (ticker intervals) available for the exchange.</p> <pre><code>usage: freqtrade list-timeframes [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [--exchange EXCHANGE] [-1]\n\noptional arguments:\n -h, --help show this help message and exit\n --exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no config is provided.\n -1, --one-column Print output in one column.\n\nCommon arguments:\n -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).\n --logfile FILE Log to the file specified. Special values are: 'syslog', 'journald'. See the documentation for more details.\n -V, --version show program's version number and exit\n -c PATH, --config PATH\n Specify configuration file (default: `config.json`). Multiple --config options may be used. Can be set to `-`\n to read config from stdin.\n -d PATH, --datadir PATH\n Path to directory with historical backtesting data.\n --userdir PATH, --user-data-dir PATH\n Path to userdata directory.\n</code></pre> <ul> <li>Example: see the timeframes for the 'binance' exchange, set in the configuration file:</li> </ul> <pre><code>$ freqtrade list-timeframes -c config_binance.json\n...\nTimeframes available for the exchange `binance`: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M\n</code></pre> <ul> <li>Example: enumerate exchanges available for Freqtrade and print timeframes supported by each of them: <pre><code>$ for i in `freqtrade list-exchanges -1`; do freqtrade list-timeframes --exchange $i; done\n</code></pre></li> </ul>"},{"location":"utils/#list-pairslist-markets","title":"List pairs/list markets","text":"<p>The <code>list-pairs</code> and <code>list-markets</code> subcommands allow to see the pairs/markets available on exchange.</p> <p>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.</p> <p>For pairs traded by Freqtrade the pair quote currency is defined by the value of the <code>stake_currency</code> configuration setting.</p> <p>You can print info about any pair/market with these subcommands - and you can filter output by quote-currency using <code>--quote BTC</code>, or by base-currency using <code>--base ETH</code> options correspondingly.</p> <p>These subcommands have same usage and same set of available options:</p> <pre><code>usage: freqtrade list-markets [-h] [-v] [--logfile FILE] [-V] [-c PATH]\n [-d PATH] [--userdir PATH] [--exchange EXCHANGE]\n [--print-list] [--print-json] [-1] [--print-csv]\n [--base BASE_CURRENCY [BASE_CURRENCY ...]]\n [--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]]\n [-a]\n\nusage: freqtrade list-pairs [-h] [-v] [--logfile FILE] [-V] [-c PATH]\n [-d PATH] [--userdir PATH] [--exchange EXCHANGE]\n [--print-list] [--print-json] [-1] [--print-csv]\n [--base BASE_CURRENCY [BASE_CURRENCY ...]]\n [--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]] [-a]\n\noptional arguments:\n -h, --help show this help message and exit\n --exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no\n config is provided.\n --print-list Print list of pairs or market symbols. By default data\n is printed in the tabular format.\n --print-json Print list of pairs or market symbols in JSON format.\n -1, --one-column Print output in one column.\n --print-csv Print exchange pair or market data in the csv format.\n --base BASE_CURRENCY [BASE_CURRENCY ...]\n Specify base currency(-ies). Space-separated list.\n --quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]\n Specify quote currency(-ies). Space-separated list.\n -a, --all Print all pairs or market symbols. By default only\n active ones are shown.\n\nCommon arguments:\n -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).\n --logfile FILE Log to the file specified. Special values are:\n 'syslog', 'journald'. See the documentation for more\n details.\n -V, --version show program's version number and exit\n -c PATH, --config PATH\n Specify configuration file (default: `config.json`).\n Multiple --config options may be used. Can be set to\n `-` to read config from stdin.\n -d PATH, --datadir PATH\n Path to directory with historical backtesting data.\n --userdir PATH, --user-data-dir PATH\n Path to userdata directory.\n</code></pre> <p>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 <code>-a</code>/<code>-all</code> option.</p> <p>Pairs/markets are sorted by its symbol string in the printed output.</p>"},{"location":"utils/#examples","title":"Examples","text":"<ul> <li>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:</li> </ul> <pre><code>$ freqtrade list-pairs --quote USD --print-json\n</code></pre> <ul> <li>Print the list of all pairs on the exchange, specified in the <code>config_binance.json</code> 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:</li> </ul> <pre><code>$ freqtrade list-pairs -c config_binance.json --all --base BTC ETH --quote USDT USD --print-list\n</code></pre> <ul> <li>Print all markets on exchange \"Kraken\", in the tabular format:</li> </ul> <pre><code>$ freqtrade list-markets --exchange kraken --all\n</code></pre>"},{"location":"utils/#test-pairlist","title":"Test pairlist","text":"<p>Use the <code>test-pairlist</code> subcommand to test the configuration of dynamic pairlists.</p> <p>Requires a configuration with specified <code>pairlists</code> attribute. Can be used to generate static pairlists to be used during backtesting / hyperopt.</p> <pre><code>usage: freqtrade test-pairlist [-h] [-c PATH]\n [--quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]]\n [-1] [--print-json]\n\noptional arguments:\n -h, --help show this help message and exit\n -c PATH, --config PATH\n Specify configuration file (default: `config.json`).\n Multiple --config options may be used. Can be set to\n `-` to read config from stdin.\n --quote QUOTE_CURRENCY [QUOTE_CURRENCY ...]\n Specify quote currency(-ies). Space-separated list.\n -1, --one-column Print output in one column.\n --print-json Print list of pairs or market symbols in JSON format.\n</code></pre>"},{"location":"utils/#examples_1","title":"Examples","text":"<p>Show whitelist when using a dynamic pairlist.</p> <pre><code>freqtrade test-pairlist --config config.json --quote USDT BTC\n</code></pre>"},{"location":"utils/#list-hyperopt-results","title":"List Hyperopt results","text":"<p>You can list the hyperoptimization epochs the Hyperopt module evaluated previously with the <code>hyperopt-list</code> sub-command.</p> <pre><code>usage: freqtrade hyperopt-list [-h] [-v] [--logfile FILE] [-V] [-c PATH]\n [-d PATH] [--userdir PATH] [--best]\n [--profitable] [--min-trades INT]\n [--max-trades INT] [--min-avg-time FLOAT]\n [--max-avg-time FLOAT] [--min-avg-profit FLOAT]\n [--max-avg-profit FLOAT]\n [--min-total-profit FLOAT]\n [--max-total-profit FLOAT]\n [--min-objective FLOAT] [--max-objective FLOAT]\n [--no-color] [--print-json] [--no-details]\n [--hyperopt-filename PATH] [--export-csv FILE]\n\noptional arguments:\n -h, --help show this help message and exit\n --best Select only best epochs.\n --profitable Select only profitable epochs.\n --min-trades INT Select epochs with more than INT trades.\n --max-trades INT Select epochs with less than INT trades.\n --min-avg-time FLOAT Select epochs above average time.\n --max-avg-time FLOAT Select epochs below average time.\n --min-avg-profit FLOAT\n Select epochs above average profit.\n --max-avg-profit FLOAT\n Select epochs below average profit.\n --min-total-profit FLOAT\n Select epochs above total profit.\n --max-total-profit FLOAT\n Select epochs below total profit.\n --min-objective FLOAT\n Select epochs above objective.\n --max-objective FLOAT\n Select epochs below objective.\n --no-color Disable colorization of hyperopt results. May be\n useful if you are redirecting output to a file.\n --print-json Print output in JSON format.\n --no-details Do not print best epoch details.\n --hyperopt-filename FILENAME\n Hyperopt result filename.Example: `--hyperopt-\n filename=hyperopt_results_2020-09-27_16-20-48.pickle`\n --export-csv FILE Export to CSV-File. This will disable table print.\n Example: --export-csv hyperopt.csv\n\nCommon arguments:\n -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).\n --logfile FILE Log to the file specified. Special values are:\n 'syslog', 'journald'. See the documentation for more\n details.\n -V, --version show program's version number and exit\n -c PATH, --config PATH\n Specify configuration file (default:\n `userdir/config.json` or `config.json` whichever\n exists). Multiple --config options may be used. Can be\n set to `-` to read config from stdin.\n -d PATH, --datadir PATH\n Path to directory with historical backtesting data.\n --userdir PATH, --user-data-dir PATH\n Path to userdata directory.\n</code></pre> <p>Note</p> <p><code>hyperopt-list</code> will automatically use the latest available hyperopt results file. You can override this using the <code>--hyperopt-filename</code> argument, and specify another, available filename (without path!).</p>"},{"location":"utils/#examples_2","title":"Examples","text":"<p>List all results, print details of the best result at the end: <pre><code>freqtrade hyperopt-list\n</code></pre></p> <p>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: <pre><code>freqtrade hyperopt-list --profitable --no-details\n</code></pre></p>"},{"location":"utils/#show-details-of-hyperopt-results","title":"Show details of Hyperopt results","text":"<p>You can show the details of any hyperoptimization epoch previously evaluated by the Hyperopt module with the <code>hyperopt-show</code> subcommand.</p> <pre><code>usage: freqtrade hyperopt-show [-h] [-v] [--logfile FILE] [-V] [-c PATH]\n [-d PATH] [--userdir PATH] [--best]\n [--profitable] [-n INT] [--print-json]\n [--hyperopt-filename PATH] [--no-header]\n\noptional arguments:\n -h, --help show this help message and exit\n --best Select only best epochs.\n --profitable Select only profitable epochs.\n -n INT, --index INT Specify the index of the epoch to print details for.\n --print-json Print output in JSON format.\n --hyperopt-filename FILENAME\n Hyperopt result filename.Example: `--hyperopt-\n filename=hyperopt_results_2020-09-27_16-20-48.pickle`\n --no-header Do not print epoch details header.\n\nCommon arguments:\n -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).\n --logfile FILE Log to the file specified. Special values are:\n 'syslog', 'journald'. See the documentation for more\n details.\n -V, --version show program's version number and exit\n -c PATH, --config PATH\n Specify configuration file (default:\n `userdir/config.json` or `config.json` whichever\n exists). Multiple --config options may be used. Can be\n set to `-` to read config from stdin.\n -d PATH, --datadir PATH\n Path to directory with historical backtesting data.\n --userdir PATH, --user-data-dir PATH\n Path to userdata directory.\n</code></pre> <p>Note</p> <p><code>hyperopt-show</code> will automatically use the latest available hyperopt results file. You can override this using the <code>--hyperopt-filename</code> argument, and specify another, available filename (without path!).</p>"},{"location":"utils/#examples_3","title":"Examples","text":"<p>Print details for the epoch 168 (the number of the epoch is shown by the <code>hyperopt-list</code> subcommand or by Hyperopt itself during hyperoptimization run):</p> <pre><code>freqtrade hyperopt-show -n 168\n</code></pre> <p>Prints JSON data with details for the last best epoch (i.e., the best of all epochs):</p> <pre><code>freqtrade hyperopt-show --best -n -1 --print-json --no-header\n</code></pre>"},{"location":"utils/#show-trades","title":"Show trades","text":"<p>Print selected (or all) trades from database to screen.</p> <pre><code>usage: freqtrade show-trades [-h] [-v] [--logfile FILE] [-V] [-c PATH]\n [-d PATH] [--userdir PATH] [--db-url PATH]\n [--trade-ids TRADE_IDS [TRADE_IDS ...]]\n [--print-json]\n\noptional arguments:\n -h, --help show this help message and exit\n --db-url PATH Override trades database URL, this is useful in custom\n deployments (default: `sqlite:///tradesv3.sqlite` for\n Live Run mode, `sqlite:///tradesv3.dryrun.sqlite` for\n Dry Run).\n --trade-ids TRADE_IDS [TRADE_IDS ...]\n Specify the list of trade ids.\n --print-json Print output in JSON format.\n\nCommon arguments:\n -v, --verbose Verbose mode (-vv for more, -vvv to get all messages).\n --logfile FILE Log to the file specified. Special values are:\n 'syslog', 'journald'. See the documentation for more\n details.\n -V, --version show program's version number and exit\n -c PATH, --config PATH\n Specify configuration file (default:\n `userdir/config.json` or `config.json` whichever\n exists). Multiple --config options may be used. Can be\n set to `-` to read config from stdin.\n -d PATH, --datadir PATH\n Path to directory with historical backtesting data.\n --userdir PATH, --user-data-dir PATH\n Path to userdata directory.\n</code></pre>"},{"location":"utils/#examples_4","title":"Examples","text":"<p>Print trades with id 2 and 3 as json</p> <pre><code>freqtrade show-trades --db-url sqlite:///tradesv3.sqlite --trade-ids 2 3 --print-json\n</code></pre>"},{"location":"webhook-config/","title":"Webhook usage","text":""},{"location":"webhook-config/#configuration","title":"Configuration","text":"<p>Enable webhooks by adding a webhook-section to your configuration file, and setting <code>webhook.enabled</code> to <code>true</code>.</p> <p>Sample configuration (tested using IFTTT).</p> <pre><code> \"webhook\": {\n \"enabled\": true,\n \"url\": \"https://maker.ifttt.com/trigger/<YOUREVENT>/with/key/<YOURKEY>/\",\n \"webhookbuy\": {\n \"value1\": \"Buying {pair}\",\n \"value2\": \"limit {limit:8f}\",\n \"value3\": \"{stake_amount:8f} {stake_currency}\"\n },\n \"webhookbuycancel\": {\n \"value1\": \"Cancelling Open Buy Order for {pair}\",\n \"value2\": \"limit {limit:8f}\",\n \"value3\": \"{stake_amount:8f} {stake_currency}\"\n },\n \"webhooksell\": {\n \"value1\": \"Selling {pair}\",\n \"value2\": \"limit {limit:8f}\",\n \"value3\": \"profit: {profit_amount:8f} {stake_currency} ({profit_ratio})\"\n },\n \"webhooksellcancel\": {\n \"value1\": \"Cancelling Open Sell Order for {pair}\",\n \"value2\": \"limit {limit:8f}\",\n \"value3\": \"profit: {profit_amount:8f} {stake_currency} ({profit_ratio})\"\n },\n \"webhookstatus\": {\n \"value1\": \"Status: {status}\",\n \"value2\": \"\",\n \"value3\": \"\"\n }\n },\n</code></pre> <p>The url in <code>webhook.url</code> 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.</p> <p>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.</p>"},{"location":"webhook-config/#webhookbuy","title":"Webhookbuy","text":"<p>The fields in <code>webhook.webhookbuy</code> are filled when the bot executes a buy. Parameters are filled using string.format. Possible parameters are:</p> <ul> <li><code>trade_id</code></li> <li><code>exchange</code></li> <li><code>pair</code></li> <li><code>limit</code></li> <li><code>amount</code></li> <li><code>open_date</code></li> <li><code>stake_amount</code></li> <li><code>stake_currency</code></li> <li><code>fiat_currency</code></li> <li><code>order_type</code></li> <li><code>current_rate</code></li> </ul>"},{"location":"webhook-config/#webhookbuycancel","title":"Webhookbuycancel","text":"<p>The fields in <code>webhook.webhookbuycancel</code> are filled when the bot cancels a buy order. Parameters are filled using string.format. Possible parameters are:</p> <ul> <li><code>trade_id</code></li> <li><code>exchange</code></li> <li><code>pair</code></li> <li><code>limit</code></li> <li><code>amount</code></li> <li><code>open_date</code></li> <li><code>stake_amount</code></li> <li><code>stake_currency</code></li> <li><code>fiat_currency</code></li> <li><code>order_type</code></li> <li><code>current_rate</code></li> </ul>"},{"location":"webhook-config/#webhooksell","title":"Webhooksell","text":"<p>The fields in <code>webhook.webhooksell</code> are filled when the bot sells a trade. Parameters are filled using string.format. Possible parameters are:</p> <ul> <li><code>trade_id</code></li> <li><code>exchange</code></li> <li><code>pair</code></li> <li><code>gain</code></li> <li><code>limit</code></li> <li><code>amount</code></li> <li><code>open_rate</code></li> <li><code>current_rate</code></li> <li><code>profit_amount</code></li> <li><code>profit_ratio</code></li> <li><code>stake_currency</code></li> <li><code>fiat_currency</code></li> <li><code>sell_reason</code></li> <li><code>order_type</code></li> <li><code>open_date</code></li> <li><code>close_date</code></li> </ul>"},{"location":"webhook-config/#webhooksellcancel","title":"Webhooksellcancel","text":"<p>The fields in <code>webhook.webhooksellcancel</code> are filled when the bot cancels a sell order. Parameters are filled using string.format. Possible parameters are:</p> <ul> <li><code>trade_id</code></li> <li><code>exchange</code></li> <li><code>pair</code></li> <li><code>gain</code></li> <li><code>limit</code></li> <li><code>amount</code></li> <li><code>open_rate</code></li> <li><code>current_rate</code></li> <li><code>profit_amount</code></li> <li><code>profit_ratio</code></li> <li><code>stake_currency</code></li> <li><code>fiat_currency</code></li> <li><code>sell_reason</code></li> <li><code>order_type</code></li> <li><code>open_date</code></li> <li><code>close_date</code></li> </ul>"},{"location":"webhook-config/#webhookstatus","title":"Webhookstatus","text":"<p>The fields in <code>webhook.webhookstatus</code> are used for regular status messages (Started / Stopped / ...). Parameters are filled using string.format.</p> <p>The only possible value here is <code>{status}</code>.</p>"},{"location":"windows_installation/","title":"Windows","text":"<p>We strongly recommend that Windows users use Docker as this will work much easier and smoother (also more secure).</p> <p>If that is not possible, try using the Windows Linux subsystem (WSL) - for which the Ubuntu instructions should work. Otherwise, try the instructions below.</p>"},{"location":"windows_installation/#install-freqtrade-manually","title":"Install freqtrade manually","text":"<p>Note</p> <p>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.</p> <p>Hint</p> <p>Using the Anaconda Distribution under Windows can greatly help with installation problems. Check out the Anaconda installation section in this document for more information.</p>"},{"location":"windows_installation/#1-clone-the-git-repository","title":"1. Clone the git repository","text":"<pre><code>git clone https://github.com/freqtrade/freqtrade.git\n</code></pre>"},{"location":"windows_installation/#2-install-ta-lib","title":"2. Install ta-lib","text":"<p>Install ta-lib according to the ta-lib documentation.</p> <p>As compiling from source on windows has heavy dependencies (requires a partial visual studio installation), there is also a repository of unofficial precompiled windows Wheels here, which needs to be downloaded and installed using <code>pip install TA_Lib\u20110.4.19\u2011cp38\u2011cp38\u2011win_amd64.whl</code> (make sure to use the version matching your python version)</p> <p>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.</p> <pre><code>cd \\path\\freqtrade\npython -m venv .env\n.env\\Scripts\\activate.ps1\n# optionally install ta-lib from wheel\n# Eventually adjust the below filename to match the downloaded wheel\npip install build_helpers/TA_Lib-0.4.19-cp38-cp38-win_amd64.whl\npip install -r requirements.txt\npip install -e .\nfreqtrade\n</code></pre> <p>Use Powershell</p> <p>The above installation script assumes you're using powershell on a 64bit windows. Commands for the legacy CMD windows console may differ.</p> <p>Thanks Owdr for the commands. Source: Issue #222</p>"},{"location":"windows_installation/#error-during-installation-on-windows","title":"Error during installation on Windows","text":"<pre><code>error: Microsoft Visual C++ 14.0 is required. Get it with \"Microsoft Visual C++ Build Tools\": http://landinghub.visualstudio.com/visual-cpp-build-tools\n</code></pre> <p>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.</p> <p>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.</p>"},{"location":"includes/pairlists/","title":"Pairlists","text":""},{"location":"includes/pairlists/#pairlists-and-pairlist-handlers","title":"Pairlists and Pairlist Handlers","text":"<p>Pairlist Handlers define the list of pairs (pairlist) that the bot should trade. They are configured in the <code>pairlists</code> section of the configuration settings.</p> <p>In your configuration, you can use Static Pairlist (defined by the <code>StaticPairList</code> Pairlist Handler) and Dynamic Pairlist (defined by the <code>VolumePairList</code> Pairlist Handler).</p> <p>Additionally, <code>AgeFilter</code>, <code>PrecisionFilter</code>, <code>PriceFilter</code>, <code>ShuffleFilter</code> and <code>SpreadFilter</code> act as Pairlist Filters, removing certain pairs and/or moving their positions in the pairlist.</p> <p>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 <code>StaticPairList</code> or <code>VolumePairList</code> as the starting Pairlist Handler.</p> <p>Inactive markets are always removed from the resulting pairlist. Explicitly blacklisted pairs (those in the <code>pair_blacklist</code> configuration setting) are also always removed from the resulting pairlist.</p>"},{"location":"includes/pairlists/#pair-blacklist","title":"Pair blacklist","text":"<p>The pair blacklist (configured via <code>exchange.pair_blacklist</code> in the configuration) disallows certain pairs from trading. This can be as simple as excluding <code>DOGE/BTC</code> - which will remove exactly this pair.</p> <p>The pair-blacklist does also support wildcards (in regex-style) - so <code>BNB/.*</code> will exclude ALL pairs that start with BNB. You may also use something like <code>.*DOWN/BTC</code> or <code>.*UP/BTC</code> to exclude leveraged tokens (check Pair naming conventions for your exchange!)</p>"},{"location":"includes/pairlists/#available-pairlist-handlers","title":"Available Pairlist Handlers","text":"<ul> <li><code>StaticPairList</code> (default, if not configured differently)</li> <li><code>VolumePairList</code></li> <li><code>AgeFilter</code></li> <li><code>PerformanceFilter</code></li> <li><code>PrecisionFilter</code></li> <li><code>PriceFilter</code></li> <li><code>ShuffleFilter</code></li> <li><code>SpreadFilter</code></li> <li><code>RangeStabilityFilter</code></li> </ul> <p>Testing pairlists</p> <p>Pairlist configurations can be quite tricky to get right. Best use the <code>test-pairlist</code> utility sub-command to test your configuration quickly.</p>"},{"location":"includes/pairlists/#static-pair-list","title":"Static Pair List","text":"<p>By default, the <code>StaticPairList</code> method is used, which uses a statically defined pair whitelist from the configuration. The pairlist also supports wildcards (in regex-style) - so <code>.*/BTC</code> will include all pairs with BTC as a stake.</p> <p>It uses configuration from <code>exchange.pair_whitelist</code> and <code>exchange.pair_blacklist</code>.</p> <pre><code>\"pairlists\": [\n {\"method\": \"StaticPairList\"}\n ],\n</code></pre> <p>By default, only currently enabled pairs are allowed. To skip pair validation against active markets, set <code>\"allow_inactive\": true</code> within the <code>StaticPairList</code> configuration. This can be useful for backtesting expired pairs (like quarterly spot-markets). This option must be configured along with <code>exchange.skip_pair_validation</code> in the exchange configuration.</p>"},{"location":"includes/pairlists/#volume-pair-list","title":"Volume Pair List","text":"<p><code>VolumePairList</code> employs sorting/filtering of pairs by their trading volume. It selects <code>number_assets</code> top pairs with sorting based on the <code>sort_key</code> (which can only be <code>quoteVolume</code>).</p> <p>When used in the chain of Pairlist Handlers in a non-leading position (after StaticPairList and other Pairlist Filters), <code>VolumePairList</code> considers outputs of previous Pairlist Handlers, adding its sorting/selection of the pairs by the trading volume.</p> <p>When used on the leading position of the chain of Pairlist Handlers, it does not consider <code>pair_whitelist</code> configuration setting, but selects the top assets from all available markets (with matching stake-currency) on the exchange.</p> <p>The <code>refresh_period</code> setting allows to define the period (in seconds), at which the pairlist will be refreshed. Defaults to 1800s (30 minutes).</p> <p><code>VolumePairList</code> is based on the ticker data from exchange, as reported by the ccxt library:</p> <ul> <li>The <code>quoteVolume</code> is the amount of quote (stake) currency traded (bought or sold) in last 24 hours.</li> </ul> <pre><code>\"pairlists\": [{\n \"method\": \"VolumePairList\",\n \"number_assets\": 20,\n \"sort_key\": \"quoteVolume\",\n \"refresh_period\": 1800\n}],\n</code></pre> <p>Note</p> <p><code>VolumePairList</code> does not support backtesting mode.</p>"},{"location":"includes/pairlists/#agefilter","title":"AgeFilter","text":"<p>Removes pairs that have been listed on the exchange for less than <code>min_days_listed</code> days (defaults to <code>10</code>).</p> <p>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.</p> <p>This filter allows freqtrade to ignore pairs until they have been listed for at least <code>min_days_listed</code> days.</p>"},{"location":"includes/pairlists/#performancefilter","title":"PerformanceFilter","text":"<p>Sorts pairs by past trade performance, as follows: 1. Positive performance. 2. No closed trades yet. 3. Negative performance.</p> <p>Trade count is used as a tie breaker.</p> <p>Note</p> <p><code>PerformanceFilter</code> does not support backtesting mode.</p>"},{"location":"includes/pairlists/#precisionfilter","title":"PrecisionFilter","text":"<p>Filters low-value coins which would not allow setting stoplosses.</p>"},{"location":"includes/pairlists/#pricefilter","title":"PriceFilter","text":"<p>The <code>PriceFilter</code> allows filtering of pairs by price. Currently the following price filters are supported:</p> <ul> <li><code>min_price</code></li> <li><code>max_price</code></li> <li><code>low_price_ratio</code></li> </ul> <p>The <code>min_price</code> 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.</p> <p>The <code>max_price</code> 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.</p> <p>The <code>low_price_ratio</code> setting removes pairs where a raise of 1 price unit (pip) is above the <code>low_price_ratio</code> ratio. This option is disabled by default, and will only apply if set to > 0.</p> <p>For <code>PriceFiler</code> at least one of its <code>min_price</code>, <code>max_price</code> or <code>low_price_ratio</code> settings must be applied.</p> <p>Calculation example:</p> <p>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 <code>low_price_ratio</code> set to 0.09 (9%) or with <code>min_price</code> set to 0.00000011, correspondingly.</p> <p>Low priced pairs</p> <p>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.</p>"},{"location":"includes/pairlists/#shufflefilter","title":"ShuffleFilter","text":"<p>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.</p> <p>Tip</p> <p>You may set the <code>seed</code> value for this Pairlist to obtain reproducible results, which can be useful for repeated backtesting sessions. If <code>seed</code> is not set, the pairs are shuffled in the non-repeatable random order.</p>"},{"location":"includes/pairlists/#spreadfilter","title":"SpreadFilter","text":"<p>Removes pairs that have a difference between asks and bids above the specified ratio, <code>max_spread_ratio</code> (defaults to <code>0.005</code>).</p> <p>Example:</p> <p>If <code>DOGE/BTC</code> maximum bid is 0.00000026 and minimum ask is 0.00000027, the ratio is calculated as: <code>1 - bid/ask ~= 0.037</code> which is <code>> 0.005</code> and this pair will be filtered out.</p>"},{"location":"includes/pairlists/#rangestabilityfilter","title":"RangeStabilityFilter","text":"<p>Removes pairs where the difference between lowest low and highest high over <code>lookback_days</code> days is below <code>min_rate_of_change</code>. Since this is a filter that requires additional data, the results are cached for <code>refresh_period</code>.</p> <p>In the below example: If the trading range over the last 10 days is <1%, remove the pair from the whitelist.</p> <pre><code>\"pairlists\": [\n {\n \"method\": \"RangeStabilityFilter\",\n \"lookback_days\": 10,\n \"min_rate_of_change\": 0.01,\n \"refresh_period\": 1440\n }\n]\n</code></pre> <p>Tip</p> <p>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.</p>"},{"location":"includes/pairlists/#full-example-of-pairlist-handlers","title":"Full example of Pairlist Handlers","text":"<p>The below example blacklists <code>BNB/BTC</code>, uses <code>VolumePairList</code> with <code>20</code> assets, sorting pairs by <code>quoteVolume</code> and applies both <code>PrecisionFilter</code> and <code>PriceFilter</code>, filtering all assets where 1 price unit is > 1%. Then the <code>SpreadFilter</code> is applied and pairs are finally shuffled with the random seed set to some predefined value.</p> <pre><code>\"exchange\": {\n \"pair_whitelist\": [],\n \"pair_blacklist\": [\"BNB/BTC\"]\n},\n\"pairlists\": [\n {\n \"method\": \"VolumePairList\",\n \"number_assets\": 20,\n \"sort_key\": \"quoteVolume\",\n },\n {\"method\": \"AgeFilter\", \"min_days_listed\": 10},\n {\"method\": \"PrecisionFilter\"},\n {\"method\": \"PriceFilter\", \"low_price_ratio\": 0.01},\n {\"method\": \"SpreadFilter\", \"max_spread_ratio\": 0.005},\n {\n \"method\": \"RangeStabilityFilter\",\n \"lookback_days\": 10,\n \"min_rate_of_change\": 0.01,\n \"refresh_period\": 1440\n },\n {\"method\": \"ShuffleFilter\", \"seed\": 42}\n ],\n</code></pre>"},{"location":"includes/pricing/","title":"Pricing","text":""},{"location":"includes/pricing/#prices-used-for-orders","title":"Prices used for orders","text":"<p>Prices for regular orders can be controlled via the parameter structures <code>bid_strategy</code> for buying and <code>ask_strategy</code> for selling. Prices are always retrieved right before an order is placed, either by querying the exchange tickers or by using the orderbook data.</p> <p>Note</p> <p>Orderbook data used by Freqtrade are the data retrieved from exchange by the ccxt's function <code>fetch_order_book()</code>, i.e. are usually data from the L2-aggregated orderbook, while the ticker data are the structures returned by the ccxt's <code>fetch_ticker()</code>/<code>fetch_tickers()</code> functions. Refer to the ccxt library documentation for more details.</p> <p>Using market orders</p> <p>Please read the section Market order pricing section when using market orders.</p>"},{"location":"includes/pricing/#buy-price","title":"Buy price","text":""},{"location":"includes/pricing/#check-depth-of-market","title":"Check depth of market","text":"<p>When check depth of market is enabled (<code>bid_strategy.check_depth_of_market.enabled=True</code>), the buy signals are filtered based on the orderbook depth (sum of all amounts) for each orderbook side.</p> <p>Orderbook <code>bid</code> (buy) side depth is then divided by the orderbook <code>ask</code> (sell) side depth and the resulting delta is compared to the value of the <code>bid_strategy.check_depth_of_market.bids_to_ask_delta</code> parameter. The buy order is only executed if the orderbook delta is greater than or equal to the configured delta value.</p> <p>Note</p> <p>A delta value below 1 means that <code>ask</code> (sell) orderbook side depth is greater than the depth of the <code>bid</code> (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).</p>"},{"location":"includes/pricing/#buy-price-side","title":"Buy price side","text":"<p>The configuration setting <code>bid_strategy.price_side</code> defines the side of the spread the bot looks for when buying.</p> <p>The following displays an orderbook.</p> <pre><code>...\n103\n102\n101 # ask\n-------------Current spread\n99 # bid\n98\n97\n...\n</code></pre> <p>If <code>bid_strategy.price_side</code> is set to <code>\"bid\"</code>, then the bot will use 99 as buying price. In line with that, if <code>bid_strategy.price_side</code> is set to <code>\"ask\"</code>, then the bot will use 101 as buying price.</p> <p>Using <code>ask</code> 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).</p>"},{"location":"includes/pricing/#buy-price-with-orderbook-enabled","title":"Buy price with Orderbook enabled","text":"<p>When buying with the orderbook enabled (<code>bid_strategy.use_order_book=True</code>), Freqtrade fetches the <code>bid_strategy.order_book_top</code> entries from the orderbook and then uses the entry specified as <code>bid_strategy.order_book_top</code> on the configured side (<code>bid_strategy.price_side</code>) of the orderbook. 1 specifies the topmost entry in the orderbook, while 2 would use the 2<sup>nd</sup> entry in the orderbook, and so on.</p>"},{"location":"includes/pricing/#buy-price-without-orderbook-enabled","title":"Buy price without Orderbook enabled","text":"<p>The following section uses <code>side</code> as the configured <code>bid_strategy.price_side</code>.</p> <p>When not using orderbook (<code>bid_strategy.use_order_book=False</code>), Freqtrade uses the best <code>side</code> price from the ticker if it's below the <code>last</code> traded price from the ticker. Otherwise (when the <code>side</code> price is above the <code>last</code> price), it calculates a rate between <code>side</code> and <code>last</code> price.</p> <p>The <code>bid_strategy.ask_last_balance</code> configuration parameter controls this. A value of <code>0.0</code> will use <code>side</code> price, while <code>1.0</code> will use the <code>last</code> price and values between those interpolate between ask and last price.</p>"},{"location":"includes/pricing/#sell-price","title":"Sell price","text":""},{"location":"includes/pricing/#sell-price-side","title":"Sell price side","text":"<p>The configuration setting <code>ask_strategy.price_side</code> defines the side of the spread the bot looks for when selling.</p> <p>The following displays an orderbook:</p> <pre><code>...\n103\n102\n101 # ask\n-------------Current spread\n99 # bid\n98\n97\n...\n</code></pre> <p>If <code>ask_strategy.price_side</code> is set to <code>\"ask\"</code>, then the bot will use 101 as selling price. In line with that, if <code>ask_strategy.price_side</code> is set to <code>\"bid\"</code>, then the bot will use 99 as selling price.</p>"},{"location":"includes/pricing/#sell-price-with-orderbook-enabled","title":"Sell price with Orderbook enabled","text":"<p>When selling with the orderbook enabled (<code>ask_strategy.use_order_book=True</code>), Freqtrade fetches the <code>ask_strategy.order_book_max</code> entries in the orderbook. Then each of the orderbook steps between <code>ask_strategy.order_book_min</code> and <code>ask_strategy.order_book_max</code> on the configured orderbook side are validated for a profitable sell-possibility based on the strategy configuration (<code>minimal_roi</code> conditions) and the sell order is placed at the first profitable spot.</p> <p>Note</p> <p>Using <code>order_book_max</code> higher than <code>order_book_min</code> only makes sense when ask_strategy.price_side is set to <code>\"ask\"</code>.</p> <p>The idea here is to place the sell order early, to be ahead in the queue.</p> <p>A fixed slot (mirroring <code>bid_strategy.order_book_top</code>) can be defined by setting <code>ask_strategy.order_book_min</code> and <code>ask_strategy.order_book_max</code> to the same number.</p> <p>Order_book_max > 1 - increased risks for stoplosses!</p> <p>Using <code>ask_strategy.order_book_max</code> higher than 1 will increase the risk the stoploss on exchange is cancelled too early, since an eventual stoploss on exchange will be cancelled as soon as the order is placed. Also, the sell order will remain on the exchange for <code>unfilledtimeout.sell</code> (or until it's filled) - which can lead to missed stoplosses (with or without using stoploss on exchange).</p> <p>Order_book_max > 1 in dry-run</p> <p>Using <code>ask_strategy.order_book_max</code> higher than 1 will result in improper dry-run results (significantly better than real orders executed on exchange), since dry-run assumes orders to be filled almost instantly. It is therefore advised to not use this setting for dry-runs.</p>"},{"location":"includes/pricing/#sell-price-without-orderbook-enabled","title":"Sell price without Orderbook enabled","text":"<p>When not using orderbook (<code>ask_strategy.use_order_book=False</code>), the price at the <code>ask_strategy.price_side</code> side (defaults to <code>\"ask\"</code>) from the ticker will be used as the sell price.</p>"},{"location":"includes/pricing/#market-order-pricing","title":"Market order pricing","text":"<p>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</p> <pre><code> \"order_types\": {\n \"buy\": \"market\",\n \"sell\": \"market\"\n // ...\n },\n \"bid_strategy\": {\n \"price_side\": \"ask\",\n // ...\n },\n \"ask_strategy\":{\n \"price_side\": \"bid\",\n // ...\n },\n</code></pre> <p>Obviously, if only one side is using limit orders, different pricing combinations can be used.</p>"},{"location":"includes/protections/","title":"Protections","text":""},{"location":"includes/protections/#protections","title":"Protections","text":"<p>Beta feature</p> <p>This feature is still in it's testing phase. Should you notice something you think is wrong please let us know via Discord, Slack or via Github Issue.</p> <p>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.</p> <p>Note</p> <p>Not all Protections will work for all strategies, and parameters will need to be tuned for your strategy to improve performance. To align your protection with your strategy, you can define protections in the strategy.</p> <p>Tip</p> <p>Each Protection can be configured multiple times with different parameters, to allow different levels of protection (short-term / long-term).</p> <p>Backtesting</p> <p>Protections are supported by backtesting and hyperopt, but must be explicitly enabled by using the <code>--enable-protections</code> flag.</p>"},{"location":"includes/protections/#available-protections","title":"Available Protections","text":"<ul> <li><code>StoplossGuard</code> Stop trading if a certain amount of stoploss occurred within a certain time window.</li> <li><code>MaxDrawdown</code> Stop trading if max-drawdown is reached.</li> <li><code>LowProfitPairs</code> Lock pairs with low profits</li> <li><code>CooldownPeriod</code> Don't enter a trade right after selling a trade.</li> </ul>"},{"location":"includes/protections/#common-settings-to-all-protections","title":"Common settings to all Protections","text":"Parameter Description <code>method</code> Protection name to use. Datatype: String, selected from available Protections <code>stop_duration_candles</code> For how many candles should the lock be set? Datatype: Positive integer (in candles) <code>stop_duration</code> how many minutes should protections be locked. Cannot be used together with <code>stop_duration_candles</code>. Datatype: Float (in minutes) <code>lookback_period_candles</code> Only trades that completed within the last <code>lookback_period_candles</code> candles will be considered. This setting may be ignored by some Protections. Datatype: Positive integer (in candles). <code>lookback_period</code> Only trades that completed after <code>current_time - lookback_period</code> will be considered. Cannot be used together with <code>lookback_period_candles</code>. This setting may be ignored by some Protections. Datatype: Float (in minutes) <code>trade_limit</code> Number of trades required at minimum (not used by all Protections). Datatype: Positive integer <p>Durations</p> <p>Durations (<code>stop_duration*</code> and <code>lookback_period*</code> can be defined in either minutes or candles). For more flexibility when testing different timeframes, all below examples will use the \"candle\" definition.</p>"},{"location":"includes/protections/#stoploss-guard","title":"Stoploss Guard","text":"<p><code>StoplossGuard</code> selects all trades within <code>lookback_period</code> in minutes (or in candles when using <code>lookback_period_candles</code>). If <code>trade_limit</code> or more trades resulted in stoploss, trading will stop for <code>stop_duration</code> in minutes (or in candles when using <code>stop_duration_candles</code>).</p> <p>This applies across all pairs, unless <code>only_per_pair</code> is set to true, which will then only look at one pair at a time.</p> <p>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.</p> <pre><code>\"protections\": [\n {\n \"method\": \"StoplossGuard\",\n \"lookback_period_candles\": 24,\n \"trade_limit\": 4,\n \"stop_duration_candles\": 4,\n \"only_per_pair\": false\n }\n],\n</code></pre> <p>Note</p> <p><code>StoplossGuard</code> considers all trades with the results <code>\"stop_loss\"</code>, <code>\"stoploss_on_exchange\"</code> and <code>\"trailing_stop_loss\"</code> if the resulting profit was negative. <code>trade_limit</code> and <code>lookback_period</code> will need to be tuned for your strategy.</p>"},{"location":"includes/protections/#maxdrawdown","title":"MaxDrawdown","text":"<p><code>MaxDrawdown</code> uses all trades within <code>lookback_period</code> in minutes (or in candles when using <code>lookback_period_candles</code>) to determine the maximum drawdown. If the drawdown is below <code>max_allowed_drawdown</code>, trading will stop for <code>stop_duration</code> in minutes (or in candles when using <code>stop_duration_candles</code>) after the last trade - assuming that the bot needs some time to let markets recover.</p> <p>The below sample stops trading for 12 candles if max-drawdown is > 20% considering all pairs - with a minimum of <code>trade_limit</code> trades - within the last 48 candles. If desired, <code>lookback_period</code> and/or <code>stop_duration</code> can be used.</p> <pre><code>\"protections\": [\n {\n \"method\": \"MaxDrawdown\",\n \"lookback_period_candles\": 48,\n \"trade_limit\": 20,\n \"stop_duration_candles\": 12,\n \"max_allowed_drawdown\": 0.2\n },\n],\n</code></pre>"},{"location":"includes/protections/#low-profit-pairs","title":"Low Profit Pairs","text":"<p><code>LowProfitPairs</code> uses all trades for a pair within <code>lookback_period</code> in minutes (or in candles when using <code>lookback_period_candles</code>) to determine the overall profit ratio. If that ratio is below <code>required_profit</code>, that pair will be locked for <code>stop_duration</code> in minutes (or in candles when using <code>stop_duration_candles</code>).</p> <p>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.</p> <pre><code>\"protections\": [\n {\n \"method\": \"LowProfitPairs\",\n \"lookback_period_candles\": 6,\n \"trade_limit\": 2,\n \"stop_duration\": 60,\n \"required_profit\": 0.02\n }\n],\n</code></pre>"},{"location":"includes/protections/#cooldown-period","title":"Cooldown Period","text":"<p><code>CooldownPeriod</code> locks a pair for <code>stop_duration</code> in minutes (or in candles when using <code>stop_duration_candles</code>) after selling, avoiding a re-entry for this pair for <code>stop_duration</code> minutes.</p> <p>The below example will stop trading a pair for 2 candles after closing a trade, allowing this pair to \"cool down\".</p> <pre><code>\"protections\": [\n {\n \"method\": \"CooldownPeriod\",\n \"stop_duration_candles\": 2\n }\n],\n</code></pre> <p>Note</p> <p>This Protection applies only at pair-level, and will never lock all pairs globally. This Protection does not consider <code>lookback_period</code> as it only looks at the latest trade.</p>"},{"location":"includes/protections/#full-example-of-protections","title":"Full example of Protections","text":"<p>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.</p> <p>The below example assumes a timeframe of 1 hour:</p> <ul> <li>Locks each pair after selling for an additional 5 candles (<code>CooldownPeriod</code>), giving other pairs a chance to get filled.</li> <li>Stops trading for 4 hours (<code>4 * 1h candles</code>) if the last 2 days (<code>48 * 1h candles</code>) had 20 trades, which caused a max-drawdown of more than 20%. (<code>MaxDrawdown</code>).</li> <li>Stops trading if more than 4 stoploss occur for all pairs within a 1 day (<code>24 * 1h candles</code>) limit (<code>StoplossGuard</code>).</li> <li>Locks all pairs that had 4 Trades within the last 6 hours (<code>6 * 1h candles</code>) with a combined profit ratio of below 0.02 (<2%) (<code>LowProfitPairs</code>).</li> <li>Locks all pairs for 2 candles that had a profit of below 0.01 (<1%) within the last 24h (<code>24 * 1h candles</code>), a minimum of 4 trades.</li> </ul> <pre><code>\"timeframe\": \"1h\",\n\"protections\": [\n {\n \"method\": \"CooldownPeriod\",\n \"stop_duration_candles\": 5\n },\n {\n \"method\": \"MaxDrawdown\",\n \"lookback_period_candles\": 48,\n \"trade_limit\": 20,\n \"stop_duration_candles\": 4,\n \"max_allowed_drawdown\": 0.2\n },\n {\n \"method\": \"StoplossGuard\",\n \"lookback_period_candles\": 24,\n \"trade_limit\": 4,\n \"stop_duration_candles\": 2,\n \"only_per_pair\": false\n },\n {\n \"method\": \"LowProfitPairs\",\n \"lookback_period_candles\": 6,\n \"trade_limit\": 2,\n \"stop_duration_candles\": 60,\n \"required_profit\": 0.02\n },\n {\n \"method\": \"LowProfitPairs\",\n \"lookback_period_candles\": 24,\n \"trade_limit\": 4,\n \"stop_duration_candles\": 2,\n \"required_profit\": 0.01\n }\n ],\n</code></pre> <p>You can use the same in your strategy, the syntax is only slightly different:</p> <pre><code>from freqtrade.strategy import IStrategy\n\nclass AwesomeStrategy(IStrategy)\n timeframe = '1h'\n protections = [\n {\n \"method\": \"CooldownPeriod\",\n \"stop_duration_candles\": 5\n },\n {\n \"method\": \"MaxDrawdown\",\n \"lookback_period_candles\": 48,\n \"trade_limit\": 20,\n \"stop_duration_candles\": 4,\n \"max_allowed_drawdown\": 0.2\n },\n {\n \"method\": \"StoplossGuard\",\n \"lookback_period_candles\": 24,\n \"trade_limit\": 4,\n \"stop_duration_candles\": 2,\n \"only_per_pair\": False\n },\n {\n \"method\": \"LowProfitPairs\",\n \"lookback_period_candles\": 6,\n \"trade_limit\": 2,\n \"stop_duration_candles\": 60,\n \"required_profit\": 0.02\n },\n {\n \"method\": \"LowProfitPairs\",\n \"lookback_period_candles\": 24,\n \"trade_limit\": 4,\n \"stop_duration_candles\": 2,\n \"required_profit\": 0.01\n }\n ]\n # ...\n</code></pre>"}]} |