海底暴风雪

富在术数不在劳身,利在局势不在力耕

freqtrade 基础学习

配置文件

{
    // 交易模式,这里有三个选项,spot (默认,现货交易),future(期货交易,可以进行做空交易), margin(当前不可用)
    "trading_mode": "spot",
    // 当交易模式不是spot时,需要设置这里,当交易模式为future时,要设置为isolated, 当交易模式为margin时设置为cross(暂时不可用)
    // "margin_mode": "isolated",
    // 最大的单数
    "max_open_trades": 5,
    // 用于交易的加密货币
    "stake_currency": "USDT",
    // 机器人可用的金额,可以开启多个机器人用于交易,平横策略间的收益差异
    "stake_amount": 200,
    // 允许机器人交易的账户总余额的比率
    "tradable_balance_ratio": 1,
    // 从虚拟币转换为哪种法定货币,这里时美金,如果转换报错,可以不设置
    // "fiat_display_currency": "USD",
    // 运行模式,虚拟运行,还是真实运行,true是虚拟运行
    "dry_run": true,
    // 要使用的时间帧 1m,5m, 15m, 30m, 1h  ...,这个歌配置可以在这里缺省,并在策略文件进行再次配置,也就是策略文件的配置强于这里
    "timeframe": "3m",
    // 虚拟运行的总金额
    "dry_run_wallet": 1000,
    // 在退出时取消未结订单
    "cancel_open_orders_on_exit": true,
    // 必须的配置
    "unfilledtimeout": {
        // 只要有信号,机器人将等待未完成的挂单完成多长时间(以分钟或秒为单位),之后订单将被取消并以当前(新)价格重复。
        "entry": 10,
        // 只要有信号,机器人将等待未履行的退出订单完成多长时间(以分钟或秒为单位),之后订单将被取消并以当前(新)价格重复
        "exit": 30
    },
    // 交易所设置
    "exchange": {
        "name": "binance",
        // API key
        "key": "",
        // API secret
        "secret": "",
        // ccxt的一些配置,在国外一般用不到,在国内可以在这里配置代理
        "ccxt_config": {},
        "ccxt_async_config": {},
        // 交易对白名单
        // 1INCH/USDT是现货交易
        // 1INCH/USDT:USDT是期货交易
        // 在这里可以使用通配符进行批量的配置,不必列出所有交易对
        // 查看交易所支持的交易对,命令:freqtrade list-markets -c config.json 或者是 freqtrade list-pairs -c config.json 
        "pair_whitelist": [
            "1INCH/USDT:USDT",
            "ALGO/USDT:USDT"
        ],
        // 黑名单
        "pair_blacklist": [
            // 黑名单通配符设置,白名单同理
            "*/BNB"
        ]
    },
    "entry_pricing": {
        // 必须配置,选择机器人应查看价差的一侧以获得进入率。默认same 还有 ask, bid, other
        "price_side": "same",
        // 允许使用订单簿输入中的费率进行输入。缺省值为true
        "use_order_book": true,
        // 机器人将使用订单簿“price_side”中的前 N ​​个汇率来进入交易。即,值为 2 将允许机器人选择Order Book Entry中的第二个条目。
        "order_book_top": 1,
        // 必须配置,插值投标价格。
        "price_last_balance": 0.0,

        "check_depth_of_market": {
            // 如果Order Book中的买单和卖单有差异,则不要进入。
            "enabled": false,
            // 订单簿中的买单与卖单的差额比例。值低于 1 表示卖单规模较大,而值大于 1 表示买单规模较大
            "bids_to_ask_delta": 1
        }
    },
    "exit_pricing": {
        // 选择机器人应查看的价差一侧以获得退出率。默认same
        "price_side": "other",
        "use_order_book": true,
        "order_book_top": 1
    },
    // 定义要使用的一个或多个配对列表。
    "pairlists": [
        // 这里的方法有很多, [点击查看详情](https://www.freqtrade.io/en/stable/plugins/#pairlists-and-pairlist-handlers)
        // 大部分默认情况下都是使用StaticPairList
        {
            "method": "StaticPairList"
        }
    ],
    // 后面还可以添加frequi的配置,以及telegrambot的配置
    "bot_name": "",
    "force_entry_enable": true,
    "initial_state": "running",
    "internals": {
        "process_throttle_secs": 5
    }
}

策略文件

策略文件要重写一些方法,以支持自定义的策略

