在 CentOS7 安装 VNPY (一)

一、安装nvpy

vnpy安装指南

0.安装Anaconda

下载并安装最新版本的Anaconda或者Miniconda (Python 3.7 64位)

wget https://repo.anaconda.com/archive/Anaconda3-2020.02-Linux-x86_64.sh

以MiniConda为例,进入已下载好 Miniconda3-latest-Linux-x86_64.sh 所在目录,终端运行如下命令开始安装。

$ bash Miniconda3-latest-Linux-x86_64.sh

安装过程中可以一直按“Enter”键继续下去,除了以下这点:

当询问是否把Miniconda设置为Python 默认环境时,把默认的”no”改成“yes”。原因是centOS已有自带的Python 2.7。

新开一个终端后,打开终端直接输入”python -V” 然后按“Enter”键,可以看到是最新的版本了。

(base) [root@cssbjqnffcsvic ~]# python -V
Python 3.7.6
(base) [root@cssbjqnffcsvic ~]# which python
/root/anaconda3/bin/python

1.下载vnpy软件包

Linux用户选择tar.gz压缩版本。下载地址如下:vnpy releases

wget https://github.com/vnpy/vnpy/archive/v2.1.2.tar.gz

更改包名字:

mv v2.1.2.tar.gz vnpy-v2.1.2.tar.gz

解压:

tar -zxvf vnpy-v2.1.2.tar.gz

进入安装目录:

[root@cssbjqnffcsvic developer]# cd vnpy-2.1.2
[root@cssbjqnffcsvic vnpy-2.1.2]# ls -l
total 56
drwxrwxr-x  4 root root  4096 Apr 14 13:21 docs
drwxrwxr-x 12 root root   218 Apr 14 13:21 examples
-rw-rw-r--  1 root root   303 Apr 14 13:21 install.bat
-rw-rw-r--  1 root root    57 Apr 14 13:21 install_osx.sh
-rw-rw-r--  1 root root   964 Apr 14 13:21 install.sh
-rw-rw-r--  1 root root  1087 Apr 14 13:21 LICENSE
-rw-rw-r--  1 root root    84 Apr 14 13:21 MANIFEST.in
-rw-rw-r--  1 root root 12367 Apr 14 13:21 README.md
-rw-rw-r--  1 root root   247 Apr 14 13:21 requirements.txt
-rw-rw-r--  1 root root  8965 Apr 14 13:21 setup.py
drwxrwxr-x  9 root root   113 Apr 14 13:21 vnpy

2. 安装vnpy

先安装gcc编译器,用于编译C++类接口文件。在终端中输入以下命令即可。

sudo apt-get  install  build-essential  #ubuntu
yum -y install gcc gcc-c++ kernel-devel  # CentOS 安装gcc、c++编译器以及内核文件
先下载gcc#
> yum install gcc pcre-devel zlib zlib-devel openssl openssl-devel

然后在vnpy根目录打开终端,输入下面命令一键安装vnpy。

bash install.sh

安装过程分为4步:

  • 下载并安装ta_lib库和numpy
  • 安装requirements.txt文件内相关依赖库
  • 安装中文编码(针对英文系统)
  • 复制vnpy到Anaconda内(若是在虚拟机上运行,需要把内存调至4g,否则报错)

错误处理:

在安装的时候报这样的错误:

gcc: error: unrecognized command line option ‘-std=c++17’
    error: command 'gcc' failed with exit status 1

百度了一下,是因为本地的gcc版本过低造成的,需要升级版本:

查看本地版本:

[root@cssbjqnffcsvic vnpy-2.1.2]# gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/libexec/gcc/x86_64-redhat-linux/4.8.5/lto-wrapper
Target: x86_64-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --... --build=x86_64-redhat-linux
Thread model: posix
gcc version 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC) 

可以看到gcc 版本为gcc version 4.8.5,太老了,升级为更新的版本:

1.安装scl源:

yum install centos-release-scl scl-utils-build

2.列出scl有哪些源可以用

 yum list all --enablerepo='centos-sclo-rh' | grep 'devtoolset'

可以看到以下源可以用:

