0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

Freqtrade:简单的加密货币自动交易机器人

科技绿洲 来源:Python实用宝典 作者:Python实用宝典 2023-10-30 10:45 次阅读

Freqtrade 是一个用 Python 编写的免费开源加密货币交易机器人。它旨在支持所有主要交易所并通过 Telegram 或 webUI 进行控制。功能包含回测、绘图和资金管理工具以及通过机器学习的策略优化。
特性:

1. 基于 Python 3.8+ :适用于任何操作系统 - Windows、macOS 和 Linux
2. 持久性 :持久性是通过 sqlite 实现的。
3. Dry-run :不花钱运行机器人。
4. 回测模拟买入/卖出策略。
5. 通过机器学习进行策略优化 :使用机器学习通过真实的交易所数据优化买入/卖出策略参数
6. 边缘头寸规模计算您的胜率、风险回报率、最佳止损位并在为每个特定市场建立头寸之前调整头寸规模。
7. 白名单加密货币 :选择你要交易的加密货币或使用动态白名单。
8. 黑名单加密货币 :选择你想要避免的加密货币。
9. 内置 WebUI :内置 Web UI 来管理你的机器人。
10. 可通过 Telegram管理:使用 Telegram 管理机器人。
11. 以法定货币显示盈亏 :以法定货币显示你的盈亏。
12. 表现状态报告 :提供你当前交易的表现状态。

1.准备

开始之前,你要确保Python和pip已经成功安装在电脑上,如果没有,可以访问这篇文章:超详细Python安装指南 进行安装。

**(可选1) **如果你用Python的目的是数据分析,可以直接安装Anaconda:Python数据分析与挖掘好帮手—Anaconda,它内置了Python和pip.

**(可选2) **此外,推荐大家用VSCode编辑器,它有许多的优点:Python 编程的最好搭档—VSCode 详细指南

在Linux/MacOS下,三行命令就能完成安装:

git clone -b develop https://github.com/freqtrade/freqtrade.git
cd freqtrade
./setup.sh --install

Windows环境下打开Cmd(开始—运行—CMD),输入命令安装依赖:

git clone https://github.com/freqtrade/freqtrade.git
cd freqtrade
# 安装ta-lib
pip install build_helpers/TA_Lib-0.4.24-cp38-cp38-win_amd64.whl
pip install -r requirements.txt
pip install -e .
freqtrade

请注意,此处安装ta-lib时项目方提供了python3.8/3.9/3.10,其他Python版本请自行搜索下载

输入freqtrade时,显示以下信息说明安装成功:

(freqtrade) D:CODEtraderfreqtrade >freqtrade
2022-02-17 19:40:50,174 - freqtrade - ERROR - Usage of Freqtrade requires a subcommand to be specified.
To have the bot executing trades in live/dry-run modes, depending on the value of the `dry_run` setting in the config, run Freqtrade as `freqtrade trade [options...]`.
To see the full list of options available, please use `freqtrade --help` or `freqtrade < command > --help`.

2.快速开始

下面教你如何开发一个简单的交易策略。

一个策略文件往往包含这些东西:

  • 指标
  • 购买规则
  • 卖出规则
  • 建议最低投资回报率
  • 强烈推荐止损

Freqtrade使用 Pandas 作为基础数据结构,它底层的OHLCV都是以Dataframe的格式存储的。

Dataframe数据流中每一行数据代表图表上的一根K线,最新的K线始终是数据库中最后一根。

dataframe.head()
                       date open high low close volume
0 2021-11-09 23:25:00+00:00  67279.67  67321.84  67255.01  67300.97   44.62253
1 2021-11-09 23:30:00+00:00  67300.97  67301.34  67183.03  67187.01   61.38076
2 2021-11-09 23:35:00+00:00  67187.02  67187.02  67031.93  67123.81  113.42728
3 2021-11-09 23:40:00+00:00  67123.80  67222.40  67080.33  67160.48   78.96008
4 2021-11-09 23:45:00+00:00  67160.48  67160.48  66901.26  66943.37  111.39292

Pandas 提供了计算指标的快速方法。为了从这种速度中受益,建议不要使用循环,而是使用矢量化方法。

矢量化操作在整个数据范围内执行计算,因此,与遍历每一行相比,在计算指标时要快得多。

dataframe.loc[(dataframe['rsi'] > 30), 'buy'] = 1

类似于上面这样的赋值方法,会自动设置rsi大于30的数据的buy列的值为1。

买入规则