首先要继承

# --- Do not remove these libs ---
from freqtrade.strategy import IStrategy
from typing import Dict, List
from functools import reduce
from pandas import DataFrame
# --------------------------------

import talib.abstract as ta
import freqtrade.vendor.qtpylib.indicators as qtpylib


class Strategy001(IStrategy):

    # 接口版本,旧版接口会有差异,比如买卖会使用buy和sell
    INTERFACE_VERSION: int = 3
    # Minimal ROI designed for the strategy.
    # This attribute will be overridden if the config file contains "minimal_roi"
    # 最新收益的表
    minimal_roi = {
        "60":  0.01,
        "30":  0.03,
        "20":  0.04,
        "0":  0.05
    }

    # Optimal stoploss designed for the strategy
    # This attribute will be overridden if the config file contains "stoploss"
    # 止损的利率
    stoploss = -0.10

    # Optimal timeframe for the strategy
    # 使用哪种时间帧
    timeframe = '5m'

    # trailing stoploss
    
    # 追踪止损,只有当为True是,后续的止损配置才会生效
    trailing_stop = False
    # 这个参数定义了跟踪止损被激活后止损点与市场价格的距离。在这种情况下,0.01可能表示止损点设置在当前市场价格的1%之下(对于多头仓位)或之上(对于空头仓位)。这意味着如果市场价格从其最高点(对于多头仓位)或最低点(对于空头仓位)回落1%,止损订单将被触发
    trailing_stop_positive = 0.01
    # 这个参数设置了跟踪止损开始激活的“偏移量”。在这个例子中,0.02可能意味着市场价格必须先向有利的方向移动2%,跟踪止损功能才开始生效。这个偏移量是设置跟踪止损点开始移动的初始阈值。一旦价格超过这个阈值,跟踪止损点将按照trailing_stop_positive的规则进行调整。
    trailing_stop_positive_offset = 0.02

    # run "populate_indicators" only for new candle
    # 这个设置意味着相关的数据处理或函数(例如,populate_indicators)仅在出现新的蜡烛图(K线图)时才会被执行。蜡烛图是金融市场中常用的图表类型,用于展示一定时间段内的价格变动。
    process_only_new_candles = True

    # Experimental settings (configuration will overide these if set)
    # 使用退出信号
    use_exit_signal = True
    # 只有盈利才退出
    exit_profit_only = True
    # 这个配置项意味着如果存在一个进场信号(entry signal),那么回报率(Return on Investment, ROI)相关的规则将被忽略或暂时不适用。
    ignore_roi_if_entry_signal = False

    # Optional order type mapping
    order_types = {
        'entry': 'limit',
        'exit': 'limit',
        'stoploss': 'market',
        'stoploss_on_exchange': False
    }

    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.
        """
        # 计算技术指标
        # dataframe['ema20'] = ta.EMA(dataframe, timeperiod=20)
        # dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50)
        # dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100)

        # heikinashi = qtpylib.heikinashi(dataframe)
        # dataframe['ha_open'] = heikinashi['open']
        # dataframe['ha_close'] = heikinashi['close']

        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        Based on TA indicators, populates the buy signal for the given dataframe
        :param dataframe: DataFrame
        :return: DataFrame with buy column
        """
        # 通过指标判断是否买入
        # dataframe.loc[
        #     (
        #         qtpylib.crossed_above(dataframe['ema20'], dataframe['ema50']) &
        #         (dataframe['ha_close'] > dataframe['ema20']) &
        #         (dataframe['ha_open'] < dataframe['ha_close'])  # green bar
        #     ),
        #     'enter_long'] = 1
        # 这里的True是要通过指标或ai返回的数据给出
        dataframe.loc[True, 'enter_long']=1
        return dataframe

    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        Based on TA indicators, populates the sell signal for the given dataframe
        :param dataframe: DataFrame
        :return: DataFrame with buy column
        """
        # 通过指标判断是否卖出
        # dataframe.loc[
        #     (
        #         qtpylib.crossed_above(dataframe['ema50'], dataframe['ema100']) &
        #         (dataframe['ha_close'] < dataframe['ema20']) &
        #         (dataframe['ha_open'] > dataframe['ha_close'])  # red bar
        #     ),
        #     'exit_long'] = 1

        # 这里的True是要通过指标或ai返回的数据给出
        dataframe.loc[True, 'exit_long']=1
        return dataframe

搜索

文章分类