[root@cssbjqnffcsvic vnpy-2.1.2]# yum list all --enablerepo='centos-sclo-rh' | grep 'devtoolset'
devtoolset-7.x86_64                        7.1-4.el7              centos-sclo-rh
devtoolset-7-all.x86_64                    7.0-5.el7              centos-sclo-rh
devtoolset-7-binutils.x86_64               2.28-11.el7            centos-sclo-rh
devtoolset-7-binutils-devel.x86_64         2.28-11.el7            centos-sclo-rh
devtoolset-7-build.x86_64                  7.1-4.el7              centos-sclo-rh
devtoolset-7-dockerfiles.x86_64            7.1-4.el7              centos-sclo-rh
devtoolset-7-dwz.x86_64                    0.12-1.1.el7           centos-sclo-rh

.
.
devtoolset-7-libstdc++-devel.x86_64        7.3.1-5.16.el7         centos-sclo-rh
devtoolset-7-libstdc++-docs.x86_64         7.3.1-5.16.el7         centos-sclo-rh
devtoolset-7-libtsan-devel.x86_64          7.3.1-5.16.el7         centos-sclo-rh
devtoolset-7-libubsan-devel.x86_64         7.3.1-5.16.el7         centos-sclo-rh
devtoolset-7-llvm.x86_64                   7.0-5.el7              centos-sclo-rh
devtoolset-7-ltrace.x86_64                 0.7.91-2.el7           centos-sclo-rh
devtoolset-7-make.x86_64                   1:4.2.1-3.el7          centos-sclo-rh
devtoolset-7-memstomp.x86_64               0.1.5-5.1.el7          centos-sclo-rh
devtoolset-7-oprofile.x86_64               1.2.0-2.el7.1          centos-sclo-rh
devtoolset-7-oprofile-devel.x86_64         1.2.0-2.el7.1          centos-sclo-rh
devtoolset-7-oprofile-jit.x86_64           1.2.0-2.el7.1          centos-sclo-rh
devtoolset-7-perftools.x86_64              7.1-4.el7              centos-sclo-rh
devtoolset-7-runtime.x86_64                7.1-4.el7              centos-sclo-rh
devtoolset-7-rust.x86_64                   7.0-5.el7              centos-sclo-rh
devtoolset-7-strace.x86_64                 4.17-7.el7             centos-sclo-rh
...
devtoolset-8.x86_64                        8.1-1.el7              centos-sclo-rh
devtoolset-8-binutils.x86_64               2.30-55.el7.2          centos-sclo-rh
...
devtoolset-8-elfutils-libelf.x86_64        0.176-1.el7            centos-sclo-rh

3.安装devtoolset-7版本的gcc、gcc-c++、gdb

yum install devtoolset-7-gcc.x86_64 devtoolset-7-gcc-c++.x86_64 devtoolset-7-gcc-gdb-plugin.x86_64 

4.查看从 SCL 中安装的包的列表:

[root@cssbjqnffcsvic vnpy-2.1.2]# scl -l
devtoolset-7

5.切换到devtoolset-7环境:

scl enable devtoolset-7 bash

6、查看版本

gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/lto-wrapper
Target: x86_64-redhat-linux
Thread model: posix
gcc version 7.3.1 20180303 (Red Hat 7.3.1-5) (GCC) 

可以看到gcc 版本升级为 7.3.1了。

然后再重新安装vnpy:

bash install.sh

可以看到安装成功了^_^:

Building wheels for collected packages: vnpy
  Building wheel for vnpy (setup.py) ... done
  Created wheel for vnpy: filename=vnpy-2.1.2-cp36-cp36m-linux_x86_64.whl size=80679122 sha256=0d9ae919a070597168b13f3915ebbca7e65d96019cc2bab1987d8d193e0f0879
  Stored in directory: /root/.cache/pip/wheels/cb/a1/fc/dcd92349dc8eae712133026e9394aa3a2ab60fba328f31df28
Successfully built vnpy
Installing collected packages: vnpy
Successfully installed vnpy-2.1.2

升级请参考该文章:
Centos7升级gcc版本方法之一使用scl软件集

3.启动VN Trader

脚本运行
除了基于VN Station的图形化启动方式外,也可以在任意目录下创建run.py,写入以下示例代码:

创建目录 ,并创建文件 run.py

> mkdir /work/Code/vnpy

4 拷贝启动文件到vnpy同级目录下:

将无界面启动的文件,文件位于:/vnpy-2.1.2/examples/no_ui/run.py

将此文件拷贝到跟vnpy目录同级的目录下,拷贝run.py到vnpy同级目录下:


cp /developer/vnpy-2.1.2/examples/no_ui/run.py   /work/Code/vnpy/

