├── async_io
├── asyncio
│ ├── __init__.py
│ └── async_executor.py
├── websocket
│ └── __init__.py
└── rest
│ └── __init__.py
├── cpp_api_binding
├── generator
│ ├── autocxxpy
│ │ ├── __init__.py
│ │ ├── clang
│ │ │ ├── __init__.py
│ │ │ └── enumerations.py
│ │ ├── type.py
│ │ ├── textholder.py
│ │ └── preprocessor.py
│ ├── __init__.py
│ ├── .gitignore
│ ├── templates
│ │ ├── wrapper_class.h
│ │ ├── hint.py.in
│ │ ├── class_generators.h
│ │ ├── wrappers.hpp
│ │ ├── class.cpp
│ │ ├── module.cpp
│ │ ├── property_helper.hpp
│ │ └── dispatcher.hpp
│ ├── tests
│ │ └── tests
│ │ │ ├── tests.vcxproj.user
│ │ │ ├── tests.vcxproj.filters
│ │ │ ├── Source.cpp
│ │ │ └── tests.vcxproj
│ ├── 3rd_party
│ │ ├── googletest
│ │ │ ├── gtest.vcxproj.user
│ │ │ ├── gtest.vcxproj.filters
│ │ │ ├── src
│ │ │ │ ├── gtest_main.cc
│ │ │ │ ├── gtest-test-part.cc
│ │ │ │ ├── gtest-typed-test.cc
│ │ │ │ └── gtest-matchers.cc
│ │ │ ├── gtest-all.cc
│ │ │ └── gtest.vcxproj
│ │ └── include
│ │ │ └── gtest
│ │ │ ├── internal
│ │ │ ├── custom
│ │ │ │ ├── README.md
│ │ │ │ ├── gtest.h
│ │ │ │ ├── gtest-port.h
│ │ │ │ └── gtest-printers.h
│ │ │ ├── gtest-port-arch.h
│ │ │ ├── gtest-string.h
│ │ │ └── gtest-param-util-generated.h.pump
│ │ │ ├── gtest_prod.h
│ │ │ ├── gtest-test-part.h
│ │ │ └── gtest-message.h
│ ├── TODO.txt
│ ├── doc
│ │ ├── ctp.md
│ │ └── converts.md
│ ├── env.props
│ ├── README.MD
│ ├── generate_ctp.py
│ ├── adaptor
│ │ └── ctpadaptor.py
│ └── tests.sln
├── TODO.txt
├── __init__.py
├── tests
│ ├── __init__.py
│ └── test.py
├── source
│ ├── CMakeLists.txt
│ └── ctp
│ │ ├── api
│ │ ├── ThostFtdcMdApi.h
│ │ ├── ThostFtdcTraderApi.h
│ │ ├── thostmduserapi_se.dll
│ │ ├── thostmduserapi_se.lib
│ │ ├── thosttraderapi_se.dll
│ │ ├── thosttraderapi_se.lib
│ │ ├── ThostFtdcUserApiDataType.h
│ │ └── ThostFtdcUserApiStruct.h
│ │ ├── CMakeLists.txt
│ │ ├── custom_wrappers
│ │ └── spi.hpp
│ │ ├── property_helper.hpp
│ │ └── dispatcher.hpp
├── third_party
│ └── include
│ │ └── pybind11
│ │ ├── common.h
│ │ ├── detail
│ │ ├── typeid.h
│ │ └── descr.h
│ │ ├── complex.h
│ │ ├── options.h
│ │ ├── functional.h
│ │ ├── eval.h
│ │ ├── buffer_info.h
│ │ ├── iostream.h
│ │ ├── chrono.h
│ │ ├── embed.h
│ │ └── operators.h
├── CMakeLists.txt
├── README.md
├── doc
│ ├── build.md
│ ├── build.linux.md
│ └── build.windows.md
├── build.bat
└── cmake
│ ├── py_find.cmake
│ ├── py.cmake
│ └── flags.cmake
├── candle_chart
├── __init__.py
├── base
│ ├── __init__.py
│ ├── data_source.py
│ ├── base.py
│ └── drawer.py
└── candle.py
├── README.md
├── code_format
└── .flake8
├── LICENSE
└── .gitignore
/async_io/asyncio/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/autocxxpy/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/cpp_api_binding/TODO.txt:
--------------------------------------------------------------------------------
1 | * use CMake as build system
--------------------------------------------------------------------------------
/async_io/websocket/__init__.py:
--------------------------------------------------------------------------------
1 | from .websocket_client import WebsocketClient
2 |
--------------------------------------------------------------------------------
/cpp_api_binding/__init__.py:
--------------------------------------------------------------------------------
1 | # this file is created only for making pylint work
2 |
--------------------------------------------------------------------------------
/candle_chart/__init__.py:
--------------------------------------------------------------------------------
1 | """
2 |
3 | """
4 | from .candle import CandleChart
5 |
6 |
--------------------------------------------------------------------------------
/cpp_api_binding/tests/__init__.py:
--------------------------------------------------------------------------------
1 | # this file is created only for making pylint work
2 |
--------------------------------------------------------------------------------
/async_io/rest/__init__.py:
--------------------------------------------------------------------------------
1 | from .rest_client import Request, RequestStatus, RestClient
2 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/__init__.py:
--------------------------------------------------------------------------------
1 | # this file is created only for making pylint work
2 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
2 | .vs/
3 |
4 | build/
5 | generated_files/
6 |
7 | *.pyc
--------------------------------------------------------------------------------
/cpp_api_binding/source/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 2.8)
2 |
3 | add_subdirectory(ctp)
4 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/templates/wrapper_class.h:
--------------------------------------------------------------------------------
1 |
2 | class Py$class_name : public $class_name
3 | {
4 | public:
5 | $body
6 | };
7 |
--------------------------------------------------------------------------------
/cpp_api_binding/source/ctp/api/ThostFtdcMdApi.h:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vnpy/vnpy_lab/HEAD/cpp_api_binding/source/ctp/api/ThostFtdcMdApi.h
--------------------------------------------------------------------------------
/cpp_api_binding/source/ctp/api/ThostFtdcTraderApi.h:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vnpy/vnpy_lab/HEAD/cpp_api_binding/source/ctp/api/ThostFtdcTraderApi.h
--------------------------------------------------------------------------------
/cpp_api_binding/source/ctp/api/thostmduserapi_se.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vnpy/vnpy_lab/HEAD/cpp_api_binding/source/ctp/api/thostmduserapi_se.dll
--------------------------------------------------------------------------------
/cpp_api_binding/source/ctp/api/thostmduserapi_se.lib:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vnpy/vnpy_lab/HEAD/cpp_api_binding/source/ctp/api/thostmduserapi_se.lib
--------------------------------------------------------------------------------
/cpp_api_binding/source/ctp/api/thosttraderapi_se.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vnpy/vnpy_lab/HEAD/cpp_api_binding/source/ctp/api/thosttraderapi_se.dll
--------------------------------------------------------------------------------
/cpp_api_binding/source/ctp/api/thosttraderapi_se.lib:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vnpy/vnpy_lab/HEAD/cpp_api_binding/source/ctp/api/thosttraderapi_se.lib
--------------------------------------------------------------------------------
/cpp_api_binding/source/ctp/api/ThostFtdcUserApiDataType.h:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vnpy/vnpy_lab/HEAD/cpp_api_binding/source/ctp/api/ThostFtdcUserApiDataType.h
--------------------------------------------------------------------------------
/cpp_api_binding/source/ctp/api/ThostFtdcUserApiStruct.h:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vnpy/vnpy_lab/HEAD/cpp_api_binding/source/ctp/api/ThostFtdcUserApiStruct.h
--------------------------------------------------------------------------------
/cpp_api_binding/third_party/include/pybind11/common.h:
--------------------------------------------------------------------------------
1 | #include "detail/common.h"
2 | #warning "Including 'common.h' is deprecated. It will be removed in v3.0. Use 'pybind11.h'."
3 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/templates/hint.py.in:
--------------------------------------------------------------------------------
1 | # noinspection PyUnresolvedReferences
2 | from typing import *
3 | # noinspection PyUnresolvedReferences
4 | from enum import Enum
5 |
6 |
7 | $hint_code
8 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # vn.py lab
2 |
3 | * cpp_api_binding:
4 | * 基于clang的C++ API结构分析
5 | * 自动生成pybind11的封装代码
6 | * 采用对象(而非字典)作为API中使用的数据结构
7 | * 使用全局Dispatcher实现Python内的异步回调,只有一个线程从而实现更好的性能(减少GIL获取开销)
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/tests/tests/tests.vcxproj.user:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | true
5 |
6 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/templates/class_generators.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 |
4 | #include
5 |
6 | #include "dispatcher.hpp"
7 | #include "property_helper.hpp"
8 | #include "wrapper_helper.hpp"
9 |
10 | $includes
11 |
12 | $class_generator_declarations
13 |
14 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/3rd_party/googletest/gtest.vcxproj.user:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | true
5 |
6 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/templates/wrappers.hpp:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 |
5 | #include "dispatcher.hpp"
6 | #include "property_helper.hpp"
7 | #include "wrapper_helper.hpp"
8 |
9 | #include "class_generators.h"
10 |
11 | $includes
12 |
13 | $wrappers
14 |
--------------------------------------------------------------------------------
/cpp_api_binding/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 2.8)
2 |
3 | project(vnpy_binding)
4 |
5 | set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake")
6 | include(cmake/flags.cmake)
7 | include(cmake/py.cmake)
8 |
9 | include_directories(third_party/include)
10 |
11 | add_subdirectory(source)
12 |
--------------------------------------------------------------------------------
/code_format/.flake8:
--------------------------------------------------------------------------------
1 | [flake8]
2 | exclude = .git,__pycache__,clang,build,dist,generated_files,templates,__init__.py,
3 | ignore =
4 | E501 line too long, fixed by black
5 | W503 line break before binary operator
6 |
7 | W293 blank line contains whitespace
8 | W291 trailing whitespace
9 |
10 | [pycodestyle]
11 | max_line_length = 79
--------------------------------------------------------------------------------
/cpp_api_binding/generator/templates/class.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #include "dispatcher.hpp"
6 | #include "property_helper.hpp"
7 | #include "wrapper_helper.hpp"
8 | #include "wrappers.hpp"
9 |
10 | #include "class_generators.h"
11 |
12 | $includes
13 |
14 | $class_generator_definition
--------------------------------------------------------------------------------
/cpp_api_binding/README.md:
--------------------------------------------------------------------------------
1 | # vnpy.bindings
2 |
3 | 这个文件夹包含了vnpy中所有对c++层的封装
4 |
5 | 所有的封装都是使用脚本生成的,使用的脚本为autocxxpy
6 |
7 | 若要看如何构建,请看[build.md](./doc/build.md)
8 |
9 | ---
10 |
11 | ## 目录结构
12 | * cmake/ cmake相关文件
13 | * source/ 所有源码都在这里
14 | * tests/ 测试相关文件
15 | * third_party/ 第三方库的文件,包括头文件,源码或者库文件
16 |
17 | ---
18 |
--------------------------------------------------------------------------------
/cpp_api_binding/doc/build.md:
--------------------------------------------------------------------------------
1 | # Building vnpy.bindings
2 |
3 | vnpy.binding使用CMake作为构建系统,正常地使用CMake去构建即可。
4 |
5 | 我们也提供了针对不同操作系统的简单教程。
6 |
7 | ## 前置要求
8 |
9 | * Python3
10 | * 支持C++17标准及以上的C++编译器(Visual Studio 2017+,GCC7+)
11 | * CMake
12 |
13 | ## 简单教程
14 | 针对不同操作系统有不同的构建方式,请查看对应的文件。
15 |
16 | * Windows : [build.windows.md](./build.windows.md)
17 | * Linux : [build.linux.md](./build.linux.md)
18 |
--------------------------------------------------------------------------------
/cpp_api_binding/build.bat:
--------------------------------------------------------------------------------
1 | @echo off
2 | if "%VS150COMNTOOLS%"=="" (
3 | echo Please run this batch file under "x64 Native Tools Command Prompt for VS 2017"
4 | echo Read the doc!
5 | exit 1
6 | )
7 |
8 | @echo on
9 | set binding_dir=%~dp0
10 | cd %binding_dir%
11 |
12 | rmdir /S /Q build
13 | mkdir build
14 | cd build
15 | cmake -G "Visual Studio 15 2017 Win64" ..
16 | msbuild vnpy_binding.sln /p:Configuration=Release /p:Platform=x64
17 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/TODO.txt:
--------------------------------------------------------------------------------
1 | todo:
2 | tests:
3 | app:
4 | * ctp test
5 |
6 | future plan:
7 | cxx_analysis:
8 | * namespaces
9 |
10 |
11 | not supported:
12 | * namespace is currently not supported
13 | * c++11 strong typed enums(treat as traditional enum)
14 | * constructor is not supported
15 | * default arguments are not supported
16 |
17 | hacks:
18 | * treat any virtual function as callback
19 | * if argument for a async callback is pointer or reference, its value will be copied, modifying its value will have no effect
20 | *
21 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/doc/ctp.md:
--------------------------------------------------------------------------------
1 | #为类ctp接口生成代码
2 |
3 | ## 为ctp接口生成代码
4 |
5 | 运行generate_ctp.py即可,生成的文件位于generated_files/目录下
6 |
7 | ## 为类ctp接口生成代码
8 |
9 | 我们提供了一个CtpAdaptor,位于generator/adaptor目录下。
10 | 参考generate_ctp.py使用即可。
11 | 额外需要手写的的custom_wrapper在/vnpy/binding/source/ctp/custeom_wrapper下已经有了成品。
12 |
13 | ## 细节
14 | ### CtpAdaptor如何工作
15 |
16 | 这个适配器作了以下工作:
17 | 1.将识别为常量的define加入全局常量之中
18 | 2.将所有Api的函数设置为final,防止python调用的时候去检查python端的overload,提升效率。
19 | 3.将所有Spi的函数设置为virtual,非final(默认就是这样的)
20 | 4.增加include一个wrapper:custeom_wrappers/spi.hpp,这个wrapper需要自己写,一般是用来自己实现spi的回调调用(以后会考虑自动生成代码)
21 |
22 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/autocxxpy/clang/__init__.py:
--------------------------------------------------------------------------------
1 | #===- __init__.py - Clang Python Bindings --------------------*- python -*--===#
2 | #
3 | # The LLVM Compiler Infrastructure
4 | #
5 | # This file is distributed under the University of Illinois Open Source
6 | # License. See LICENSE.TXT for details.
7 | #
8 | #===------------------------------------------------------------------------===#
9 |
10 | r"""
11 | Clang Library Bindings
12 | ======================
13 |
14 | This package provides access to the Clang compiler and libraries.
15 |
16 | The available modules are:
17 |
18 | cindex
19 |
20 | Bindings for the Clang indexing library.
21 | """
22 |
23 | __all__ = ['cindex']
24 |
25 |
--------------------------------------------------------------------------------
/cpp_api_binding/source/ctp/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | project(vnctp)
2 |
3 | set(HEADERS
4 | class_generators.h
5 | dispatcher.hpp
6 | property_helper.hpp
7 | vnctptd.cpp
8 | wrappers.hpp
9 | wrapper_helper.hpp
10 | )
11 |
12 |
13 | set(SOURCES
14 | classes_1.cpp
15 | classes_2.cpp
16 | classes_3.cpp
17 | classes_4.cpp
18 | vnctp.cpp
19 | )
20 |
21 | include_directories(${PY_INCLUDE_DIRS})
22 | link_directories(${PY_LIBRARY_DIRS})
23 | include_directories("${CMAKE_CURRENT_SOURCE_DIR}/api")
24 | link_directories("${CMAKE_CURRENT_SOURCE_DIR}/api")
25 |
26 |
27 | add_library(vnctp SHARED ${SOURCES})
28 | target_link_libraries(vnctp ${PY_LIBRARIES})
29 | target_link_libraries(vnctp thostmduserapi_se thosttraderapi_se)
30 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/env.props:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | $(SolutionDir)..\build\tests\$(Platform)\$(Configuration)\
7 | $(SolutionDir)..\build\tests\intermediate\$(ProjectName)\$(Platform)\$(Configuration)\
8 | $(SolutionDir)\3rd_party\include;$(SolutionDir)\templates;$(IncludePath)
9 |
10 |
11 |
12 | stdcpp17
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/candle_chart/base/__init__.py:
--------------------------------------------------------------------------------
1 | """
2 |
3 | """
4 | from .axis import (
5 | AutoGeneratedAxisDataSource,
6 | AxisBase,
7 | AxisDataSource,
8 | BarAxisX,
9 | BarAxisY,
10 | CandleLabelDataSource,
11 | DateTimeDataSource,
12 | GridDrawer,
13 | LabelDrawer,
14 | LineGridDataSource,
15 | LineGridDrawer,
16 | TextLabelDrawer,
17 | TextLabelInfo,
18 | ValueAxisX,
19 | ValueAxisY,
20 | CandleAxisX,
21 | ValueLabelDataSource,
22 | ValueSequenceGenerator,
23 | )
24 | from .base import Alignment, DrawConfig, DrawingCache, Orientation
25 | from .data_source import CandleData, CandleDataSource, DataSource, DataSourceQObject
26 | from .drawer import BarChartDrawer, CandleChartDrawer, ChartDrawerBase, HistogramDrawer
27 | from .chart import ChartWidget
28 | from .advanced_chart import AdvancedChartWidget
29 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/templates/module.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #include "dispatcher.hpp"
6 | #include "property_helper.hpp"
7 | #include "wrapper_helper.hpp"
8 |
9 | #include "class_generators.h"
10 |
11 | $includes
12 |
13 | void init_dispatcher()
14 | {
15 | autocxxpy::dispatcher::instance().start();
16 | }
17 |
18 | void generate_classes(pybind11::module &m)
19 | {
20 | $classes_code
21 | }
22 |
23 | void generate_enums(pybind11::module &m)
24 | {
25 | $enums_code
26 | }
27 |
28 | void generate_constants(pybind11::module &m)
29 | {
30 | $constants_code
31 | }
32 |
33 | // begin generated code - combined_class_generator_definitions
34 | // code will appear only when split_in_files is off
35 | $combined_class_generator_definitions
36 | // end generated code
37 |
38 | PYBIND11_MODULE($module_name, m)
39 | {
40 | init_dispatcher();
41 | generate_classes(m);
42 | generate_constants(m);
43 | generate_enums(m);
44 | }
45 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/tests/tests/tests.vcxproj.filters:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF}
6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx
7 |
8 |
9 | {93995380-89BD-4b04-88EB-625FBE52EBFB}
10 | h;hh;hpp;hxx;hm;inl;inc;ipp;xsd
11 |
12 |
13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01}
14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms
15 |
16 |
17 |
18 |
19 | Source Files
20 |
21 |
22 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/3rd_party/googletest/gtest.vcxproj.filters:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF}
6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx
7 |
8 |
9 | {93995380-89BD-4b04-88EB-625FBE52EBFB}
10 | h;hh;hpp;hxx;hm;inl;inc;ipp;xsd
11 |
12 |
13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01}
14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms
15 |
16 |
17 |
18 |
19 | Source Files
20 |
21 |
22 |
--------------------------------------------------------------------------------
/cpp_api_binding/doc/build.linux.md:
--------------------------------------------------------------------------------
1 | # Building vnpy.binding on Linux
2 |
3 | 目前只有Ubuntu和CentOS两种Linux发行版的教程。
4 |
5 | ## 硬件要求
6 |
7 | 使用G++编译vnpy.binding需要至少3G的可用内存,否则请调整虚拟内存大小。
8 |
9 | ## Ubuntu
10 |
11 | 首先是安装编译套件,python3及其依赖库,git,cmake:
12 | ```bash
13 | sudo apt install -y build-essential python3.7 python3.7-dev git cmake
14 | ```
15 |
16 | 然后克隆vnpy源码:
17 | ```bash
18 | git clone https://github.com/vnpy/vnpy.git
19 | cd vnpy
20 | git checkout v2.0-DEV
21 | ```
22 |
23 | 构建
24 | ```bash
25 | cd binding
26 | mkdir build; cd build
27 | cmake ..
28 | make
29 | ```
30 |
31 |
32 | ## CentOS
33 |
34 | 首先启用epel和scl源
35 | ```bash
36 | sudo yum install -y epel-release centos-release-scl
37 | ```
38 |
39 | 然后安装编译套件,python3及其依赖库,git,cmake:
40 | ```bash
41 | sudo yum install -y devtoolset-7 python36 python36-devel git cmake3
42 | ```
43 |
44 | 接着克隆vnpy源码:
45 | ```bash
46 | git clone https://github.com/vnpy/vnpy.git
47 | cd vnpy
48 | git checkout v2.0-DEV
49 | ```
50 |
51 | 最后启用gcc7并构建:
52 | ```bash
53 | cd binding
54 | mkdir build; cd build
55 | scl enable devtoolset-7 bash
56 | cmake3 ..
57 | make
58 | ```
59 |
60 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/README.MD:
--------------------------------------------------------------------------------
1 | # autocxxpy
2 |
3 | ## 项目主旨
4 |
5 | 这个项目意在分析C++头文件,并且生成一个对应的pyd文件,以便python调用。
6 | 作为vnpy的一个代码生成工具,目前主要用来生成vnpy.binding的代码,以便vnpy调用C++的东西。
7 |
8 | ## 特点
9 |
10 | * 可以从头文件以及相应的依赖库直接生pyd文件对应的代码。
11 | * 可以在C++层自定义任何函数的转化细节
12 | * 精准的分析:基于clang进行语法分析,不会因为代码格式而出现分析失误。
13 |
14 | ## 可以做到哪些东西
15 | 目前可以正确分析C++的以下元素:
16 | 全局域:
17 | define
18 | enum
19 | class/struct
20 | functions
21 | typedef
22 | class:
23 | data member(variable)
24 | method(functions)
25 | destructor
26 |
27 | ## 分析正确率
28 | 基于CLang编译器,分析的正确率取决于clang。
29 |
30 | ## 转化细节
31 |
32 | 请看[converts.md](doc/converts.md)
33 |
34 | ## 如何使用
35 |
36 | 在使用之前,先下载[clang]。如果需要其他版本的CLang,[请看这里](http://releases.llvm.org/download.html)。
37 | 安装好clang之后将所需的库复制至/vnpy/binding/generator/目录下。
38 | 在Windows下所需的库是libclang.dll。Linux下则为libclang.so。
39 |
40 | 如果想为类ctp接口生成代码,请看[ctp.md](doc/ctp.md)
41 |
42 | 如果想为新接口生成代码,请看[converts.md](doc/converts.md)
43 |
44 | ## 以后会增加哪些支持
45 | 增加什么的分析主要看以后遇到哪些接口。
46 | 若目前的生成器能无法分析所遇到接口的所有元素,那么肯定会增加新功能。
47 |
48 |
49 | [clang]:http://releases.llvm.org/7.0.1/LLVM-7.0.1-win64.exe
--------------------------------------------------------------------------------
/cpp_api_binding/cmake/py_find.cmake:
--------------------------------------------------------------------------------
1 | # try to find python use : user_defined_path, FindPython3 and FindPythonLibs
2 | # outputs: PY_LIBRARIES PY_INCLUDE_DIRS
3 |
4 | # check if user supplied path
5 | if(USER_PYTHON_LIBRARIY AND USER_PYTHON_INCLUDE_DIRS)
6 | set(PY_LIBRARIES ${USER_PYTHON_LIBRARIY})
7 | set(PY_INCLUDE_DIRS ${USER_PYTHON_INCLUDE_DIRS})
8 | message("use user supplied python paths")
9 | return()
10 | endif()
11 |
12 | if (${CMAKE_VERSION} VERSION_GREATER "3.12.0")
13 | find_package(Python3)
14 |
15 | if(${Python3_LIBRARIES} AND ${Python3_INCLUDE_DIRS})
16 | set(PY_LIBRARIES ${Python3_LIBRARIES})
17 | set(PY_INCLUDE_DIRS ${Python3_INCLUDE_DIRS})
18 | message("use FindPython3 found python paths")
19 | return()
20 | endif()
21 | endif()
22 |
23 | find_package(PythonLibs 3)
24 |
25 | if(PYTHON_LIBRARIES AND PYTHON_INCLUDE_DIRS)
26 | set(PY_LIBRARIES ${PYTHON_LIBRARIES})
27 | set(PY_INCLUDE_DIRS ${PYTHON_INCLUDE_DIRS})
28 | message("use FindPythonLibs found python paths")
29 | return()
30 | endif()
31 |
32 | message(WARNING "no python path found!")
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 vn.py
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/autocxxpy/type.py:
--------------------------------------------------------------------------------
1 | # encoding: utf-8
2 | import re
3 |
4 | base_types = {
5 | "char8_t",
6 | "char16_t",
7 | "char32_t",
8 | "wchar_t",
9 | "char",
10 | "short",
11 | "int",
12 | "long",
13 | "long long" "unsigned char",
14 | "unsigned short",
15 | "unsigned int",
16 | "unsigned long",
17 | "unsigned long long",
18 | "float",
19 | "double",
20 | }
21 |
22 |
23 | def is_array_type(t: str):
24 | return "[" in t
25 |
26 |
27 | def array_base(t: str):
28 | """
29 | :raise ValueError if t is not a array type
30 | """
31 | return t[: t.index("[") - 1]
32 |
33 |
34 | def is_pointer_type(t: str):
35 | return "*" in t
36 |
37 |
38 | _REMOVE_POINTER_RE = re.compile("[ \t]*\\*[ \t]*")
39 |
40 |
41 | def pointer_base(t: str):
42 | return _REMOVE_POINTER_RE.sub("", t)
43 |
44 |
45 | def is_reference_type(t: str):
46 | return "&" in t
47 |
48 |
49 | def remove_cvref(t: str):
50 | return (
51 | t.replace("const ", "")
52 | .replace("volatile ", "")
53 | .replace("&", "")
54 | .strip()
55 | )
56 |
--------------------------------------------------------------------------------
/cpp_api_binding/source/ctp/custom_wrappers/spi.hpp:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 |
5 | #include "../api/ThostFtdcMdApi.h"
6 | #include "../wrapper_helper.hpp"
7 |
8 | namespace autocxxpy
9 | {
10 |
11 | template
12 | struct spi_vector_wrapper
13 | {
14 | static constexpr auto value = [](CThostFtdcMdApi *instance, std::vector &arg)
15 | {
16 | return (instance->*method)(&arg.at(0), static_cast(arg.size()));
17 | };
18 | };
19 |
20 | #define DEF_SPI_VECTOR_CALLING_WRAPPER(method) \
21 | template <>\
22 | struct calling_wrapper \
23 | : spi_vector_wrapper\
24 | {};
25 |
26 | DEF_SPI_VECTOR_CALLING_WRAPPER(&CThostFtdcMdApi::SubscribeMarketData)
27 | DEF_SPI_VECTOR_CALLING_WRAPPER(&CThostFtdcMdApi::UnSubscribeMarketData)
28 | DEF_SPI_VECTOR_CALLING_WRAPPER(&CThostFtdcMdApi::SubscribeForQuoteRsp)
29 | DEF_SPI_VECTOR_CALLING_WRAPPER(&CThostFtdcMdApi::UnSubscribeForQuoteRsp)
30 | //template <>
31 | //struct calling_wrapper<&CThostFtdcMdApi::SubscribeMarketData>
32 | // : spi_vector_wrapper<&CThostFtdcMdApi::SubscribeMarketData>
33 | //{};
34 | }
35 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/generate_ctp.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import os
3 |
4 | from adaptor.ctpadaptor import CtpAdaptor
5 | from autocxxpy.generator import GeneratorOptions, Generator
6 |
7 | logger = logging.getLogger(__file__)
8 |
9 |
10 | def clear_dir(path: str):
11 | for file in os.listdir(path):
12 | os.unlink(os.path.join(path, file))
13 |
14 |
15 | def main():
16 | options: GeneratorOptions = CtpAdaptor(
17 | "../source/ctp/api/ThostFtdcMdApi.h",
18 | "../source/ctp/api/ThostFtdcTraderApi.h",
19 | ).parse()
20 |
21 | options.includes.append("api/ThostFtdcTraderApi.h")
22 | options.includes.append("api/ThostFtdcMdApi.h")
23 | options.split_in_files = True
24 | options.module_name = "vnctp"
25 | options.max_classes_in_one_file = 100
26 |
27 | saved_files = Generator(options=options).generate()
28 | output_dir = "./generated_files"
29 | # clear output dir
30 | if not os.path.exists(output_dir):
31 | os.mkdir(output_dir)
32 | clear_dir(output_dir)
33 |
34 | for name, data in saved_files.items():
35 | with open(f"{output_dir}/{name}", "wt") as f:
36 | f.write(data)
37 |
38 |
39 | if __name__ == "__main__":
40 | main()
41 |
--------------------------------------------------------------------------------
/cpp_api_binding/doc/build.windows.md:
--------------------------------------------------------------------------------
1 | # Building vnpy.binding on Windows
2 |
3 | ## 环境要求
4 |
5 | 在编译之前,你必须确保已经安装好如下组件:
6 | * [Python3][Python]
7 | * [CMake][CMake]
8 | * [Visual Studio 2017][VS2017] with C++ Desktop Development
9 |
10 | > 在安装CMake的时候必须勾选将CMake加入PATH
11 | > 在安装Visual Studio的时候必须勾选使用C++的桌面开发(Desktop Development with C++)
12 |
13 | ## 一键编译
14 |
15 | 打开开始菜单-Visual Studio 2017-x64 Native Tools Command Prompt for VS 2017
16 | 将vnpy/binding/build.bat拖入弹出的控制台,回车运行即可。
17 |
18 |
19 | ## 手动编译
20 |
21 | 确保你安装好了Python3,CMake还有Visual Studio和C++编译环境,下载好[vnpy]并解压。
22 | 打开开始菜单-Visual Studio 2017-x64 Native Tools Command Prompt for VS 2017
23 | 在弹出的控制台中运行以下命令(将vnpy解压目录改为你将vnpy解压到的目录):
24 | ```bat
25 | cd vnpy解压目录
26 | mkdir binding\build
27 | cd binding\build
28 | cmake -G "Visual Studio 15 2017 Win64" ..
29 | msbuild vnpy_binding.sln /p:Configuration=Release /p:Platform=x64
30 | ```
31 |
32 | [Python]:https://www.python.org/ftp/python/3.7.2/python-3.7.2-amd64-webinstall.exe
33 | [CMake]:https://github.com/Kitware/CMake/releases/download/v3.13.3/cmake-3.13.3-win64-x64.msi
34 | [VS2017]:https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=Community&rel=15#
35 | [vnpy]:https://github.com/vnpy/vnpy/archive/v2.0-DEV.zip
36 |
--------------------------------------------------------------------------------
/cpp_api_binding/cmake/py.cmake:
--------------------------------------------------------------------------------
1 | # try to find python use : user_defined_path, FindPython3 and FindPythonLibs
2 | # outputs: USER_PYTHON_LIBRARIY USER_PYTHON_INCLUDE_DIRS
3 |
4 |
5 | # ignore default input library in MSVC first
6 | if (CMAKE_CXX_COMPILER_ID MATCHES MSVC)
7 | set(CMAKE_SHARED_LINKER_FLAGS_DEBUG "${CMAKE_SHARED_LINKER_FLAGS_DEBUG} /NODEFAULTLIB:\"python37_d.lib\"")
8 | set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} /NODEFAULTLIB:\"python37.lib\"")
9 | endif()
10 |
11 | # define user options
12 | set(USER_PYTHON_LIBRARIY ${USER_PYTHON_LIBRARIY} CACHE PATH "include dir for python3, eg: C:/Python37/include")
13 | set(USER_PYTHON_INCLUDE_DIRS ${USER_PYTHON_INCLUDE_DIRS} CACHE FILEPATH "Helpstring, eg: C:/Python37/libs/python3.lib")
14 |
15 | include(cmake/py_find.cmake)
16 |
17 | set(USER_PYTHON_LIBRARIY ${PY_LIBRARIES} CACHE PATH "include dir for python3, eg: C:/Python37/include" FORCE)
18 | set(USER_PYTHON_INCLUDE_DIRS ${PY_INCLUDE_DIRS} CACHE FILEPATH "Helpstring, eg: C:/Python37/libs/python3.lib" FORCE)
19 |
20 | message("USER_PYTHON_LIBRARIY : ${USER_PYTHON_LIBRARIY}")
21 | message("USER_PYTHON_INCLUDE_DIRS : ${USER_PYTHON_INCLUDE_DIRS}")
22 |
23 | include_directories(${USER_PYTHON_INCLUDE_DIRS})
24 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/autocxxpy/clang/enumerations.py:
--------------------------------------------------------------------------------
1 | #===- enumerations.py - Python Enumerations ------------------*- python -*--===#
2 | #
3 | # The LLVM Compiler Infrastructure
4 | #
5 | # This file is distributed under the University of Illinois Open Source
6 | # License. See LICENSE.TXT for details.
7 | #
8 | #===------------------------------------------------------------------------===#
9 |
10 | # pylint: skip-file
11 |
12 | """
13 | Clang Enumerations
14 | ==================
15 |
16 | This module provides static definitions of enumerations that exist in libclang.
17 |
18 | Enumerations are typically defined as a list of tuples. The exported values are
19 | typically munged into other types or classes at module load time.
20 |
21 | All enumerations are centrally defined in this file so they are all grouped
22 | together and easier to audit. And, maybe even one day this file will be
23 | automatically generated by scanning the libclang headers!
24 | """
25 |
26 | # Maps to CXTokenKind. Note that libclang maintains a separate set of token
27 | # enumerations from the C++ API.
28 | TokenKinds = [
29 | ('PUNCTUATION', 0),
30 | ('KEYWORD', 1),
31 | ('IDENTIFIER', 2),
32 | ('LITERAL', 3),
33 | ('COMMENT', 4),
34 | ]
35 |
36 | __all__ = ['TokenKinds']
37 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/doc/converts.md:
--------------------------------------------------------------------------------
1 | # 生成细节
2 |
3 | autocxxpy核心分为三部分:
4 | * CXXParser:负责分析C++文件,输出defines,class,function,constants之类的信息
5 | * PreProcessor:负责分析CXXParser的结果,对一些特别的量进行识别,比如定义成常量的define,一个类是否是纯类等等
6 | * Generator:负责生成代码
7 |
8 | ## 生成过程
9 | 要使用这个生成器,首先指定要分析的头文件,使用CXXParser分析。
10 | ```python
11 | r0: CXXParseResult = CXXParser([self.md_header, self.td_header]).parse()
12 | ```
13 | 然后将结果传入预处理器
14 | ```python
15 | r1: PreProcessorResult = PreProcessor(r0).process()
16 | ```
17 | 最后将第一步和第二部的结果一起传入Generator。
18 | 注意:除了classes以外,所有参数都可以置空或者仅从第一步提取。
19 | 最终返回的是一组字典```Dict[str, str]```,记录着生成的文件名和对应的内容。
20 | 用户只需要江这些结果保存下来即可。
21 | ```python
22 | options = GeneratorOptions(
23 | typedefs=r0.typedefs,
24 | constants=r0.variables & r1.const_macros,
25 | functions=r0.functions,
26 | classes=r1.classes,
27 | dict_classes=r1.dict_classes,
28 | enums=r0.enums,
29 | )
30 |
31 | ```
32 |
33 | ## Q & A
34 | ### 为什么会有PreProcessor
35 | 理想情况下,一个cxx到pyd的生成器应该是只需要提供头文件,即可生成正确的pyd文件。
36 | 但是cxx语法丰富,包容各种写法。虽然主流写法大体是一致的,但是我们也不能忽视大量非主流写法的存在。要包容所有的写法是一件比较困难的事情。
37 | 这些写法虽然不会导致最终无法生成pyd,但是会导致pyd难以使用,或者使得最终生成的文件效率低下。
38 | 例如有些人可能会用define定义常量或者内联函数。忽略掉这些东西显然会降低我们的python端的代码体验。
39 | 所以我们使用PreProcessor将一些分析奇葩写法得到的结果转换成主流写法的结果。
40 | 如果你觉得这些转化是多余的,你可以不使用PreProcessor的结果。
41 |
42 |
--------------------------------------------------------------------------------
/cpp_api_binding/source/ctp/property_helper.hpp:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 | #include
6 | #include
7 |
8 | #include
9 |
10 |
11 | namespace autocxxpy
12 | {
13 | template
14 | auto wrap_getter(value_type class_type::*member)
15 | {
16 | return [member](const class_type &instance)->const value_type & {
17 | return instance.*member;
18 | };
19 | }
20 |
21 |
22 | template
23 | auto wrap_setter(value_type class_type::*member)
24 | {
25 | return [member](class_type &instance, const value_type &value) {
26 | instance.*member = value;
27 | };
28 | }
29 |
30 | template
31 | using string_literal = char[size];
32 |
33 | template
34 | auto wrap_getter(string_literal class_type::*member)
35 | {
36 | return [member](const class_type &instance) {
37 | //return std::string_view(instance.*member);
38 | return instance.*member;
39 | };
40 | }
41 |
42 |
43 | template
44 | auto wrap_setter(string_literal class_type::*member)
45 | {
46 | return [member](class_type &instance, const std::string_view &value) {
47 | #ifdef _MSC_VER
48 | strcpy_s(instance.*member, value.data());
49 | #else
50 | strcpy(instance.*member, value.data());
51 | #endif
52 | };
53 | //return [member](class_type &instance, const py::str &) {
54 | // strcpy_s(instance.*member, str->raw_str());
55 | //};
56 | }
57 |
58 | #define AUTOCXXPY_DEF_PROPERTY(cls, name) \
59 | def_property(#name, autocxxpy::wrap_getter(&cls::name), autocxxpy::wrap_setter(&cls::name))
60 | }
61 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/templates/property_helper.hpp:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 | #include
6 | #include
7 |
8 | #include
9 |
10 |
11 | namespace autocxxpy
12 | {
13 | template
14 | auto wrap_getter(value_type class_type::*member)
15 | {
16 | return [member](const class_type &instance)->const value_type & {
17 | return instance.*member;
18 | };
19 | }
20 |
21 |
22 | template
23 | auto wrap_setter(value_type class_type::*member)
24 | {
25 | return [member](class_type &instance, const value_type &value) {
26 | instance.*member = value;
27 | };
28 | }
29 |
30 | template
31 | using string_literal = char[size];
32 |
33 | template
34 | auto wrap_getter(string_literal class_type::*member)
35 | {
36 | return [member](const class_type &instance) {
37 | //return std::string_view(instance.*member);
38 | return instance.*member;
39 | };
40 | }
41 |
42 |
43 | template
44 | auto wrap_setter(string_literal class_type::*member)
45 | {
46 | return [member](class_type &instance, const std::string_view &value) {
47 | #ifdef _MSC_VER
48 | strcpy_s(instance.*member, value.data());
49 | #else
50 | strcpy(instance.*member, value.data());
51 | #endif
52 | };
53 | //return [member](class_type &instance, const py::str &) {
54 | // strcpy_s(instance.*member, str->raw_str());
55 | //};
56 | }
57 |
58 | #define AUTOCXXPY_DEF_PROPERTY(cls, name) \
59 | def_property(#name, autocxxpy::wrap_getter(&cls::name), autocxxpy::wrap_setter(&cls::name))
60 | }
61 |
--------------------------------------------------------------------------------
/cpp_api_binding/third_party/include/pybind11/detail/typeid.h:
--------------------------------------------------------------------------------
1 | /*
2 | pybind11/detail/typeid.h: Compiler-independent access to type identifiers
3 |
4 | Copyright (c) 2016 Wenzel Jakob
5 |
6 | All rights reserved. Use of this source code is governed by a
7 | BSD-style license that can be found in the LICENSE file.
8 | */
9 |
10 | #pragma once
11 |
12 | #include
13 | #include
14 |
15 | #if defined(__GNUG__)
16 | #include
17 | #endif
18 |
19 | NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
20 | NAMESPACE_BEGIN(detail)
21 | /// Erase all occurrences of a substring
22 | inline void erase_all(std::string &string, const std::string &search) {
23 | for (size_t pos = 0;;) {
24 | pos = string.find(search, pos);
25 | if (pos == std::string::npos) break;
26 | string.erase(pos, search.length());
27 | }
28 | }
29 |
30 | PYBIND11_NOINLINE inline void clean_type_id(std::string &name) {
31 | #if defined(__GNUG__)
32 | int status = 0;
33 | std::unique_ptr res {
34 | abi::__cxa_demangle(name.c_str(), nullptr, nullptr, &status), std::free };
35 | if (status == 0)
36 | name = res.get();
37 | #else
38 | detail::erase_all(name, "class ");
39 | detail::erase_all(name, "struct ");
40 | detail::erase_all(name, "enum ");
41 | #endif
42 | detail::erase_all(name, "pybind11::");
43 | }
44 | NAMESPACE_END(detail)
45 |
46 | /// Return a string representation of a C++ type
47 | template static std::string type_id() {
48 | std::string name(typeid(T).name());
49 | detail::clean_type_id(name);
50 | return name;
51 | }
52 |
53 | NAMESPACE_END(PYBIND11_NAMESPACE)
54 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | *.egg-info/
24 | .installed.cfg
25 | *.egg
26 | MANIFEST
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | nosetests.xml
45 | coverage.xml
46 | *.cover
47 | .hypothesis/
48 | .pytest_cache/
49 |
50 | # Translations
51 | *.mo
52 | *.pot
53 |
54 | # Django stuff:
55 | *.log
56 | local_settings.py
57 | db.sqlite3
58 |
59 | # Flask stuff:
60 | instance/
61 | .webassets-cache
62 |
63 | # Scrapy stuff:
64 | .scrapy
65 |
66 | # Sphinx documentation
67 | docs/_build/
68 |
69 | # PyBuilder
70 | target/
71 |
72 | # Jupyter Notebook
73 | .ipynb_checkpoints
74 |
75 | # pyenv
76 | .python-version
77 |
78 | # celery beat schedule file
79 | celerybeat-schedule
80 |
81 | # SageMath parsed files
82 | *.sage.py
83 |
84 | # Environments
85 | .env
86 | .venv
87 | env/
88 | venv/
89 | ENV/
90 | env.bak/
91 | venv.bak/
92 |
93 | # Spyder project settings
94 | .spyderproject
95 | .spyproject
96 |
97 | # Rope project settings
98 | .ropeproject
99 |
100 | # mkdocs documentation
101 | /site
102 |
103 | # mypy
104 | .mypy_cache/
105 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/3rd_party/include/gtest/internal/custom/README.md:
--------------------------------------------------------------------------------
1 | # Customization Points
2 |
3 | The custom directory is an injection point for custom user configurations.
4 |
5 | ## Header `gtest.h`
6 |
7 | ### The following macros can be defined:
8 |
9 | * `GTEST_OS_STACK_TRACE_GETTER_` - The name of an implementation of
10 | `OsStackTraceGetterInterface`.
11 | * `GTEST_CUSTOM_TEMPDIR_FUNCTION_` - An override for `testing::TempDir()`. See
12 | `testing::TempDir` for semantics and signature.
13 |
14 | ## Header `gtest-port.h`
15 |
16 | The following macros can be defined:
17 |
18 | ### Flag related macros:
19 |
20 | * `GTEST_FLAG(flag_name)`
21 | * `GTEST_USE_OWN_FLAGFILE_FLAG_` - Define to 0 when the system provides its
22 | own flagfile flag parsing.
23 | * `GTEST_DECLARE_bool_(name)`
24 | * `GTEST_DECLARE_int32_(name)`
25 | * `GTEST_DECLARE_string_(name)`
26 | * `GTEST_DEFINE_bool_(name, default_val, doc)`
27 | * `GTEST_DEFINE_int32_(name, default_val, doc)`
28 | * `GTEST_DEFINE_string_(name, default_val, doc)`
29 |
30 | ### Logging:
31 |
32 | * `GTEST_LOG_(severity)`
33 | * `GTEST_CHECK_(condition)`
34 | * Functions `LogToStderr()` and `FlushInfoLog()` have to be provided too.
35 |
36 | ### Threading:
37 |
38 | * `GTEST_HAS_NOTIFICATION_` - Enabled if Notification is already provided.
39 | * `GTEST_HAS_MUTEX_AND_THREAD_LOCAL_` - Enabled if `Mutex` and `ThreadLocal`
40 | are already provided. Must also provide `GTEST_DECLARE_STATIC_MUTEX_(mutex)`
41 | and `GTEST_DEFINE_STATIC_MUTEX_(mutex)`
42 | * `GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)`
43 | * `GTEST_LOCK_EXCLUDED_(locks)`
44 |
45 | ### Underlying library support features
46 |
47 | * `GTEST_HAS_CXXABI_H_`
48 |
49 | ### Exporting API symbols:
50 |
51 | * `GTEST_API_` - Specifier for exported symbols.
52 |
53 | ## Header `gtest-printers.h`
54 |
55 | * See documentation at `gtest/gtest-printers.h` for details on how to define a
56 | custom printer.
57 |
--------------------------------------------------------------------------------
/cpp_api_binding/cmake/flags.cmake:
--------------------------------------------------------------------------------
1 | set(CMAKE_CXX_STANDARD 17)
2 |
3 |
4 | set(CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE} CACHE STRING "")
5 | if ("${CMAKE_BUILD_TYPE}" STREQUAL "")
6 | set(CMAKE_BUILD_TYPE Release CACHE STRING "" FORCE)
7 | endif()
8 |
9 | if (CMAKE_BUILD_TYPE STREQUAL "Release")
10 | add_definitions(/DNDEBUG)
11 | endif()
12 |
13 | if (CMAKE_CXX_COMPILER_ID MATCHES GNU)
14 |
15 | set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wno-strict-aliasing")
16 | set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -Ofast")
17 |
18 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wno-class-memaccess")
19 | set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -Ofast -s")
20 |
21 | #MinGW cross-compile
22 | if (WIN32)
23 | set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static")
24 | else()
25 | set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static-libgcc -static-libstdc++")
26 | endif()
27 |
28 | if (${CMAKE_VERSION} VERSION_LESS "3.1.0")
29 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17")
30 | endif()
31 |
32 | # add debug information
33 | set(CMAKE_C_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -ggdb")
34 |
35 | elseif (CMAKE_CXX_COMPILER_ID MATCHES MSVC)
36 | set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /EHsc /MP /bigobj")
37 | set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /EHsc /Ox /Ob2 /Ot /Oi /MT /GL /MP")
38 | set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} /LTCG")
39 |
40 | add_definitions(/D_CRT_SECURE_NO_WARNINGS)
41 | add_definitions(/D_CRT_NONSTDC_NO_WARNINGS)
42 | add_definitions(/DNOMINMAX)
43 |
44 | elseif (CMAKE_CXX_COMPILER_ID MATCHES Clang)
45 |
46 | set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall")
47 | set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -Ofast")
48 |
49 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wno-missing-braces")
50 | set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -Ofast")
51 | endif()
52 |
--------------------------------------------------------------------------------
/candle_chart/base/data_source.py:
--------------------------------------------------------------------------------
1 | from dataclasses import dataclass
2 | from datetime import datetime
3 | from typing import Generic, Iterable, List, TYPE_CHECKING, TypeVar
4 |
5 | from PyQt5.QtCore import QObject, pyqtSignal
6 |
7 | if TYPE_CHECKING:
8 | from .base import Alignment
9 |
10 | T = TypeVar("T")
11 |
12 |
13 | class DataSourceQObject(QObject):
14 | data_removed = pyqtSignal(int, int) # (start: int, end: int)
15 |
16 |
17 | class DataSource(Generic[T]):
18 | """
19 | DataSource for a Drawer.
20 | A DataSource is just like a list, but not all the operation is supported in list.
21 | Supported operations are:
22 | append(), clear(), __len__(), __getitem__(),
23 | """
24 |
25 | def __init__(self, parent=None):
26 | super().__init__()
27 | self.data_list: List[T] = []
28 | self.qobject = DataSourceQObject(parent)
29 |
30 | def extend(self, seq: Iterable[T]) -> None:
31 | self.data_list.extend(seq)
32 |
33 | def append(self, object: T) -> None:
34 | self.data_list.append(object)
35 |
36 | def clear(self) -> None:
37 | self.qobject.data_removed.emit(0, len(self.data_list))
38 | self.data_list.clear()
39 |
40 | def append_by_sequence(self, xs: List[float], align: "Alignment", item: List[T]):
41 | raise NotImplementedError()
42 |
43 | def __getitem__(self, item):
44 | return self.data_list[item]
45 |
46 | def __len__(self):
47 | return len(self.data_list)
48 |
49 | def __str__(self):
50 | return str(self.data_list)
51 |
52 | def __repr__(self):
53 | return repr(self.data_list)
54 |
55 |
56 | @dataclass
57 | class CandleData:
58 | """
59 | Represent a single record in DataSource for CandleChartDrawer
60 | """
61 |
62 | open_price: float
63 | low_price: float
64 | high_price: float
65 | close_price: float
66 | datetime: datetime
67 |
68 |
69 | CandleDataSource = DataSource["CandleData"]
70 | HistogramDataSource = DataSource[float]
71 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/3rd_party/include/gtest/internal/custom/gtest.h:
--------------------------------------------------------------------------------
1 | // Copyright 2015, Google Inc.
2 | // All rights reserved.
3 | //
4 | // Redistribution and use in source and binary forms, with or without
5 | // modification, are permitted provided that the following conditions are
6 | // met:
7 | //
8 | // * Redistributions of source code must retain the above copyright
9 | // notice, this list of conditions and the following disclaimer.
10 | // * Redistributions in binary form must reproduce the above
11 | // copyright notice, this list of conditions and the following disclaimer
12 | // in the documentation and/or other materials provided with the
13 | // distribution.
14 | // * Neither the name of Google Inc. nor the names of its
15 | // contributors may be used to endorse or promote products derived from
16 | // this software without specific prior written permission.
17 | //
18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 | //
30 | // Injection point for custom user configurations. See README for details
31 | //
32 | // ** Custom implementation starts here **
33 |
34 | #ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
35 | #define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
36 |
37 | #endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
38 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/3rd_party/include/gtest/internal/custom/gtest-port.h:
--------------------------------------------------------------------------------
1 | // Copyright 2015, Google Inc.
2 | // All rights reserved.
3 | //
4 | // Redistribution and use in source and binary forms, with or without
5 | // modification, are permitted provided that the following conditions are
6 | // met:
7 | //
8 | // * Redistributions of source code must retain the above copyright
9 | // notice, this list of conditions and the following disclaimer.
10 | // * Redistributions in binary form must reproduce the above
11 | // copyright notice, this list of conditions and the following disclaimer
12 | // in the documentation and/or other materials provided with the
13 | // distribution.
14 | // * Neither the name of Google Inc. nor the names of its
15 | // contributors may be used to endorse or promote products derived from
16 | // this software without specific prior written permission.
17 | //
18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 | //
30 | // Injection point for custom user configurations. See README for details
31 | //
32 | // ** Custom implementation starts here **
33 |
34 | #ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
35 | #define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
36 |
37 | #endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
38 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/adaptor/ctpadaptor.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import os
3 |
4 | from autocxxpy.cxxparser import CXXFileParser, CXXParseResult
5 | from autocxxpy.generator import GeneratorOptions
6 | from autocxxpy.preprocessor import PreProcessorResult, PreProcessor
7 |
8 | logger = logging.getLogger(__file__)
9 |
10 |
11 | def clear_dir(path: str):
12 | for file in os.listdir(path):
13 | os.unlink(os.path.join(path, file))
14 |
15 |
16 | class CtpAdaptor:
17 | def __init__(self, td_header, md_header):
18 | self.td_header = td_header
19 | self.md_header = md_header
20 |
21 | def parse(self) -> GeneratorOptions:
22 | r0: CXXParseResult = CXXFileParser(
23 | [self.md_header, self.td_header]
24 | ).parse()
25 | r1: PreProcessorResult = PreProcessor(r0).process()
26 |
27 | constants = r0.variables
28 | constants.update(r1.const_macros)
29 | constants = {
30 | k: v for k, v in constants.items() if not k.startswith("_")
31 | }
32 |
33 | functions = r0.functions
34 | classes = r1.classes
35 |
36 | # make all api "final" to improve performance
37 | for c in classes.values():
38 | type = c.name[-3:]
39 | if type == "Api":
40 | for ms in c.functions.values():
41 | for m in ms:
42 | if m.is_virtual:
43 | m.is_pure_virtual = False
44 | m.is_final = True
45 | elif type == "Spi":
46 | for ms in c.functions.values():
47 | for m in ms:
48 | m.is_virtual = True
49 | # m.is_pure_virtual = True
50 | m.is_final = False
51 |
52 | options = GeneratorOptions(
53 | typedefs=r0.typedefs,
54 | constants=constants,
55 | functions=functions,
56 | classes=classes,
57 | dict_classes=r1.dict_classes,
58 | enums=r0.enums,
59 | )
60 | options.includes = ["custom_wrappers/spi.hpp"]
61 | return options
62 |
--------------------------------------------------------------------------------
/cpp_api_binding/tests/test.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 |
4 | print(sys.path)
5 | print(os.environ)
6 |
7 | import vnctp # noqa
8 | from vnctp import (
9 | CThostFtdcTraderApi,
10 | CThostFtdcTraderSpi,
11 | CThostFtdcRspAuthenticateField,
12 | CThostFtdcRspInfoField,
13 | CThostFtdcRspUserLoginField,
14 | CThostFtdcUserLogoutField,
15 | ) # noqa
16 |
17 | print(vnctp)
18 | print(dir(vnctp))
19 |
20 | for i in dir(vnctp):
21 | print(f"{i} : {vnctp.__dict__[i]}")
22 |
23 | print("creating ctp api")
24 | api = CThostFtdcTraderApi.CreateFtdcTraderApi("flow2")
25 |
26 | print("creating ctp spi")
27 |
28 |
29 | # pylint: disable=invalid-name
30 | class Spi(CThostFtdcTraderSpi):
31 | def OnFrontConnected(self) -> None:
32 | print("OnFrontConnected!")
33 |
34 | def OnFrontDisconnected(self, nReason: int) -> None:
35 | print("OnFrontDisconnected!")
36 |
37 | def OnRspAuthenticate(
38 | self,
39 | pRspAuthenticateField: CThostFtdcRspAuthenticateField,
40 | pRspInfo: CThostFtdcRspInfoField,
41 | nRequestID: int,
42 | bIsLast: bool,
43 | ) -> None:
44 | print("OnRspAuthenticate!")
45 |
46 | def OnRspUserLogin(
47 | self,
48 | pRspUserLogin: CThostFtdcRspUserLoginField,
49 | pRspInfo: CThostFtdcRspInfoField,
50 | nRequestID: int,
51 | bIsLast: bool,
52 | ) -> None:
53 | print("OnRspUserLogin!")
54 |
55 | def OnRspUserLogout(
56 | self,
57 | pUserLogout: CThostFtdcUserLogoutField,
58 | pRspInfo: CThostFtdcRspInfoField,
59 | nRequestID: int,
60 | bIsLast: bool,
61 | ) -> None:
62 | print("OnRspUserLogout!")
63 |
64 | def OnRspError(
65 | self, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool
66 | ) -> None:
67 | print("OnRspError!")
68 |
69 |
70 | # pylint: enable=invalid-name
71 |
72 |
73 | spi = Spi()
74 |
75 | print("registering spi")
76 | api.RegisterSpi(spi)
77 | print("registering front")
78 | api.RegisterFront("tcp://180.168.146.187:10030")
79 | print("Init() ...")
80 | api.Init()
81 |
82 | print("Join() ...")
83 | while True:
84 | pass
85 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/3rd_party/include/gtest/internal/custom/gtest-printers.h:
--------------------------------------------------------------------------------
1 | // Copyright 2015, Google Inc.
2 | // All rights reserved.
3 | //
4 | // Redistribution and use in source and binary forms, with or without
5 | // modification, are permitted provided that the following conditions are
6 | // met:
7 | //
8 | // * Redistributions of source code must retain the above copyright
9 | // notice, this list of conditions and the following disclaimer.
10 | // * Redistributions in binary form must reproduce the above
11 | // copyright notice, this list of conditions and the following disclaimer
12 | // in the documentation and/or other materials provided with the
13 | // distribution.
14 | // * Neither the name of Google Inc. nor the names of its
15 | // contributors may be used to endorse or promote products derived from
16 | // this software without specific prior written permission.
17 | //
18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 | //
30 | // This file provides an injection point for custom printers in a local
31 | // installation of gTest.
32 | // It will be included from gtest-printers.h and the overrides in this file
33 | // will be visible to everyone.
34 | //
35 | // Injection point for custom user configurations. See README for details
36 | //
37 | // ** Custom implementation starts here **
38 |
39 | #ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
40 | #define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
41 |
42 | #endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
43 |
--------------------------------------------------------------------------------
/cpp_api_binding/third_party/include/pybind11/complex.h:
--------------------------------------------------------------------------------
1 | /*
2 | pybind11/complex.h: Complex number support
3 |
4 | Copyright (c) 2016 Wenzel Jakob
5 |
6 | All rights reserved. Use of this source code is governed by a
7 | BSD-style license that can be found in the LICENSE file.
8 | */
9 |
10 | #pragma once
11 |
12 | #include "pybind11.h"
13 | #include
14 |
15 | /// glibc defines I as a macro which breaks things, e.g., boost template names
16 | #ifdef I
17 | # undef I
18 | #endif
19 |
20 | NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
21 |
22 | template struct format_descriptor, detail::enable_if_t::value>> {
23 | static constexpr const char c = format_descriptor::c;
24 | static constexpr const char value[3] = { 'Z', c, '\0' };
25 | static std::string format() { return std::string(value); }
26 | };
27 |
28 | #ifndef PYBIND11_CPP17
29 |
30 | template constexpr const char format_descriptor<
31 | std::complex, detail::enable_if_t::value>>::value[3];
32 |
33 | #endif
34 |
35 | NAMESPACE_BEGIN(detail)
36 |
37 | template struct is_fmt_numeric, detail::enable_if_t::value>> {
38 | static constexpr bool value = true;
39 | static constexpr int index = is_fmt_numeric::index + 3;
40 | };
41 |
42 | template class type_caster> {
43 | public:
44 | bool load(handle src, bool convert) {
45 | if (!src)
46 | return false;
47 | if (!convert && !PyComplex_Check(src.ptr()))
48 | return false;
49 | Py_complex result = PyComplex_AsCComplex(src.ptr());
50 | if (result.real == -1.0 && PyErr_Occurred()) {
51 | PyErr_Clear();
52 | return false;
53 | }
54 | value = std::complex((T) result.real, (T) result.imag);
55 | return true;
56 | }
57 |
58 | static handle cast(const std::complex &src, return_value_policy /* policy */, handle /* parent */) {
59 | return PyComplex_FromDoubles((double) src.real(), (double) src.imag());
60 | }
61 |
62 | PYBIND11_TYPE_CASTER(std::complex, _("complex"));
63 | };
64 | NAMESPACE_END(detail)
65 | NAMESPACE_END(PYBIND11_NAMESPACE)
66 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/tests.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.28307.168
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest", "3rd_party\googletest\gtest.vcxproj", "{064DCEC7-172B-4334-8DF4-75A4EC7C8DD8}"
7 | EndProject
8 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tests", "tests\tests\tests.vcxproj", "{BDE8B29F-8E69-4B91-9AEF-520FB6CA883A}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|x64 = Debug|x64
13 | Debug|x86 = Debug|x86
14 | Release|x64 = Release|x64
15 | Release|x86 = Release|x86
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {064DCEC7-172B-4334-8DF4-75A4EC7C8DD8}.Debug|x64.ActiveCfg = Debug|x64
19 | {064DCEC7-172B-4334-8DF4-75A4EC7C8DD8}.Debug|x64.Build.0 = Debug|x64
20 | {064DCEC7-172B-4334-8DF4-75A4EC7C8DD8}.Debug|x86.ActiveCfg = Debug|Win32
21 | {064DCEC7-172B-4334-8DF4-75A4EC7C8DD8}.Debug|x86.Build.0 = Debug|Win32
22 | {064DCEC7-172B-4334-8DF4-75A4EC7C8DD8}.Release|x64.ActiveCfg = Release|x64
23 | {064DCEC7-172B-4334-8DF4-75A4EC7C8DD8}.Release|x64.Build.0 = Release|x64
24 | {064DCEC7-172B-4334-8DF4-75A4EC7C8DD8}.Release|x86.ActiveCfg = Release|Win32
25 | {064DCEC7-172B-4334-8DF4-75A4EC7C8DD8}.Release|x86.Build.0 = Release|Win32
26 | {BDE8B29F-8E69-4B91-9AEF-520FB6CA883A}.Debug|x64.ActiveCfg = Debug|x64
27 | {BDE8B29F-8E69-4B91-9AEF-520FB6CA883A}.Debug|x64.Build.0 = Debug|x64
28 | {BDE8B29F-8E69-4B91-9AEF-520FB6CA883A}.Debug|x86.ActiveCfg = Debug|Win32
29 | {BDE8B29F-8E69-4B91-9AEF-520FB6CA883A}.Debug|x86.Build.0 = Debug|Win32
30 | {BDE8B29F-8E69-4B91-9AEF-520FB6CA883A}.Release|x64.ActiveCfg = Release|x64
31 | {BDE8B29F-8E69-4B91-9AEF-520FB6CA883A}.Release|x64.Build.0 = Release|x64
32 | {BDE8B29F-8E69-4B91-9AEF-520FB6CA883A}.Release|x86.ActiveCfg = Release|Win32
33 | {BDE8B29F-8E69-4B91-9AEF-520FB6CA883A}.Release|x86.Build.0 = Release|Win32
34 | EndGlobalSection
35 | GlobalSection(SolutionProperties) = preSolution
36 | HideSolutionNode = FALSE
37 | EndGlobalSection
38 | GlobalSection(ExtensibilityGlobals) = postSolution
39 | SolutionGuid = {BF779EA3-BC4C-49BE-9218-F292B16F85F5}
40 | EndGlobalSection
41 | EndGlobal
42 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/3rd_party/googletest/src/gtest_main.cc:
--------------------------------------------------------------------------------
1 | // Copyright 2006, Google Inc.
2 | // All rights reserved.
3 | //
4 | // Redistribution and use in source and binary forms, with or without
5 | // modification, are permitted provided that the following conditions are
6 | // met:
7 | //
8 | // * Redistributions of source code must retain the above copyright
9 | // notice, this list of conditions and the following disclaimer.
10 | // * Redistributions in binary form must reproduce the above
11 | // copyright notice, this list of conditions and the following disclaimer
12 | // in the documentation and/or other materials provided with the
13 | // distribution.
14 | // * Neither the name of Google Inc. nor the names of its
15 | // contributors may be used to endorse or promote products derived from
16 | // this software without specific prior written permission.
17 | //
18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 |
30 | #include
31 | #include "gtest/gtest.h"
32 |
33 | #ifdef ARDUINO
34 | void setup() {
35 | // Since Arduino doesn't have a command line, fake out the argc/argv arguments
36 | int argc = 1;
37 | const auto arg0 = "PlatformIO";
38 | char* argv0 = const_cast(arg0);
39 | char** argv = &argv0;
40 |
41 | testing::InitGoogleTest(&argc, argv);
42 | }
43 |
44 | void loop() { RUN_ALL_TESTS(); }
45 |
46 | #else
47 |
48 | GTEST_API_ int main(int argc, char **argv) {
49 | printf("Running main() from %s\n", __FILE__);
50 | testing::InitGoogleTest(&argc, argv);
51 | return RUN_ALL_TESTS();
52 | }
53 | #endif
54 |
--------------------------------------------------------------------------------
/cpp_api_binding/third_party/include/pybind11/options.h:
--------------------------------------------------------------------------------
1 | /*
2 | pybind11/options.h: global settings that are configurable at runtime.
3 |
4 | Copyright (c) 2016 Wenzel Jakob
5 |
6 | All rights reserved. Use of this source code is governed by a
7 | BSD-style license that can be found in the LICENSE file.
8 | */
9 |
10 | #pragma once
11 |
12 | #include "detail/common.h"
13 |
14 | NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
15 |
16 | class options {
17 | public:
18 |
19 | // Default RAII constructor, which leaves settings as they currently are.
20 | options() : previous_state(global_state()) {}
21 |
22 | // Class is non-copyable.
23 | options(const options&) = delete;
24 | options& operator=(const options&) = delete;
25 |
26 | // Destructor, which restores settings that were in effect before.
27 | ~options() {
28 | global_state() = previous_state;
29 | }
30 |
31 | // Setter methods (affect the global state):
32 |
33 | options& disable_user_defined_docstrings() & { global_state().show_user_defined_docstrings = false; return *this; }
34 |
35 | options& enable_user_defined_docstrings() & { global_state().show_user_defined_docstrings = true; return *this; }
36 |
37 | options& disable_function_signatures() & { global_state().show_function_signatures = false; return *this; }
38 |
39 | options& enable_function_signatures() & { global_state().show_function_signatures = true; return *this; }
40 |
41 | // Getter methods (return the global state):
42 |
43 | static bool show_user_defined_docstrings() { return global_state().show_user_defined_docstrings; }
44 |
45 | static bool show_function_signatures() { return global_state().show_function_signatures; }
46 |
47 | // This type is not meant to be allocated on the heap.
48 | void* operator new(size_t) = delete;
49 |
50 | private:
51 |
52 | struct state {
53 | bool show_user_defined_docstrings = true; //< Include user-supplied texts in docstrings.
54 | bool show_function_signatures = true; //< Include auto-generated function signatures in docstrings.
55 | };
56 |
57 | static state &global_state() {
58 | static state instance;
59 | return instance;
60 | }
61 |
62 | state previous_state;
63 | };
64 |
65 | NAMESPACE_END(PYBIND11_NAMESPACE)
66 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/3rd_party/googletest/gtest-all.cc:
--------------------------------------------------------------------------------
1 | // Copyright 2008, Google Inc.
2 | // All rights reserved.
3 | //
4 | // Redistribution and use in source and binary forms, with or without
5 | // modification, are permitted provided that the following conditions are
6 | // met:
7 | //
8 | // * Redistributions of source code must retain the above copyright
9 | // notice, this list of conditions and the following disclaimer.
10 | // * Redistributions in binary form must reproduce the above
11 | // copyright notice, this list of conditions and the following disclaimer
12 | // in the documentation and/or other materials provided with the
13 | // distribution.
14 | // * Neither the name of Google Inc. nor the names of its
15 | // contributors may be used to endorse or promote products derived from
16 | // this software without specific prior written permission.
17 | //
18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 |
30 | //
31 | // Google C++ Testing and Mocking Framework (Google Test)
32 | //
33 | // Sometimes it's desirable to build Google Test by compiling a single file.
34 | // This file serves this purpose.
35 |
36 | // This line ensures that gtest.h can be compiled on its own, even
37 | // when it's fused.
38 | #include "gtest/gtest.h"
39 |
40 | // The following lines pull in the real gtest *.cc files.
41 | #include "src/gtest.cc"
42 | #include "src/gtest-death-test.cc"
43 | #include "src/gtest-filepath.cc"
44 | #include "src/gtest-matchers.cc"
45 | #include "src/gtest-port.cc"
46 | #include "src/gtest-printers.cc"
47 | #include "src/gtest-test-part.cc"
48 | #include "src/gtest-typed-test.cc"
49 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/3rd_party/include/gtest/gtest_prod.h:
--------------------------------------------------------------------------------
1 | // Copyright 2006, Google Inc.
2 | // All rights reserved.
3 | //
4 | // Redistribution and use in source and binary forms, with or without
5 | // modification, are permitted provided that the following conditions are
6 | // met:
7 | //
8 | // * Redistributions of source code must retain the above copyright
9 | // notice, this list of conditions and the following disclaimer.
10 | // * Redistributions in binary form must reproduce the above
11 | // copyright notice, this list of conditions and the following disclaimer
12 | // in the documentation and/or other materials provided with the
13 | // distribution.
14 | // * Neither the name of Google Inc. nor the names of its
15 | // contributors may be used to endorse or promote products derived from
16 | // this software without specific prior written permission.
17 | //
18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 |
30 | //
31 | // Google C++ Testing and Mocking Framework definitions useful in production code.
32 | // GOOGLETEST_CM0003 DO NOT DELETE
33 |
34 | #ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_
35 | #define GTEST_INCLUDE_GTEST_GTEST_PROD_H_
36 |
37 | // When you need to test the private or protected members of a class,
38 | // use the FRIEND_TEST macro to declare your tests as friends of the
39 | // class. For example:
40 | //
41 | // class MyClass {
42 | // private:
43 | // void PrivateMethod();
44 | // FRIEND_TEST(MyClassTest, PrivateMethodWorks);
45 | // };
46 | //
47 | // class MyClassTest : public testing::Test {
48 | // // ...
49 | // };
50 | //
51 | // TEST_F(MyClassTest, PrivateMethodWorks) {
52 | // // Can call MyClass::PrivateMethod() here.
53 | // }
54 | //
55 | // Note: The test class must be in the same namespace as the class being tested.
56 | // For example, putting MyClassTest in an anonymous namespace will not work.
57 |
58 | #define FRIEND_TEST(test_case_name, test_name)\
59 | friend class test_case_name##_##test_name##_Test
60 |
61 | #endif // GTEST_INCLUDE_GTEST_GTEST_PROD_H_
62 |
--------------------------------------------------------------------------------
/cpp_api_binding/source/ctp/dispatcher.hpp:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 |
10 | namespace autocxxpy
11 | {
12 | class dispatcher
13 | {
14 | public:
15 | using task_type = std::function;
16 | using task_list_type = std::vector;
17 | public:
18 | inline void add(const task_type &f)
19 | {
20 | {
21 | std::lock_guard l(_m);
22 | _ts.push_back(f);
23 | }
24 | this->_notify_one();
25 | }
26 | void start()
27 | {
28 | _run = true;
29 | _thread = std::thread(&dispatcher::_loop, this);
30 | }
31 | void stop()
32 | {
33 | _run = false;
34 | }
35 | void join()
36 | {
37 | assert(!this->_run);
38 | this->_notify_one();
39 | _thread.join();
40 | }
41 | public:
42 | inline static dispatcher &instance()
43 | {
44 | static dispatcher *_instance = nullptr;
45 | if (_instance != nullptr)
46 | return *_instance;
47 |
48 | static std::mutex m;
49 | std::lock_guard l(m);
50 | if (_instance == nullptr)
51 | _instance = new dispatcher;
52 | return *_instance;
53 | }
54 | protected:
55 | void _loop()
56 | {
57 | while (_run)
58 | {
59 | task_list_type ts;
60 | {
61 | auto l = _wait_and_lock();
62 | ts = this->_ts;
63 | _ts.clear();
64 | l.unlock();
65 | }
66 | _process_all(ts);
67 | }
68 | }
69 |
70 | inline void _process_all(const task_list_type &ts)
71 | {
72 | for (const auto &task : ts)
73 | {
74 | task();
75 | }
76 | }
77 |
78 | inline void _notify_one()
79 | {
80 | return _cv.notify_one();
81 | }
82 |
83 | inline std::unique_lock _wait_and_lock()
84 | {
85 | std::unique_lock l(_m);
86 | _cv.wait(l, [this]()
87 | {
88 | return !_run || _ts.size();
89 | });
90 | return std::move(l);
91 | }
92 |
93 | protected:
94 | volatile bool _run = false;
95 | std::thread _thread;
96 | std::mutex _m;
97 | std::condition_variable _cv;
98 | task_list_type _ts;
99 | };
100 | }
101 |
102 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/templates/dispatcher.hpp:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 |
10 | namespace autocxxpy
11 | {
12 | class dispatcher
13 | {
14 | public:
15 | using task_type = std::function;
16 | using task_list_type = std::vector;
17 | public:
18 | inline void add(const task_type &f)
19 | {
20 | {
21 | std::lock_guard l(_m);
22 | _ts.push_back(f);
23 | }
24 | this->_notify_one();
25 | }
26 | void start()
27 | {
28 | _run = true;
29 | _thread = std::thread(&dispatcher::_loop, this);
30 | }
31 | void stop()
32 | {
33 | _run = false;
34 | }
35 | void join()
36 | {
37 | assert(!this->_run);
38 | this->_notify_one();
39 | _thread.join();
40 | }
41 | public:
42 | inline static dispatcher &instance()
43 | {
44 | static dispatcher *_instance = nullptr;
45 | if (_instance != nullptr)
46 | return *_instance;
47 |
48 | static std::mutex m;
49 | std::lock_guard l(m);
50 | if (_instance == nullptr)
51 | _instance = new dispatcher;
52 | return *_instance;
53 | }
54 | protected:
55 | void _loop()
56 | {
57 | while (_run)
58 | {
59 | task_list_type ts;
60 | {
61 | auto l = _wait_and_lock();
62 | ts = this->_ts;
63 | _ts.clear();
64 | l.unlock();
65 | }
66 | _process_all(ts);
67 | }
68 | }
69 |
70 | inline void _process_all(const task_list_type &ts)
71 | {
72 | for (const auto &task : ts)
73 | {
74 | task();
75 | }
76 | }
77 |
78 | inline void _notify_one()
79 | {
80 | return _cv.notify_one();
81 | }
82 |
83 | inline std::unique_lock _wait_and_lock()
84 | {
85 | std::unique_lock l(_m);
86 | _cv.wait(l, [this]()
87 | {
88 | return !_run || _ts.size();
89 | });
90 | return std::move(l);
91 | }
92 |
93 | protected:
94 | volatile bool _run = false;
95 | std::thread _thread;
96 | std::mutex _m;
97 | std::condition_variable _cv;
98 | task_list_type _ts;
99 | };
100 | }
101 |
102 |
--------------------------------------------------------------------------------
/candle_chart/base/base.py:
--------------------------------------------------------------------------------
1 | from dataclasses import dataclass
2 | from enum import Enum
3 | from typing import Optional, TYPE_CHECKING, TypeVar, Union
4 |
5 | from PyQt5.QtCore import QPointF, QRectF
6 | from PyQt5.QtGui import QColor, QTransform
7 |
8 | if TYPE_CHECKING:
9 | pass
10 |
11 | T = TypeVar("T")
12 |
13 | ColorType = Union[
14 | str, # "red", "#RGB", "#RRGGBB", "#AARRGGBB", "#RRRGGGBBB", "#RRRRGGGGBBBB"
15 | int, # Qt.GlobalColor
16 | QColor, # QtCore.QColor
17 | None, # Don't draw
18 | ]
19 |
20 |
21 | class Orientation(Enum):
22 | HORIZONTAL = 1
23 | VERTICAL = 2
24 |
25 |
26 | class Alignment(Enum):
27 | BEFORE = 0
28 | MID = 1
29 | AFTER = 2
30 |
31 |
32 | @dataclass()
33 | class DrawingCache:
34 | # intermediate variables to speed up calculation
35 | drawer_transform: Optional["QTransform"] = None # 坐标转化矩阵(UI->drawer)
36 | ui_transform: Optional[QTransform] = None # 坐标转化矩阵(drawer->UI)
37 | drawer_area: Optional["QRectF"] = None # drawer坐标的世界大小
38 | drawer_area_width: Optional["float"] = None
39 | # self.drawer_area_height: Optional['float'] = None
40 | plot_area: Optional[QRectF] = None # UI坐标中属于绘制区域的部分
41 | # self.plot_area_width: Optional['float'] = None
42 | # self.plot_area_height: Optional['float'] = None
43 | p2d_w: Optional[float] = None # drawer_area.width / plot_area.width
44 | p2d_h: Optional[float] = None # drawer_area.height / plot_area.height
45 |
46 | def drawer_to_ui(self, value: T) -> T:
47 | """
48 | 将drawer坐标系中的值(点或者矩形)转化为UI坐标系
49 | """
50 | return self.drawer_transform.map(value)
51 |
52 | def drawer_x_to_ui(self, value: float) -> float:
53 | """
54 | 将drawer坐标系中的x值转化为UI坐标系中的x值
55 | """
56 | return self.drawer_transform.map(QPointF(value, value)).x()
57 |
58 | def drawer_y_to_ui(self, value: float) -> float:
59 | """
60 | 将drawer坐标系中的y值转化为UI坐标系中的y值
61 | """
62 | return self.drawer_transform.map(QPointF(value, value)).y()
63 |
64 | def ui_width_to_drawer(self, value: float) -> float:
65 | return value * self.p2d_w
66 |
67 | def ui_height_to_drawer(self, value: float) -> float:
68 | return value * self.p2d_h
69 |
70 | def ui_to_drawer(self, value: T) -> T:
71 | return self.ui_transform.map(value)
72 |
73 | def ui_x_to_drawer(self, value: float) -> float:
74 | return self.ui_transform.map(QPointF(value, value)).x()
75 |
76 | def ui_y_to_drawer(self, value: float) -> float:
77 | return self.ui_transform.map(QPointF(value, value)).y()
78 |
79 |
80 | @dataclass()
81 | class DrawConfig:
82 | begin: int = 0 # 第一个绘制的元素
83 | end: int = 0 # 最后一个绘制的元素+1:也就是说绘制元素的范围为[begin, end)
84 | y_low: float = 0 # 图表顶端所代表的y值
85 | y_high: float = 1 # 图表底端所代表的y值
86 |
87 | drawing_cache: Optional["DrawingCache"] = None
88 |
--------------------------------------------------------------------------------
/async_io/asyncio/async_executor.py:
--------------------------------------------------------------------------------
1 | """
2 | support for asyncio
3 | If you use this module, call async_executor.start() at startup.
4 | and call async_executor.stop() at cleanup.
5 | call async_executor.join() if you want to wait until it exit.
6 | """
7 | import asyncio
8 | import threading
9 | from typing import Coroutine, Iterable, Union
10 |
11 |
12 | class AsyncExecutor:
13 |
14 | def __init__(self):
15 | self.loop = asyncio.new_event_loop()
16 | self._thread = threading.Thread(target=self._exec)
17 |
18 | def start(self):
19 | self._thread.start()
20 |
21 | def stop(self):
22 | self.loop.stop()
23 |
24 | def join(self):
25 | self._thread.join()
26 |
27 | def _exec(self):
28 | self.loop.call_soon(lambda: None)
29 | self.loop.run_forever()
30 |
31 |
32 | class SyncWrapper:
33 | wrapper_loop = asyncio.new_event_loop()
34 |
35 | def __init__(self, co: Coroutine):
36 | self.co = co
37 | self.result = None
38 |
39 | def __call__(self, *args, **kwargs):
40 | if self.result is None:
41 | try:
42 | if loop is asyncio.get_running_loop():
43 | # fucking shit
44 | self.schedule_new_coroutine()
45 | else:
46 | self.schedule_coroutine()
47 | except RuntimeError:
48 | self.schedule_coroutine()
49 | return self.result
50 |
51 | def schedule_coroutine(self):
52 | task = asyncio.run_coroutine_threadsafe(self.co, loop=loop)
53 | self.result = task.result()
54 |
55 | def schedule_new_coroutine(self):
56 | thread = threading.Thread(target=self.run)
57 | thread.start()
58 | thread.join()
59 |
60 | def run(self):
61 | self.result = self.wrapper_loop.run_until_complete(self.co)
62 |
63 |
64 | def wrap_as_sync(co: Coroutine):
65 | """
66 | run a coroutine in ANY context, and return its result.
67 | """
68 | return SyncWrapper(co)
69 |
70 |
71 | def create_async_task(co: Coroutine):
72 | """
73 | start a coroutine asynchronously in ANY context, ignoring its result.
74 | """
75 | return loop.create_task(co)
76 |
77 |
78 | def wait_for_async_task(task: asyncio.Task):
79 | return wrap_as_sync(asyncio.wait([task], loop=loop))()
80 |
81 |
82 | def start_asyncio():
83 | global ref_count
84 | with ref_count_lock:
85 | if ref_count == 0:
86 | async_executor.start()
87 | ref_count = ref_count + 1
88 |
89 |
90 | def stop_asyncio():
91 | global ref_count
92 | with ref_count_lock:
93 | ref_count = ref_count - 1
94 | if ref_count == 0:
95 | async_executor.stop()
96 |
97 |
98 | def join_asyncio():
99 | async_executor.join()
100 |
101 | ref_count = 0
102 | ref_count_lock = threading.Lock()
103 | async_executor: "AsyncExecutor" = AsyncExecutor()
104 | loop = async_executor.loop
105 |
--------------------------------------------------------------------------------
/cpp_api_binding/third_party/include/pybind11/functional.h:
--------------------------------------------------------------------------------
1 | /*
2 | pybind11/functional.h: std::function<> support
3 |
4 | Copyright (c) 2016 Wenzel Jakob
5 |
6 | All rights reserved. Use of this source code is governed by a
7 | BSD-style license that can be found in the LICENSE file.
8 | */
9 |
10 | #pragma once
11 |
12 | #include "pybind11.h"
13 | #include
14 |
15 | NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
16 | NAMESPACE_BEGIN(detail)
17 |
18 | template
19 | struct type_caster> {
20 | using type = std::function;
21 | using retval_type = conditional_t::value, void_type, Return>;
22 | using function_type = Return (*) (Args...);
23 |
24 | public:
25 | bool load(handle src, bool convert) {
26 | if (src.is_none()) {
27 | // Defer accepting None to other overloads (if we aren't in convert mode):
28 | if (!convert) return false;
29 | return true;
30 | }
31 |
32 | if (!isinstance(src))
33 | return false;
34 |
35 | auto func = reinterpret_borrow(src);
36 |
37 | /*
38 | When passing a C++ function as an argument to another C++
39 | function via Python, every function call would normally involve
40 | a full C++ -> Python -> C++ roundtrip, which can be prohibitive.
41 | Here, we try to at least detect the case where the function is
42 | stateless (i.e. function pointer or lambda function without
43 | captured variables), in which case the roundtrip can be avoided.
44 | */
45 | if (auto cfunc = func.cpp_function()) {
46 | auto c = reinterpret_borrow(PyCFunction_GET_SELF(cfunc.ptr()));
47 | auto rec = (function_record *) c;
48 |
49 | if (rec && rec->is_stateless &&
50 | same_type(typeid(function_type), *reinterpret_cast(rec->data[1]))) {
51 | struct capture { function_type f; };
52 | value = ((capture *) &rec->data)->f;
53 | return true;
54 | }
55 | }
56 |
57 | value = [func](Args... args) -> Return {
58 | gil_scoped_acquire acq;
59 | object retval(func(std::forward(args)...));
60 | /* Visual studio 2015 parser issue: need parentheses around this expression */
61 | return (retval.template cast());
62 | };
63 | return true;
64 | }
65 |
66 | template
67 | static handle cast(Func &&f_, return_value_policy policy, handle /* parent */) {
68 | if (!f_)
69 | return none().inc_ref();
70 |
71 | auto result = f_.template target();
72 | if (result)
73 | return cpp_function(*result, policy).release();
74 | else
75 | return cpp_function(std::forward(f_), policy).release();
76 | }
77 |
78 | PYBIND11_TYPE_CASTER(type, _("Callable[[") + concat(make_caster::name...) + _("], ")
79 | + make_caster::name + _("]"));
80 | };
81 |
82 | NAMESPACE_END(detail)
83 | NAMESPACE_END(PYBIND11_NAMESPACE)
84 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/autocxxpy/textholder.py:
--------------------------------------------------------------------------------
1 | # encoding: utf-8
2 | from typing import Optional, Union
3 |
4 |
5 | class Indent:
6 | class IdentStart:
7 | def __init__(self, text):
8 | self.text = text
9 |
10 | class IdentEnd:
11 | def __init__(self, text):
12 | self.text = text
13 |
14 | class IdentEndLater:
15 | def __init__(self, text):
16 | self.text = text
17 |
18 | def __init__(self, text: Optional[Union[str, "TextHolder"]] = None):
19 | self.text = text
20 |
21 | def __add__(self, other: str):
22 | assert self.text is None
23 | return Indent(other)
24 |
25 | def __radd__(self, other: str):
26 | assert self.text is None
27 | return Indent.IdentStart(other)
28 |
29 | def __rsub__(self, other: str):
30 | assert self.text is None
31 | return Indent.IdentEnd(other)
32 |
33 |
34 | class IndentLater:
35 | def __rsub__(self, other: str):
36 | return Indent.IdentEndLater(other)
37 |
38 |
39 | class TextHolder:
40 | def __init__(self, text: Optional[str] = None):
41 | super().__init__()
42 | if text is None:
43 | text = ""
44 | self.text = text
45 | self.ident_text = " "
46 | self._ident = 0
47 |
48 | def __add__(self, other: Union[str, int]):
49 | if isinstance(other, Indent.IdentStart):
50 | self.append(other.text)
51 | self.ident(1)
52 | elif isinstance(other, Indent.IdentEnd):
53 | self.ident(-1)
54 | self.append(other.text)
55 | elif isinstance(other, Indent.IdentEndLater):
56 | self.append(other.text)
57 | self.ident(-1)
58 | elif isinstance(other, Indent):
59 | self.append(
60 | TextHolder(str(other.text)).ident_all(
61 | n=self._ident + 1, ident_text=self.ident_text
62 | ),
63 | add_ident=False,
64 | )
65 | elif isinstance(other, str):
66 | self.append(other)
67 | elif isinstance(other, TextHolder):
68 | self.append(
69 | TextHolder(str(other.text)).ident_all(
70 | n=self._ident, ident_text=self.ident_text
71 | ),
72 | add_ident=False,
73 | )
74 | elif isinstance(other, int):
75 | self.ident(other)
76 | else:
77 | raise TypeError(f"can only add str or int, but {type(other)} got")
78 | return self
79 |
80 | def __sub__(self, other):
81 | if isinstance(other, int):
82 | self.ident(-other)
83 | else:
84 | raise TypeError(f"can only add str or int, but {type(other)} got")
85 | return self
86 |
87 | def __bool__(self):
88 | return bool(self.text)
89 |
90 | def __str__(self):
91 | return self.text
92 |
93 | def append(
94 | self,
95 | text: Union[str, "TextHolder"],
96 | ensure_new_line=True,
97 | ignore_empty=True,
98 | add_ident=True,
99 | ):
100 | strtext = str(text)
101 | if ignore_empty and not strtext:
102 | return self
103 | if not strtext.endswith("\n") and ensure_new_line:
104 | strtext += "\n"
105 | if add_ident:
106 | self.text += self._ident * self.ident_text + strtext
107 | else:
108 | self.text += strtext
109 | return self
110 |
111 | def ident_all(self, n: int = 1, ident_text: str = None):
112 | if ident_text is None:
113 | ident_text = self.ident_text
114 | text = self.text
115 | if text.endswith("\n"):
116 | text = text[:-1]
117 | return "\n".join([ident_text * n + i for i in text.split("\n")])
118 |
119 | def ident(self, n: int = 1):
120 | self._ident += n
121 | return self
122 |
--------------------------------------------------------------------------------
/cpp_api_binding/third_party/include/pybind11/detail/descr.h:
--------------------------------------------------------------------------------
1 | /*
2 | pybind11/detail/descr.h: Helper type for concatenating type signatures at compile time
3 |
4 | Copyright (c) 2016 Wenzel Jakob
5 |
6 | All rights reserved. Use of this source code is governed by a
7 | BSD-style license that can be found in the LICENSE file.
8 | */
9 |
10 | #pragma once
11 |
12 | #include "common.h"
13 |
14 | NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
15 | NAMESPACE_BEGIN(detail)
16 |
17 | #if !defined(_MSC_VER)
18 | # define PYBIND11_DESCR_CONSTEXPR static constexpr
19 | #else
20 | # define PYBIND11_DESCR_CONSTEXPR const
21 | #endif
22 |
23 | /* Concatenate type signatures at compile time */
24 | template
25 | struct descr {
26 | char text[N + 1];
27 |
28 | constexpr descr() : text{'\0'} { }
29 | constexpr descr(char const (&s)[N+1]) : descr(s, make_index_sequence()) { }
30 |
31 | template
32 | constexpr descr(char const (&s)[N+1], index_sequence) : text{s[Is]..., '\0'} { }
33 |
34 | template
35 | constexpr descr(char c, Chars... cs) : text{c, static_cast(cs)..., '\0'} { }
36 |
37 | static constexpr std::array types() {
38 | return {{&typeid(Ts)..., nullptr}};
39 | }
40 | };
41 |
42 | template
43 | constexpr descr plus_impl(const descr &a, const descr &b,
44 | index_sequence, index_sequence) {
45 | return {a.text[Is1]..., b.text[Is2]...};
46 | }
47 |
48 | template
49 | constexpr descr operator+(const descr &a, const descr &b) {
50 | return plus_impl(a, b, make_index_sequence(), make_index_sequence());
51 | }
52 |
53 | template
54 | constexpr descr _(char const(&text)[N]) { return descr(text); }
55 | constexpr descr<0> _(char const(&)[1]) { return {}; }
56 |
57 | template struct int_to_str : int_to_str { };
58 | template struct int_to_str<0, Digits...> {
59 | static constexpr auto digits = descr(('0' + Digits)...);
60 | };
61 |
62 | // Ternary description (like std::conditional)
63 | template
64 | constexpr enable_if_t> _(char const(&text1)[N1], char const(&)[N2]) {
65 | return _(text1);
66 | }
67 | template
68 | constexpr enable_if_t> _(char const(&)[N1], char const(&text2)[N2]) {
69 | return _(text2);
70 | }
71 |
72 | template
73 | constexpr enable_if_t _(const T1 &d, const T2 &) { return d; }
74 | template
75 | constexpr enable_if_t _(const T1 &, const T2 &d) { return d; }
76 |
77 | template auto constexpr _() -> decltype(int_to_str::digits) {
78 | return int_to_str::digits;
79 | }
80 |
81 | template constexpr descr<1, Type> _() { return {'%'}; }
82 |
83 | constexpr descr<0> concat() { return {}; }
84 |
85 | template
86 | constexpr descr concat(const descr &descr) { return descr; }
87 |
88 | template
89 | constexpr auto concat(const descr &d, const Args &...args)
90 | -> decltype(std::declval>() + concat(args...)) {
91 | return d + _(", ") + concat(args...);
92 | }
93 |
94 | template
95 | constexpr descr type_descr(const descr &descr) {
96 | return _("{") + descr + _("}");
97 | }
98 |
99 | NAMESPACE_END(detail)
100 | NAMESPACE_END(PYBIND11_NAMESPACE)
101 |
--------------------------------------------------------------------------------
/candle_chart/candle.py:
--------------------------------------------------------------------------------
1 | from typing import Sequence
2 |
3 | from vnpy.chart.base import (AdvancedChartWidget, CandleAxisX, CandleChartDrawer, CandleDataSource,
4 | ChartWidget, HistogramDrawer, ValueAxisY)
5 | from vnpy.chart.base.advanced_chart import CrossHairBarAxisX, SubChartWrapper
6 | from vnpy.chart.base.data_source import HistogramDataSource
7 | from vnpy.trader.object import BarData
8 |
9 |
10 | class CandleChart(AdvancedChartWidget):
11 | """"""
12 |
13 | def __init__(self, parent=None):
14 | """"""
15 | super().__init__(parent)
16 | self.__init_ui()
17 |
18 | def __init_ui(self):
19 | # main chart: candle chart
20 | candle_ds = CandleDataSource()
21 | candle_drawer = CandleChartDrawer(candle_ds)
22 | candle_chart = ChartWidget(self)
23 | candle_chart.add_drawer(candle_drawer)
24 | candle_chart.add_axis(CandleAxisX(candle_ds), ValueAxisY())
25 | candle_chart.clip_plot_area = False # disabling clip makes it runs a bit faster
26 |
27 | # volume chart: His
28 | volume_ds = HistogramDataSource()
29 | volume_drawer = HistogramDrawer(volume_ds)
30 | volume_chart = ChartWidget(self)
31 | volume_chart.add_drawer(volume_drawer)
32 | volume_chart.add_axis(CandleAxisX(candle_ds), ValueAxisY())
33 |
34 | candle_wrapper = self.add_chart(candle_chart, 4)
35 | volume_wrapper = self.add_chart(volume_chart, 1)
36 |
37 | # create cross hair
38 | candle_wrapper.create_cross_hair_y()
39 | candle_wrapper.set_cross_hair_x(CrossHairBarAxisX(candle_chart.all_axis_x[0]))
40 | volume_wrapper.create_cross_hair_y()
41 | volume_wrapper.set_cross_hair_x(CrossHairBarAxisX(volume_chart.all_axis_x[0]))
42 |
43 | # link vertical line of cross hair
44 | candle_wrapper.link_x_to(volume_wrapper)
45 | volume_wrapper.link_x_to(candle_wrapper)
46 |
47 | self.candle_ds: "CandleDataSource" = candle_ds
48 | self.volume_ds: "HistogramDataSource" = volume_ds
49 | self.candle_chart: "SubChartWrapper" = candle_wrapper
50 | self.volume_chart: "SubChartWrapper" = volume_wrapper
51 | self.setMouseTracking(True)
52 |
53 | def update_bar(self, bar: BarData):
54 | """
55 | Update one bar data into the chart.
56 |
57 | The bar data may be a new one or an existing one.
58 | """
59 | self.candle_ds.append(bar)
60 | self.volume_ds.append(bar.volume)
61 | begin, end = self.get_x_range()
62 | self.set_x_range(begin, end + 1)
63 |
64 | def update_bars(self, bars: Sequence[BarData]):
65 | """
66 | Update a list of bar data into the chart.
67 | """
68 | self.candle_ds.extend(bars)
69 | self.volume_ds.extend([i.volume for i in bars])
70 | begin, end = self.get_x_range()
71 | self.set_x_range(begin, end + len(bars))
72 | pass
73 |
74 | def clear(self):
75 | """
76 | Clear all data displayed in the chart.
77 | """
78 | self.candle_ds.clear()
79 | self.volume_ds.clear()
80 | pass
81 |
82 | def set_volume_visible(self, visible: bool):
83 | """
84 | Set if the volume data visible on the chart.
85 | """
86 | self.volume_chart.set_chart_visible(visible)
87 |
88 | def set_cursor_visible(self, visible: bool):
89 | """
90 | Set if the cross cursor visible on the chart.
91 | """
92 | self.candle_chart.set_crosshair_visible(visible)
93 | self.volume_chart.set_crosshair_visible(visible)
94 |
95 | def to_left_end(self):
96 | """
97 | Scroll chart to the left end.
98 | """
99 | begin, end = self.get_x_range()
100 | new_end = len(self.candle_ds)
101 | self.scroll_x(new_end - end)
102 |
103 | def to_right_end(self):
104 | """
105 | Scroll chart to the right end.
106 | """
107 | begin, end = self.get_x_range()
108 | self.scroll_x(0 - begin)
109 |
--------------------------------------------------------------------------------
/cpp_api_binding/generator/3rd_party/include/gtest/internal/gtest-port-arch.h:
--------------------------------------------------------------------------------
1 | // Copyright 2015, Google Inc.
2 | // All rights reserved.
3 | //
4 | // Redistribution and use in source and binary forms, with or without
5 | // modification, are permitted provided that the following conditions are
6 | // met:
7 | //
8 | // * Redistributions of source code must retain the above copyright
9 | // notice, this list of conditions and the following disclaimer.
10 | // * Redistributions in binary form must reproduce the above
11 | // copyright notice, this list of conditions and the following disclaimer
12 | // in the documentation and/or other materials provided with the
13 | // distribution.
14 | // * Neither the name of Google Inc. nor the names of its
15 | // contributors may be used to endorse or promote products derived from
16 | // this software without specific prior written permission.
17 | //
18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 | //
30 | // The Google C++ Testing and Mocking Framework (Google Test)
31 | //
32 | // This header file defines the GTEST_OS_* macro.
33 | // It is separate from gtest-port.h so that custom/gtest-port.h can include it.
34 |
35 | #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
36 | #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
37 |
38 | // Determines the platform on which Google Test is compiled.
39 | #ifdef __CYGWIN__
40 | # define GTEST_OS_CYGWIN 1
41 | # elif defined(__MINGW__) || defined(__MINGW32__) || defined(__MINGW64__)
42 | # define GTEST_OS_WINDOWS_MINGW 1
43 | # define GTEST_OS_WINDOWS 1
44 | #elif defined _WIN32
45 | # define GTEST_OS_WINDOWS 1
46 | # ifdef _WIN32_WCE
47 | # define GTEST_OS_WINDOWS_MOBILE 1
48 | # elif defined(WINAPI_FAMILY)
49 | # include
50 | # if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
51 | # define GTEST_OS_WINDOWS_DESKTOP 1
52 | # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
53 | # define GTEST_OS_WINDOWS_PHONE 1
54 | # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
55 | # define GTEST_OS_WINDOWS_RT 1
56 | # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE)
57 | # define GTEST_OS_WINDOWS_PHONE 1
58 | # define GTEST_OS_WINDOWS_TV_TITLE 1
59 | # else
60 | // WINAPI_FAMILY defined but no known partition matched.
61 | // Default to desktop.
62 | # define GTEST_OS_WINDOWS_DESKTOP 1
63 | # endif
64 | # else
65 | # define GTEST_OS_WINDOWS_DESKTOP 1
66 | # endif // _WIN32_WCE
67 | #elif defined __OS2__
68 | # define GTEST_OS_OS2 1
69 | #elif defined __APPLE__
70 | # define GTEST_OS_MAC 1
71 | # if TARGET_OS_IPHONE
72 | # define GTEST_OS_IOS 1
73 | # endif
74 | #elif defined __FreeBSD__
75 | # define GTEST_OS_FREEBSD 1
76 | #elif defined __Fuchsia__
77 | # define GTEST_OS_FUCHSIA 1
78 | #elif defined __linux__
79 | # define GTEST_OS_LINUX 1
80 | # if defined __ANDROID__
81 | # define GTEST_OS_LINUX_ANDROID 1
82 | # endif
83 | #elif defined __MVS__
84 | # define GTEST_OS_ZOS 1
85 | #elif defined(__sun) && defined(__SVR4)
86 | # define GTEST_OS_SOLARIS 1
87 | #elif defined(_AIX)
88 | # define GTEST_OS_AIX 1
89 | #elif defined(__hpux)
90 | # define GTEST_OS_HPUX 1
91 | #elif defined __native_client__
92 | # define GTEST_OS_NACL 1
93 | #elif defined __NetBSD__
94 | # define GTEST_OS_NETBSD 1
95 | #elif defined __OpenBSD__
96 | # define GTEST_OS_OPENBSD 1
97 | #elif defined __QNX__
98 | # define GTEST_OS_QNX 1
99 | #endif // __CYGWIN__
100 |
101 | #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
102 |
--------------------------------------------------------------------------------
/cpp_api_binding/third_party/include/pybind11/eval.h:
--------------------------------------------------------------------------------
1 | /*
2 | pybind11/exec.h: Support for evaluating Python expressions and statements
3 | from strings and files
4 |
5 | Copyright (c) 2016 Klemens Morgenstern and
6 | Wenzel Jakob
7 |
8 | All rights reserved. Use of this source code is governed by a
9 | BSD-style license that can be found in the LICENSE file.
10 | */
11 |
12 | #pragma once
13 |
14 | #include "pybind11.h"
15 |
16 | NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
17 |
18 | enum eval_mode {
19 | /// Evaluate a string containing an isolated expression
20 | eval_expr,
21 |
22 | /// Evaluate a string containing a single statement. Returns \c none
23 | eval_single_statement,
24 |
25 | /// Evaluate a string containing a sequence of statement. Returns \c none
26 | eval_statements
27 | };
28 |
29 | template
30 | object eval(str expr, object global = globals(), object local = object()) {
31 | if (!local)
32 | local = global;
33 |
34 | /* PyRun_String does not accept a PyObject / encoding specifier,
35 | this seems to be the only alternative */
36 | std::string buffer = "# -*- coding: utf-8 -*-\n" + (std::string) expr;
37 |
38 | int start;
39 | switch (mode) {
40 | case eval_expr: start = Py_eval_input; break;
41 | case eval_single_statement: start = Py_single_input; break;
42 | case eval_statements: start = Py_file_input; break;
43 | default: pybind11_fail("invalid evaluation mode");
44 | }
45 |
46 | PyObject *result = PyRun_String(buffer.c_str(), start, global.ptr(), local.ptr());
47 | if (!result)
48 | throw error_already_set();
49 | return reinterpret_steal