def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) - > DataFrame:
    """
    Based on TA indicators, populates the buy signal for the given dataframe
    :param dataframe: DataFrame populated with indicators
    :param metadata: Additional information, like the currently traded pair
    :return: DataFrame with buy column
    """
    dataframe.loc[
        (
            (qtpylib.crossed_above(dataframe['rsi'], 30)) & # Signal: RSI crosses above 30
            (dataframe['tema'] <= dataframe['bb_middleband']) & # Guard
            (dataframe['tema'] > dataframe['tema'].shift(1)) & # Guard
            (dataframe['volume'] > 0) # Make sure Volume is not 0
        ),
        'buy'] = 1

    return dataframe

请注意,一定要不修改并返回"open", "high", "low", "close", "volume"列,这些是基础行情数据,如果返回错误的数据将可能会导致一些奇怪数据的产生。

如上所示的方法中,符合条件的数据的buy值会被设为1代表买入,否则为0或nan值。

卖出规则

def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) - > DataFrame:
    """
    Based on TA indicators, populates the sell signal for the given dataframe
    :param dataframe: DataFrame populated with indicators
    :param metadata: Additional information, like the currently traded pair
    :return: DataFrame with buy column
    """
    dataframe.loc[
        (
            (qtpylib.crossed_above(dataframe['rsi'], 70)) & # Signal: RSI crosses above 70
            (dataframe['tema'] > dataframe['bb_middleband']) & # Guard
            (dataframe['tema'] < dataframe['tema'].shift(1)) & # Guard
            (dataframe['volume'] > 0) # Make sure Volume is not 0
        ),
        'sell'] = 1
    return dataframe

与买入类似,这里不赘述了。

最小投资回报率

在类中增加这个初始化变量,能控制投资回报率:

minimal_roi = {
    "40": 0.0,
    "30": 0.01,
    "20": 0.02,
    "0": 0.04
}

上述配置意味着:

  • 只要达到 4% 的利润就卖出
  • 达到 2% 利润时卖出(20 分钟后生效)
  • 达到 1% 利润时卖出(30 分钟后生效)
  • 交易未亏损时卖出(40 分钟后生效)

此处的计算包含费用。

要完全禁用 ROI,请将其设置为一个非常高的数字:

minimal_roi = {
    "0": 100
}

虽然从技术上讲并没有完全禁用,但一旦交易达到 10000% 利润,它就会卖出。

止损

强烈建议设置止损,以保护资金免受不利的剧烈波动。

设置 10% 止损的示例:

stoploss = -0.10

一个完整代码如下:

上滑查看更多代码

# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement
# flake8: noqa: F401
# isort: skip_file
# --- Do not remove these libs ---
from reimport A
import numpyas np# noqa
import pandasas pd# noqa
from pandasimport DataFrame

from freqtrade.strategyimport (BooleanParameter, CategoricalParameter, DecimalParameter,
IStrategy, IntParameter)

# --------------------------------
# 你自己所需要的模块放在这里
import talib.abstractas ta
import freqtrade.vendor.qtpylib.indicatorsas qtpylib


# This class is a sample. Feel free to customize it.
class SampleStrategy(IStrategy):
"""
This is a sample strategy to inspire you.
More information in https://www.freqtrade.io/en/latest/strategy-customization/
You can:
:return: a Dataframe with all mandatory indicators for the strategies
- Rename the class name (Do not forget to update class_name)
- Add any methods you want to build your strategy
- Add any lib you need to build your strategy
You must keep:
- the lib in the section "Do not remove these libs"
- the methods: populate_indicators, populate_buy_trend, populate_sell_trend
You should keep:
- timeframe, minimal_roi, stoploss, trailing_*
"""

# Strategy interface version - allow new iterations of the strategy interface.
# Check the documentation or the Sample strategy to get the latest version.
INTERFACE_VERSION =2

# 设定最小投资回报
minimal_roi = {
"60":0.01,
"30":0.02,
"0":0.04
}

# 止损
stoploss =-0.10

# 指标参数
buy_rsi = IntParameter(low=1, high=50, default=30, space='buy', optimize=True, load=True)
sell_rsi = IntParameter(low=50, high=100, default=70, space='sell', optimize=True, load=True)

# K线时间
timeframe ='5m'

# 在新K线出现时执行
process_only_new_candles =False

# These values can be overridden in the "ask_strategy" section in the config.
use_sell_signal =True
sell_profit_only =False
ignore_roi_if_buy_signal =False

# 预准备K线数
startup_candle_count: int =30

# 下单类型
order_types = {
'buy':'limit',
'sell':'limit',
'stoploss':'market',
'stoploss_on_exchange':False
}

# 订单有效时间(gtc: 除非取消否则一直有效)
order_time_in_force = {
'buy':'gtc',
'sell':'gtc'
}