该文件说明:

该run.py文件里面默认配置了cta策略的启动,默认连接CTP,我们需要更改ctp连接信息:

如果要期货模拟盘操作,先到simnow上面注册个模拟账号,可以获取相关信息。

5 在该目录下,执行启动

执行:

python run.py 

运行成功^_^:

(base) [root@cssbjqnffcsvic vnpy]# python run.py
启动CTA策略守护父进程
启动子进程
子进程启动成功
2020-04-30 22:57:43,777  INFO: 主引擎创建成功
Invalid port: Success
2020-04-30 22:57:43,806  INFO: 注册日志事件监听
2020-04-30 22:57:43,806  INFO: 连接CTP接口
Invalid port: Success
Invalid port: Success
2020-04-30 22:57:53,835  INFO: CTA策略引擎初始化成功
2020-04-30 22:57:53,835  INFO: CTA策略初始化完成
Invalid port: Success
Invalid port: Success
Invalid port: Success
Invalid port: Success

Invalid port: Success
Invalid port: Success
Invalid port: Success
Invalid port: Success
2020-04-30 22:58:53,859  INFO: CTA策略全部初始化
2020-04-30 22:58:53,859  INFO: CTA策略全部启动
Invalid port: Success
Invalid port: Success
Invalid port: Success
Invalid port: Success
Invalid port: Success
...

重要总结:Vnpy安装成功,但是启动文件出现QT有关的错误,原来是加载错文件了,我们在Linux下必须运行无界面的,之前一直在Linux(CentOS7)系统上运行有界面的启动文件,所以,一直报错,因此要用examles目录下的no_ui文件来运行。

run.py

import multiprocessing
from time import sleep
from datetime import datetime, time
from logging import INFO

from vnpy.event import EventEngine
from vnpy.trader.setting import SETTINGS
from vnpy.trader.engine import MainEngine

from vnpy.gateway.ctp import CtpGateway
from vnpy.app.cta_strategy import CtaStrategyApp
from vnpy.app.cta_strategy.base import EVENT_CTA_LOG

SETTINGS["log.active"] = True
SETTINGS["log.level"] = INFO
SETTINGS["log.console"] = True

ctp_setting = {
    "用户名": "",
    "密码": "",
    "经纪商代码": "",
    "交易服务器": "",
    "行情服务器": "",
    "产品名称": "",
    "授权编码": "",
    "产品信息": ""
}

def run_child():
    """
    Running in the child process.
    """
    SETTINGS["log.file"] = True

    event_engine = EventEngine()
    main_engine = MainEngine(event_engine)
    main_engine.add_gateway(CtpGateway)
    cta_engine = main_engine.add_app(CtaStrategyApp)
    main_engine.write_log("主引擎创建成功")

    log_engine = main_engine.get_engine("log")
    event_engine.register(EVENT_CTA_LOG, log_engine.process_log_event)
    main_engine.write_log("注册日志事件监听")

    main_engine.connect(ctp_setting, "CTP")
    main_engine.write_log("连接CTP接口")

    sleep(10)

    cta_engine.init_engine()
    main_engine.write_log("CTA策略初始化完成")

    cta_engine.init_all_strategies()
    sleep(60)   # Leave enough time to complete strategy initialization
    main_engine.write_log("CTA策略全部初始化")

    cta_engine.start_all_strategies()
    main_engine.write_log("CTA策略全部启动")

    while True:
        sleep(1)

def run_parent():
    """
    Running in the parent process.
    """
    print("启动CTA策略守护父进程")

    # Chinese futures market trading period (day/night)
    DAY_START = time(8, 45)
    DAY_END = time(15, 30)

    NIGHT_START = time(20, 45)
    NIGHT_END = time(2, 45)

    child_process = None

    while True:
        current_time = datetime.now().time()
        trading = False

        # Check whether in trading period
        if (
            (current_time >= DAY_START and current_time <= DAY_END)
            or (current_time >= NIGHT_START)
            or (current_time <= NIGHT_END)
        ):
            trading = True

        # Start child process in trading period
        if trading and child_process is None:
            print("启动子进程")
            child_process = multiprocessing.Process(target=run_child)
            child_process.start()
            print("子进程启动成功")

        # 非记录时间则退出子进程
        if not trading and child_process is not None:
            print("关闭子进程")
            child_process.terminate()
            child_process.join()
            child_process = None
            print("子进程关闭成功")

        sleep(5)

