{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Freqtrade","text":"
Star
Fork
Download
Follow @freqtrade
"},{"location":"#introduction","title":"Introduction","text":"Freqtrade is a crypto-currency algorithmic trading software developed in python (3.6+) and supported on Windows, macOS and Linux.
DISCLAIMER
This software is for educational purposes only. Do not risk money which you are afraid to lose. USE THE SOFTWARE AT YOUR OWN RISK. THE AUTHORS AND ALL AFFILIATES ASSUME NO RESPONSIBILITY FOR YOUR TRADING RESULTS.
Always start by running a trading bot in Dry-run and do not engage money before you understand how it works and what profit/loss you should expect.
We strongly recommend you to have basic coding skills and Python knowledge. Do not hesitate to read the source code and understand the mechanisms of this bot, algorithms and techniques implemented in it.
"},{"location":"#features","title":"Features","text":"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.
"},{"location":"#hardware-requirements","title":"Hardware requirements","text":"To run this bot we recommend you a cloud instance with a minimum of:
Alternatively
For any questions not covered by the documentation or for further information about the bot, we encourage you to join our passionate Slack community.
Click here to join the Freqtrade Slack channel.
"},{"location":"#ready-to-try","title":"Ready to try?","text":"Begin by reading our installation guide for docker, or for installation without docker.
"},{"location":"advanced-hyperopt/","title":"Advanced Hyperopt","text":"This page explains some advanced Hyperopt topics that may require higher coding skills and Python knowledge than creation of an ordinal hyperoptimization class.
"},{"location":"advanced-hyperopt/#derived-hyperopt-classes","title":"Derived hyperopt classes","text":"Custom hyperop classes can be derived in the same way it can be done for strategies.
Applying to hyperoptimization, as an example, you may override how dimensions are defined in your optimization hyperspace:
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
and then quickly switch between hyperopt classes, running optimization process with hyperopt class you need in each particular case:
$ freqtrade hyperopt --hyperopt MyAwesomeHyperOpt ...\nor\n$ freqtrade hyperopt --hyperopt MyAwesomeHyperOpt2 ...\n
"},{"location":"advanced-hyperopt/#creating-and-using-a-custom-loss-function","title":"Creating and using a custom loss function","text":"To use a custom loss function class, make sure that the function hyperopt_loss_function
is defined in your custom hyperopt loss class. For the sample below, you then need to add the command line parameter --hyperopt-loss SuperDuperHyperOptLoss
to your hyperopt call so this function is being used.
A sample of this can be found below, which is identical to the Default Hyperopt loss implementation. A full sample can be found in userdata/hyperopts.
from 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 *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_percent.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
Currently, the arguments are:
results
: DataFrame containing the result The following columns are available in results (corresponds to the output-file of backtesting when used with --export trades
): pair, profit_percent, profit_abs, open_time, close_time, open_index, close_index, trade_duration, open_at_end, open_rate, close_rate, sell_reason
trade_count
: Amount of trades (identical to len(results)
)min_date
: Start date of the hyperopting TimeFramemin_date
: End date of the hyperopting TimeFrameThis function needs to return a floating point number (float
). Smaller numbers will be interpreted as better results. The parameters and balancing for this is up to you.
Note
This function is called once per iteration - so please make sure to have this as optimized as possible to not slow hyperopt down unnecessarily.
Note
Please keep the arguments *args
and **kwargs
in the interface to allow us to extend this interface later.
This page explains some advanced tasks and configuration options that can be performed after the bot installation and may be uselful in some environments.
If you do not know what things mentioned here mean, you probably do not need it.
"},{"location":"advanced-setup/#configure-the-bot-running-as-a-systemd-service","title":"Configure the bot running as a systemd service","text":"Copy the freqtrade.service
file to your systemd user directory (usually ~/.config/systemd/user
) and update WorkingDirectory
and ExecStart
to match your setup.
Note
Certain systems (like Raspbian) don't load service unit files from the user directory. In this case, copy freqtrade.service
into /etc/systemd/user/
(requires superuser permissions).
After that you can start the daemon with:
systemctl --user start freqtrade\n
For this to be persistent (run when user is logged out) you'll need to enable linger
for your freqtrade user.
sudo loginctl enable-linger \"$USER\"\n
If you run the bot as a service, you can use systemd service manager as a software watchdog monitoring freqtrade bot state and restarting it in the case of failures. If the internals.sd_notify
parameter is set to true in the configuration or the --sd-notify
command line option is used, the bot will send keep-alive ping messages to systemd using the sd_notify (systemd notifications) protocol and will also tell systemd its current state (Running or Stopped) when it changes.
The freqtrade.service.watchdog
file contains an example of the service unit configuration file which uses systemd as the watchdog.
Note
The sd_notify communication between the bot and the systemd service manager will not work if the bot runs in a Docker container.
"},{"location":"advanced-setup/#advanced-logging","title":"Advanced Logging","text":"On many Linux systems the bot can be configured to send its log messages to syslog
or journald
system services. Logging to a remote syslog
server is also available on Windows. The special values for the --logfilename
command line option can be used for this.
To send Freqtrade log messages to a local or remote syslog
service use the --logfilename
command line option with the value in the following format:
--logfilename syslog:<syslog_address>
-- send log messages to syslog
service using the <syslog_address>
as the syslog address.The syslog address can be either a Unix domain socket (socket filename) or a UDP socket specification, consisting of IP address and UDP port, separated by the :
character.
So, the following are the examples of possible usages:
--logfilename syslog:/dev/log
-- log to syslog (rsyslog) using the /dev/log
socket, suitable for most systems.--logfilename syslog
-- same as above, the shortcut for /dev/log
.--logfilename syslog:/var/run/syslog
-- log to syslog (rsyslog) using the /var/run/syslog
socket. Use this on MacOS.--logfilename syslog:localhost:514
-- log to local syslog using UDP socket, if it listens on port 514.--logfilename syslog:<ip>:514
-- log to remote syslog at IP address and port 514. This may be used on Windows for remote logging to an external syslog server.Log messages are send to syslog
with the user
facility. So you can see them with the following commands:
tail -f /var/log/user
, or On many systems syslog
(rsyslog
) fetches data from journald
(and vice versa), so both --logfilename syslog
or --logfilename journald
can be used and the messages be viewed with both journalctl
and a syslog viewer utility. You can combine this in any way which suites you better.
For rsyslog
the messages from the bot can be redirected into a separate dedicated log file. To achieve this, add
if $programname startswith \"freqtrade\" then -/var/log/freqtrade.log\n
to one of the rsyslog configuration files, for example at the end of the /etc/rsyslog.d/50-default.conf
. For syslog
(rsyslog
), the reduction mode can be switched on. This will reduce the number of repeating messages. For instance, multiple bot Heartbeat messages will be reduced to a single message when nothing else happens with the bot. To achieve this, set in /etc/rsyslog.conf
:
# Filter duplicated messages\n$RepeatedMsgReduction on\n
"},{"location":"advanced-setup/#logging-to-journald","title":"Logging to journald","text":"This needs the systemd
python package installed as the dependency, which is not available on Windows. Hence, the whole journald logging functionality is not available for a bot running on Windows.
To send Freqtrade log messages to journald
system service use the --logfilename
command line option with the value in the following format:
--logfilename journald
-- send log messages to journald
.Log messages are send to journald
with the user
facility. So you can see them with the following commands:
journalctl -f
-- shows Freqtrade log messages sent to journald
along with other log messages fetched by journald
.journalctl -f -u freqtrade.service
-- this command can be used when the bot is run as a systemd
service.There are many other options in the journalctl
utility to filter the messages, see manual pages for this utility.
On many systems syslog
(rsyslog
) fetches data from journald
(and vice versa), so both --logfilename syslog
or --logfilename journald
can be used and the messages be viewed with both journalctl
and a syslog viewer utility. You can combine this in any way which suites you better.
This page explains how to validate your strategy performance by using Backtesting.
Backtesting requires historic data to be available. To learn how to get data for the pairs and exchange you're interested in, head over to the Data Downloading section of the documentation.
"},{"location":"backtesting/#test-your-strategy-with-backtesting","title":"Test your strategy with Backtesting","text":"Now you have good Buy and Sell strategies and some historic data, you want to test it against real data. This is what we call backtesting.
Backtesting will use the crypto-currencies (pairs) from your config file and load ticker data from user_data/data/<exchange>
by default. If no data is available for the exchange / pair / ticker interval combination, backtesting will ask you to download them first using freqtrade download-data
. For details on downloading, please refer to the Data Downloading section in the documentation.
The result of backtesting will confirm if your bot has better odds of making a profit than a loss.
Using dynamic pairlists for backtesting
While using dynamic pairlists during backtesting is not possible, a dynamic pairlist using current data can be generated via the test-pairlist
command, and needs to be specified as \"pair_whitelist\"
attribute in the configuration.
freqtrade backtesting\n
"},{"location":"backtesting/#with-1-min-tickers","title":"With 1 min tickers","text":"freqtrade backtesting --ticker-interval 1m\n
"},{"location":"backtesting/#using-a-different-on-disk-ticker-data-source","title":"Using a different on-disk ticker-data source","text":"Assume you downloaded the history data from the Bittrex exchange and kept it in the user_data/data/bittrex-20180101
directory. You can then use this data for backtesting as follows:
freqtrade --datadir user_data/data/bittrex-20180101 backtesting\n
"},{"location":"backtesting/#with-a-custom-strategy-file","title":"With a (custom) strategy file","text":"freqtrade backtesting -s SampleStrategy\n
Where -s SampleStrategy
refers to the class name within the strategy file sample_strategy.py
found in the freqtrade/user_data/strategies
directory.
freqtrade backtesting --strategy-list SampleStrategy1 AwesomeStrategy --ticker-interval 5m\n
Where SampleStrategy1
and AwesomeStrategy
refer to class names of strategies.
freqtrade backtesting --export trades\n
The exported trades can be used for further analysis, or can be used by the plotting script plot_dataframe.py
in the scripts directory.
freqtrade backtesting --export trades --export-filename=backtest_samplestrategy.json\n
Please also read about the strategy startup period.
"},{"location":"backtesting/#supplying-custom-fee-value","title":"Supplying custom fee value","text":"Sometimes your account has certain fee rebates (fee reductions starting with a certain account size or monthly volume), which are not visible to ccxt. To account for this in backtesting, you can use the --fee
command line option to supply this value to backtesting. This fee must be a ratio, and will be applied twice (once for trade entry, and once for trade exit).
For example, if the buying and selling commission fee is 0.1% (i.e., 0.001 written as ratio), then you would run backtesting as the following:
freqtrade backtesting --fee 0.001\n
Note
Only supply this option (or the corresponding configuration parameter) if you want to experiment with different fee values. By default, Backtesting fetches the default fee from the exchange pair/market info.
"},{"location":"backtesting/#running-backtest-with-smaller-testset-by-using-timerange","title":"Running backtest with smaller testset by using timerange","text":"Use the --timerange
argument to change how much of the testset you want to use.
For example, running backtesting with the --timerange=20190501-
option will use all available data starting with May 1st, 2019 from your inputdata.
freqtrade backtesting --timerange=20190501-\n
You can also specify particular dates or a range span indexed by start and stop.
The full timerange specification:
--timerange=-20180131
--timerange=20180131-
--timerange=20180131-20180301
--timerange=1527595200-1527618600
The most important in the backtesting is to understand the result.
A backtesting result will look like that:
========================================================= 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
The 1st table contains all trades the bot made, including \"left open trades\".
The 2nd table contains a recap of sell reasons. This table can tell you which area needs some additional work (i.e. all sell_signal
trades are losses, so we should disable the sell-signal or work on improving that).
The 3rd table contains all trades the bot had to forcesell
at the end of the backtest period to present a full picture. This is necessary to simulate realistic behaviour, 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 extracted separately for clarity.
The last line will give you the overall performance of your strategy, here:
| TOTAL | 429 | 0.36 | 152.41 | 0.00762792 | 76.20 | 4:12:00 | 186 | 243 |\n
The bot has made 429
trades for an average duration of 4:12:00
, with a performance of 76.20%
(profit), that means it has earned a total of 0.00762792 BTC
starting with a capital of 0.01 BTC.
The column avg profit %
shows the average profit for all trades made while the column cum profit %
sums up all the profits/losses. The column tot profit %
shows instead the total profit % in relation to allocated capital (max_open_trades * stake_amount
). In the above results we have max_open_trades=2
and stake_amount=0.005
in config so tot_profit %
will be (76.20/100) * (0.005 * 2) =~ 0.00762792 BTC
.
Your strategy performance is influenced by your buy strategy, your sell strategy, and also by the minimal_roi
and stop_loss
you have set.
For example, if your minimal_roi
is only \"0\": 0.01
you cannot expect the bot to make more profit than 1% (because it will sell every time a trade reaches 1%).
\"minimal_roi\": {\n \"0\": 0.01\n},\n
On the other hand, if you set a too high minimal_roi
like \"0\": 0.55
(55%), there is almost no chance that the bot will ever reach this profit. Hence, keep in mind that your performance is an integral mix of all different elements of the strategy, your configuration, and the crypto-currency pairs you have set up.
Since backtesting lacks some detailed information about what happens within a candle, it needs to take a few assumptions:
<N>=-1
ROI entries use low as sell value, unless N falls on the candle open (e.g. 120: -1
for 1h candles)Taking these assumptions, backtesting tries to mirror real trading as closely as possible. However, backtesting will never replace running a strategy in dry-run mode. Also, keep in mind that past results don't guarantee future success.
In addition to the above assumptions, strategy authors should carefully read the Common Mistakes section, to avoid using data in backtesting which is not available in real market conditions.
"},{"location":"backtesting/#further-backtest-result-analysis","title":"Further backtest-result analysis","text":"To further analyze your backtest results, you can export the trades. You can then load the trades to perform further analysis as shown in our data analysis backtesting section.
"},{"location":"backtesting/#backtesting-multiple-strategies","title":"Backtesting multiple strategies","text":"To compare multiple strategies, a list of Strategies can be provided to backtesting.
This is limited to 1 ticker-interval per run, however, data is only loaded once from disk so if you have multiple strategies you'd like to compare, this will give a nice runtime boost.
All listed Strategies need to be in the same directory.
freqtrade backtesting --timerange 20180401-20180410 --ticker-interval 5m --strategy-list Strategy001 Strategy002 --export trades\n
This will save the results to user_data/backtest_results/backtest-result-<strategy>.json
, injecting the strategy-name into the target filename. There will be an additional table comparing win/losses of the different strategies (identical to the \"Total\" row in the first table). Detailed output for all strategies one after the other will be available, so make sure to scroll up to see the details per strategy.
=========================================================== STRATEGY SUMMARY ===========================================================\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
"},{"location":"backtesting/#next-step","title":"Next step","text":"Great, your strategy is profitable. What if the bot can give your the optimal parameters to use for your strategy? Your next step is to learn how to find optimal parameters with Hyperopt
"},{"location":"bot-usage/","title":"Start the bot","text":"This page explains the different parameters of the bot and how to run it.
Note
If you've used setup.sh
, don't forget to activate your virtual environment (source .env/bin/activate
) before running freqtrade commands.
usage: freqtrade [-h] [-V]\n {trade,backtesting,edge,hyperopt,create-userdir,list-exchanges,list-timeframes,download-data,plot-dataframe,plot-profit}\n ...\n\nFree, open source crypto trading bot\n\npositional arguments:\n {trade,backtesting,edge,hyperopt,create-userdir,list-exchanges,list-timeframes,download-data,plot-dataframe,plot-profit}\n trade Trade module.\n backtesting Backtesting module.\n edge Edge module.\n hyperopt Hyperopt module.\n create-userdir Create user-data directory.\n list-exchanges Print available exchanges.\n list-timeframes Print available ticker intervals (timeframes) for the\n exchange.\n download-data Download backtesting data.\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
"},{"location":"bot-usage/#bot-trading-commands","title":"Bot trading commands","text":"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.\n
"},{"location":"bot-usage/#how-to-specify-which-configuration-file-be-used","title":"How to specify which configuration file be used?","text":"The bot allows you to select which configuration file you want to use by means of the -c/--config
command line option:
freqtrade trade -c path/far/far/away/config.json\n
Per default, the bot loads the config.json
configuration file from the current working directory.
The bot allows you to use multiple configuration files by specifying multiple -c/--config
options in the command line. Configuration parameters defined in the latter configuration files override parameters with the same name defined in the previous configuration files specified in the command line earlier.
For example, you can make a separate configuration file with your key and secret for the Exchange you use for trading, specify default configuration file with empty key and secret values while running in the Dry Mode (which does not actually require them):
freqtrade trade -c ./config.json\n
and specify both configuration files when running in the normal Live Trade Mode:
freqtrade trade -c ./config.json -c path/to/secrets/keys.config.json\n
This could help you hide your private Exchange key and Exchange secret on you local machine by setting appropriate file permissions for the file which contains actual secrets and, additionally, prevent unintended disclosure of sensitive private data when you publish examples of your configuration in the project issues or in the Internet.
See more details on this technique with examples in the documentation page on configuration.
"},{"location":"bot-usage/#where-to-store-custom-data","title":"Where to store custom data","text":"Freqtrade allows the creation of a user-data directory using freqtrade create-userdir --userdir someDirectory
. This directory will look as follows:
user_data/\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
You can add the entry \"user_data_dir\" setting to your configuration, to always point your bot to this directory. Alternatively, pass in --userdir
to every command. The bot will fail to start if the directory does not exist, but will create necessary subdirectories.
This directory should contain your custom strategies, custom hyperopts and hyperopt loss functions, backtesting historical data (downloaded using either backtesting command or the download script) and plot outputs.
It is recommended to use version control to keep track of changes to your strategies.
"},{"location":"bot-usage/#how-to-use-strategy","title":"How to use --strategy?","text":"This parameter will allow you to load your custom strategy class. Per default without --strategy
or -s
the bot will load the DefaultStrategy
included with the bot (freqtrade/strategy/default_strategy.py
).
The bot will search your strategy file within user_data/strategies
and freqtrade/strategy
.
To load a strategy, simply pass the class name (e.g.: CustomStrategy
) in this parameter.
Example: In user_data/strategies
you have a file my_awesome_strategy.py
which has a strategy class called AwesomeStrategy
to load it:
freqtrade trade --strategy AwesomeStrategy\n
If the bot does not find your strategy file, it will display in an error message the reason (File not found, or errors in your code).
Learn more about strategy file in Strategy Customization.
"},{"location":"bot-usage/#how-to-use-strategy-path","title":"How to use --strategy-path?","text":"This parameter allows you to add an additional strategy lookup path, which gets checked before the default locations (The passed path must be a directory!):
freqtrade trade --strategy AwesomeStrategy --strategy-path /some/directory\n
"},{"location":"bot-usage/#how-to-install-a-strategy","title":"How to install a strategy?","text":"This is very simple. Copy paste your strategy file into the directory user_data/strategies
or use --strategy-path
. And voila, the bot is ready to use it.
When you run the bot in Dry-run mode, per default no transactions are stored in a database. If you want to store your bot actions in a DB using --db-url
. This can also be used to specify a custom database in production mode. Example command:
freqtrade trade -c config.json --db-url sqlite:///tradesv3.dry_run.sqlite\n
"},{"location":"bot-usage/#backtesting-commands","title":"Backtesting commands","text":"Backtesting also uses the config specified via -c/--config
.
usage: freqtrade backtesting [-h] [-v] [--logfile FILE] [-V] [-c PATH]\n [-d PATH] [--userdir PATH] [-s NAME]\n [--strategy-path PATH] [-i TICKER_INTERVAL]\n [--timerange TIMERANGE] [--max-open-trades INT]\n [--stake-amount STAKE_AMOUNT] [--fee FLOAT]\n [--eps] [--dmmp]\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 TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL\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 --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 --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
"},{"location":"bot-usage/#getting-historic-data-for-backtesting","title":"Getting historic data for backtesting","text":"The first time your run Backtesting, you will need to download some historic data first. This can be accomplished by using freqtrade download-data
. Check the corresponding Data Downloading section for more details
To optimize your strategy, you can use hyperopt parameter hyperoptimization to find optimal parameter values for your stategy.
usage: freqtrade hyperopt [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]\n [--userdir PATH] [-s NAME] [--strategy-path PATH]\n [-i TICKER_INTERVAL] [--timerange TIMERANGE]\n [--max-open-trades INT]\n [--stake-amount STAKE_AMOUNT] [--fee FLOAT]\n [--hyperopt NAME] [--hyperopt-path PATH] [--eps]\n [-e INT]\n [--spaces {all,buy,sell,roi,stoploss,trailing,default} [{all,buy,sell,roi,stoploss,trailing,default} ...]]\n [--dmmp] [--print-all] [--no-color] [--print-json]\n [-j JOBS] [--random-state INT] [--min-trades INT]\n [--continue] [--hyperopt-loss NAME]\n\noptional arguments:\n -h, --help show this help message and exit\n -i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL\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 --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 -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 --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 --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 best result detailization 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 --continue Continue hyperopt from previous runs. By default,\n temporary files will be removed and hyperopt will\n start from scratch.\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: DefaultHyperOptLoss,\n OnlyProfitHyperOptLoss, SharpeHyperOptLoss,\n SharpeHyperOptLossDaily.(default:\n `DefaultHyperOptLoss`).\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
"},{"location":"bot-usage/#edge-commands","title":"Edge commands","text":"To know your trade expectancy and winrate against historical data, you can use Edge.
usage: freqtrade edge [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH]\n [--userdir PATH] [-s NAME] [--strategy-path PATH]\n [-i TICKER_INTERVAL] [--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 TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL\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
To understand edge and how to read the results, please read the edge documentation.
"},{"location":"bot-usage/#next-step","title":"Next step","text":"The optimal strategy of the bot will change with time depending of the market trends. The next step is to Strategy Customization.
"},{"location":"configuration/","title":"Configure the bot","text":"Freqtrade has many configurable features and possibilities. By default, these settings are configured via the configuration file (see below).
"},{"location":"configuration/#the-freqtrade-configuration-file","title":"The Freqtrade configuration file","text":"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).
Per default, the bot loads the configuration from the config.json
file, located in the current working directory.
You can specify a different configuration file used by the bot with the -c/--config
command line option.
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.
If you used the Quick start method for installing the bot, the installation script should have already created the default configuration file (config.json
) for you.
If default configuration file is not created we recommend you to copy and use the config.json.example
as a template for your bot configuration.
The Freqtrade configuration file is to be written in the JSON format.
Additionally to the standard JSON syntax, you may use one-line // ...
and multi-line /* ... */
comments in your configuration files and trailing commas in the lists of parameters.
Do not worry if you are not familiar with JSON format -- simply open the configuration file with an editor of your choice, make some changes to the parameters you need, save your changes and, finally, restart the bot or, if it was previously stopped, run it again with the changes you made to the configuration. The bot validates syntax of the configuration file at startup and will warn you if you made any errors editing it, pointing out problematic lines.
"},{"location":"configuration/#configuration-parameters","title":"Configuration parameters","text":"The table below will list all configuration parameters available.
Freqtrade can also load many options via command line (CLI) arguments (check out the commands --help
output for details). The prevelance for all Options is as follows:
Mandatory parameters are marked as Required, which means that they are required to be set in one of the possible ways.
Parameter Descriptionmax_open_trades
Required. Number of trades open your bot will have. If -1 then it is ignored (i.e. potentially unlimited open trades). More information below. Datatype: Positive integer or -1. stake_currency
Required. Crypto-currency used for trading. Strategy Override. Datatype: String stake_amount
Required. Amount of crypto-currency your bot will use for each trade. Set it to \"unlimited\"
to allow the bot to use all available balance. More information below. Strategy Override. Datatype: Positive float or \"unlimited\"
. tradable_balance_ratio
Ratio of the total account balance the bot is allowed to trade. More information below. Defaults to 0.99
99%). Datatype: Positive float between 0.1
and 1.0
. amend_last_stake_amount
Use reduced last stake amount if necessary. More information below. Defaults to false
. Datatype: Boolean last_stake_amount_min_ratio
Defines minimum stake amount that has to be left and executed. Applies only to the last stake amount when it's amended to a reduced value (i.e. if amend_last_stake_amount
is set to true
). More information below. Defaults to 0.5
. Datatype: Float (as ratio) amount_reserve_percent
Reserve some amount in min pair stake amount. The bot will reserve amount_reserve_percent
+ stoploss value when calculating min pair stake amount in order to avoid possible trade refusals. Defaults to 0.05
(5%). Datatype: Positive Float as ratio. ticker_interval
The ticker interval to use (e.g 1m
, 5m
, 15m
, 30m
, 1h
...). Strategy Override. Datatype: String fiat_display_currency
Fiat currency used to show your profits. More information below. Datatype: String dry_run
Required. Define if the bot must be in Dry Run or production mode. Defaults to true
. Datatype: Boolean dry_run_wallet
Define the starting amount in stake currency for the simulated wallet used by the bot running in the Dry Run mode.Defaults to 1000
. Datatype: Float process_only_new_candles
Enable processing of indicators only when new candles arrive. If false each loop populates the indicators, this will mean the same candle is processed many times creating system load but can be useful of your strategy depends on tick data not only candle. Strategy Override. Defaults to false
. Datatype: Boolean minimal_roi
Required. Set the threshold in percent the bot will use to sell a trade. More information below. Strategy Override. Datatype: Dict stoploss
Required. Value of the stoploss in percent used by the bot. More details in the stoploss documentation. Strategy Override. Datatype: Float (as ratio) trailing_stop
Enables trailing stoploss (based on stoploss
in either configuration or strategy file). More details in the stoploss documentation. Strategy Override. Datatype: Boolean trailing_stop_positive
Changes stoploss once profit has been reached. More details in the stoploss documentation. Strategy Override. Datatype: Float trailing_stop_positive_offset
Offset on when to apply trailing_stop_positive
. Percentage value which should be positive. More details in the stoploss documentation. Strategy Override. Defaults to 0.0
(no offset). Datatype: Float trailing_only_offset_is_reached
Only apply trailing stoploss when the offset is reached. stoploss documentation. Strategy Override. Defaults to false
. Datatype: Boolean unfilledtimeout.buy
Required. How long (in minutes) the bot will wait for an unfilled buy order to complete, after which the order will be cancelled. Strategy Override. Datatype: Integer unfilledtimeout.sell
Required. How long (in minutes) the bot will wait for an unfilled sell order to complete, after which the order will be cancelled. Strategy Override. Datatype: Integer bid_strategy.ask_last_balance
Required. Set the bidding price. More information below. bid_strategy.use_order_book
Enable buying using the rates in Order Book Bids. Datatype: Boolean bid_strategy.order_book_top
Bot will use the top N rate in Order Book Bids to buy. I.e. a value of 2 will allow the bot to pick the 2nd bid rate in Order Book Bids. Defaults to 1
. Datatype: Positive Integer bid_strategy. check_depth_of_market.enabled
Do not buy if the difference of buy orders and sell orders is met in Order Book. Check market depth. Defaults to false
. Datatype: Boolean bid_strategy. check_depth_of_market.bids_to_ask_delta
The difference ratio of buy orders and sell orders found in Order Book. A value below 1 means sell order size is greater, while value greater than 1 means buy order size is higher. Check market depth Defaults to 0
. Datatype: Float (as ratio) ask_strategy.use_order_book
Enable selling of open trades using Order Book Asks. Datatype: Boolean ask_strategy.order_book_min
Bot will scan from the top min to max Order Book Asks searching for a profitable rate. Defaults to 1
. Datatype: Positive Integer ask_strategy.order_book_max
Bot will scan from the top min to max Order Book Asks searching for a profitable rate. Defaults to 1
. Datatype: Positive Integer ask_strategy.use_sell_signal
Use sell signals produced by the strategy in addition to the minimal_roi
. Strategy Override. Defaults to true
. Datatype: Boolean ask_strategy.sell_profit_only
Wait until the bot makes a positive profit before taking a sell decision. Strategy Override. Defaults to false
. Datatype: Boolean ask_strategy.ignore_roi_if_buy_signal
Do not sell if the buy signal is still active. This setting takes preference over minimal_roi
and use_sell_signal
. Strategy Override. Defaults to false
. Datatype: Boolean order_types
Configure order-types depending on the action (\"buy\"
, \"sell\"
, \"stoploss\"
, \"stoploss_on_exchange\"
). More information below. Strategy Override. Datatype: Dict order_time_in_force
Configure time in force for buy and sell orders. More information below. Strategy Override. Datatype: Dict exchange.name
Required. Name of the exchange class to use. List below. Datatype: String exchange.sandbox
Use the 'sandbox' version of the exchange, where the exchange provides a sandbox for risk-free integration. See here in more details. Datatype: Boolean exchange.key
API key to use for the exchange. Only required when you are in production mode.Keep it in secret, do not disclose publicly. Datatype: String exchange.secret
API secret to use for the exchange. Only required when you are in production mode.Keep it in secret, do not disclose publicly. Datatype: String exchange.password
API password to use for the exchange. Only required when you are in production mode and for exchanges that use password for API requests.Keep it in secret, do not disclose publicly. Datatype: String exchange.pair_whitelist
List of pairs to use by the bot for trading and to check for potential trades during backtesting. Not used by VolumePairList (see below). Datatype: List exchange.pair_blacklist
List of pairs the bot must absolutely avoid for trading and backtesting (see below). Datatype: List exchange.ccxt_config
Additional CCXT parameters passed to the regular ccxt instance. Parameters may differ from exchange to exchange and are documented in the ccxt documentation Datatype: Dict exchange.ccxt_async_config
Additional CCXT parameters passed to the async ccxt instance. Parameters may differ from exchange to exchange and are documented in the ccxt documentation Datatype: Dict exchange.markets_refresh_interval
The interval in minutes in which markets are reloaded. Defaults to 60
minutes. Datatype: Positive Integer edge.*
Please refer to edge configuration document for detailed explanation. experimental.block_bad_exchanges
Block exchanges known to not work with freqtrade. Leave on default unless you want to test if that exchange works now. Defaults to true
. Datatype: Boolean pairlists
Define one or more pairlists to be used. More information below. Defaults to StaticPairList
. Datatype: List of Dicts telegram.enabled
Enable the usage of Telegram. Datatype: Boolean telegram.token
Your Telegram bot token. Only required if telegram.enabled
is true
. Keep it in secret, do not disclose publicly. Datatype: String telegram.chat_id
Your personal Telegram account id. Only required if telegram.enabled
is true
. Keep it in secret, do not disclose publicly. Datatype: String webhook.enabled
Enable usage of Webhook notifications Datatype: Boolean webhook.url
URL for the webhook. Only required if webhook.enabled
is true
. See the webhook documentation for more details. Datatype: String webhook.webhookbuy
Payload to send on buy. Only required if webhook.enabled
is true
. See the webhook documentation for more details. Datatype: String webhook.webhookbuycancel
Payload to send on buy order cancel. Only required if webhook.enabled
is true
. See the webhook documentation for more details. Datatype: String webhook.webhooksell
Payload to send on sell. Only required if webhook.enabled
is true
. See the webhook documentation for more details. Datatype: String webhook.webhooksellcancel
Payload to send on sell order cancel. Only required if webhook.enabled
is true
. See the webhook documentation for more details. Datatype: String webhook.webhookstatus
Payload to send on status calls. Only required if webhook.enabled
is true
. See the webhook documentation for more details. Datatype: String api_server.enabled
Enable usage of API Server. See the API Server documentation for more details. Datatype: Boolean api_server.listen_ip_address
Bind IP address. See the API Server documentation for more details. Datatype: IPv4 api_server.listen_port
Bind Port. See the API Server documentation for more details. Datatype: Integer between 1024 and 65535 api_server.username
Username for API server. See the API Server documentation for more details. Keep it in secret, do not disclose publicly. Datatype: String api_server.password
Password for API server. See the API Server documentation for more details. Keep it in secret, do not disclose publicly. Datatype: String db_url
Declares database URL to use. NOTE: This defaults to sqlite:///tradesv3.dryrun.sqlite
if dry_run
is true
, and to sqlite:///tradesv3.sqlite
for production instances. Datatype: String, SQLAlchemy connect string initial_state
Defines the initial application state. More information below. Defaults to stopped
. Datatype: Enum, either stopped
or running
forcebuy_enable
Enables the RPC Commands to force a buy. More information below. Datatype: Boolean strategy
Required Defines Strategy class to use. Recommended to be set via --strategy NAME
. Datatype: ClassName strategy_path
Adds an additional strategy lookup path (must be a directory). Datatype: String internals.process_throttle_secs
Set the process throttle. Value in second. Defaults to 5
seconds. Datatype: Positive Intege internals.heartbeat_interval
Print heartbeat message every N seconds. Set to 0 to disable heartbeat messages. Defaults to 60
seconds. Datatype: Positive Integer or 0 internals.sd_notify
Enables use of the sd_notify protocol to tell systemd service manager about changes in the bot state and issue keep-alive pings. See here for more details. Datatype: Boolean logfile
Specifies logfile name. Uses a rolling strategy for log file rotation for 10 files with the 1MB limit per file. Datatype: String user_data_dir
Directory containing user data. Defaults to ./user_data/
. Datatype: String dataformat_ohlcv
Data format to use to store OHLCV historic data. Defaults to json
. Datatype: String dataformat_trades
Data format to use to store trades historic data. Defaults to jsongz
. Datatype: String"},{"location":"configuration/#parameters-in-the-strategy","title":"Parameters in the strategy","text":"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.
minimal_roi
ticker_interval
stoploss
trailing_stop
trailing_stop_positive
trailing_stop_positive_offset
trailing_only_offset_is_reached
process_only_new_candles
order_types
order_time_in_force
stake_currency
stake_amount
unfilledtimeout
use_sell_signal
(ask_strategy)sell_profit_only
(ask_strategy)ignore_roi_if_buy_signal
(ask_strategy)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.
"},{"location":"configuration/#available-balance","title":"Available balance","text":"By default, the bot assumes that the complete amount - 1%
is at it's disposal, and when using dynamic stake amount, it will split the complete balance into max_open_trades
buckets per trade. Freqtrade will reserve 1% for eventual fees when entering a trade and will therefore not touch that by default.
You can configure the \"untouched\" amount by using the tradable_balance_ratio
setting.
For example, if you have 10 ETH available in your wallet on the exchange and tradable_balance_ratio=0.5
(which is 50%), then the bot will use a maximum amount of 5 ETH for trading and considers this as available balance. The rest of the wallet is untouched by the trades.
Warning
The tradable_balance_ratio
setting applies to the current balance (free balance + tied up in trades). Therefore, assuming the starting balance of 1000, a configuration with tradable_balance_ratio=0.99
will not guarantee that 10 currency units will always remain available on the exchange. For example, the free amount may reduce to 5 units if the total balance is reduced to 500 (either by a losing streak, or by withdrawing balance).
Assuming we have the tradable balance of 1000 USDT, stake_amount=400
, and max_open_trades=3
. The bot would open 2 trades, and will be unable to fill the last trading slot, since the requested 400 USDT are no longer available, since 800 USDT are already tied in other trades.
To overcome this, the option amend_last_stake_amount
can be set to True
, which will enable the bot to reduce stake_amount to the available balance in order to fill the last trade slot.
In the example above this would mean:
Note
This option only applies with Static stake amount - since Dynamic stake amount divides the balances evenly.
Note
The minimum last stake amount can be configured using amend_last_stake_amount
- which defaults to 0.5 (50%). This means that the minimum stake amount that's ever used is stake_amount * 0.5
. This avoids very low stake amounts, that are close to the minimum tradable amount for the pair and can be refused by the exchange.
The stake_amount
configuration statically configures the amount of stake-currency your bot will use for each trade.
The minimal configuration value is 0.0001, however, please check your exchange's trading minimums for the stake currency you're using to avoid problems.
This setting works in combination with max_open_trades
. The maximum capital engaged in trades is stake_amount * max_open_trades
. For example, the bot will at most use (0.05 BTC x 3) = 0.15 BTC, assuming a configuration of max_open_trades=3
and stake_amount=0.05
.
Note
This setting respects the available balance configuration.
"},{"location":"configuration/#dynamic-stake-amount","title":"Dynamic stake amount","text":"Alternatively, you can use a dynamic stake amount, which will use the available balance on the exchange, and divide that equally by the amount of allowed trades (max_open_trades
).
To configure this, set stake_amount=\"unlimited\"
. We also recommend to set tradable_balance_ratio=0.99
(99%) - to keep a minimum balance for eventual fees.
In this case a trade amount is calculated as:
currency_balance / (max_open_trades - current_open_trades)\n
To allow the bot to trade all the available stake_currency
in your account (minus tradable_balance_ratio
) set
\"stake_amount\" : \"unlimited\",\n\"tradable_balance_ratio\": 0.99,\n
Note
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).
When using Dry-Run Mode
When using \"stake_amount\" : \"unlimited\",
in combination with Dry-Run, the balance will be simulated starting with a stake of dry_run_wallet
which will evolve over time. It is therefore important to set dry_run_wallet
to a sensible value (like 0.05 or 0.01 for BTC and 1000 or 100 for USDT, for example), otherwise it may simulate trades with 100 BTC (or more) or 0.05 USDT (or less) at once - which may not correspond to your real available balance or is less than the exchange minimal limit for the order amount for the stake currency.
The minimal_roi
configuration parameter is a JSON object where the key is a duration in minutes and the value is the minimum ROI in percent. See the example below:
\"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
Most of the strategy files already include the optimal minimal_roi
value. This parameter can be set in either Strategy or Configuration file. If you use it in the configuration file, it will override the minimal_roi
value from the strategy file. If it is not set in either Strategy or Configuration, a default of 1000% {\"0\": 10}
is used, and minimal roi is disabled unless your trade generates 1000% profit.
Special case to forcesell after a specific time
A special case presents using \"<N>\": -1
as ROI. This forces the bot to sell a trade after N Minutes, no matter if it's positive or negative, so represents a time-limited force-sell.
Go to the stoploss documentation for more details.
"},{"location":"configuration/#understand-trailing-stoploss","title":"Understand trailing stoploss","text":"Go to the trailing stoploss Documentation for details on trailing stoploss.
"},{"location":"configuration/#understand-initial_state","title":"Understand initial_state","text":"The initial_state
configuration parameter is an optional field that defines the initial application state. Possible values are running
or stopped
. (default=running
) If the value is stopped
the bot has to be started with /start
first.
The forcebuy_enable
configuration parameter enables the usage of forcebuy commands via Telegram. This is disabled for security reasons by default, and will show a warning message on startup if enabled. For example, you can send /forcebuy ETH/BTC
Telegram command when this feature if enabled to the bot, who then buys the pair and holds it until a regular sell-signal (ROI, stoploss, /forcesell) appears.
This can be dangerous with some strategies, so use with care.
See the telegram documentation for details on usage.
"},{"location":"configuration/#understand-process_throttle_secs","title":"Understand process_throttle_secs","text":"The process_throttle_secs
configuration parameter is an optional field that defines in seconds how long the bot should wait before asking the strategy if we should buy or a sell an asset. After each wait period, the strategy is asked again for every opened trade wether or not we should sell, and for all the remaining pairs (either the dynamic list of pairs or the static list of pairs) if we should buy.
The order_types
configuration parameter maps actions (buy
, sell
, stoploss
) to order-types (market
, limit
, ...) as well as configures stoploss to be on the exchange and defines stoploss on exchange update interval in seconds.
This allows to buy using limit orders, sell using limit-orders, and create stoplosses using 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. If stoploss_on_exchange
and trailing_stop
are both set, then the bot will use stoploss_on_exchange_interval
to check and update the stoploss on exchange periodically. order_types
can be set in the configuration file or in the strategy. order_types
set in the configuration file overwrites values set in the strategy as a whole, so you need to configure the whole order_types
dictionary in one place.
If this is configured, the following 4 values (buy
, sell
, stoploss
and stoploss_on_exchange
) need to be present, otherwise the bot will fail to start.
emergencysell
is an optional value, which defaults to market
and is used when creating stoploss on exchange orders fails. The below is the default which is used if this is not configured in either strategy or configuration file.
Since stoploss_on_exchange
uses limit orders, the exchange needs 2 prices, the stoploss_price and the Limit price. stoploss
defines the stop-price - and limit should be slightly below this. This defaults to 0.99 / 1% (configurable via stoploss_on_exchange_limit_ratio
). Calculation example: we bought the asset at 100. Stop-price is 95, then limit would be 95 * 0.99 = 94.05$
- so the stoploss will happen between 95$ and 94.05$.
Syntax for Strategy:
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
Configuration:
\"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
Note
Not all exchanges support \"market\" orders. The following message will be shown if your exchange does not support market orders: \"Exchange <yourexchange> does not support market orders.\"
Note
Stoploss on exchange interval is not mandatory. Do not change its value if you are unsure of what you are doing. For more information about how stoploss works please refer to the stoploss documentation.
Note
If stoploss_on_exchange
is enabled and the stoploss is cancelled manually on the exchange, then the bot will create a new order.
Warning: stoploss_on_exchange failures
If stoploss on exchange creation fails for some reason, then an \"emergency sell\" is initiated. By default, this will sell the asset using a market order. The order-type for the emergency-sell can be changed by setting the emergencysell
value in the order_types
dictionary - however this is not advised.
The order_time_in_force
configuration parameter defines the policy by which the order is executed on the exchange. Three commonly used time in force are:
GTC (Good Till Canceled):
This is most of the time the default time in force. It means the order will remain on exchange till it is canceled by user. It can be fully or partially fulfilled. If partially fulfilled, the remaining will stay on the exchange till cancelled.
FOK (Full Or Kill):
It means if the order is not executed immediately AND fully then it is canceled by the exchange.
IOC (Immediate Or Canceled):
It is the same as FOK (above) except it can be partially fulfilled. The remaining part is automatically cancelled by the exchange.
The order_time_in_force
parameter contains a dict with buy and sell time in force policy values. This can be set in the configuration file or in the strategy. Values set in the configuration file overwrites values set in the strategy.
The possible values are: gtc
(default), fok
or ioc
.
\"order_time_in_force\": {\n \"buy\": \"gtc\",\n \"sell\": \"gtc\"\n},\n
Warning
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.
"},{"location":"configuration/#exchange-configuration","title":"Exchange configuration","text":"Freqtrade is based on CCXT library that supports over 100 cryptocurrency exchange markets and trading APIs. The complete up-to-date list can be found in the CCXT repo homepage. However, the bot was tested with only Bittrex and Binance.
The bot was tested with the following exchanges:
Feel free to test other exchanges and submit your PR to improve the bot.
"},{"location":"configuration/#sample-exchange-configuration","title":"Sample exchange configuration","text":"A exchange configuration for \"binance\" would look as follows:
\"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
This configuration enables binance, as well as rate limiting to avoid bans from the exchange. \"rateLimit\": 200
defines a wait-event of 0.2s between each call. This can also be completely disabled by setting \"enableRateLimit\"
to false.
Note
Optimal settings for rate limiting depend on the exchange and the size of the whitelist, so an ideal parameter will vary on many other settings. We try to provide sensible defaults per exchange where possible, if you encounter bans please make sure that \"enableRateLimit\"
is enabled and increase the \"rateLimit\"
parameter step by step.
Advanced options can be configured using the _ft_has_params
setting, which will override Defaults and exchange-specific behaviours.
Available options are listed in the exchange-class as _ft_has_default
.
For example, to test the order type FOK
with Kraken, and modify candle_limit to 200 (so you only get 200 candles per call):
\"exchange\": {\n \"name\": \"kraken\",\n \"_ft_has_params\": {\n \"order_time_in_force\": [\"gtc\", \"fok\"],\n \"ohlcv_candle_limit\": 200\n }\n
Warning
Please make sure to fully understand the impacts of these settings before modifying them.
"},{"location":"configuration/#what-values-can-be-used-for-fiat_display_currency","title":"What values can be used for fiat_display_currency?","text":"The fiat_display_currency
configuration parameter sets the base currency to use for the conversion from coin to fiat in the bot Telegram reports.
The valid values are:
\"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
In addition to fiat currencies, a range of cryto currencies are supported.
The valid values are:
\"BTC\", \"ETH\", \"XRP\", \"LTC\", \"BCH\", \"USDT\"\n
"},{"location":"configuration/#prices-used-for-orders","title":"Prices used for orders","text":"Prices for regular orders can be controlled via the parameter structures bid_strategy
for buying and ask_strategy
for selling. Prices are always retrieved right before an order is placed, either by querying the exchange tickers or by using the orderbook data.
Note
Orderbook data used by Freqtrade are the data retrieved from exchange by the ccxt's function fetch_order_book()
, i.e. are usually data from the L2-aggregated orderbook, while the ticker data are the structures returned by the ccxt's fetch_ticker()
/fetch_tickers()
functions. Refer to the ccxt library documentation for more details.
When check depth of market is enabled (bid_strategy.check_depth_of_market.enabled=True
), the buy signals are filtered based on the orderbook depth (sum of all amounts) for each orderbook side.
Orderbook bid
(buy) side depth is then divided by the orderbook ask
(sell) side depth and the resulting delta is compared to the value of the bid_strategy.check_depth_of_market.bids_to_ask_delta
parameter. The buy order is only executed if the orderbook delta is greater than or equal to the configured delta value.
Note
A delta value below 1 means that ask
(sell) orderbook side depth is greater than the depth of the bid
(buy) orderbook side, while a value greater than 1 means opposite (depth of the buy side is higher than the depth of the sell side).
When buying with the orderbook enabled (bid_strategy.use_order_book=True
), Freqtrade fetches the bid_strategy.order_book_top
entries from the orderbook and then uses the entry specified as bid_strategy.order_book_top
on the bid
(buy) side of the orderbook. 1 specifies the topmost entry in the orderbook, while 2 would use the 2nd entry in the orderbook, and so on.
When not using orderbook (bid_strategy.use_order_book=False
), Freqtrade uses the best ask
(sell) price from the ticker if it's below the last
traded price from the ticker. Otherwise (when the ask
price is not below the last
price), it calculates a rate between ask
and last
price.
The bid_strategy.ask_last_balance
configuration parameter controls this. A value of 0.0
will use ask
price, while 1.0
will use the last
price and values between those interpolate between ask and last price.
Using ask
price often guarantees quicker success in the bid, but the bot can also end up paying more than what would have been necessary.
When selling with the orderbook enabled (ask_strategy.use_order_book=True
), Freqtrade fetches the ask_strategy.order_book_max
entries in the orderbook. Then each of the orderbook steps between ask_strategy.order_book_min
and ask_strategy.order_book_max
on the ask
orderbook side are validated for a profitable sell-possibility based on the strategy configuration and the sell order is placed at the first profitable spot.
The idea here is to place the sell order early, to be ahead in the queue.
A fixed slot (mirroring bid_strategy.order_book_top
) can be defined by setting ask_strategy.order_book_min
and ask_strategy.order_book_max
to the same number.
Orderbook and stoploss_on_exchange
Using ask_strategy.order_book_max
higher than 1 may increase the risk, since an eventual stoploss on exchange will be needed to be cancelled as soon as the order is placed.
When not using orderbook (ask_strategy.use_order_book=False
), the bid
price from the ticker will be used as the sell price.
Pairlists define the list of pairs that the bot should trade. There are StaticPairList
and dynamic Whitelists available.
PrecisionFilter
and PriceFilter
act as filters, removing low-value pairs.
All pairlists can be chained, and a combination of all pairlists will become your new whitelist. Pairlists are executed in the sequence they are configured. You should always configure either StaticPairList
or DynamicPairList
as starting pairlists.
Inactive markets and blacklisted pairs are always removed from the resulting pair_whitelist
.
StaticPairList
(default, if not configured differently)VolumePairList
PrecisionFilter
PriceFilter
SpreadFilter
Testing pairlists
Pairlist configurations can be quite tricky to get right. Best use the test-pairlist
subcommand to test your configuration quickly.
By default, the StaticPairList
method is used, which uses a statically defined pair whitelist from the configuration.
It uses configuration from exchange.pair_whitelist
and exchange.pair_blacklist
.
\"pairlists\": [\n {\"method\": \"StaticPairList\"}\n ],\n
"},{"location":"configuration/#volume-pair-list","title":"Volume Pair List","text":"VolumePairList
selects number_assets
top pairs based on sort_key
, which can be one of askVolume
, bidVolume
and quoteVolume
and defaults to quoteVolume
.
VolumePairList
considers outputs of previous pairlists unless it's the first configured pairlist, it does not consider pair_whitelist
, but selects the top assets from all available markets (with matching stake-currency) on the exchange.
refresh_period
allows setting the period (in seconds), at which the pairlist will be refreshed. Defaults to 1800s (30 minutes).
\"pairlists\": [{\n \"method\": \"VolumePairList\",\n \"number_assets\": 20,\n \"sort_key\": \"quoteVolume\",\n \"refresh_period\": 1800,\n],\n
"},{"location":"configuration/#precision-filter","title":"Precision Filter","text":"Filters low-value coins which would not allow setting a stoploss.
"},{"location":"configuration/#price-pair-filter","title":"Price Pair Filter","text":"The PriceFilter
allows filtering of pairs by price. Currently, only low_price_ratio
is implemented, where a raise of 1 price unit (pip) is below the low_price_ratio
ratio. This option is disabled by default, and will only apply if set to <> 0.
Calculation example: Min price precision is 8 decimals. If price is 0.00000011 - one step would be 0.00000012 - which is almost 10% higher than the previous value.
These pairs are dangerous since it may be impossible to place the desired stoploss - and often result in high losses.
"},{"location":"configuration/#spread-filter","title":"Spread Filter","text":"Removes pairs that have a difference between asks and bids above the specified ratio (default 0.005
). Example: If DOGE/BTC
maximum bid is 0.00000026 and minimum ask is 0.00000027 the ratio is calculated as: 1 - bid/ask ~= 0.037
which is > 0.005
The below example blacklists BNB/BTC
, uses VolumePairList
with 20
assets, sorting by quoteVolume
and applies both PrecisionFilter
and PriceFilter
, filtering all assets where 1 priceunit is > 1%.
\"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\": \"PrecisionFilter\"},\n {\"method\": \"PriceFilter\", \"low_price_ratio\": 0.01}\n ],\n
"},{"location":"configuration/#switch-to-dry-run-mode","title":"Switch to Dry-run mode","text":"We recommend starting the bot in the Dry-run mode to see how your bot will behave and what is the performance of your strategy. In the Dry-run mode the bot does not engage your money. It only runs a live simulation without creating trades on the exchange.
config.json
configuration file.dry-run
to true
and specify db_url
for a persistence database.\"dry_run\": true,\n\"db_url\": \"sqlite:///tradesv3.dryrun.sqlite\",\n
\"exchange\": {\n \"name\": \"bittrex\",\n \"key\": \"key\",\n \"secret\": \"secret\",\n ...\n}\n
Once you will be happy with your bot performance running in the Dry-run mode, you can switch it to production mode.
Note
A simulated wallet is available during dry-run mode, and will assume a starting capital of dry_run_wallet
(defaults to 1000).
/balance
) are simulated.stoploss_on_exchange
, the stop_loss price is assumed to be filled.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.
"},{"location":"configuration/#setup-your-exchange-account","title":"Setup your exchange account","text":"You will need to create API Keys (usually you get key
and secret
, some exchanges require an additional password
) from the Exchange website and you'll need to insert this into the appropriate fields in the configuration or when asked by the freqtrade new-config
command. API Keys are usually only required for live trading (trading for real money, bot running in \"production mode\", executing real orders on the exchange) and are not required for the bot running in dry-run (trade simulation) mode. When you setup the bot in dry-run mode, you may fill these fields with empty values.
Edit your config.json
file.
Switch dry-run to false and don't forget to adapt your database URL if set:
\"dry_run\": false,\n
Insert your Exchange API key (change them by fake api keys):
\"exchange\": {\n \"name\": \"bittrex\",\n \"key\": \"af8ddd35195e9dc500b9a6f799f6f5c93d89193b\",\n \"secret\": \"08a9dc6db3d7b53e1acebd9275677f4b0a04f1a5\",\n ...\n}\n
You should also make sure to read the Exchanges section of the documentation to be aware of potential configuration details specific to your exchange.
"},{"location":"configuration/#using-proxy-with-freqtrade","title":"Using proxy with Freqtrade","text":"To use a proxy with freqtrade, add the kwarg \"aiohttp_trust_env\"=true
to the \"ccxt_async_kwargs\"
dict in the exchange section of the configuration.
An example for this can be found in config_full.json.example
\"ccxt_async_config\": {\n \"aiohttp_trust_env\": true\n}\n
Then, export your proxy settings using the variables \"HTTP_PROXY\"
and \"HTTPS_PROXY\"
set to the appropriate values
export HTTP_PROXY=\"http://addr:port\"\nexport HTTPS_PROXY=\"http://addr:port\"\nfreqtrade\n
"},{"location":"configuration/#embedding-strategies","title":"Embedding Strategies","text":"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.
"},{"location":"configuration/#encoding-a-string-as-base64","title":"Encoding a string as BASE64","text":"This is a quick example, how to generate the BASE64 string in python
from base64 import urlsafe_b64encode\n\nwith open(file, 'r') as f:\n content = f.read()\ncontent = urlsafe_b64encode(content.encode('utf-8'))\n
The variable 'content', will contain the strategy file in a BASE64 encoded form. Which can now be set in your configurations file as following
\"strategy\": \"NameOfStrategy:BASE64String\"\n
Please ensure that 'NameOfStrategy' is identical to the strategy name!
"},{"location":"configuration/#next-step","title":"Next step","text":"Now you have configured your config.json, the next step is to start your bot.
"},{"location":"data-analysis/","title":"Analyzing bot data with Jupyter notebooks","text":"You can analyze the results of backtests and trading history easily using Jupyter notebooks. Sample notebooks are located at user_data/notebooks/
.
Sometimes it can be desired to use a system-wide installation of Jupyter notebook, and use a jupyter kernel from the virtual environment. This prevents you from installing the full jupyter suite multiple times per system, and provides an easy way to switch between tasks (freqtrade / other analytics tasks).
For this to work, first activate your virtual environment and run the following commands:
# 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
Note
This section is provided for completeness, the Freqtrade Team won't provide full support for problems with this setup and will recommend to install Jupyter in the virtual environment directly, as that is the easiest way to get jupyter notebooks up and running. For help with this setup please refer to the Project Jupyter documentation or help channels.
"},{"location":"data-analysis/#fine-print","title":"Fine print","text":"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.
"},{"location":"data-analysis/#recommended-workflow","title":"Recommended workflow","text":"Task Tool Bot operations CLI Repetitive tasks Shell scripts Data analysis & visualization NotebookUse the CLI to * download historical data * run a backtest * run with real-time data * export results
Collect these actions in shell scripts * save complicated commands with arguments * execute multi-step operations * automate testing strategies and preparing data for analysis
Use a notebook to * visualize data * munge and plot to generate insights
Jupyter notebooks execute from the notebook directory. The following snippet searches for the project root, so relative paths remain consistent.
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
"},{"location":"data-analysis/#load-multiple-configuration-files","title":"Load multiple configuration files","text":"This option can be useful to inspect the results of passing in multiple configs. This will also run through the whole Configuration initialization, so the configuration is completely initialized to be passed to other methods.
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
For Interactive environments, have an additional configuration specifying user_data_dir
and pass this in last, so you don't have to change directories while running the bot. Best avoid relative paths, since this starts at the storage location of the jupyter notebook, unless the directory is changed.
{\n \"user_data_dir\": \"~/.freqtrade/\"\n}\n
"},{"location":"data-analysis/#further-data-analysis-documentation","title":"Further Data analysis documentation","text":"user_data/notebooks/strategy_analysis_example.ipynb
)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.
"},{"location":"data-download/","title":"Data Downloading","text":""},{"location":"data-download/#getting-data-for-backtesting-and-hyperopt","title":"Getting data for backtesting and hyperopt","text":"To download data (candles / OHLCV) needed for backtesting and hyperoptimization use the freqtrade download-data
command.
If no additional parameter is specified, freqtrade will download data for \"1m\"
and \"5m\"
timeframes for the last 30 days. Exchange and pairs will come from config.json
(if specified using -c/--config
). Otherwise --exchange
becomes mandatory.
Tip: Updating existing data
If you already have backtesting data available in your data-directory and would like to refresh this data up to today, use --days xx
with a number slightly higher than the missing number of days. Freqtrade will keep the available data and only download the missing data. Be carefull 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.
usage: freqtrade download-data [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-p PAIRS [PAIRS ...]]\n [--pairs-file FILE] [--days INT] [--dl-trades] [--exchange EXCHANGE]\n [-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} ...]]\n [--erase] [--data-format-ohlcv {json,jsongz}] [--data-format-trades {json,jsongz}]\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-separated.\n --pairs-file FILE File containing a list of pairs to download.\n --days INT Download data for given number of days.\n --dl-trades Download trades instead of OHLCV data. The bot will resample trades to the desired timeframe as specified as\n --timeframes/-t.\n --exchange EXCHANGE Exchange name (default: `bittrex`). Only valid if no config is provided.\n -t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} ...], --timeframes {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} ...]\n Specify which tickers to download. Space-separated list. Default: `1m 5m`.\n --erase Clean all existing data for the selected exchange/pairs/timeframes.\n --data-format-ohlcv {json,jsongz}\n Storage format for downloaded ohlcv data. (default: `json`).\n --data-format-trades {json,jsongz}\n Storage format for downloaded trades data. (default: `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: '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
"},{"location":"data-download/#data-format","title":"Data format","text":"Freqtrade currently supports 2 dataformats, json
(plain \"text\" json files) and jsongz
(a gzipped version of json files). By default, OHLCV data is stored as json
data, while trades data is stored as jsongz
data.
This can be changed via the --data-format-ohlcv
and --data-format-trades
parameters respectivly.
If the default dataformat has been changed during download, then the keys dataformat_ohlcv
and dataformat_trades
in the configuration file need to be adjusted to the selected dataformat as well.
Note
You can convert between data-formats using the convert-data and convert-trade-data methods.
"},{"location":"data-download/#subcommand-convert-data","title":"Subcommand convert data","text":"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} --format-to {json,jsongz}\n [--erase]\n [-t {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} ...]]\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}\n Source format for data conversion.\n --format-to {json,jsongz}\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} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} ...], --timeframes {1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} [{1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w} ...]\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: `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
"},{"location":"data-download/#example-converting-data","title":"Example converting data","text":"The following command will convert all ohlcv (candle) data available in ~/.freqtrade/data/binance
from json to jsongz, saving diskspace in the process. It'll also remove original json data files (--erase
parameter).
freqtrade convert-data --format-from json --format-to jsongz --data-dir ~/.freqtrade/data/binance -t 5m 15m --erase\n
"},{"location":"data-download/#subcommand-convert-trade-data","title":"Subcommand convert-trade data","text":"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} --format-to {json,jsongz}\n [--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}\n Source format for data conversion.\n --format-to {json,jsongz}\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: `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
"},{"location":"data-download/#example-converting-trades","title":"Example converting trades","text":"The following command will convert all available trade-data in ~/.freqtrade/data/kraken
from jsongz to json. It'll also remove original jsongz data files (--erase
parameter).
freqtrade convert-trade-data --format-from jsongz --format-to json --data-dir ~/.freqtrade/data/kraken --erase\n
"},{"location":"data-download/#pairs-file","title":"Pairs file","text":"In alternative to the whitelist from config.json
, a pairs.json
file can be used.
If you are using Binance for example:
user_data/data/binance
and copy or create the pairs.json
file in that directory.pairs.json
file to contain the currency pairs you are interested in.mkdir -p user_data/data/binance\ncp freqtrade/tests/testdata/pairs.json user_data/data/binance\n
The format of the pairs.json
file is a simple json list. Mixing different stake-currencies is allowed for this file, since it's only used for downloading.
[\n \"ETH/BTC\",\n \"ETH/USDT\",\n \"BTC/USDT\",\n \"XRP/ETH\"\n]\n
"},{"location":"data-download/#start-download","title":"Start download","text":"Then run:
freqtrade download-data --exchange binance\n
This will download ticker data for all the currency pairs you defined in pairs.json
.
--datadir user_data/data/some_directory
.pairs.json
from some other directory, use --pairs-file some_other_dir/pairs.json
.--days 10
(defaults to 30 days).--timeframes
to specify which tickers to download. Default is --timeframes 1m 5m
which will download 1-minute and 5-minute tickers.-c/--config
option. With this, the script uses the whitelist defined in the config as the list of currency pairs to download data for and does not require the pairs.json file. You can combine -c/--config
with most other options.By default, download-data
subcommand downloads Candles (OHLCV) data. Some exchanges also provide historic trade-data via their API. This data can be useful if you need many different timeframes, since it is only downloaded once, and then resampled locally to the desired timeframes.
Since this data is large by default, the files use gzip by default. They are stored in your data-directory with the naming convention of <pair>-trades.json.gz
(ETH_BTC-trades.json.gz
). Incremental mode is also supported, as for historic OHLCV data, so downloading the data once per week with --days 8
will create an incremental data-repository.
To use this mode, simply add --dl-trades
to your call. This will swap the download method to download trades, and resamples the data locally.
Example call:
freqtrade download-data --exchange binance --pairs XRP/ETH ETH/BTC --days 20 --dl-trades\n
Note
While this method uses async calls, it will be slow, since it requires the result of the previous call to generate the next request to the exchange.
Warning
The historic trades are not available during Freqtrade dry-run and live trade modes because all exchanges tested provide this data with a delay of few 100 candles, so it's not suitable for real-time trading.
Kraken user
Kraken users should read this before starting to download data.
"},{"location":"data-download/#next-step","title":"Next step","text":"Great, you now have backtest data downloaded, so you can now start backtesting your strategy.
"},{"location":"deprecated/","title":"Deprecated features","text":"This page contains description of the command line arguments, configuration parameters and the bot features that were declared as DEPRECATED by the bot development team and are no longer supported. Please avoid their usage in your configuration.
"},{"location":"deprecated/#removed-features","title":"Removed features","text":""},{"location":"deprecated/#the-refresh-pairs-cached-command-line-option","title":"the--refresh-pairs-cached
command line option","text":"--refresh-pairs-cached
in the context of backtesting, hyperopt and edge allows to refresh candle data for backtesting. Since this leads to much confusion, and slows down backtesting (while not being part of backtesting) this has been singled out as a seperate freqtrade subcommand freqtrade download-data
.
This command line option was deprecated in 2019.7-dev (develop branch) and removed in 2019.9 (master branch).
"},{"location":"deprecated/#the-dynamic-whitelist-command-line-option","title":"The --dynamic-whitelist command line option","text":"This command line option was deprecated in 2018 and removed freqtrade 2019.6-dev (develop branch) and in freqtrade 2019.7 (master branch).
"},{"location":"deprecated/#the-live-command-line-option","title":"the--live
command line option","text":"--live
in the context of backtesting allowed to download the latest tick data for backtesting. Did only download the latest 500 candles, so was ineffective in getting good backtest data. Removed in 2019-7-dev (develop branch) and in freqtrade 2019-8 (master branch)
This page is intended for developers of Freqtrade, people who want to contribute to the Freqtrade codebase or documentation, or people who want to understand the source code of the application they're running.
All contributions, bug reports, bug fixes, documentation improvements, enhancements and ideas are welcome. We track issues on GitHub and also have a dev channel in slack where you can ask questions.
"},{"location":"developer/#documentation","title":"Documentation","text":"Documentation is available at https://freqtrade.io and needs to be provided with every new feature PR.
Special fields for the documentation (like Note boxes, ...) can be found here.
"},{"location":"developer/#developer-setup","title":"Developer setup","text":"To configure a development environment, best use the setup.sh
script and answer \"y\" when asked \"Do you want to install dependencies for dev [y/N]? \". Alternatively (if your system is not supported by the setup.sh script), follow the manual installation process and run pip3 install -e .[all]
.
This will install all required tools for development, including pytest
, flake8
, mypy
, and coveralls
.
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).
"},{"location":"developer/#checking-log-content-in-tests","title":"Checking log content in tests","text":"Freqtrade uses 2 main methods to check log content in tests, log_has()
and log_has_re()
(to check using regex, in case of dynamic log-messages). These are available from conftest.py
and can be imported in any test module.
A sample check looks as follows:
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
"},{"location":"developer/#local-docker-usage","title":"Local docker usage","text":"The fastest and easiest way to start up is to use docker-compose.develop which gives developers the ability to start the bot up with all the required dependencies, without needing to install any freqtrade specific dependencies on your local machine.
"},{"location":"developer/#install","title":"Install","text":"rm docker-compose.yml && mv docker-compose.develop.yml docker-compose.yml\n
"},{"location":"developer/#docker-compose","title":"Docker Compose","text":""},{"location":"developer/#starting","title":"Starting","text":"docker-compose up\n
"},{"location":"developer/#rebuilding","title":"Rebuilding","text":"docker-compose build\n
"},{"location":"developer/#execing-effectively-ssh-into-the-container","title":"Execing (effectively SSH into the container)","text":"The exec
command requires that the container already be running, if you want to start it that can be effected by docker-compose up
or docker-compose run freqtrade_develop
docker-compose exec freqtrade_develop /bin/bash\n
"},{"location":"developer/#modules","title":"Modules","text":""},{"location":"developer/#dynamic-pairlist","title":"Dynamic Pairlist","text":"You have a great idea for a new pair selection algorithm you would like to try out? Great. Hopefully you also want to contribute this back upstream.
Whatever your motivations are - This should get you off the ground in trying to develop a new Pairlist provider.
First of all, have a look at the VolumePairList provider, and best copy this file with a name of your new Pairlist Provider.
This is a simple provider, which however serves as a good example on how to start developing.
Next, modify the classname of the provider (ideally align this with the Filename).
The base-class provides an instance of the exchange (self._exchange
) the pairlist manager (self._pairlistmanager
), as well as the main configuration (self._config
), the pairlist dedicated configuration (self._pairlistconfig
) and the absolute position within the list of pairlists.
self._exchange = exchange\n self._pairlistmanager = pairlistmanager\n self._config = config\n self._pairlistconfig = pairlistconfig\n self._pairlist_pos = pairlist_pos\n
Now, let's step through the methods which require actions:
"},{"location":"developer/#pairlist-configuration","title":"Pairlist configuration","text":"Configuration for PairListProvider is done in the bot configuration file in the element \"pairlist\"
. This Pairlist-object may contain configurations with additional configurations for the configured pairlist. By convention, \"number_assets\"
is used to specify the maximum number of pairs to keep in the whitelist. Please follow this to ensure a consistent user experience.
Additional elements can be configured as needed. VolumePairList
uses \"sort_key\"
to specify the sorting value - however feel free to specify whatever is necessary for your great algorithm to be successfull and dynamic.
Returns a description used for Telegram messages. This should contain the name of the Provider, as well as a short description containing the number of assets. Please follow the format \"PairlistName - top/bottom X pairs\"
.
Override this method and run all calculations needed in this method. This is called with each iteration of the bot - so consider implementing caching for compute/network heavy calculations.
It get's passed a pairlist (which can be the result of previous pairlists) as well as tickers
, a pre-fetched version of get_tickers()
.
It must return the resulting pairlist (which may then be passed into the next pairlist filter).
Validations are optional, the parent class exposes a _verify_blacklist(pairlist)
and _whitelist_for_active_markets(pairlist)
to do default filters. Use this if you limit your result to a certain number of pairs - so the endresult is not shorter than expected.
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
"},{"location":"developer/#_gen_pair_whitelist","title":"_gen_pair_whitelist","text":"This is a simple method used by VolumePairList
- however serves as a good example. In VolumePairList, this implements different methods of sorting, does early validation so only the expected number of pairs is returned.
Note
This section is a Work in Progress and is not a complete guide on how to test a new exchange with Freqtrade.
Most exchanges supported by CCXT should work out of the box.
"},{"location":"developer/#stoploss-on-exchange","title":"Stoploss On Exchange","text":"Check if the new exchange supports Stoploss on Exchange orders through their API.
Since CCXT does not provide unification for Stoploss On Exchange yet, we'll need to implement the exchange-specific parameters ourselfs. Best look at binance.py
for an example implementation of this. You'll need to dig through the documentation of the Exchange's API on how exactly this can be done. CCXT Issues may also provide great help, since others may have implemented something similar for their projects.
While fetching OHLCV data, we're may end up getting incomplete candles (Depending on the exchange). To demonstrate this, we'll use daily candles (\"1d\"
) to keep things simple. We query the api (ct.fetch_ohlcv()
) for the timeframe and look at the date of the last entry. If this entry changes or shows the date of a \"incomplete\" candle, then we should drop this since having incomplete candles is problematic because indicators assume that only complete candles are passed to them, and will generate a lot of false buy signals. By default, we're therefore removing the last candle assuming it's incomplete.
To check how the new exchange behaves, you can use the following snippet:
import ccxt\nfrom datetime import datetime\nfrom freqtrade.data.converter import parse_ticker_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 = parse_ticker_dataframe(raw, timeframe, pair=pair, drop_incomplete=False)\n\nprint(df1.tail(1))\nprint(datetime.utcnow())\n
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
The output will show the last entry from the Exchange as well as the current UTC date. If the day shows the same day, then the last candle can be assumed as incomplete and should be dropped (leave the setting \"ohlcv_partial_candle\"
from the exchange-class untouched / True). Otherwise, set \"ohlcv_partial_candle\"
to False
to not drop Candles (shown in the example above). Another way is to run this command multiple times in a row and observe if the volume is changing (while the date remains the same).
To keep the jupyter notebooks aligned with the documentation, the following should be ran after updating a example notebook.
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
"},{"location":"developer/#continuous-integration","title":"Continuous integration","text":"This documents some decisions taken for the CI Pipeline.
master
and develop
._pi
- so tags will be :master_pi
and develop_pi
./freqtrade/freqtrade_commit
containing the commit this image is based of.master
or develop
.This part of the documentation is aimed at maintainers, and shows how to create a release.
"},{"location":"developer/#create-release-branch","title":"Create release branch","text":"First, pick a commit that's about one week old (to not include latest additions to releases).
# create new branch\ngit checkout -b new_release <commitid>\n
Determine if crucial bugfixes have been made between this commit and the current state, and eventually cherry-pick these.
freqtrade/__init__.py
and add the version matching the current date (for example 2019.7
for July 2019). Minor versions can be 2019.7-1
should we need to do a second release that month.Note
Make sure that the master branch is uptodate!
# Needs to be done before merging / pulling that branch.\ngit log --oneline --no-decorate --no-merges master..new_release\n
To keep the release-log short, best wrap the full git changelog into a collapsible details secction.
<details>\n<summary>Expand full changelog</summary>\n\n... Full git changelog\n\n</details>\n
"},{"location":"developer/#create-github-release-tag","title":"Create github release / tag","text":"Once the PR against master is merged (best right after merging):
-dev
(2019.6 -> 2019.6-dev
).To create a pypi release, please run the following commands:
Additional requirement: wheel
, twine
(for uploading), account on pypi with proper permissions.
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
Please don't push non-releases to the productive / real pypi instance.
"},{"location":"docker/","title":"Using Freqtrade with Docker","text":""},{"location":"docker/#install-docker","title":"Install Docker","text":"Start by downloading and installing Docker CE for your platform:
Optionally, docker-compose should be installed and available to follow the docker quick start guide.
Once you have Docker installed, simply prepare the config file (e.g. config.json
) and run the image for freqtrade
as explained below.
Freqtrade provides an official Docker image on Dockerhub, as well as a docker-compose file ready for usage.
Note
The following section assumes that docker and docker-compose is installed and available to the logged in user.
Note
All below comands use relative directories and will have to be executed from the directory containing the docker-compose.yml
file.
Create a new directory and place the docker-compose file in this directory.
mkdir ft_userdata\ncd ft_userdata/\n# Download the docker-compose file from the repository\ncurl https://raw.githubusercontent.com/freqtrade/freqtrade/develop/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
The above snippet creates a new directory called \"ft_userdata\", downloads the latest compose file and pulls the freqtrade image. The last 2 steps in the snippet create the directory with user-data, as well as (interactively) the default configuration based on your selections.
Note
You can edit the configuration at any time, which is available as user_data/config.json
(within the directory ft_userdata
) when using the above configuration.
The configuration is now available as user_data/config.json
. You should now copy your strategy to user_data/strategies/
- and add the Strategy class name to the docker-compose.yml
file, replacing SampleStrategy
. If you wish to run the bot with the SampleStrategy, just leave it as it is.
Warning
The SampleStrategy
is there for your reference and give you ideas for your own strategy. Please always backtest the strategy and use dry-run for some time before risking real money!
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).
docker-compose up -d\n
"},{"location":"docker/#docker-compose-logs","title":"Docker-compose logs","text":"Logs will be written to user_data/freqtrade.log
. Alternatively, you can check the latest logs using docker-compose logs -f
.
The database will be in the user_data directory as well, and will be called user_data/tradesv3.sqlite
.
To update freqtrade when using docker-compose is as simple as running the following 2 commands:
# Download the latest image\ndocker-compose pull\n# Restart the image\ndocker-compose up -d\n
This will first pull the latest image, and will then restart the container with the just pulled version.
Note
You should always check the changelog for breaking changes / manual interventions required and make sure the bot starts correctly after the update.
"},{"location":"docker/#going-from-here","title":"Going from here","text":"Advanced users may edit the docker-compose file further to include all possible options or arguments.
All possible freqtrade arguments will be available by running docker-compose run --rm freqtrade <command> <optional arguments>
.
docker-compose run --rm
Including --rm
will clean up the container after completion, and is highly recommended for all modes except trading mode (running with freqtrade trade
command).
Download backtesting data for 5 days for the pair ETH/BTC and 1h timeframe from Binance. The data will be stored in the directory user_data/data/
on the host.
docker-compose run --rm freqtrade download-data --pairs ETH/BTC --exchange binance --days 5 -t 1h\n
Head over to the Data Downloading Documentation for more details on downloading data.
"},{"location":"docker/#example-backtest-with-docker-compose","title":"Example: Backtest with docker-compose","text":"Run backtesting in docker-containers for SampleStrategy and specified timerange of historical data, on 5m timeframe:
docker-compose run --rm freqtrade backtesting --config user_data/config.json --strategy SampleStrategy --timerange 20190801-20191001 -i 5m\n
Head over to the Backtesting Documentation to learn more.
"},{"location":"docker/#additional-dependencies-with-docker-compose","title":"Additional dependencies with docker-compose","text":"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 Dockerfile.technical for an example).
You'll then also need to modify the docker-compose.yml
file and uncomment the build step, as well as rename the image to avoid naming collisions.
image: freqtrade_custom\n build:\n context: .\n dockerfile: \"./Dockerfile.<yourextension>\"\n
You can then run docker-compose build
to build the docker image, and run it using the commands described above.
Warning
The below documentation is provided for completeness and assumes that you are somewhat familiar with running docker containers. If you're just starting out with docker, we recommend to follow the Freqtrade with docker-compose instructions.
"},{"location":"docker/#download-the-official-freqtrade-docker-image","title":"Download the official Freqtrade docker image","text":"Pull the image from docker hub.
Branches / tags available can be checked out on Dockerhub tags page.
docker pull freqtradeorg/freqtrade:develop\n# Optionally tag the repository so the run-commands remain shorter\ndocker tag freqtradeorg/freqtrade:develop freqtrade\n
To update the image, simply run the above commands again and restart your running container.
Should you require additional libraries, please build the image yourself.
Docker image update frequency
The official docker images with tags master
, develop
and latest
are automatically rebuild once a week to keep the base image uptodate. In addition to that, every merge to develop
will trigger a rebuild for develop
and latest
.
Even though you will use docker, you'll still need some files from the github repository.
"},{"location":"docker/#clone-the-git-repository","title":"Clone the git repository","text":"Linux/Mac/Windows with WSL
git clone https://github.com/freqtrade/freqtrade.git\n
Windows with docker
git clone --config core.autocrlf=input https://github.com/freqtrade/freqtrade.git\n
"},{"location":"docker/#copy-configjsonexample-to-configjson","title":"Copy config.json.example
to config.json
","text":"cd freqtrade\ncp -n config.json.example config.json\n
To understand the configuration options, please refer to the Bot Configuration page.
"},{"location":"docker/#create-your-database-file","title":"Create your database file","text":"Production
touch tradesv3.sqlite\n````\n\nDry-Run\n\n```bash\ntouch tradesv3.dryrun.sqlite\n
Note
Make sure to use the path to this file when starting the bot in docker.
"},{"location":"docker/#build-your-own-docker-image","title":"Build your own Docker image","text":"Best start by pulling the official docker image from dockerhub as explained here to speed up building.
To add additional libraries to your docker image, best check out Dockerfile.technical which adds the technical module to the image.
docker build -t freqtrade -f Dockerfile.technical .\n
If you are developing using Docker, use Dockerfile.develop
to build a dev Docker image, which will also set up develop dependencies:
docker build -f Dockerfile.develop -t freqtrade-dev .\n
Note
For security reasons, your configuration file will not be included in the image, you will need to bind mount it. It is also advised to bind mount an SQLite database file (see the \"5. Run a restartable docker image\" section) to keep it between updates.
"},{"location":"docker/#verify-the-docker-image","title":"Verify the Docker image","text":"After the build process you can verify that the image was created with:
docker images\n
The output should contain the freqtrade image.
"},{"location":"docker/#run-the-docker-image","title":"Run the Docker image","text":"You can run a one-off container that is immediately deleted upon exiting with the following command (config.json
must be in the current working directory):
docker run --rm -v `pwd`/config.json:/freqtrade/config.json -it freqtrade\n
Warning
In this example, the database will be created inside the docker instance and will be lost when you will refresh your image.
"},{"location":"docker/#adjust-timezone","title":"Adjust timezone","text":"By default, the container will use UTC timezone. Should you find this irritating please add the following to your docker commands:
"},{"location":"docker/#linux","title":"Linux","text":"-v /etc/timezone:/etc/timezone:ro\n\n# Complete command:\ndocker run --rm -v /etc/timezone:/etc/timezone:ro -v `pwd`/config.json:/freqtrade/config.json -it freqtrade\n
"},{"location":"docker/#macos","title":"MacOS","text":"There is known issue in OSX Docker versions after 17.09.1, whereby /etc/localtime
cannot be shared causing Docker to not start. A work-around for this is to start with the following cmd.
docker run --rm -e TZ=`ls -la /etc/localtime | cut -d/ -f8-9` -v `pwd`/config.json:/freqtrade/config.json -it freqtrade\n
More information on this docker issue and work-around can be read here.
"},{"location":"docker/#run-a-restartable-docker-image","title":"Run a restartable docker image","text":"To run a restartable instance in the background (feel free to place your configuration and database files wherever it feels comfortable on your filesystem).
"},{"location":"docker/#move-your-config-file-and-database","title":"Move your config file and database","text":"The following will assume that you place your configuration / database files to ~/.freqtrade
, which is a hidden directory in your home directory. Feel free to use a different directory and replace the directory in the upcomming commands.
mkdir ~/.freqtrade\nmv config.json ~/.freqtrade\nmv tradesv3.sqlite ~/.freqtrade\n
"},{"location":"docker/#run-the-docker-image_1","title":"Run the docker image","text":"docker run -d \\\n --name freqtrade \\\n -v ~/.freqtrade/config.json:/freqtrade/config.json \\\n -v ~/.freqtrade/user_data/:/freqtrade/user_data \\\n -v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \\\n freqtrade trade --db-url sqlite:///tradesv3.sqlite --strategy MyAwesomeStrategy\n
Note
When using docker, it's best to specify --db-url
explicitly to ensure that the database URL and the mounted database file match.
Note
All available bot command line parameters can be added to the end of the docker run
command.
Note
You can define a restart policy in docker. It can be useful in some cases to use the --restart unless-stopped
flag (crash of freqtrade or reboot of your system).
You can use the following commands to monitor and manage your container:
docker logs freqtrade\ndocker logs -f freqtrade\ndocker restart freqtrade\ndocker stop freqtrade\ndocker start freqtrade\n
For more information on how to operate Docker, please refer to the official Docker documentation.
Note
You do not need to rebuild the image for configuration changes, it will suffice to edit config.json
and restart the container.
The following assumes that the download/setup of the docker image have been completed successfully. Also, backtest-data should be available at ~/.freqtrade/user_data/
.
docker run -d \\\n --name freqtrade \\\n -v /etc/localtime:/etc/localtime:ro \\\n -v ~/.freqtrade/config.json:/freqtrade/config.json \\\n -v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \\\n -v ~/.freqtrade/user_data/:/freqtrade/user_data/ \\\n freqtrade backtesting --strategy AwsomelyProfitableStrategy\n
Head over to the Backtesting Documentation for more details.
Note
Additional bot command line parameters can be appended after the image name (freqtrade
in the above example).
This page explains how to use Edge Positioning module in your bot in order to enter into a trade only if the trade has a reasonable win rate and risk reward ratio, and consequently adjust your position size and stoploss.
Warning
Edge positioning is not compatible with dynamic (volume-based) whitelist.
Note
Edge does not consider anything else than buy/sell/stoploss signals. So trailing stoploss, ROI, and everything else are ignored in its calculation.
"},{"location":"edge/#introduction","title":"Introduction","text":"Trading is all about probability. No one can claim that he has a strategy working all the time. You have to assume that sometimes you lose.
But it doesn't mean there is no rule, it only means rules should work \"most of the time\". Let's play a game: we toss a coin, heads: I give you 10, tails: you give me 10. Is it an interesting game? No, it's quite boring, isn't it?
But let's say the probability that we have heads is 80% (because our coin has the displaced distribution of mass or other defect), and the probability that we have tails is 20%. Now it is becoming interesting...
That means 10$ X 80% versus 10$ X 20%. 8$ versus 2. That means over time you will win 8 risking only 2$ on each toss of coin.
Let's complicate it more: you win 80% of the time but only 2, I win 20% of the time but 8. The calculation is: 80% X 2$ versus 20% X 8. It is becoming boring again because overtime you win 1.6 (80% X 2 (80% X 2 (80% X 2 (80% X 2) and me 1.6 (20% X 8) too.
The question is: How do you calculate that? How do you know if you wanna play?
The answer comes to two factors:
Win Rate (W) is is the mean over some amount of trades (N) what is the percentage of winning trades to total number of trades (note that we don't consider how much you gained but only if you won or not).
W = (Number of winning trades) / (Total number of trades) = (Number of winning trades) / N\n
Complementary Loss Rate (L) is defined as
L = (Number of losing trades) / (Total number of trades) = (Number of losing trades) / N\n
or, which is the same, as
L = 1 \u2013 W\n
"},{"location":"edge/#risk-reward-ratio","title":"Risk Reward Ratio","text":"Risk Reward Ratio (R) is a formula used to measure the expected gains of a given investment against the risk of loss. It is basically what you potentially win divided by what you potentially lose:
R = Profit / Loss\n
Over time, on many trades, you can calculate your risk reward by dividing your average profit on winning trades by your average loss on losing trades:
Average profit = (Sum of profits) / (Number of winning trades)\n\nAverage loss = (Sum of losses) / (Number of losing trades)\n\nR = (Average profit) / (Average loss)\n
"},{"location":"edge/#expectancy","title":"Expectancy","text":"At this point we can combine W and R to create an expectancy ratio. This is a simple process of multiplying the risk reward ratio by the percentage of winning trades and subtracting the percentage of losing trades, which is calculated as follows:
Expectancy Ratio = (Risk Reward Ratio X Win Rate) \u2013 Loss Rate = (R X W) \u2013 L\n
So lets say your Win rate is 28% and your Risk Reward Ratio is 5:
Expectancy = (5 X 0.28) \u2013 0.72 = 0.68\n
Superficially, this means that on average you expect this strategy\u2019s trades to return .68 times the size of your loses. This is important for two reasons: First, it may seem obvious, but you know right away that you have a positive return. Second, you now have a number you can compare to other candidate systems to make decisions about which ones you employ.
It is important to remember that any system with an expectancy greater than 0 is profitable using past data. The key is finding one that will be profitable in the future.
You can also use this value to evaluate the effectiveness of modifications to this system.
NOTICE: 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.
"},{"location":"edge/#how-does-it-work","title":"How does it work?","text":"If enabled in config, Edge will go through historical data with a range of stoplosses in order to find buy and sell/stoploss signals. It then calculates win rate and expectancy over N trades for each stoploss. Here is an example:
Pair Stoploss Win Rate Risk Reward Ratio Expectancy XZC/ETH -0.01 0.50 1.176384 0.088 XZC/ETH -0.02 0.51 1.115941 0.079 XZC/ETH -0.03 0.52 1.359670 0.228 XZC/ETH -0.04 0.51 1.234539 0.117The goal here is to find the best stoploss for the strategy in order to have the maximum expectancy. In the above example stoploss at 3% leads to the maximum expectancy according to historical data.
Edge module then forces stoploss value it evaluated to your strategy dynamically.
"},{"location":"edge/#position-size","title":"Position size","text":"Edge also dictates the stake amount for each trade to the bot according to the following factors:
Allowed capital at risk is calculated as follows:
Allowed capital at risk = (Capital available_percentage) X (Allowed risk per trade)\n
Stoploss is calculated as described above against historical data.
Your position size then will be:
Position size = (Allowed capital at risk) / Stoploss\n
Example:
Let's say the stake currency is ETH and you have 10 ETH on the exchange, your capital available percentage is 50% and you would allow 1% of risk for each trade. thus your available capital for trading is 10 x 0.5 = 5 ETH and allowed capital at risk would be 5 x 0.01 = 0.05 ETH.
Let's assume Edge has calculated that for XLM/ETH market your stoploss should be at 2%. So your position size will be 0.05 / 0.02 = 2.5 ETH.
Bot takes a position of 2.5 ETH on XLM/ETH (call it trade 1). Up next, you receive another buy signal while trade 1 is still open. This time on BTC/ETH market. Edge calculated stoploss for this market at 4%. So your position size would be 0.05 / 0.04 = 1.25 ETH (call it trade 2).
Note that available capital for trading didn\u2019t change for trade 2 even if you had already trade 1. The available capital doesn\u2019t mean the free amount on your wallet.
Now you have two trades open. The bot receives yet another buy signal for another market: ADA/ETH. This time the stoploss is calculated at 1%. So your position size is 0.05 / 0.01 = 5 ETH. But there are already 3.75 ETH blocked in two previous trades. So the position size for this third trade would be 5 \u2013 3.75 = 1.25 ETH.
Available capital doesn\u2019t change before a position is sold. Let\u2019s assume that trade 1 receives a sell signal and it is sold with a profit of 1 ETH. Your total capital on exchange would be 11 ETH and the available capital for trading becomes 5.5 ETH.
So the Bot receives another buy signal for trade 4 with a stoploss at 2% then your position size would be 0.055 / 0.02 = 2.75 ETH.
"},{"location":"edge/#configurations","title":"Configurations","text":"Edge module has following configuration options:
Parameter Descriptionenabled
If true, then Edge will run periodically. Defaults to false
. Datatype: Boolean process_throttle_secs
How often should Edge run in seconds. Defaults to 3600
(once per hour). Datatype: Integer calculate_since_number_of_days
Number of days of data against which Edge calculates Win Rate, Risk Reward and Expectancy. Note that it downloads historical data so increasing this number would lead to slowing down the bot. Defaults to 7
. Datatype: Integer capital_available_percentage
DEPRECATED - replaced with tradable_balance_ratio
This is the percentage of the total capital on exchange in stake currency. As an example if you have 10 ETH available in your wallet on the exchange and this value is 0.5 (which is 50%), then the bot will use a maximum amount of 5 ETH for trading and considers it as available capital. Defaults to 0.5
. Datatype: Float allowed_risk
Ratio of allowed risk per trade. Defaults to 0.01
(1%)). Datatype: Float stoploss_range_min
Minimum stoploss. Defaults to -0.01
. Datatype: Float stoploss_range_max
Maximum stoploss. Defaults to -0.10
. Datatype: Float stoploss_range_step
As an example if this is set to -0.01 then Edge will test the strategy for [-0.01, -0,02, -0,03 ..., -0.09, -0.10]
ranges. Note than having a smaller step means having a bigger range which could lead to slow calculation. If you set this parameter to -0.001, you then slow down the Edge calculation by a factor of 10. Defaults to -0.001
. Datatype: Float minimum_winrate
It filters out pairs which don't have at least minimum_winrate. This comes handy if you want to be conservative and don't comprise win rate in favour of risk reward ratio. Defaults to 0.60
. Datatype: Float minimum_expectancy
It filters out pairs which have the expectancy lower than this number. Having an expectancy of 0.20 means if you put 10$ on a trade you expect a 12$ return. Defaults to 0.20
. Datatype: Float min_trade_number
When calculating W, R and E (expectancy) against historical data, you always want to have a minimum number of trades. The more this number is the more Edge is reliable. Having a win rate of 100% on a single trade doesn't mean anything at all. But having a win rate of 70% over past 100 trades means clearly something. Defaults to 10
(it is highly recommended not to decrease this number). Datatype: Integer max_trade_duration_minute
Edge will filter out trades with long duration. If a trade is profitable after 1 month, it is hard to evaluate the strategy based on it. But if most of trades are profitable and they have maximum duration of 30 minutes, then it is clearly a good sign.NOTICE: While configuring this value, you should take into consideration your ticker interval. As an example filtering out trades having duration less than one day for a strategy which has 4h interval does not make sense. Default value is set assuming your strategy interval is relatively small (1m or 5m, etc.).Defaults to 1440
(one day). Datatype: Integer remove_pumps
Edge will remove sudden pumps in a given market while going through historical data. However, given that pumps happen very often in crypto markets, we recommend you keep this off.Defaults to false
. Datatype: Boolean"},{"location":"edge/#running-edge-independently","title":"Running Edge independently","text":"You can run Edge independently in order to see in details the result. Here is an example:
freqtrade edge\n
An example of its output:
pair stoploss win rate risk reward ratio required risk reward expectancy total number of trades average duration (min) AGI/BTC -0.02 0.64 5.86 0.56 3.41 14 54 NXS/BTC -0.03 0.64 2.99 0.57 1.54 11 26 LEND/BTC -0.02 0.82 2.05 0.22 1.50 11 36 VIA/BTC -0.01 0.55 3.01 0.83 1.19 11 48 MTH/BTC -0.09 0.56 2.82 0.80 1.12 18 52 ARDR/BTC -0.04 0.42 3.14 1.40 0.73 12 42 BCPT/BTC -0.01 0.71 1.34 0.40 0.67 14 30 WINGS/BTC -0.02 0.56 1.97 0.80 0.65 27 42 VIBE/BTC -0.02 0.83 0.91 0.20 0.59 12 35 MCO/BTC -0.02 0.79 0.97 0.27 0.55 14 31 GNT/BTC -0.02 0.50 2.06 1.00 0.53 18 24 HOT/BTC -0.01 0.17 7.72 4.81 0.50 209 7 SNM/BTC -0.03 0.71 1.06 0.42 0.45 17 38 APPC/BTC -0.02 0.44 2.28 1.27 0.44 25 43 NEBL/BTC -0.03 0.63 1.29 0.58 0.44 19 59"},{"location":"edge/#update-cached-pairs-with-the-latest-data","title":"Update cached pairs with the latest data","text":"Edge requires historic data the same way as backtesting does. Please refer to the Data Downloading section of the documentation for details.
"},{"location":"edge/#precising-stoploss-range","title":"Precising stoploss range","text":"freqtrade edge --stoplosses=-0.01,-0.1,-0.001 #min,max,step\n
"},{"location":"edge/#advanced-use-of-timerange","title":"Advanced use of timerange","text":"freqtrade edge --timerange=20181110-20181113\n
Doing --timerange=-20190901
will get all available data until September 1st (excluding September 1st 2019).
The full timerange specification:
--timerange=-20180131
--timerange=20180131-
--timerange=20180131-20180301
--timerange=1527595200-1527618600
This page combines common gotchas and informations which are exchange-specific and most likely don't apply to other exchanges.
"},{"location":"exchanges/#binance","title":"Binance","text":"Stoploss on Exchange
Binance supports stoploss_on_exchange
and uses stop-loss-limit orders. It provides great advantages, so we recommend to benefit from it.
For Binance, please add \"BNB/<STAKE>\"
to your blacklist to avoid issues. Accounts having BNB accounts use this to pay for fees - if your first trade happens to be on BNB
, further trades will consume this position and make the initial BNB order unsellable as the expected amount is not there anymore.
Binance has been split into 3, and users must use the correct ccxt exchange ID for their exchange, otherwise API keys are not recognized.
binance
.binanceus
.binanceje
.Stoploss on Exchange
Kraken supports stoploss_on_exchange
and uses stop-loss-market orders. It provides great advantages, so we recommend to benefit from it, however since the resulting order is a stoploss-market order, sell-rates are not guaranteed, which makes this feature less secure than on other exchanges. This limitation is based on kraken's policy source and source2 - which has stoploss-limit orders disabled.
The Kraken API does only provide 720 historic candles, which is sufficient for Freqtrade dry-run and live trade modes, but is a problem for backtesting. To download data for the Kraken exchange, using --dl-trades
is mandatory, otherwise the bot will download the same 720 candles over and over, and you'll not have enough backtest data.
Bittrex does not support market orders. If you have a message at the bot startup about this, you should change order type values set in your configuration and/or in the strategy from \"market\"
to \"limit\"
. See some more details on this here in the FAQ.
Bittrex split its exchange into US and International versions. The International version has more pairs available, however the API always returns all pairs, so there is currently no automated way to detect if you're affected by the restriction.
If you have restricted pairs in your whitelist, you'll get a warning message in the log on Freqtrade startup for each restricted pair.
The warning message will look similar to the following:
[...] Message: bittrex {\"success\":false,\"message\":\"RESTRICTED_MARKET\",\"result\":null,\"explanation\":null}\"\n
If you're an \"International\" customer on the Bittrex exchange, then this warning will probably not impact you. If you're a US customer, the bot will fail to create orders for these pairs, and you should remove them from your whitelist.
You can get a list of restricted markets by using the following snippet:
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
"},{"location":"exchanges/#random-notes-for-other-exchanges","title":"Random notes for other exchanges","text":"theocean
) exchange uses Web3 functionality and requires web3
python package to be installed: $ pip3 install web3\n
Most exchanges return incomplete candles via their ohlcv / klines interface. By default, Freqtrade assumes that incomplete candles are returned and removes the last candle assuming it's an incomplete candle.
Whether your exchange returns incomplete candles or not can be checked using the helper script from the Contributor documentation.
If the exchange does return incomplete candles and you would like to have incomplete candles in your strategy, you can set the following parameter in the configuration file.
{\n\n \"exchange\": {\n \"_ft_has_params\": {\"ohlcv_partial_candle\": false}\n }\n}\n
Danger of repainting
Changing this parameter makes the strategy responsible to avoid repainting and handle this accordingly. Doing this is therefore not recommended, and should only be performed by experienced users who are fully aware of the impact this setting has.
"},{"location":"faq/","title":"Freqtrade FAQ","text":""},{"location":"faq/#freqtrade-common-issues","title":"Freqtrade common issues","text":""},{"location":"faq/#the-bot-does-not-start","title":"The bot does not start","text":"Running the bot with freqtrade trade --config config.json
does show the output freqtrade: command not found
.
This could have the following reasons:
source .env/bin/activate
to activate the virtual environmentDepending on the buy strategy, the amount of whitelisted coins, the situation of the market etc, it can take up to hours to find good entry position for a trade. Be patient!
"},{"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":"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.
"},{"location":"faq/#id-like-to-change-the-stake-amount-can-i-just-stop-the-bot-with-stop-and-then-change-the-configjson-and-run-it-again","title":"I\u2019d like to change the stake amount. Can I just stop the bot with /stop and then change the config.json and run it again?","text":"Not quite. Trades are persisted to a database but the configuration is currently only read when the bot is killed and restarted. /stop
more like pauses. You can stop your bot, adjust settings and start it again.
That's great. We have a nice backtesting and hyperoptimization setup. See the tutorial here|Testing-new-strategies-with-Hyperopt.
"},{"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":"You can use the /forcesell all
command from Telegram.
Currently known to happen for US Bittrex users.
Read the Bittrex section about restricted markets for more information.
"},{"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":"As the message says, Bittrex does not support market orders and you have one of the order types set to \"market\". Probably your strategy was written with other exchanges in mind and sets \"market\" orders for \"stoploss\" orders, which is correct and preferable for most of the exchanges supporting market orders (but not for Bittrex).
To fix it for Bittrex, redefine order types in the strategy to use \"limit\" instead of \"market\":
order_types = {\n ...\n 'stoploss': 'limit',\n ...\n }\n
Same fix should be done in the configuration file, if order types are defined in your custom config rather than in the strategy.
"},{"location":"faq/#how-do-i-search-the-bot-logs-for-something","title":"How do I search the bot logs for something?","text":"By default, the bot writes its log into stderr stream. This is implemented this way so that you can easily separate the bot's diagnostics messages from Backtesting, Edge and Hyperopt results, output from other various Freqtrade utility subcommands, as well as from the output of your custom print()
's you may have inserted into your strategy. So if you need to search the log messages with the grep utility, you need to redirect stderr to stdout and disregard stdout.
$ freqtrade --some-options 2>&1 >/dev/null | grep 'something'\n
(note, 2>&1
and >/dev/null
should be written in this order)$ freqtrade --some-options 2> >(grep 'something') >/dev/null\n
or $ freqtrade --some-options 2> >(grep -v 'something' 1>&2)\n
--logfile
option: $ freqtrade --logfile /path/to/mylogfile.log --some-options\n
and then grep it as: $ cat /path/to/mylogfile.log | grep 'something'\n
or even on the fly, as the bot works and the logfile grows: $ tail -f /path/to/mylogfile.log | grep 'something'\n
from a separate terminal window.On Windows, the --logfilename
option is also supported by Freqtrade and you can use the findstr
command to search the log for the string of interest:
> type \\path\\to\\mylogfile.log | findstr \"something\"\n
"},{"location":"faq/#hyperopt-module","title":"Hyperopt module","text":""},{"location":"faq/#how-many-epoch-do-i-need-to-get-a-good-hyperopt-result","title":"How many epoch do I need to get a good Hyperopt result?","text":"Per default Hyperopt called without the -e
/--epochs
command line option will only run 100 epochs, means 100 evals 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.
We recommend you to run it at least 10.000 epochs:
freqtrade hyperopt -e 10000\n
or if you want intermediate result to see
for i in {1..100}; do freqtrade hyperopt -e 100; done\n
"},{"location":"faq/#why-it-is-so-long-to-run-hyperopt","title":"Why it is so long to run hyperopt?","text":"Finding a great Hyperopt results takes time.
If you wonder why it takes a while to find great hyperopt results
This answer was written during the under the release 0.15.1, when we had:
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 evals. Did you run 100 000 evals? Congrats, you've done roughly 1 / 100 000 th of the search space.
"},{"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":"The Edge module is mostly a result of brainstorming of @mishaker and @creslinux freqtrade team members.
You can find further info on expectancy, winrate, risk management and position size in the following sources:
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 scikit-optimize
package to accomplish this. The search will burn all your CPU cores, make your laptop sound like a fighter jet and still take a long time.
In general, the search for best parameters starts with a few random combinations and then uses Bayesian search with a ML regressor algorithm (currently ExtraTreesRegressor) to quickly find a combination of parameters in the search hyperspace that minimizes the value of the loss function.
Hyperopt requires historic data to be available, just as backtesting does. To learn how to get data for the pairs and exchange you're interested in, head over to the Data Downloading section of the documentation.
Bug
Hyperopt can crash when used with only 1 CPU Core as found out in Issue #1133
"},{"location":"hyperopt/#prepare-hyperopting","title":"Prepare Hyperopting","text":"Before we start digging into Hyperopt, we recommend you to take a look at the sample hyperopt file located in user_data/hyperopts/.
Configuring hyperopt is similar to writing your own strategy, and many tasks will be similar and a lot of code can be copied across from the strategy.
The simplest way to get started is to use freqtrade new-hyperopt --hyperopt AwesomeHyperopt
. This will create a new hyperopt file from a template, which will be located under user_data/hyperopts/AwesomeHyperopt.py
.
Depending on the space you want to optimize, only some of the below are required:
buy_strategy_generator
- for buy signal optimizationindicator_space
- for buy signal optimzationsell_strategy_generator
- for sell signal optimizationsell_indicator_space
- for sell signal optimzationNote
populate_indicators
needs to create all indicators any of thee spaces may use, otherwise hyperopt will not work.
Optional - can also be loaded from a strategy:
populate_indicators
from your strategy - otherwise default-strategy will be usedpopulate_buy_trend
from your strategy - otherwise default-strategy will be usedpopulate_sell_trend
from your strategy - otherwise default-strategy will be usedNote
Assuming the optional methods are not in your hyperopt file, please use --strategy AweSomeStrategy
which contains these methods so hyperopt can use these methods instead.
Rarely you may also need to override:
roi_space
- for custom ROI optimization (if you need the ranges for the ROI parameters in the optimization hyperspace that differ from default)generate_roi_table
- for custom ROI optimization (if you need the ranges for the values in the ROI table that differ from default or the number of entries (steps) in the ROI table which differs from the default 4 steps)stoploss_space
- for custom stoploss optimization (if you need the range for the stoploss parameter in the optimization hyperspace that differs from default)trailing_space
- for custom trailing stop optimization (if you need the ranges for the trailing stop parameters in the optimization hyperspace that differ from default)Quickly optimize ROI, stoploss and trailing stoploss
You can quickly optimize the spaces roi
, stoploss
and trailing
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.
# Have a working strategy at hand.\nfreqtrade new-hyperopt --hyperopt EmptyHyperopt\n\nfreqtrade hyperopt --hyperopt EmptyHyperopt --spaces roi stoploss trailing --strategy MyWorkingStrategy --config config.json -e 100\n
"},{"location":"hyperopt/#1-install-a-custom-hyperopt-file","title":"1. Install a Custom Hyperopt File","text":"Put your hyperopt file into the directory user_data/hyperopts
.
Let assume you want a hyperopt file awesome_hyperopt.py
: Copy the file user_data/hyperopts/sample_hyperopt.py
into user_data/hyperopts/awesome_hyperopt.py
There are two places you need to change in your hyperopt file to add a new buy hyperopt for testing:
indicator_space()
- the parameters hyperopt shall be optimizing.populate_buy_trend()
- applying the parameters.There you have two different types of indicators: 1. guards
and 2. triggers
.
Hyperoptimization will, for each eval 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\".
If you have updated the buy strategy, i.e. changed the contents of populate_buy_trend()
method, you have to update the guards
and triggers
your hyperopt must use correspondingly.
Similar to the buy-signal above, sell-signals can also be optimized. Place the corresponding settings into the following methods
sell_indicator_space()
- the parameters hyperopt shall be optimizing.populate_sell_trend()
- applying the parameters.The configuration and rules are the same than for buy signals. To avoid naming collisions in the search-space, please prefix all sell-spaces with sell-
.
The Strategy exposes the ticker-interval as self.ticker_interval
. The same value is available as class-attribute HyperoptName.ticker_interval
. In the case of the linked sample-value this would be SampleHyperOpt.ticker_interval
.
Let's say you are curious: should you use MACD crossings or lower Bollinger Bands to trigger your buys. And you also wonder should you use RSI or ADX to help with those buy decisions. If you decide to use RSI or ADX, which values should I use for them? So let's use hyperparameter optimization to solve this mystery.
We will start by defining a search space:
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
Above definition says: I have five parameters I want you to randomly combine to find the best combination. Two of them are integer values (adx-value
and rsi-value
) and I want you test in the range of values 20 to 40. Then we have three category variables. First two are either True
or False
. We use these to either enable or disable the ADX and RSI guards. The last one we call trigger
and use it to decide which buy trigger we want to use.
So let's write the buy strategy using these values:
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 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
Hyperopting will now call this populate_buy_trend
as many times you ask it (epochs
) with different value combinations. It will then use the given historical data and make buys based on the buy signals generated with the above function and based on the results it will end with telling you which paramter combination produced the best profits.
The above setup expects to find ADX, RSI and Bollinger Bands in the populated indicators. When you want to test an indicator that isn't used by the bot currently, remember to add it to the populate_indicators()
method in your custom hyperopt file.
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.
By default, Freqtrade uses a loss function, which has been with freqtrade since the beginning and optimizes mostly for short trade duration and avoiding losses.
A different loss function can be specified by using the --hyperopt-loss <Class-name>
argument. This class should be in its own file within the user_data/hyperopts/
directory.
Currently, the following loss functions are builtin:
DefaultHyperOptLoss
(default legacy Freqtrade hyperoptimization loss function)OnlyProfitHyperOptLoss
(which takes only amount of profit into consideration)SharpeHyperOptLoss
(optimizes Sharpe Ratio calculated on the trade returns)SharpeHyperOptLossDaily
(optimizes Sharpe Ratio calculated on daily trade returns)Creation of a custom loss function is covered in the Advanced Hyperopt part of the documentation.
"},{"location":"hyperopt/#execute-hyperopt","title":"Execute Hyperopt","text":"Once you have updated your hyperopt configuration you can run it. Because hyperopt tries a lot of combinations to find the best parameters it will take time to get a good result. More time usually results in better results.
We strongly recommend to use screen
or tmux
to prevent any connection loss.
freqtrade hyperopt --config config.json --hyperopt <hyperoptname> -e 5000 --spaces all\n
Use <hyperoptname>
as the name of the custom hyperopt used.
The -e
option will set how many evaluations hyperopt will do. We recommend running at least several thousand evaluations.
The --spaces all
option determines that all possible parameters should be optimized. Possibilities are listed below.
Note
By default, hyperopt will erase previous results and start from scratch. Continuation can be archived by using --continue
.
Warning
When switching parameters or changing configuration options, make sure to not use the argument --continue
so temporary results can be removed.
If you would like to hyperopt parameters using an alternate ticker data that you have on-disk, use the --datadir PATH
option. Default hyperopt will use data from directory user_data/data
.
Use the --timerange
argument to change how much of the testset you want to use. For example, to use one month of data, pass the following parameter to the hyperopt call:
freqtrade hyperopt --timerange 20180401-20180501\n
"},{"location":"hyperopt/#running-hyperopt-using-methods-from-a-strategy","title":"Running Hyperopt using methods from a strategy","text":"Hyperopt can reuse populate_indicators
, populate_buy_trend
, populate_sell_trend
from your strategy, assuming these methods are not in your custom hyperopt file, and a strategy is provided.
freqtrade hyperopt --strategy SampleStrategy --customhyperopt SampleHyperopt\n
"},{"location":"hyperopt/#running-hyperopt-with-smaller-search-space","title":"Running Hyperopt with Smaller Search Space","text":"Use the --spaces
option to limit the search space used by hyperopt. Letting Hyperopt optimize everything is a huuuuge search space. Often it might make more sense to start by just searching for initial buy algorithm. Or maybe you just want to optimize your stoploss or roi table for that awesome new buy strategy you have.
Legal values are:
all
: optimize everythingbuy
: just search for a new buy strategysell
: just search for a new sell strategyroi
: just optimize the minimal profit table for your strategystoploss
: search for the best stoploss valuetrailing
: search for the best trailing stop valuesdefault
: all
except trailing
--spaces roi stoploss
The default Hyperopt Search Space, used when no --space
command line option is specified, does not include the trailing
hyperspace. We recommend you to run optimization for the trailing
hyperspace separately, when the best parameters for other hyperspaces were found, validated and pasted into your custom strategy.
In some situations, you may need to run Hyperopt (and Backtesting) with the --eps
/--enable-position-staking
and --dmmp
/--disable-max-market-positions
arguments.
By default, hyperopt emulates the behavior of the Freqtrade Live Run/Dry Run, where only one open trade is allowed for every traded pair. The total number of trades open for all pairs is also limited by the max_open_trades
setting. During Hyperopt/Backtesting this may lead to some potential trades to be hidden (or masked) by previosly open trades.
The --eps
/--enable-position-stacking
argument allows emulation of buying the same pair multiple times, while --dmmp
/--disable-max-market-positions
disables applying max_open_trades
during Hyperopt/Backtesting (which is equal to setting max_open_trades
to a very high number).
Note
Dry/live runs will NOT use position stacking - therefore it does make sense to also validate the strategy without this as it's closer to reality.
You can also enable position stacking in the configuration file by explicitly setting \"position_stacking\"=true
.
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 a leading asterisk sign at the Hyperopt output.
The initial state for generation of these random values (random state) is controlled by the value of the --random-state
command line option. You can set it to some arbitrary value of your choice to obtain reproducible results.
If you have not set this value explicitly in the command line options, Hyperopt seeds the random state with some random value for you. The random state value for each Hyperopt run is shown in the log, so you can copy and paste it into the --random-state
command line option to repeat the set of the initial random epochs used.
If you have not changed anything in the command line options, configuration, timerange, Strategy and Hyperopt classes, historical data and the Loss Function -- you should obtain same hyperoptimization results with same random state value used.
"},{"location":"hyperopt/#understand-the-hyperopt-result","title":"Understand the Hyperopt Result","text":"Once Hyperopt is completed you can use the result to create a new strategy. Given the following result from hyperopt:
Best result:\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
You should understand this result like:
bb_lower
.adx-enabled: False
)rsi-enabled: True
and the best value is 29.0
(rsi-value: 29.0
)You have to look inside your strategy file into buy_strategy_generator()
method, what those values match to.
So for example you had rsi-value: 29.0
so we would look at rsi
-block, that translates to the following code block:
(dataframe['rsi'] < 29.0)\n
Translating your whole hyperopt result as the new buy-signal would then look like:
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
By default, hyperopt prints colorized results -- epochs with positive profit are printed in the green color. This highlighting helps you find epochs that can be interesting for later analysis. Epochs with zero total profit or with negative profits (losses) are printed in the normal color. If you do not need colorization of results (for instance, when you are redirecting hyperopt output to a file) you can switch colorization off by specifying the --no-color
option in the command line.
You can use the --print-all
command line option if you would like to see all results in the hyperopt output, not only the best ones. When --print-all
is used, current best results are also colorized by default -- they are printed in bold (bright) style. This can also be switched off with the --no-color
command line option.
If you are optimizing ROI (i.e. if optimization search-space contains 'all', 'default' or 'roi'), your result will look as follows and include a ROI table:
Best result:\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
In order to use this best ROI table found by Hyperopt in backtesting and for live trades/dry-run, copy-paste it as the value of the minimal_roi
attribute of your custom strategy:
# Minimal ROI designed for the strategy.\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
As stated in the comment, you can also use it as the value of the minimal_roi
setting in the configuration file.
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 ticker_interval used. By default the values vary in the following ranges (for some of the most used ticker intervals, values are rounded to 5 digits after the decimal point):
# 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.0These ranges should be sufficient in most cases. The minutes in the steps (ROI dict keys) are scaled linearly depending on the ticker interval used. The ROI values in the steps (ROI dict values) are scaled logarithmically depending on the ticker interval used.
If you have the generate_roi_table()
and roi_space()
methods in your custom hyperopt file, remove them in order to utilize these adaptive ROI tables and the ROI hyperoptimization space generated by Freqtrade by default.
Override the roi_space()
method if you need components of the ROI tables to vary in other ranges. Override the generate_roi_table()
and roi_space()
methods and implement your own custom approach for generation of the ROI tables during hyperoptimization if you need a different structure of the ROI tables or other amount of rows (steps). A sample for these methods can be found in user_data/hyperopts/sample_hyperopt_advanced.py.
If you are optimizing stoploss values (i.e. if optimization search-space contains 'all', 'default' or 'stoploss'), your result will look as follows and include stoploss:
Best result:\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
In order to use this best stoploss value found by Hyperopt in backtesting and for live trades/dry-run, copy-paste it as the value of the stoploss
attribute of your custom strategy:
# Optimal stoploss designed for the strategy\n # This attribute will be overridden if the config file contains \"stoploss\"\n stoploss = -0.27996\n
As stated in the comment, you can also use it as the value of the stoploss
setting in the configuration file.
If you are optimizing stoploss values, Freqtrade creates the 'stoploss' optimization hyperspace for you. By default, the stoploss values in that hyperspace vary in the range -0.35...-0.02, which is sufficient in most cases.
If you have the stoploss_space()
method in your custom hyperopt file, remove it in order to utilize Stoploss hyperoptimization space generated by Freqtrade by default.
Override the stoploss_space()
method and define the desired range in it if you need stoploss values to vary in other range during hyperoptimization. A sample for this method can be found in user_data/hyperopts/sample_hyperopt_advanced.py.
If you are optimizing trailing stop values (i.e. if optimization search-space contains 'all' or 'trailing'), your result will look as follows and include trailing stop parameters:
Best result:\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
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:
# 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
As stated in the comment, you can also use it as the values of the corresponding settings in the configuration file.
"},{"location":"hyperopt/#default-trailing-stop-search-space","title":"Default Trailing Stop Search Space","text":"If you are optimizing trailing stop values, Freqtrade creates the 'trailing' optimization hyperspace for you. By default, the trailing_stop
parameter is always set to True in that hyperspace, the value of the trailing_only_offset_is_reached
vary between True and False, the values of the trailing_stop_positive
and trailing_stop_positive_offset
parameters vary in the ranges 0.02...0.35 and 0.01...0.1 correspondingly, which is sufficient in most cases.
Override the trailing_space()
method and define the desired range in it if you need values of the trailing stop parameters to vary in other ranges during hyperoptimization. A sample for this method can be found in user_data/hyperopts/sample_hyperopt_advanced.py.
After you run Hyperopt for the desired amount of epochs, you can later list all results for analysis, select only best or profitable once, and show the details for any of the epochs previously evaluated. This can be done with the hyperopt-list
and hyperopt-show
subcommands. The usage of these subcommands is described in the Utils chapter.
Once the optimized strategy has been implemented into your strategy, you should backtest this strategy to make sure everything is working as expected.
To achieve same results (number of trades, their durations, profit, etc.) than during Hyperopt, please use same set of arguments --dmmp
/--disable-max-market-positions
and --eps
/--enable-position-stacking
for Backtesting.
Now you have a perfect bot and want to control it from Telegram. Your next step is to learn the Telegram usage.
"},{"location":"installation/","title":"Installation","text":"This page explains how to prepare your environment for running the bot.
Please consider using the prebuilt docker images to get started quickly while trying out freqtrade evaluating how it operates.
"},{"location":"installation/#prerequisite","title":"Prerequisite","text":""},{"location":"installation/#requirements","title":"Requirements","text":"Click each one for install guide:
We also recommend a Telegram bot, which is optional but recommended.
"},{"location":"installation/#quick-start","title":"Quick start","text":"Freqtrade provides the Linux/MacOS Easy Installation script to install all dependencies and help you configure the bot.
Note
Windows installation is explained here.
The easiest way to install and run Freqtrade is to clone the bot Github repository and then run the Easy Installation script, if it's available for your platform.
Version considerations
When cloning the repository the default working branch has the name develop
. This branch contains all last features (can be considered as relatively stable, thanks to automated tests). The master
branch contains the code of the last release (done usually once per month on an approximately one week old snapshot of the develop
branch to prevent packaging bugs, so potentially it's more stable).
Note
Python3.6 or higher and the corresponding pip
are assumed to be available. The install-script will warn you and stop if that's not the case. git
is also needed to clone the Freqtrade repository.
This can be achieved with the following commands:
git clone https://github.com/freqtrade/freqtrade.git\ncd freqtrade\ngit checkout master # Optional, see (1)\n./setup.sh --install\n
(1) This command switches the cloned repository to the use of the master
branch. It's not needed if you wish to stay on the develop
branch. You may later switch between branches at any time with the git checkout master
/git checkout develop
commands.
If you are on Debian, Ubuntu or MacOS Freqtrade provides the script to install, update, configure and reset the codebase of your bot.
$ ./setup.sh\nusage:\n -i,--install Install freqtrade from scratch\n -u,--update Command git pull to update.\n -r,--reset Hard reset your develop/master branch.\n -c,--config Easy config generator (Will override your existing file).\n
** --install **
With this option, the script will install the bot and most dependencies: You will need to have git and python3.6+ installed beforehand for this to work.
ta-lib
.env/
This option is a combination of installation tasks, --reset
and --config
.
** --update **
This option will pull the last version of your current branch and update your virtualenv. Run the script with this option periodically to update your bot.
** --reset **
This option will hard reset your branch (only if you are on either master
or develop
) and recreate your virtualenv.
** --config **
DEPRECATED - use freqtrade new-config -c config.json
instead.
We've included/collected install instructions for Ubuntu 16.04, MacOS, and Windows. These are guidelines and your success may vary with other distros. OS Specific steps are listed first, the Common section below is necessary for all systems.
Note
Python3.6 or higher and the corresponding pip are assumed to be available.
"},{"location":"installation/#linux-ubuntu-1604","title":"Linux - Ubuntu 16.04","text":""},{"location":"installation/#install-necessary-dependencies","title":"Install necessary dependencies","text":"sudo apt-get update\nsudo apt-get install build-essential git\n
"},{"location":"installation/#raspberry-pi-raspbian","title":"Raspberry Pi / Raspbian","text":"The following assumes the latest Raspbian Buster lite image from at least September 2019. This image comes with python3.7 preinstalled, making it easy to get freqtrade up and running.
Tested using a Raspberry Pi 3 with the Raspbian Buster lite image, all updates applied.
sudo apt-get install python3-venv libatlas-base-dev\ngit clone https://github.com/freqtrade/freqtrade.git\ncd freqtrade\n\nbash setup.sh -i\n
Installation duration
Depending on your internet speed and the Raspberry Pi version, installation can take multiple hours to complete.
Note
The above does not install hyperopt dependencies. To install these, please use python3 -m pip install -e .[hyperopt]
. We do not advise to run hyperopt on a Raspberry Pi, since this is a very resource-heavy operation, which should be done on powerful machine.
Use the provided ta-lib installation script
sudo ./build_helpers/install_ta-lib.sh\n
Note
This will use the ta-lib tar.gz included in this repository.
"},{"location":"installation/#ta-lib-manual-installation","title":"TA-Lib manual installation","text":"Official webpage: https://mrjbq7.github.io/ta-lib/install.html
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
Note
An already downloaded version of ta-lib is included in the repository, as the sourceforge.net source seems to have problems frequently.
"},{"location":"installation/#2-setup-your-python-virtual-environment-virtualenv","title":"2. Setup your Python virtual environment (virtualenv)","text":"Note
This step is optional but strongly recommended to keep your system organized
python3 -m venv .env\nsource .env/bin/activate\n
"},{"location":"installation/#3-install-freqtrade","title":"3. Install Freqtrade","text":"Clone the git repository:
git clone https://github.com/freqtrade/freqtrade.git\ncd freqtrade\n
Optionally checkout the master branch to get the latest stable release:
git checkout master\n
"},{"location":"installation/#4-install-python-dependencies","title":"4. Install python dependencies","text":"python3 -m pip install --upgrade pip\npython3 -m pip install -e .\n
"},{"location":"installation/#5-initialize-the-configuration","title":"5. Initialize the configuration","text":"# Initialize the user_directory\nfreqtrade create-userdir --userdir user_data/\n\n# Create a new configuration file\nfreqtrade new-config --config config.json\n
To edit the config please refer to Bot Configuration.
"},{"location":"installation/#6-run-the-bot","title":"6. Run the Bot","text":"If this is the first time you run the bot, ensure you are running it in Dry-run \"dry_run\": true,
otherwise it will start to buy and sell coins.
freqtrade trade -c config.json\n
Note: If you run the bot on a server, you should consider using Docker or a terminal multiplexer like screen
or tmux
to avoid that the bot is stopped on logout.
On Linux, as an optional post-installation task, you may wish to setup the bot to run as a systemd
service or configure it to send the log messages to the syslog
/rsyslog
or journald
daemons. See Advanced Logging for details.
Freqtrade can also be installed using Anaconda (or Miniconda).
conda env create -f environment.yml\n
Note
This requires the ta-lib C-library to be installed first.
"},{"location":"installation/#windows","title":"Windows","text":"We recommend that Windows users use Docker as this will work much easier and smoother (also more secure).
If that is not possible, try using the Windows Linux subsystem (WSL) - for which the Ubuntu instructions should work. If that is not available on your system, feel free to try the instructions below, which led to success for some.
"},{"location":"installation/#install-freqtrade-manually","title":"Install freqtrade manually","text":"Note
Make sure to use 64bit Windows and 64bit Python to avoid problems with backtesting or hyperopt due to the memory constraints 32bit applications have under Windows.
Hint
Using the Anaconda Distribution under Windows can greatly help with installation problems. Check out the Conda section in this document for more information.
"},{"location":"installation/#clone-the-git-repository","title":"Clone the git repository","text":"git clone https://github.com/freqtrade/freqtrade.git\n
"},{"location":"installation/#install-ta-lib","title":"Install ta-lib","text":"Install ta-lib according to the ta-lib documentation.
As compiling from source on windows has heavy dependencies (requires a partial visual studio installation), there is also a repository of unofficial precompiled windows Wheels here, which needs to be downloaded and installed using pip install TA_Lib\u20110.4.17\u2011cp36\u2011cp36m\u2011win32.whl
(make sure to use the version matching your python version)
>cd \\path\\freqtrade-develop\n>python -m venv .env\n>.env\\Scripts\\activate.bat\nREM optionally install ta-lib from wheel\nREM >pip install TA_Lib\u20110.4.17\u2011cp36\u2011cp36m\u2011win32.whl\n>pip install -r requirements.txt\n>pip install -e .\n>freqtrade\n
Thanks Owdr for the commands. Source: Issue #222
"},{"location":"installation/#error-during-installation-under-windows","title":"Error during installation under Windows","text":"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
Unfortunately, many packages requiring compilation don't provide a pre-build wheel. It is therefore mandatory to have a C/C++ compiler installed and available for your python environment to use.
The easiest way is to download install Microsoft Visual Studio Community here and make sure to install \"Common Tools for Visual C++\" to enable building c code on Windows. Unfortunately, this is a heavy download / dependency (~4Gb) so you might want to consider WSL or docker first.
Now you have an environment ready, the next step is Bot Configuration.
"},{"location":"installation/#troubleshooting","title":"Troubleshooting","text":""},{"location":"installation/#macos-installation-error","title":"MacOS installation error","text":"Newer versions of MacOS may have installation failed with errors like error: command 'g++' failed with exit status 1
.
This error will require explicit installation of the SDK Headers, which are not installed by default in this version of MacOS. For MacOS 10.14, this can be accomplished with the below command.
open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg\n
If this file is inexistant, then you're probably on a different version of MacOS, so you may need to consult the internet for specific resolution details.
"},{"location":"plotting/","title":"Plotting","text":"This page explains how to plot prices, indicators and profits.
"},{"location":"plotting/#installation-setup","title":"Installation / Setup","text":"Plotting modules use the Plotly library. You can install / upgrade this by running the following command:
pip install -U -r requirements-plot.txt\n
"},{"location":"plotting/#plot-price-and-indicators","title":"Plot price and indicators","text":"The freqtrade plot-dataframe
subcommand shows an interactive graph with three subplots:
--indicators2
Possible arguments:
usage: freqtrade plot-dataframe [-h] [-v] [--logfile FILE] [-V] [-c PATH] [-d PATH] [--userdir PATH] [-s NAME]\n [--strategy-path PATH] [-p PAIRS [PAIRS ...]] [--indicators1 INDICATORS1 [INDICATORS1 ...]]\n [--indicators2 INDICATORS2 [INDICATORS2 ...]] [--plot-limit INT] [--db-url PATH]\n [--trade-source {DB,file}] [--export EXPORT] [--export-filename PATH] [--timerange TIMERANGE]\n [-i TICKER_INTERVAL]\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-separated.\n --indicators1 INDICATORS1 [INDICATORS1 ...]\n Set indicators from your strategy you want in the 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 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 values cause huge files. Default: 750.\n --db-url PATH Override trades database URL, this is useful in custom deployments (default: `sqlite:///tradesv3.sqlite`\n for Live Run mode, `sqlite:///tradesv3.dryrun.sqlite` for Dry Run).\n --trade-source {DB,file}\n Specify the source for trades (Can be DB or file (backtest file)) Default: file\n --export EXPORT Export backtest results, argument are: trades. Example: `--export=trades`\n --export-filename PATH\n Save backtest results to the file with this filename. Requires `--export` to be set as well. Example:\n `--export-filename=user_data/backtest_results/backtest_today.json`\n --timerange TIMERANGE\n Specify what timerange of data to use.\n -i TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL\n Specify ticker interval (`1m`, `5m`, `30m`, `1h`, `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: '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`). 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\nStrategy arguments:\n -s NAME, --strategy NAME\n Specify strategy class name which will be used by the bot.\n --strategy-path PATH Specify additional strategy lookup path.\n
Example:
freqtrade plot-dataframe -p BTC/ETH\n
The -p/--pairs
argument can be used to specify pairs you would like to plot.
Note
The freqtrade plot-dataframe
subcommand generates one plot-file per pair.
Specify custom indicators. Use --indicators1
for the main plot and --indicators2
for the subplot below (if values are in a different range than prices).
Tip
You will almost certainly want to specify a custom strategy! This can be done by adding -s Classname
/ --strategy ClassName
to the command.
freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH --indicators1 sma ema --indicators2 macd\n
"},{"location":"plotting/#further-usage-examples","title":"Further usage examples","text":"To plot multiple pairs, separate them with a space:
freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH XRP/ETH\n
To plot a timerange (to zoom in)
freqtrade plot-dataframe --strategy AwesomeStrategy -p BTC/ETH --timerange=20180801-20180805\n
To plot trades stored in a database use --db-url
in combination with --trade-source DB
:
freqtrade plot-dataframe --strategy AwesomeStrategy --db-url sqlite:///tradesv3.dry_run.sqlite -p BTC/ETH --trade-source DB\n
To plot trades from a backtesting result, use --export-filename <filename>
freqtrade plot-dataframe --strategy AwesomeStrategy --export-filename user_data/backtest_results/backtest-result.json -p BTC/ETH\n
"},{"location":"plotting/#plot-dataframe-basics","title":"Plot dataframe basics","text":"The plot-dataframe
subcommand requires backtesting data, a strategy and either a backtesting-results file or a database, containing trades corresponding to the strategy.
The resulting plot will have the following elements:
--indicators1
.--indicators2
.Bollinger Bands
Bollinger bands are automatically added to the plot if the columns bb_lowerband
and bb_upperband
exist, and are painted as a light blue area spanning from the lower band to the upper band.
An advanced plot configuration can be specified in the strategy in the plot_config
parameter.
Additional features when using plot_config include:
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.
Sample configuration with inline comments explaining the process:
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 },\n 'subplots': {\n # Create subplot MACD\n \"MACD\": {\n 'macd': {'color': 'blue'},\n 'macdsignal': {'color': 'orange'},\n },\n # Additional subplot RSI\n \"RSI\": {\n 'rsi': {'color': 'red'},\n }\n }\n }\n
Note
The above configuration assumes that ema10
, ema50
, macd
, macdsignal
and rsi
are columns in the DataFrame created by the strategy.
The plot-profit
subcommand shows an interactive graph with three plots:
The first graph is good to get a grip of how the overall market progresses.
The second graph will show if your algorithm works or doesn't. Perhaps you want an algorithm that steadily makes small profits, or one that acts less often, but makes big swings.
The third graph can be useful to spot outliers, events in pairs that cause profit spikes.
Possible options for the freqtrade plot-profit
subcommand:
usage: freqtrade plot-profit [-h] [-v] [--logfile FILE] [-V] [-c PATH]\n [-d PATH] [--userdir PATH] [-p PAIRS [PAIRS ...]]\n [--timerange TIMERANGE] [--export EXPORT]\n [--export-filename PATH] [--db-url PATH]\n [--trade-source {DB,file}] [-i TICKER_INTERVAL]\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 TICKER_INTERVAL, --ticker-interval TICKER_INTERVAL\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: `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
The -p/--pairs
argument, can be used to limit the pairs that are considered for this calculation.
Examples:
Use custom backtest-export file
freqtrade plot-profit -p LTC/BTC --export-filename user_data/backtest_results/backtest-result-Strategy005.json\n
Use custom database
freqtrade plot-profit -p LTC/BTC --db-url sqlite:///tradesv3.sqlite --trade-source DB\n
freqtrade --datadir user_data/data/binance_save/ plot-profit -p LTC/BTC\n
"},{"location":"rest-api/","title":"REST API Usage","text":""},{"location":"rest-api/#configuration","title":"Configuration","text":"Enable the rest API by adding the api_server section to your configuration and setting api_server.enabled
to true
.
Sample configuration:
\"api_server\": {\n \"enabled\": true,\n \"listen_ip_address\": \"127.0.0.1\",\n \"listen_port\": 8080,\n \"username\": \"Freqtrader\",\n \"password\": \"SuperSecret1!\"\n },\n
Security warning
By default, the configuration listens on localhost only (so it's not reachable from other systems). We strongly recommend to not expose this API to the internet and choose a strong, unique password, since others will potentially be able to control your bot.
Password selection
Please make sure to select a very strong, unique password to protect your bot from unauthorized access.
You can then access the API by going to http://127.0.0.1:8080/api/v1/ping
in a browser to check if the API is running correctly. This should return the response:
{\"status\":\"pong\"}\n
All other endpoints return sensitive info and require authentication, so are not available through a web browser.
To generate a secure password, either use a password manager, or use the below code snipped.
import secrets\nsecrets.token_hex()\n
"},{"location":"rest-api/#configuration-with-docker","title":"Configuration with docker","text":"If you run your bot using docker, you'll need to have the bot listen to incomming connections. The security is then handled by docker.
\"api_server\": {\n \"enabled\": true,\n \"listen_ip_address\": \"0.0.0.0\",\n \"listen_port\": 8080\n },\n
Add the following to your docker command:
-p 127.0.0.1:8080:8080\n
A complete sample-command may then look as follows:
docker run -d \\\n --name freqtrade \\\n -v ~/.freqtrade/config.json:/freqtrade/config.json \\\n -v ~/.freqtrade/user_data/:/freqtrade/user_data \\\n -v ~/.freqtrade/tradesv3.sqlite:/freqtrade/tradesv3.sqlite \\\n -p 127.0.0.1:8080:8080 \\\n freqtrade trade --db-url sqlite:///tradesv3.sqlite --strategy MyAwesomeStrategy\n
Security warning
By using -p 8080:8080
the API is available to everyone connecting to the server under the correct port, so others may be able to control your bot.
You can consume the API by using the script scripts/rest_client.py
. The client script only requires the requests
module, so Freqtrade does not need to be installed on the system.
python3 scripts/rest_client.py <command> [optional parameters]\n
By default, the script assumes 127.0.0.1
(localhost) and port 8080
to be used, however you can specify a configuration file to override this behaviour.
{\n \"api_server\": {\n \"enabled\": true,\n \"listen_ip_address\": \"0.0.0.0\",\n \"listen_port\": 8080\n }\n}\n
python3 scripts/rest_client.py --config rest_config.json <command> [optional parameters]\n
"},{"location":"rest-api/#available-commands","title":"Available commands","text":"Command Default Description start
Starts the trader stop
Stops the trader stopbuy
Stops the trader from opening new trades. Gracefully closes open trades according to their rules. reload_conf
Reloads the configuration file show_config
Shows part of the current configuration with relevant settings to operation status
Lists all open trades count
Displays number of trades used and available profit
Display a summary of your profit/loss from close trades and some stats about your performance forcesell <trade_id>
Instantly sells the given trade (Ignoring minimum_roi
). forcesell all
Instantly sells all open trades (Ignoring minimum_roi
). forcebuy <pair> [rate]
Instantly buys the given pair. Rate is optional. (forcebuy_enable
must be set to True) performance
Show performance of each finished trade grouped by pair balance
Show account balance per currency daily <n>
7 Shows profit or loss per day, over the last n days whitelist
Show the current whitelist blacklist [pair]
Show the current blacklist, or adds a pair to the blacklist. edge
Show validated pairs by Edge if it is enabled. version
Show version Possible commands can be listed from the rest-client script using the help
command.
python3 scripts/rest_client.py help\n
Possible commands:\nbalance\n Get the account balance\n :returns: json object\n\nblacklist\n Show the current blacklist\n :param add: List of coins to add (example: \"BNB/BTC\")\n :returns: json object\n\ncount\n Returns the amount of open trades\n :returns: json object\n\ndaily\n Returns the amount of open trades\n :returns: json object\n\nedge\n Returns information about edge\n :returns: json object\n\nforcebuy\n Buy an asset\n :param pair: Pair to buy (ETH/BTC)\n :param price: Optional - price to buy\n :returns: json object of the trade\n\nforcesell\n Force-sell a trade\n :param tradeid: Id of the trade (can be received via status command)\n :returns: json object\n\nperformance\n Returns the performance of the different coins\n :returns: json object\n\nprofit\n Returns the profit summary\n :returns: json object\n\nreload_conf\n Reload configuration\n :returns: json object\n\nshow_config\n Returns part of the configuration, relevant for trading operations.\n :return: json object containing the version\n\nstart\n Start the bot if it's in stopped state.\n :returns: json object\n\nstatus\n Get the status of open trades\n :returns: json object\n\nstop\n Stop the bot. Use start to restart\n :returns: json object\n\nstopbuy\n Stop buying (but handle sells gracefully).\n use reload_conf to reset\n :returns: json object\n\nversion\n Returns the version of the bot\n :returns: json object containing the version\n\nwhitelist\n Show the current whitelist\n :returns: json object\n
"},{"location":"sandbox-testing/","title":"Sandbox API testing","text":"Where an exchange provides a sandbox for risk-free integration, or end-to-end, testing CCXT provides access to these.
This document is a *light overview of configuring Freqtrade and GDAX sandbox. This can be useful to developers and trader alike as Freqtrade is quite customisable.
When testing your API connectivity, make sure to use the following URLs. Website* https://public.sandbox.gdax.com REST API* https://api-public.sandbox.gdax.com
"},{"location":"sandbox-testing/#configure-a-sandbox-account-on-gdax","title":"Configure a Sandbox account on Gdax","text":"Aim of this document section
This link will redirect to the sandbox main page to login / create account dialogues: https://public.sandbox.pro.coinbase.com/orders/
After registration and Email confimation you wil be redirected into your sanbox account. It is easy to verify you're in sandbox by checking the URL bar.
https://public.sandbox.pro.coinbase.com/
"},{"location":"sandbox-testing/#enable-2fa-a-prerequisite-to-creating-sandbox-api-keys","title":"Enable 2Fa (a prerequisite to creating sandbox API Keys)","text":"From within sand box site select your profile, top right.
Or as a direct link: https://public.sandbox.pro.coinbase.com/profile
From the menu panel to the left of the screen select
Security: \"View or Update\"
In the new site select \"enable authenticator\" as typical google Authenticator.
From within sandbox select profile>api>create api-keys
or as a direct link: https://public.sandbox.pro.coinbase.com/profile/api
Click on \"create one\" and ensure view and trade are \"checked\" and sumbit your 2FA
To add funds, use the web interface deposit and withdraw buttons.
To begin select 'Wallets' from the top menu.
Or as a direct link: https://public.sandbox.pro.coinbase.com/wallets
This process may be repeated for other currencies, ETH as example
"},{"location":"sandbox-testing/#configure-freqtrade-to-use-gax-sandbox","title":"Configure Freqtrade to use Gax Sandbox","text":"The aim of this document section
Freqtrade makes use of CCXT which in turn provides a list of URLs to Freqtrade. These include ['test']
and ['api']
.
[Test]
if available will point to an Exchanges sandbox. [Api]
normally used, and resolves to live API target on the exchange To make use of sandbox / test add \"sandbox\": true, to your config.json
\"exchange\": {\n \"name\": \"gdax\",\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
Also insert your
Ensure Freqtrade logs show the sandbox URL, and trades made are shown in sandbox. ** Typically the BTC/USD has the most activity in sandbox to test against.
"},{"location":"sandbox-testing/#gdax-old-candles-problem","title":"GDAX - Old Candles problem","text":"It is my experience that GDAX sandbox candles may be 20+- minutes out of date. This can cause trades to fail as one of Freqtrades safety checks.
To disable this check, add / change the \"outdated_offset\"
parameter in the exchange section of your configuration to adjust for this delay. Example based on the above configuration:
\"exchange\": {\n \"name\": \"gdax\",\n \"sandbox\": true,\n \"key\": \"5wowfxemogxeowo;heiohgmd\",\n \"secret\": \"/ZMH1P62rCVmwefewrgcewX8nh4gob+lywxfwfxwwfxwfNsH1ySgvWCUR/w==\",\n \"password\": \"1bkjfkhfhfu6sr\",\n \"outdated_offset\": 30\n \"pair_whitelist\": [\n \"BTC/USD\"\n
"},{"location":"sql_cheatsheet/","title":"SQL Helper","text":"This page contains some help if you want to edit your sqlite db.
"},{"location":"sql_cheatsheet/#install-sqlite3","title":"Install sqlite3","text":"Ubuntu/Debian installation
sudo apt-get install sqlite3\n
"},{"location":"sql_cheatsheet/#open-the-db","title":"Open the DB","text":"sqlite3\n.open <filepath>\n
"},{"location":"sql_cheatsheet/#table-structure","title":"Table structure","text":""},{"location":"sql_cheatsheet/#list-tables","title":"List tables","text":".tables\n
"},{"location":"sql_cheatsheet/#display-table-structure","title":"Display table structure","text":".schema <table_name>\n
"},{"location":"sql_cheatsheet/#trade-table-structure","title":"Trade table structure","text":"CREATE TABLE trades (\n id INTEGER NOT NULL,\n exchange VARCHAR NOT NULL,\n pair VARCHAR NOT NULL,\n is_open BOOLEAN NOT NULL,\n fee_open FLOAT NOT NULL,\n fee_close FLOAT NOT NULL,\n open_rate FLOAT,\n open_rate_requested FLOAT,\n close_rate FLOAT,\n close_rate_requested FLOAT,\n close_profit FLOAT,\n stake_amount FLOAT NOT NULL,\n amount FLOAT,\n open_date DATETIME NOT NULL,\n close_date DATETIME,\n open_order_id VARCHAR,\n stop_loss FLOAT,\n initial_stop_loss FLOAT,\n stoploss_order_id VARCHAR,\n stoploss_last_update DATETIME,\n max_rate FLOAT,\n sell_reason VARCHAR,\n strategy VARCHAR,\n ticker_interval INTEGER,\n PRIMARY KEY (id),\n CHECK (is_open IN (0, 1))\n);\n
"},{"location":"sql_cheatsheet/#get-all-trades-in-the-table","title":"Get all trades in the table","text":"SELECT * FROM trades;\n
"},{"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":"Warning
Manually selling a pair on the exchange will not be detected by the bot and it will try to sell anyway. Whenever possible, forcesell should be used to accomplish the same thing. It is strongly advised to backup your database file before making any manual changes.
Note
This should not be necessary after /forcesell, as forcesell orders are closed automatically by the bot on the next iteration.
UPDATE trades\nSET is_open=0, close_date=<close_date>, close_rate=<close_rate>, close_profit=close_rate/open_rate-1, sell_reason=<sell_reason> \nWHERE id=<trade_ID_to_update>;\n
"},{"location":"sql_cheatsheet/#example","title":"Example","text":"UPDATE trades\nSET is_open=0, close_date='2017-12-20 03:08:45.103418', close_rate=0.19638016, close_profit=0.0496, sell_reason='force_sell' \nWHERE id=31;\n
"},{"location":"sql_cheatsheet/#insert-manually-a-new-trade","title":"Insert manually a new trade","text":"INSERT INTO trades (exchange, pair, is_open, fee_open, fee_close, open_rate, stake_amount, amount, open_date)\nVALUES ('bittrex', 'ETH/BTC', 1, 0.0025, 0.0025, <open_rate>, <stake_amount>, <amount>, '<datetime>')\n
"},{"location":"sql_cheatsheet/#example_1","title":"Example:","text":"INSERT INTO trades (exchange, pair, is_open, fee_open, fee_close, open_rate, stake_amount, amount, open_date)\nVALUES ('bittrex', 'ETH/BTC', 1, 0.0025, 0.0025, 0.00258580, 0.002, 0.7715262081, '2017-11-28 12:44:24.000000')\n
"},{"location":"sql_cheatsheet/#fix-wrong-fees-in-the-table","title":"Fix wrong fees in the table","text":"If your DB was created before PR#200 was merged (before 12/23/17).
UPDATE trades SET fee=0.0025 WHERE fee=0.005;\n
"},{"location":"stoploss/","title":"Stop Loss","text":"The stoploss
configuration parameter is loss in percentage that should trigger a sale. For example, value -0.10
will cause immediate sell if the profit dips below -10% for a given trade. This parameter is optional.
Most of the strategy files already include the optimal stoploss
value.
Info
All stoploss properties mentioned in this file can be set in the Strategy, or in the configuration. Configuration values will override the strategy values.
"},{"location":"stoploss/#stop-loss-types","title":"Stop Loss Types","text":"At this stage the bot contains the following stoploss support modes:
Those stoploss modes can be on exchange or off 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.
In case of stoploss on exchange there is another parameter called stoploss_on_exchange_interval
. This configures the interval in seconds at which the bot will check the stoploss and update it if necessary.
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. The bot cannot do this 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.
Note
Stoploss on exchange is only supported for Binance (stop-loss-limit) and Kraken (stop-loss-market) as of now.
"},{"location":"stoploss/#static-stop-loss","title":"Static Stop Loss","text":"This is very simple, you define a stop loss of x (as a ratio of price, i.e. x * 100% of price). This will try to sell the asset once the loss exceeds the defined loss.
"},{"location":"stoploss/#trailing-stop-loss","title":"Trailing Stop Loss","text":"The initial value for this is stoploss
, just as you would define your static Stop loss. To enable trailing stoploss:
trailing_stop = True\n
This will now activate an algorithm, which automatically moves the stop loss up every time the price of your asset increases.
For example, simplified math:
In summary: The stoploss will be adjusted to be always be 2% of the highest observed price.
"},{"location":"stoploss/#custom-positive-stoploss","title":"Custom positive stoploss","text":"It is also possible to have a default stop loss, when you are in the red with your buy, but once your profit surpasses a certain percentage, the system will utilize a new stop loss, which can have a different value. For example your default stop loss is 5%, but once you have 1.1% profit, it will be changed to be only a 1% stop loss, which trails the green candles until it goes below them.
Both values require trailing_stop
to be set to true.
trailing_stop_positive = 0.01\n trailing_stop_positive_offset = 0.011\n
The 0.01 would translate to a 1% stop loss, once you hit 1.1% profit. Before this, stoploss
is used for the trailing stoploss.
Read the next section to keep stoploss at 5% of the entry point.
Tip
Make sure to have this value (trailing_stop_positive_offset
) lower than minimal ROI, otherwise minimal ROI will apply first and sell the trade.
It is also possible to use a static stoploss until the offset is reached, and then trail the trade to take profits once the market turns.
If \"trailing_only_offset_is_reached\": true
then the trailing stoploss is only activated once the offset is reached. Until then, the stoploss remains at the configured stoploss
. This option can be used with or without trailing_stop_positive
, but uses trailing_stop_positive_offset
as offset.
trailing_stop_positive_offset = 0.011\n trailing_only_offset_is_reached = true\n
Simplified example:
stoploss = 0.05\n trailing_stop_positive_offset = 0.03\n trailing_only_offset_is_reached = True\n
A stoploss on an open trade can be changed by changing the value in the configuration or strategy and use the /reload_conf
command (alternatively, completely stopping and restarting the bot also works).
The new stoploss value will be applied to open trades (and corresponding log-messages will be generated).
"},{"location":"stoploss/#limitations","title":"Limitations","text":"Stoploss values cannot be changed if trailing_stop
is enabled and the stoploss has already been adjusted, or if Edge is enabled (since Edge would recalculate stoploss based on the current market situation).
This page explains where to customize your strategies, and add new indicators.
"},{"location":"strategy-customization/#install-a-custom-strategy-file","title":"Install a custom strategy file","text":"This is very simple. Copy paste your strategy file into the directory user_data/strategies
.
Let assume you have a class called AwesomeStrategy
in the file AwesomeStrategy.py
:
user_data/strategies
(you should have user_data/strategies/AwesomeStrategy.py
--strategy AwesomeStrategy
(the parameter is the class name)freqtrade trade --strategy AwesomeStrategy\n
"},{"location":"strategy-customization/#develop-your-own-strategy","title":"Develop your own strategy","text":"The bot includes a default strategy file. Also, several other strategies are available in the strategy repository.
You will however most likely have your own idea for a strategy. This document intends to help you develop one for yourself.
To get started, use freqtrade new-strategy --strategy AwesomeStrategy
. This will create a new strategy file from a template, which will be located under user_data/strategies/AwesomeStrategy.py
.
Note
This is just a template file, which will most likely not be profitable out of the box.
"},{"location":"strategy-customization/#anatomy-of-a-strategy","title":"Anatomy of a strategy","text":"A strategy file contains all the information needed to build a good strategy:
The bot also include a sample strategy called SampleStrategy
you can update: user_data/strategies/sample_strategy.py
. You can test it with the parameter: --strategy SampleStrategy
Additionally, there is an attribute called INTERFACE_VERSION
, which defines the version of the strategy interface the bot should use. The current version is 2 - which is also the default when it's not set explicitly in the strategy.
Future versions will require this to be set.
freqtrade trade --strategy AwesomeStrategy\n
For the following section we will use the user_data/strategies/sample_strategy.py file as reference.
Strategies and Backtesting
To avoid problems and unexpected differences between Backtesting and dry/live modes, please be aware that during backtesting the full time-interval is passed to the populate_*()
methods at once. It is therefore best to use vectorized operations (across the whole dataframe, not loops) and avoid index referencing (df.iloc[-1]
), but instead use df.shift()
to get to the previous candle.
Warning: Using future data
Since backtesting passes the full time interval to the populate_*()
methods, the strategy author needs to take care to avoid having the strategy utilize data from the future. Some common patterns for this are listed in the Common Mistakes section of this document.
Buy and sell strategies need indicators. You can add more indicators by extending the list contained in the method populate_indicators()
from your strategy file.
You should only add the indicators used in either populate_buy_trend()
, populate_sell_trend()
, or to populate another indicator, otherwise performance may suffer.
It's important to always return the dataframe without removing/modifying the columns \"open\", \"high\", \"low\", \"close\", \"volume\"
, otherwise these fields would contain something unexpected.
Sample:
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: Raw data from the exchange and parsed by parse_ticker_dataframe()\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
Want more indicator examples?
Look into the user_data/strategies/sample_strategy.py. Then uncomment indicators you need.
"},{"location":"strategy-customization/#strategy-startup-period","title":"Strategy startup period","text":"Most indicators have an instable startup period, in which they are either not available, or the calculation is incorrect. This can lead to inconsistencies, since Freqtrade does not know how long this instable period should be. To account for this, the strategy can be assigned the startup_candle_count
attribute. This should be set to the maximum number of candles that the strategy requires to calculate stable indicators.
In this example strategy, this should be set to 100 (startup_candle_count = 100
), since the longest needed history is 100 candles.
dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100)\n
By letting the bot know how much history is needed, backtest trades can start at the specified timerange during backtesting and hyperopt.
Warning
startup_candle_count
should be below ohlcv_candle_limit
(which is 500 for most exchanges) - since only this amount of candles will be available during Dry-Run/Live Trade operations.
Let's try to backtest 1 month (January 2019) of 5m candles using the an example strategy with EMA100, as above.
freqtrade backtesting --timerange 20190101-20190201 --ticker-interval 5m\n
Assuming startup_candle_count
is set to 100, backtesting knows it needs 100 candles to generate valid buy signals. It will load data from 20190101 - (100 * 5m)
- which is ~2019-12-31 15:30:00. If this data is available, indicators will be calculated with this extended timerange. The instable startup period (up to 2019-01-01 00:00:00) will then be removed before starting backtesting.
Note
If data for the startup period is not available, then the timerange will be adjusted to account for this startup period - so Backtesting would start at 2019-01-01 08:30:00.
"},{"location":"strategy-customization/#buy-signal-rules","title":"Buy signal rules","text":"Edit the method populate_buy_trend()
in your strategy file to update your buy strategy.
It's important to always return the dataframe without removing/modifying the columns \"open\", \"high\", \"low\", \"close\", \"volume\"
, otherwise these fields would contain something unexpected.
This will method will also define a new column, \"buy\"
, which needs to contain 1 for buys, and 0 for \"no action\".
Sample from user_data/strategies/sample_strategy.py
:
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
Note
Buying requires sellers to buy from - therefore volume needs to be > 0 (dataframe['volume'] > 0
) to make sure that the bot does not buy/sell in no-activity periods.
Edit the method populate_sell_trend()
into your strategy file to update your sell strategy. Please note that the sell-signal is only used if use_sell_signal
is set to true in the configuration.
It's important to always return the dataframe without removing/modifying the columns \"open\", \"high\", \"low\", \"close\", \"volume\"
, otherwise these fields would contain something unexpected.
This will method will also define a new column, \"sell\"
, which needs to contain 1 for sells, and 0 for \"no action\".
Sample from user_data/strategies/sample_strategy.py
:
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
"},{"location":"strategy-customization/#minimal-roi","title":"Minimal ROI","text":"This dict defines the minimal Return On Investment (ROI) a trade should reach before selling, independent from the sell signal.
It is of the following format, with the dict key (left side of the colon) being the minutes passed since the trade opened, and the value (right side of the colon) being the percentage.
minimal_roi = {\n \"40\": 0.0,\n \"30\": 0.01,\n \"20\": 0.02,\n \"0\": 0.04\n}\n
The above configuration would therefore mean:
The calculation does include fees.
To disable ROI completely, set it to an insanely high number:
minimal_roi = {\n \"0\": 100\n}\n
While technically not completely disabled, this would sell once the trade reaches 10000% Profit.
"},{"location":"strategy-customization/#stoploss","title":"Stoploss","text":"Setting a stoploss is highly recommended to protect your capital from strong moves against you.
Sample:
stoploss = -0.10\n
This would signify a stoploss of -10%.
For the full documentation on stoploss features, look at the dedicated stoploss page.
If your exchange supports it, it's recommended to also set \"stoploss_on_exchange\"
in the order_types dictionary, so your stoploss is on the exchange and cannot be missed due to network problems, high load or other reasons.
For more information on order_types please look here.
"},{"location":"strategy-customization/#ticker-interval","title":"Ticker interval","text":"This is the set of candles the bot should download and use for the analysis. Common values are \"1m\"
, \"5m\"
, \"15m\"
, \"1h\"
, however all values supported by your exchange should work.
Please note that the same buy/sell signals may work with one interval, but not the other. This setting is accessible within the strategy by using self.ticker_interval
.
The metadata-dict (available for populate_buy_trend
, populate_sell_trend
, populate_indicators
) contains additional information. Currently this is pair
, which can be accessed using metadata['pair']
- and will return a pair in the format XRP/BTC
.
The Metadata-dict should not be modified and does not persist information across multiple calls. Instead, have a look at the section Storing information
"},{"location":"strategy-customization/#storing-information","title":"Storing information","text":"Storing information can be accomplished by creating a new dictionary within the strategy class.
The name of the variable can be chosen at will, but should be prefixed with cust_
to avoid naming collisions with predefined strategy variables.
class Awesomestrategy(IStrategy):\n # Create custom dictionary\n cust_info = {}\n def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n # Check if the entry already exists\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
Warning
The data is not persisted after a bot-restart (or config-reload). Also, the amount of data should be kept smallish (no DataFrames and such), otherwise the bot will start to consume a lot of memory and eventually run out of memory and crash.
Note
If the data is pair-specific, make sure to use pair as one of the keys in the dictionary.
"},{"location":"strategy-customization/#additional-data-dataprovider","title":"Additional data (DataProvider)","text":"The strategy provides access to the DataProvider
. This allows you to get additional data to use in your strategy.
All methods return None
in case of failure (do not raise an exception).
Please always check the mode of operation to select the correct method to get data (samples see below).
"},{"location":"strategy-customization/#possible-options-for-dataprovider","title":"Possible options for DataProvider","text":"available_pairs
- Property with tuples listing cached pairs with their intervals (pair, interval).ohlcv(pair, timeframe)
- Currently cached ticker data for the pair, returns DataFrame or empty DataFrame.historic_ohlcv(pair, timeframe)
- Returns historical data stored on disk.get_pair_dataframe(pair, timeframe)
- This is a universal method, which returns either historical data (for backtesting) or cached live data (for the Dry-Run and Live-Run modes).orderbook(pair, maximum)
- Returns latest orderbook data for the pair, a dict with bids/asks with a total of maximum
entries.market(pair)
- Returns market data for the pair: fees, limits, precisions, activity flag, etc. See ccxt documentation for more details on Market data structure.runmode
- Property containing the current runmode.if 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
Warning about backtesting
Be carefull when using dataprovider in backtesting. historic_ohlcv()
(and get_pair_dataframe()
for the backtesting runmode) provides the full time-range in one go, so please be aware of it and make sure to not \"look into the future\" to avoid surprises when running in dry/live mode).
Warning in hyperopt
This option cannot currently be used during hyperopt.
"},{"location":"strategy-customization/#orderbook","title":"Orderbook","text":"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
Warning
The order book is not part of the historic data which means backtesting and hyperopt will not work if this method is used.
"},{"location":"strategy-customization/#available-pairs","title":"Available Pairs","text":"if self.dp:\n for pair, ticker in self.dp.available_pairs:\n print(f\"available {pair}, {ticker}\")\n
"},{"location":"strategy-customization/#get-data-for-non-tradeable-pairs","title":"Get data for non-tradeable pairs","text":"Data for additional, informative pairs (reference pairs) can be beneficial for some strategies. Ohlcv data for these pairs will be downloaded as part of the regular whitelist refresh process and is available via DataProvider
just as other pairs (see above). These parts will not be traded unless they are also specified in the pair whitelist, or have been selected by Dynamic Whitelisting.
The pairs need to be specified as tuples in the format (\"pair\", \"interval\")
, with pair as the first and time interval as the second argument.
Sample:
def informative_pairs(self):\n return [(\"ETH/USDT\", \"5m\"),\n (\"BTC/TUSD\", \"15m\"),\n ]\n
Warning
As these pairs will be refreshed as part of the regular whitelist refresh, it's best to keep this list short. All intervals 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 time-intervals when possible to avoid hammering the exchange with too many requests and risk being blocked.
"},{"location":"strategy-customization/#additional-data-wallets","title":"Additional data (Wallets)","text":"The strategy provides access to the Wallets
object. This contains the current balances on the exchange.
Note
Wallets is not available during backtesting / hyperopt.
Please always check if Wallets
is available to avoid failures during backtesting.
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
"},{"location":"strategy-customization/#possible-options-for-wallets","title":"Possible options for Wallets","text":"get_free(asset)
- currently available balance to tradeget_used(asset)
- currently tied up balance (open orders)get_total(asset)
- total available balance - sum of the 2 aboveA history of Trades can be retrieved in the strategy by querying the database.
At the top of the file, import Trade.
from freqtrade.persistence import Trade\n
The following example queries for the current pair and trades from today, however other filters can easily be added.
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 == 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
Get amount of stake_currency currently invested in Trades:
if self.config['runmode'].value in ('live', 'dry_run'):\n total_stakes = Trade.total_open_trades_stakes()\n
Retrieve performance per pair. Returns a List of dicts per pair.
if self.config['runmode'].value in ('live', 'dry_run'):\n performance = Trade.get_overall_performance()\n
Sample return value: ETH/BTC had 5 trades, with a total profit of 1.5% (ratio of 0.015).
{'pair': \"ETH/BTC\", 'profit': 0.015, 'count': 5}\n
Warning
Trade history is not available during backtesting or hyperopt.
"},{"location":"strategy-customization/#prevent-trades-from-happening-for-a-specific-pair","title":"Prevent trades from happening for a specific pair","text":"Freqtrade locks pairs automatically for the current candle (until that candle is over) when a pair is sold, preventing an immediate re-buy of that pair.
Locked pairs will show the message Pair <pair> is currently locked.
.
Sometimes it may be desired to lock a pair after certain events happen (e.g. multiple losing trades in a row).
Freqtrade has an easy method to do this from within the strategy, by calling self.lock_pair(pair, until)
. until
must be a datetime object in the future, after which trading will be reenabled for that pair.
Locks can also be lifted manually, by calling self.unlock_pair(pair)
.
To verify if a pair is currently locked, use self.is_pair_locked(pair)
.
Note
Locked pairs are not persisted, so a restart of the bot, or calling /reload_conf
will reset locked pairs.
Warning
Locking pairs is not functioning during backtesting.
"},{"location":"strategy-customization/#pair-locking-example","title":"Pair locking example","text":"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 == 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
"},{"location":"strategy-customization/#print-created-dataframe","title":"Print created dataframe","text":"To inspect the created dataframe, you can issue a print-statement in either populate_buy_trend()
or populate_sell_trend()
. You may also want to print the pair so it's clear what data is currently shown.
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
Printing more than a few rows is also possible (simply use print(dataframe)
instead of print(dataframe.tail())
), however not recommended, as that will be very verbose (~500 lines per pair every 5 seconds).
If you want to use a strategy from a different directory you can pass --strategy-path
freqtrade trade --strategy AwesomeStrategy --strategy-path /some/directory\n
"},{"location":"strategy-customization/#derived-strategies","title":"Derived strategies","text":"The strategies can be derived from other strategies. This avoids duplication of your custom strategy code. You can use this technique to override small parts of your main strategy, leaving the rest untouched:
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
Both attributes and methods may be overriden, altering behavior of the original strategy in a way you need.
"},{"location":"strategy-customization/#common-mistakes-when-developing-strategies","title":"Common mistakes when developing strategies","text":"Backtesting analyzes the whole time-range at once for performance reasons. Because of this, strategy authors need to make sure that strategies do not look-ahead into the future. This is a common pain-point, which can cause huge differences between backtesting and dry/live run methods, since they all use data which is not available during dry/live runs, so these strategies will perform well during backtesting, but will fail / perform badly in real conditions.
The following lists some common patterns which should be avoided to prevent frustration:
shift(-1)
. This uses data from the future, which is not available..iloc[-1]
or any other absolute position in the dataframe, this will be different between dry-run and backtesting.dataframe['volume'].mean()
. This uses the full DataFrame for backtesting, including data from the future. Use dataframe['volume'].rolling(<window>).mean()
instead.resample('1h')
. This uses the left border of the interval, so moves data from an hour to the start of the hour. Use .resample('1h', label='right')
instead.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.
We also got a strategy-sharing channel in our Slack community which is a great place to get and/or share ideas.
"},{"location":"strategy-customization/#next-step","title":"Next step","text":"Now you have a perfect strategy you probably want to backtest it. Your next step is to learn How to use the Backtesting.
"},{"location":"strategy_analysis_example/","title":"Strategy analysis example","text":"Debugging a strategy can be time-consuming. Freqtrade offers helper functions to visualize raw data. The following assumes you work with SampleStrategy, data for 5m timeframe from Binance and have downloaded them into the data directory in the default location.
"},{"location":"strategy_analysis_example/#setup","title":"Setup","text":"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[\"ticker_interval\"] = \"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
# 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[\"ticker_interval\"],\n pair=pair)\n\n# Confirm success\nprint(\"Loaded \" + str(len(candles)) + f\" rows of data for {pair} from {data_location}\")\ncandles.head()\n
"},{"location":"strategy_analysis_example/#load-and-run-strategy","title":"Load and run strategy","text":"# 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
"},{"location":"strategy_analysis_example/#display-the-trade-details","title":"Display the trade details","text":"data.head()
would also work, however most indicators have some \"startup\" data at the top of the dataframe.crossed*()
functions with completely different unitsanalyze_ticker()
does not necessarily mean that 200 trades will be made during backtesting. * Assuming you use only one condition such as, df['rsi'] < 30
as buy condition, this will generate multiple \"buy\" signals for each pair in sequence (until rsi returns > 29). The bot will only buy on the first of these signals (and also only if a trade-slot (\"max_open_trades\") is still available), or on one of the middle signals, as soon as a \"slot\" becomes available. # Report results\nprint(f\"Generated {df['buy'].sum()} buy signals\")\ndata = df.set_index('date', drop=False)\ndata.tail()\n
"},{"location":"strategy_analysis_example/#load-existing-objects-into-a-jupyter-notebook","title":"Load existing objects into a Jupyter notebook","text":"The following cells assume that you have already generated data using the cli. They will allow you to drill deeper into your results, and perform analysis which otherwise would make the output very difficult to digest due to information overload.
"},{"location":"strategy_analysis_example/#load-backtest-results-to-pandas-dataframe","title":"Load backtest results to pandas dataframe","text":"Analyze a trades dataframe (also used below for plotting)
from freqtrade.data.btanalysis import load_backtest_data\n\n# Load backtest results\ntrades = load_backtest_data(config[\"user_data_dir\"] / \"backtest_results/backtest-result.json\")\n\n# Show value-counts per pair\ntrades.groupby(\"pair\")[\"sell_reason\"].value_counts()\n
"},{"location":"strategy_analysis_example/#load-live-trading-results-into-a-pandas-dataframe","title":"Load live trading results into a pandas dataframe","text":"In case you did already some trading and want to analyze your performance
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
"},{"location":"strategy_analysis_example/#analyze-the-loaded-trades-for-trade-parallelism","title":"Analyze the loaded trades for trade parallelism","text":"This can be useful to find the best max_open_trades
parameter, when used with backtesting in conjunction with --disable-max-market-positions
.
analyze_trade_parallelism()
returns a timeseries dataframe with an \"open_trades\" column, specifying the number of open trades for each candle.
from freqtrade.data.btanalysis import analyze_trade_parallelism\n\n# Analyze the above\nparallel_trades = analyze_trade_parallelism(trades, '5m')\n\n\nparallel_trades.plot()\n
"},{"location":"strategy_analysis_example/#plot-results","title":"Plot results","text":"Freqtrade offers interactive plotting capabilities based on plotly.
from freqtrade.plot.plotting import generate_candlestick_graph\n# Limit graph period to keep plotly quick and reactive\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,\n indicators1=['sma20', 'ema50', 'ema55'],\n indicators2=['rsi', 'macd', 'macdsignal', 'macdhist']\n )\n
# Show graph inline\n# graph.show()\n\n# Render graph in a seperate window\ngraph.show(renderer=\"browser\")\n
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.
"},{"location":"telegram-usage/","title":"Telegram usage","text":""},{"location":"telegram-usage/#setup-your-telegram-bot","title":"Setup your Telegram bot","text":"Below we explain how to create your Telegram Bot, and how to get your Telegram user id.
"},{"location":"telegram-usage/#1-create-your-telegram-bot","title":"1. Create your Telegram bot","text":"Start a chat with the Telegram BotFather
Send the message /newbot
.
BotFather response:
Alright, a new bot. How are we going to call it? Please choose a name for your bot.
Choose the public name of your bot (e.x. Freqtrade bot
)
BotFather response:
Good. Now let's choose a username for your bot. It must end in bot
. Like this, for example: TetrisBot or tetris_bot.
Choose the name id of your bot and send it to the BotFather (e.g. \"My_own_freqtrade_bot
\")
BotFather response:
Done! Congratulations on your new bot. You will find it at t.me/yourbots_name_bot
. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you've finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.
Use this token to access the HTTP API: 22222222:APITOKEN
For a description of the Bot API, see this page: https://core.telegram.org/bots/api Father bot will return you the token (API key)
Copy the API Token (22222222:APITOKEN
in the above example) and keep use it for the config parameter token
.
Don't forget to start the conversation with your bot, by clicking /START
button
Talk to the userinfobot
Get your \"Id\", you will use it for the config parameter chat_id
.
Per default, the Telegram bot shows predefined commands. Some commands are only available by sending them to the bot. The table below list the official commands. You can ask at any moment for help with /help
.
/start
Starts the trader /stop
Stops the trader /stopbuy
Stops the trader from opening new trades. Gracefully closes open trades according to their rules. /reload_conf
Reloads the configuration file /show_config
Shows part of the current configuration with relevant settings to operation /status
Lists all open trades /status table
List all open trades in a table format. Pending buy orders are marked with an asterisk () Pending sell orders are marked with a double asterisk (*) /count
Displays number of trades used and available /profit
Display a summary of your profit/loss from close trades and some stats about your performance /forcesell <trade_id>
Instantly sells the given trade (Ignoring minimum_roi
). /forcesell all
Instantly sells all open trades (Ignoring minimum_roi
). /forcebuy <pair> [rate]
Instantly buys the given pair. Rate is optional. (forcebuy_enable
must be set to True) /performance
Show performance of each finished trade grouped by pair /balance
Show account balance per currency /daily <n>
7 Shows profit or loss per day, over the last n days /whitelist
Show the current whitelist /blacklist [pair]
Show the current blacklist, or adds a pair to the blacklist. /edge
Show validated pairs by Edge if it is enabled. /help
Show help message /version
Show version"},{"location":"telegram-usage/#telegram-commands-in-action","title":"Telegram commands in action","text":"Below, example of Telegram message you will receive for each command.
"},{"location":"telegram-usage/#start","title":"/start","text":"Status: running
Stopping trader ...
Status: stopped
status: Setting max_open_trades to 0. Run /reload_conf to reset.
Prevents the bot from opening new trades by temporarily setting \"max_open_trades\" to 0. Open trades will be handled via their regular rules (ROI / Sell-signal, stoploss, ...).
After this, give the bot time to close off open trades (can be checked via /status table
). Once all positions are sold, run /stop
to completely stop the bot.
/reload_conf
resets \"max_open_trades\" to the value set in the configuration and resets this command.
Warning
The stop-buy signal is ONLY active while the bot is running, and is not persisted anyway, so restarting the bot will cause this to reset.
"},{"location":"telegram-usage/#status","title":"/status","text":"For each open trade, the bot will send you the following message.
Trade ID: 123
(since 1 days ago)
Current Pair: CVC/BTC Open Since: 1 days ago
Amount: 26.64180098
Open Rate: 0.00007489
Current Rate: 0.00007489
Current Profit: 12.95%
Stoploss: 0.00007389 (-0.02%)
Return the status of all open trades in a table format.
ID Pair Since Profit\n---- -------- ------- --------\n 67 SC/BTC 1 d 13.33%\n 123 CVC/BTC 1 h 12.95%\n
"},{"location":"telegram-usage/#count","title":"/count","text":"Return the number of trades used and available.
current max\n--------- -----\n 2 10\n
"},{"location":"telegram-usage/#profit","title":"/profit","text":"Return a summary of your profit/loss and performance.
ROI: Close trades \u2219 0.00485701 BTC (258.45%)
\u2219 62.968 USD
ROI: All trades \u2219 0.00255280 BTC (143.43%)
\u2219 33.095 EUR
Total Trade Count: 138
First Trade opened: 3 days ago
Latest Trade opened: 2 minutes ago
Avg. Duration: 2:33:45
Best Performing: PAY/BTC: 50.23%
BITTREX: Selling BTC/LTC with limit 0.01650000 (profit: ~-4.07%, -0.00008168)
BITTREX: Buying ETH/BTC with limit 0.03400000
(1.000000 ETH
, 225.290 USD
)
Note that for this to work, forcebuy_enable
needs to be set to true.
More details
","text":""},{"location":"telegram-usage/#performance","title":"/performanceReturn the performance of each crypto-currency the bot has sold.
Performance: 1. RCN/BTC 57.77%
2. PAY/BTC 56.91%
3. VIB/BTC 47.07%
4. SALT/BTC 30.24%
5. STORJ/BTC 27.24%
...
Return the balance of all crypto-currency your have on the exchange.
Currency: BTC Available: 3.05890234 Balance: 3.05890234 Pending: 0.0
Currency: CVC Available: 86.64180098 Balance: 86.64180098 Pending: 0.0
","text":""},{"location":"telegram-usage/#daily","title":"/dailyPer default /daily
will return the 7 last days. The example below if for /daily 3
:
Daily Profit over the last 3 days:
Day Profit BTC Profit USD\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
","text":""},{"location":"telegram-usage/#whitelist","title":"/whitelist Shows the current whitelist
Using whitelist StaticPairList
with 22 pairs IOTA/BTC, NEO/BTC, TRX/BTC, VET/BTC, ADA/BTC, ETC/BTC, NCASH/BTC, DASH/BTC, XRP/BTC, XVG/BTC, EOS/BTC, LTC/BTC, OMG/BTC, BTG/BTC, LSK/BTC, ZEC/BTC, HOT/BTC, IOTX/BTC, XMR/BTC, AST/BTC, XLM/BTC, NANO/BTC
Shows the current blacklist. If Pair is set, then this pair will be added to the pairlist. Also supports multiple pairs, seperated by a space. Use /reload_conf
to reset the blacklist.
Using blacklist StaticPairList
with 2 pairs DODGE/BTC
, HOT/BTC
.
Shows pairs validated by Edge along with their corresponding winrate, expectancy and stoploss values.
Edge only validated following pairs:
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
","text":""},{"location":"telegram-usage/#version","title":"/version Version: 0.14.3
Besides the Live-Trade and Dry-Run run modes, the backtesting
, edge
and hyperopt
optimization subcommands, and the download-data
subcommand which prepares historical data, the bot contains a number of utility subcommands. They are described in this section.
Creates the directory structure to hold your files for freqtrade. Will also create strategy and hyperopt examples for you to get started. Can be used multiple times - using --reset
will reset the sample strategy and hyperopt files to their default state.
usage: freqtrade create-userdir [-h] [--userdir PATH] [--reset]\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
Warning
Using --reset
may result in loss of data, since this will overwrite all sample files without asking again.
\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
"},{"location":"utils/#create-new-config","title":"Create new config","text":"Creates a new configuration file, asking some questions which are important selections for a configuration.
usage: freqtrade new-config [-h] [-c PATH]\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
Warning
Only vital questions are asked. Freqtrade offers a lot more configuration possibilities, which are listed in the Configuration documentation
"},{"location":"utils/#create-config-examples","title":"Create config examples","text":"$ 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'): 5\n? Please insert your ticker interval: 15m\n? Please insert your display Currency (for reporting): USD\n? Select exchange binance\n? Do you want to enable Telegram? No\n
"},{"location":"utils/#create-new-strategy","title":"Create new strategy","text":"Creates a new strategy from a template similar to SampleStrategy. The file will be named inline with your class name, and will not overwrite existing files.
Results will be located in user_data/strategies/<strategyclassname>.py
.
usage: freqtrade new-strategy [-h] [--userdir PATH] [-s NAME]\n [--template {full,minimal}]\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}\n Use a template which is either `minimal` or `full`\n (containing multiple sample indicators). Default:\n `full`.\n
"},{"location":"utils/#sample-usage-of-new-strategy","title":"Sample usage of new-strategy","text":"freqtrade new-strategy --strategy AwesomeStrategy\n
With custom user directory
freqtrade new-strategy --userdir ~/.freqtrade/ --strategy AwesomeStrategy\n
"},{"location":"utils/#create-new-hyperopt","title":"Create new hyperopt","text":"Creates a new hyperopt from a template similar to SampleHyperopt. The file will be named inline with your class name, and will not overwrite existing files.
Results will be located in user_data/hyperopts/<classname>.py
.
usage: freqtrade new-hyperopt [-h] [--userdir PATH] [--hyperopt NAME]\n [--template {full,minimal}]\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}\n Use a template which is either `minimal` or `full`\n (containing multiple sample indicators). Default:\n `full`.\n
"},{"location":"utils/#sample-usage-of-new-hyperopt","title":"Sample usage of new-hyperopt","text":"freqtrade new-hyperopt --hyperopt AwesomeHyperopt\n
With custom user directory
freqtrade new-hyperopt --userdir ~/.freqtrade/ --hyperopt AwesomeHyperopt\n
"},{"location":"utils/#list-strategies-and-list-hyperopts","title":"List Strategies and List Hyperopts","text":"Use the list-strategies
subcommand to see all strategies in one particular directory and the list-hyperopts
subcommand to list custom Hyperopts.
These subcommands are useful for finding problems in your environment with loading strategies or hyperopt classes: modules with strategies or hyperopt classes that contain errors and failed to load are printed in red (LOAD FAILED), while strategies or hyperopt classes with duplicate names are printed in yellow (DUPLICATE NAME).
usage: freqtrade list-strategies [-h] [-v] [--logfile FILE] [-V] [-c PATH]\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
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
Warning
Using these commands will try to load all python files from a directory. This can be a security risk if untrusted files reside in this directory, since all module-level code is executed.
Example: Search default strategies and hyperopts directories (within the default userdir).
freqtrade list-strategies\nfreqtrade list-hyperopts\n
Example: Search strategies and hyperopts directory within the userdir.
freqtrade list-strategies --userdir ~/.freqtrade/\nfreqtrade list-hyperopts --userdir ~/.freqtrade/\n
Example: Search dedicated strategy path.
freqtrade list-strategies --strategy-path ~/.freqtrade/strategies/\n
Example: Search dedicated hyperopt path.
freqtrade list-hyperopt --hyperopt-path ~/.freqtrade/hyperopts/\n
"},{"location":"utils/#list-exchanges","title":"List Exchanges","text":"Use the list-exchanges
subcommand to see the exchanges available for the bot.
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
$ 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
$ 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
Use the list-timeframes
subcommand to see the list of ticker intervals (timeframes) available for the exchange.
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
$ 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
$ for i in `freqtrade list-exchanges -1`; do freqtrade list-timeframes --exchange $i; done\n
The list-pairs
and list-markets
subcommands allow to see the pairs/markets available on exchange.
Pairs are markets with the '/' character between the base currency part and the quote currency part in the market symbol. For example, in the 'ETH/BTC' pair 'ETH' is the base currency, while 'BTC' is the quote currency.
For pairs traded by Freqtrade the pair quote currency is defined by the value of the stake_currency
configuration setting.
You can print info about any pair/market with these subcommands - and you can filter output by quote-currency using --quote BTC
, or by base-currency using --base ETH
options correspondingly.
These subcommands have same usage and same set of available options:
usage: freqtrade list-markets [-h] [-v] [--logfile FILE] [-V] [-c PATH]\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
By default, only active pairs/markets are shown. Active pairs/markets are those that can currently be traded on the exchange. The see the list of all pairs/markets (not only the active ones), use the -a
/-all
option.
Pairs/markets are sorted by its symbol string in the printed output.
"},{"location":"utils/#examples","title":"Examples","text":"$ freqtrade list-pairs --quote USD --print-json\n
config_binance.json
configuration file (i.e. on the \"Binance\" exchange) with base currencies BTC or ETH and quote currencies USDT or USD, as the human-readable list with summary:$ freqtrade list-pairs -c config_binance.json --all --base BTC ETH --quote USDT USD --print-list\n
$ freqtrade list-markets --exchange kraken --all\n
"},{"location":"utils/#test-pairlist","title":"Test pairlist","text":"Use the test-pairlist
subcommand to test the configuration of dynamic pairlists.
Requires a configuration with specified pairlists
attribute. Can be used to generate static pairlists to be used during backtesting / hyperopt.
usage: freqtrade test-pairlist [-h] [-c PATH]\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
"},{"location":"utils/#examples_1","title":"Examples","text":"Show whitelist when using a dynamic pairlist.
freqtrade test-pairlist --config config.json --quote USDT BTC\n
"},{"location":"utils/#list-hyperopt-results","title":"List Hyperopt results","text":"You can list the hyperoptimization epochs the Hyperopt module evaluated previously with the hyperopt-list
subcommand.
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] [--no-color]\n [--print-json] [--no-details]\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 on above average time.\n --max-avg-time FLOAT Select epochs on under average time.\n --min-avg-profit FLOAT\n Select epochs on above average profit.\n --max-avg-profit FLOAT\n Select epochs on below average profit.\n --min-total-profit FLOAT\n Select epochs on above total profit.\n --max-total-profit FLOAT\n Select epochs on below total profit.\n --no-color Disable colorization of hyperopt results. May be\n useful if you are redirecting output to a file.\n --print-json Print best result detailization in JSON format.\n --no-details Do not print best epoch details.\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
"},{"location":"utils/#examples_2","title":"Examples","text":"List all results, print details of the best result at the end:
freqtrade hyperopt-list\n
List only epochs with positive profit. Do not print the details of the best epoch, so that the list can be iterated in a script:
freqtrade hyperopt-list --profitable --no-details\n
"},{"location":"utils/#show-details-of-hyperopt-results","title":"Show details of Hyperopt results","text":"You can show the details of any hyperoptimization epoch previously evaluated by the Hyperopt module with the hyperopt-show
subcommand.
usage: freqtrade hyperopt-show [-h] [-v] [--logfile FILE] [-V] [-c PATH]\n [-d PATH] [--userdir PATH] [--best]\n [--profitable] [-n INT] [--print-json]\n [--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 best result detailization in JSON format.\n --no-header Do not print epoch details header.\n
"},{"location":"utils/#examples_3","title":"Examples","text":"Print details for the epoch 168 (the number of the epoch is shown by the hyperopt-list
subcommand or by Hyperopt itself during hyperoptimization run):
freqtrade hyperopt-show -n 168\n
Prints JSON data with details for the last best epoch (i.e., the best of all epochs):
freqtrade hyperopt-show --best -n -1 --print-json --no-header\n
"},{"location":"webhook-config/","title":"Webhook usage","text":""},{"location":"webhook-config/#configuration","title":"Configuration","text":"Enable webhooks by adding a webhook-section to your configuration file, and setting webhook.enabled
to true
.
Sample configuration (tested using IFTTT).
\"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}\"\n },\n \"webhooksellcancel\": {\n \"value1\": \"Cancelling Open Sell Order for {pair}\",\n \"value2\": \"limit {limit:8f}\",\n \"value3\": \"profit: {profit_amount:8f} {stake_currency}\"\n },\n \"webhookstatus\": {\n \"value1\": \"Status: {status}\",\n \"value2\": \"\",\n \"value3\": \"\"\n }\n },\n
The url in webhook.url
should point to the correct url for your webhook. If you're using IFTTT (as shown in the sample above) please insert our event and key to the url.
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.
"},{"location":"webhook-config/#webhookbuy","title":"Webhookbuy","text":"The fields in webhook.webhookbuy
are filled when the bot executes a buy. Parameters are filled using string.format. Possible parameters are:
exchange
pair
limit
amount
open_date
stake_amount
stake_currency
fiat_currency
order_type
current_rate
The fields in webhook.webhookbuycancel
are filled when the bot cancels a buy order. Parameters are filled using string.format. Possible parameters are:
exchange
pair
limit
amount
open_date
stake_amount
stake_currency
fiat_currency
order_type
current_rate
The fields in webhook.webhooksell
are filled when the bot sells a trade. Parameters are filled using string.format. Possible parameters are:
exchange
pair
gain
limit
amount
open_rate
current_rate
profit_amount
profit_percent
stake_currency
fiat_currency
sell_reason
order_type
open_date
close_date
The fields in webhook.webhooksellcancel
are filled when the bot cancels a sell order. Parameters are filled using string.format. Possible parameters are:
exchange
pair
gain
limit
amount
open_rate
current_rate
profit_amount
profit_percent
stake_currency
fiat_currency
sell_reason
order_type
open_date
close_date
The fields in webhook.webhookstatus
are used for regular status messages (Started / Stopped / ...). Parameters are filled using string.format.
The only possible value here is {status}
.