plot_config = {
'main_plot': {
'tema': {},
'sar': {'color':'white'},
},
'subplots': {
"MACD": {
'macd': {'color':'blue'},
'macdsignal': {'color':'orange'},
},
"RSI": {
'rsi': {'color':'red'},
}
}
}

def informative_pairs(self):
"""
Define additional, informative pair/interval combinations to be cached from the exchange.
These pair/interval combinations are non-tradeable, unless they are part
of the whitelist as well.
For more information, please consult the documentation
:return: List of tuples in the format (pair, interval)
Sample: return [("ETH/USDT", "5m"),
("BTC/USDT", "15m"),
]
"""

return []

def populate_indicators(self, dataframe: DataFrame, metadata: dict) - > DataFrame:
"""
Adds several different TA indicators to the given DataFrame
Performance Note: For the best performance be frugal on the number of indicators
you are using. Let uncomment only the indicator you are using in your strategies
or your hyperopt configuration, otherwise you will waste your memory and CPU usage.
:param dataframe: Dataframe with data from the exchange
:param metadata: Additional information, like the currently traded pair
:return: a Dataframe with all mandatory indicators for the strategies
"""


# Momentum Indicators
# ------------------------------------

dataframe['adx'] = ta.ADX(dataframe)
dataframe['rsi'] = ta.RSI(dataframe)
stoch_fast = ta.STOCHF(dataframe)
dataframe['fastd'] = stoch_fast['fastd']
dataframe['fastk'] = stoch_fast['fastk']

# MACD
macd = ta.MACD(dataframe)
dataframe['macd'] = macd['macd']
dataframe['macdsignal'] = macd['macdsignal']
dataframe['macdhist'] = macd['macdhist']

# MFI
dataframe['mfi'] = ta.MFI(dataframe)

# Bollinger Bands
bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)
dataframe['bb_lowerband'] = bollinger['lower']
dataframe['bb_middleband'] = bollinger['mid']
dataframe['bb_upperband'] = bollinger['upper']
dataframe["bb_percent"] = (
(dataframe["close"] - dataframe["bb_lowerband"]) /
(dataframe["bb_upperband"] - dataframe["bb_lowerband"])
)
dataframe["bb_width"] = (
(dataframe["bb_upperband"] - dataframe["bb_lowerband"]) / dataframe["bb_middleband"]
)

# Parabolic SAR
dataframe['sar'] = ta.SAR(dataframe)

# TEMA - Triple Exponential Moving Average
dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9)

hilbert = ta.HT_SINE(dataframe)
dataframe['htsine'] = hilbert['sine']
dataframe['htleadsine'] = hilbert['leadsine']

return dataframe

def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) - > DataFrame:
"""
Based on TA indicators, populates the buy signal for the given dataframe
:param dataframe: DataFrame populated with indicators
:param metadata: Additional information, like the currently traded pair
:return: DataFrame with buy column
"""

dataframe.loc[
(
# Signal: RSI crosses above 30
(qtpylib.crossed_above(dataframe['rsi'], self.buy_rsi.value)) &
(dataframe['tema'] <= dataframe['bb_middleband']) &# Guard: tema below BB middle
(dataframe['tema'] > dataframe['tema'].shift(1)) &# Guard: tema is raising
(dataframe['volume'] >0)# Make sure Volume is not 0
),'buy'] =1

return dataframe

def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) - > DataFrame:
"""
Based on TA indicators, populates the sell signal for the given dataframe
:param dataframe: DataFrame populated with indicators
:param metadata: Additional information, like the currently traded pair
:return: DataFrame with sell column
"""

dataframe.loc[
(
# Signal: RSI crosses above 70
(qtpylib.crossed_above(dataframe['rsi'], self.sell_rsi.value)) &
(dataframe['tema'] > dataframe['bb_middleband']) &# Guard: tema above BB middle
(dataframe['tema'] < dataframe['tema'].shift(1)) &# Guard: tema is falling
(dataframe['volume'] >0)# Make sure Volume is not 0
),'sell'] =1
return dataframe

3.启动机器人

启动机器人前还需要设定配置,配置模板在 config/examples 下面。

比如币安的配置,你还需要输入key和secret:

"exchange": {
        "name": "binance",
        "key": "your_exchange_key",
        "secret": "your_exchange_secret",
        ......
  }
}

启动机器人:

freqtrade trade --strategy AwesomeStrategy --strategy-path /some/directory -c path/far/far/away/config.json

--strategy-path 指定策略文件位置

-c 参数指定配置文件位置

比如我把策略放在了user_data/strategies下,配置放在了config_examples下,这么输入命令启动机器人即可:

freqtrade trade --strategy SampleStrategy --strategy-path user_data/strategies -c config_examples/config_binance.example.json