if __name__ == "__main__":
    run_parent()

参考文章:
在linux上安装vnpy--完全支持火币网将交易

====================== Linux安装下边的不用看了 ==================

我们的环境是 CentOS7,报了这样一个错误:
ImportError: libGL.so.1: cannot open shared object file: No such file or directory,安装对应的软件:

yum install mesa-libGL.x86_64

继续执行,又报了这样的错误:

[root@cssvnpy]# python run.py                                                                        
qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application
 may fix this problem.

Available platform plugins are: eglfs, linuxfb, minimal, minimalegl, offscreen, vnc, wayland-egl, wayland, waylan
d-xcomposite-egl, wayland-xcomposite-glx, webgl, xcb.

Aborted

设置环境变量 export QT_DEBUG_PLUGINS=1
加了这个环境变量,让我看到了QT程序加载的过程,看到了详细的报错信息。
最后一部分是这样的:

export QT_DEBUG_PLUGINS=1
[root@css vnpy]# python run.py
QFactoryLoader::QFactoryLoader() checking directory path "/root/anaconda3/lib/python3.6/site-packages/PyQt5/Qt/pl
ugins/platforms" ...
QFactoryLoader::QFactoryLoader() looking at "/root/anaconda3/lib/python3.6/site-packages/PyQt5/Qt/plugins/platfor
ms/libqeglfs.so"
Found metadata in lib /root/anaconda3/lib/python3.6/site-packages/PyQt5/Qt/plugins/platforms/libqeglfs.so, metada
ta=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "eglfs"
        ]
    },

...
Got keys from plugin meta data ("webgl")
QFactoryLoader::QFactoryLoader() looking at "/root/anaconda3/lib/python3.6/site-packages/PyQt5/Qt/plugins/platfor
ms/libqxcb.so"
Found metadata in lib /root/anaconda3/lib/python3.6/site-packages/PyQt5/Qt/plugins/platforms/libqxcb.so, metadata
=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "xcb"
        ]
    },
    "archreq": 0,
    "className": "QXcbIntegrationPlugin",
    "debug": false,
    "version": 331264
}

Got keys from plugin meta data ("xcb")
QFactoryLoader::QFactoryLoader() checking directory path "/root/anaconda3/bin/platforms" ...
Cannot load library /root/anaconda3/lib/python3.6/site-packages/PyQt5/Qt/plugins/platforms/libqxcb.so: (libfontco
nfig.so.1: cannot open shared object file: No such file or directory)
QLibraryPrivate::loadPlugin failed on "/root/anaconda3/lib/python3.6/site-packages/PyQt5/Qt/plugins/platforms/lib
qxcb.so" : "Cannot load library /root/anaconda3/lib/python3.6/site-packages/PyQt5/Qt/plugins/platforms/libqxcb.so
: (libfontconfig.so.1: cannot open shared object file: No such file or directory)"
qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application
 may fix this problem.

Available platform plugins are: eglfs, linuxfb, minimal, minimalegl, offscreen, vnc, wayland-egl, wayland, waylan
d-xcomposite-egl, wayland-xcomposite-glx, webgl, xcb.

Aborted

找库:find / | grep libQt5XcbQpa.so

[root@cssbjqnffcsvic vnpy]# find / | grep libQt5XcbQpa.so                                                                    
/root/anaconda3/pkgs/qt-5.9.5-h7e424d6_0/lib/libQt5XcbQpa.so.5.9.5                                                           
/root/anaconda3/pkgs/qt-5.9.5-h7e424d6_0/lib/libQt5XcbQpa.so.5                                                               
/root/anaconda3/pkgs/qt-5.9.5-h7e424d6_0/lib/libQt5XcbQpa.so                                                                 
/root/anaconda3/pkgs/qt-5.9.5-h7e424d6_0/lib/libQt5XcbQpa.so.5.9                                                             
/root/anaconda3/lib/python3.6/site-packages/PyQt5/Qt/lib/libQt5XcbQpa.so.5                                                   
/root/anaconda3/lib/libQt5XcbQpa.so                                                                                          
/root/anaconda3/lib/libQt5XcbQpa.so.5                                                                                        
/root/anaconda3/lib/libQt5XcbQpa.so.5.9                                                                                      
/root/anaconda3/lib/libQt5XcbQpa.so.5.9.5                                                                                    
[root@cssbjqnffcsvic vnpy]# cat /etc/ld.so.conf                                                                              
include ld.so.conf.d/*.conf                                                                                                  
/usr/lib                                                                                                                     
[root@cssbjqnffcsvic vnpy]# vim /etc/ld.so.conf                                                                              
[root@cssbjqnffcsvic vnpy]# ldconfig                                                                                         
[root@cssbjqnffcsvic vnpy]# cat /etc/ld.so.conf                                                                              
include ld.so.conf.d/*.conf                                                                                                  
/usr/lib                                                                                                                     
/root/anaconda3/lib                         

看到问题没?/root/anaconda3/lib/libQt5XcbQpa.so这个库有问题。于是我把libQt5XcbQpa.so,也放在运行目录下。
奇迹发生了,一切OK了!!!

相关文章:
关于qt缺少xcb问题终极解决办法

又报这样的错:

libfontconfig.so.1: cannot open shared object file: No such file or directory

安装库:

yum -y install fontconfig-devel

问题仍然存在:

[root@cssbjqnffcsvic vnpy]# python run.py
qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "/root/anaconda3/plugins/platforms" even
 though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the 
application may fix this problem.

Available platform plugins are: eglfs (from /root/anaconda3/plugins/platforms), minimal (from /root/an
aconda3/plugins/platforms), minimalegl (from /root/anaconda3/plugins/platforms), offscreen (from /root
/anaconda3/plugins/platforms), vnc (from /root/anaconda3/plugins/platforms), xcb (from /root/anaconda3
/plugins/platforms), eglfs, linuxfb, minimal, minimalegl, offscreen, vnc, wayland-egl, wayland, waylan
d-xcomposite-egl, wayland-xcomposite-glx, webgl, xcb.

Aborted

再次查看GCC版本:

[root@cssbjqnffcsvic plugins]# gcc --version
gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

我们可以发现,gcc是2015年的,版本确实是低。

然后我们就来升级一下。

yum install centos-release-scl 
root@cssbjqnffcsvic ~]# scl enable devtoolset-7 bash
[root@cssbjqnffcsvic ~]# which gcc
/opt/rh/devtoolset-7/root/usr/bin/gcc
[root@cssbjqnffcsvic ~]# gcc --version
gcc (GCC) 7.3.1 20180303 (Red Hat 7.3.1-5)
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

安装dev-gcc

yum install devtoolset-7-gcc*

安装psycopg是出错:Error: pg_config executable not found.
  装psycopg是出错

  执行

    python setup.py install

  running build running build_py running build_ext Error: pg_config executable not found. Please add the directory containing pg_config to the PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'.

需要安装postgresql-devel插件

  yum install postgresql-devel*

————————————————
原文链接:https://blog.csdn.net/u012965373/article/details/52066580

python 软连接

查看 /usr/bin/python 是哪个Python版本,这里默认的是python2.7,所以,要更改为3.6,建立一个软连接:

[root@cssbjqnffcsvic bin]# rm -r python
rm: remove symbolic link ‘python’? yes
[root@cssbjqnffcsvic bin]# ls -l| grep python
lrwxrwxrwx    1 root root          9 Apr 14 15:22 python2 -> python2.7                                       
-rwxr-xr-x    1 root root       7216 Aug  7  2019 python2.7                                                  
-rwxr-xr-x    1 root root       1835 Aug  7  2019 python2.7-config                                           
lrwxrwxrwx    1 root root         16 Apr 14 15:23 python2-config -> python2.7-config                         
lrwxrwxrwx    1 root root         14 Apr 14 15:23 python-config -> python2-config  
# which python
# whereis python
ln -s /root/anaconda3/bin/python3.6 /usr/bin/python

相关文章:
python升级带来的yum异常:File "/usr/bin/yum", line 30

二、加密货币策略测试

在Linux服务端使用无界面获取行情数据。
crypto.py

# -*- coding:utf-8 -*-

"""
@author: Corwien
@file: crypto.py
@time: 20/5/5 22:51
"""
import multiprocessing
from time import sleep
from datetime import datetime, time
from logging import INFO

from vnpy.event import EventEngine
from vnpy.trader.setting import SETTINGS
from vnpy.trader.engine import MainEngine

from vnpy.gateway.ctp import CtpGateway
from vnpy.app.cta_strategy import CtaStrategyApp
from vnpy.app.cta_strategy.base import EVENT_CTA_LOG

# 导入币安接口
from vnpy.gateway.binance import BinanceGateway

SETTINGS["log.active"] = True
SETTINGS["log.level"] = INFO
SETTINGS["log.console"] = True

ctp_setting = {
    "用户名": "",
    "密码": "",
    "经纪商代码": "",
    "交易服务器": "",
    "行情服务器": "",
    "产品名称": "",
    "授权编码": "",
    "产品信息": ""
}

# binance配置,参考binance_gateway默认配置参数
binance_setting = {
    "key": "jNG6xxxx123456",
    "secret": "6gxxxxxxxxxxxxxxxxx90836363e",
    "session_number": 3,
    "proxy_host": "",
    "proxy_port": 0,
}

def run_child():
    """
    Running in the child process.
    """
    SETTINGS["log.file"] = True

    event_engine = EventEngine()
    main_engine = MainEngine(event_engine)
    main_engine.add_gateway(CtpGateway)
    main_engine.add_gateway(BinanceGateway)

    cta_engine = main_engine.add_app(CtaStrategyApp)
    main_engine.write_log("主引擎创建成功")

    gateway_names = main_engine.get_all_gateway_names()
    print('gateway_names:{0}'.format(gateway_names))

    log_engine = main_engine.get_engine("log")
    event_engine.register(EVENT_CTA_LOG, log_engine.process_log_event)
    main_engine.write_log("注册日志事件监听")

    # 这里需要大写
    main_engine.connect(binance_setting, "BINANCE")
    main_engine.write_log("连接Binance接口")

    sleep(10)

    cta_engine.init_engine()
    main_engine.write_log("CTA策略初始化完成")

    cta_engine.init_all_strategies()
    sleep(60)   # Leave enough time to complete strategy initialization
    main_engine.write_log("CTA策略全部初始化")

    cta_engine.start_all_strategies()
    main_engine.write_log("CTA策略全部启动")

    while True:
        sleep(1)

def run_parent():
    """
    Running in the parent process.
    """
    print("启动CTA策略守护父进程")

    # Chinese futures market trading period (day/night)
    DAY_START = time(8, 45)
    DAY_END = time(15, 30)

    NIGHT_START = time(20, 45)
    NIGHT_END = time(2, 45)

    child_process = None

    while True:
        current_time = datetime.now().time()
        trading = False

        # Check whether in trading period
        # 数字货币是全天24小时交易,不需要判断时间点
        """

        if (
            (current_time >= DAY_START and current_time <= DAY_END)
            or (current_time >= NIGHT_START)
            or (current_time <= NIGHT_END)
        ):
            trading = True
        """
        trading = True

        # Start child process in trading period
        if trading and child_process is None:
            print("启动子进程")
            child_process = multiprocessing.Process(target=run_child)
            child_process.start()
            print("子进程启动成功")

        # 非记录时间则退出子进程
        if not trading and child_process is not None:
            print("关闭子进程")
            child_process.terminate()
            child_process.join()
            child_process = None
            print("子进程关闭成功")

        sleep(5)

if __name__ == "__main__":
    run_child()  # 数字货币是24小时交易,没有定时启停的需求,确实直接运行run_child就行了。
    #run_parent() # 守护父进程先去掉,直接运行run_child()

运行脚本:

python crypto.py 

打印日志:

# python crypto.py                                                          
gateway_names:['CTP', 'BINANCE']
2020-05-05 11:03:32,557  INFO: 主引擎创建成功
2020-05-05 11:03:32,557  INFO: 注册日志事件监听
2020-05-05 11:03:32,561  INFO: REST API启动成功
2020-05-05 11:03:32,562  INFO: Binance
2020-05-05 11:03:38,070  INFO: 账户资金查询成功
2020-05-05 11:03:38,418  INFO: 委托信息查询成功
2020-05-05 11:03:38,940  INFO: 合约信息查询成功
2020-05-05 11:03:42,572  INFO: CTA策略引擎初始化成功
2020-05-05 11:03:42,573  INFO: CTA策略初始化完成
2020-05-05 11:03:44,728  INFO: 交易Websocket API连接成功
2020-05-05 11:04:42,633  INFO: CTA策略全部初始化
2020-05-05 11:04:42,633  INFO: CTA策略全部启动

参考文章:
python 升级后 yum 报错 centOS7,version `XZ_5.1.2alpha' not found
linux(centos7)下安装vnpy2的坑
vn.py快速入门6 - 开发第一个量化策略

为者常成,行者常至