由于篇幅问题,本文只是介绍了freqtrade的冰山一角,在启动机器人前,一定要进行回测并进行模拟交易。

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 机器人
    +关注

    关注

    206

    文章

    27033

    浏览量

    201401
  • 数据
    +关注

    关注

    8

    文章

    6511

    浏览量

    87600
  • 操作系统
    +关注

    关注

    37

    文章

    6284

    浏览量

    121877
  • python
    +关注

    关注

    51

    文章

    4675

    浏览量

    83466
收藏 人收藏

    评论

    相关推荐

    什么是工业机器人

    自动存入程序存储器中在机器人自动工作时,控制系统从程序存储器中检出相应信息,将指令信号传给驱动机构,使执行机构再现示教的各种动作。示教输入程序的工业机器人称为示教再现型工业
    发表于 01-19 10:58

    机器人与未来

    时代的向往。近年来,随着科技的进步,机械、电子、计算机、自动化等传统学科及产业的成熟、交叉、融合,为机器人时代的到来奠定了基础。机器人从此不再是实验室和工厂的专属,而是逐渐走入人们生活的方方面面。它们形态各异
    发表于 12-29 14:56

    自动接水机器人

    这个机器人比较高大,但也是由金属拼装件套件拼装而成。控制板是苹果板,机器人的底部安装有巡线传感器,可以自动循黑线前进,这样只需从你的房间或者办公位置布置一条黑线到饮水机,机器人就可以沿
    发表于 03-25 14:28

    工业机器人应用广泛

    和压机的加工设备中。码垛机:工业机器人将瓦楞纸箱或其他包装物品以规定的图案装载到托盘上。机器人码垛机依靠固定位置或具有特殊工具的顶置式龙门架机器人,与各个负载组件相连接,构建简单到托盘
    发表于 09-07 17:20

    数字货币交易系统中的货币资产指数详解

    `数字货币交易指数一直都是市场参与者一个重要的参考工具,在对市场的研究和操作上面,指数工具具有着不可替代的作用。 数字货币交易系统资产交易
    发表于 05-25 14:37

    币圈熊市之下如何进行投资?炒币机器人币小秘为你答疑

    ` 在数字货币市场中是否存在智能化的量化交易炒币机器人或系统,而这些炒币机器人又是否真实有效是很大投资者迫切想要了解的,现在有一款智能数资管家横空出世,它叫做币小秘。根据财经网
    发表于 06-30 16:10

    机器人是什么?

    或者一个吹管——任何有助于它工作的东西。图5: 传感器的表征图像传感器今天的大多数机器人几乎是又聋又瞎。传感器可以为机器人提供一些有限的反馈,使其能够完成自己的工作。与最简单的生物的感官和能力相比
    发表于 03-31 10:31

    加密货币交易机器人日益流行的原因是什么?

    机器执行任务的速度比人类快得多。事实上,众所周知,99%的华尔街交易是由机器人进行的。根据加密货币市场,由
    发表于 09-11 14:27 593次阅读

    跨平台加密货币交易所Exenium介绍

    Exenium是一个跨平台加密货币交易所,旨在解决当前高度波动的加密市场面临的复杂问题。 作为世界上第一个聊天机器人
    发表于 12-19 13:44 707次阅读

    自动智能交易机器人软件有哪些种类?

    货币自动交易机器人软件的新时代已经使许多人获得了财务自由。现代技术不需要您接受个人培训,您不必阅读大量有关证券的书籍,您也不必并试图了解您所在国家政策和经济。分析是
    发表于 02-21 17:14 423次阅读

    什么是加密货币交易机器人

    加密货币交易机器人是一种计算机程序,可以在适当的时间内自动进行各种加密
    发表于 08-29 10:36 1143次阅读

    如何利用机器人加密货币交易中获得实际利润

    目前有几种类型的交易机器人,包括套利机器人在内,能从不同交易所的价格差异中套利。通常每个交易所的比特币价格都会有所不同;例如,Bitstam
    发表于 09-05 14:17 978次阅读

    加密货币交易机器人是怎样运作起来的

    加密货币交易机器人通过访问交易平台上的数据来为用户工作。
    发表于 09-16 10:20 652次阅读

    今年2月,加密货币交易量超1万亿美元

    据The Block Research统计的加密货币交易数据显示,今年2月份,加密货币交易量超1
    的头像 发表于 03-02 09:19 1927次阅读

    Freqtrade加密货币算法交易软件

    freqtrade.zip
    发表于 06-06 15:37 1次下载
    <b class='flag-5'>Freqtrade</b><b class='flag-5'>加密</b><b class='flag-5'>货币</b>算法<b class='flag-5'>交易</b>软件