├── easyfut ├── __init__.py ├── web │ ├── __init__.py │ ├── handlers │ │ ├── __init__.py │ │ ├── position.py │ │ ├── account.py │ │ ├── quote.py │ │ ├── ticks.py │ │ ├── klines.py │ │ ├── base.py │ │ └── order.py │ ├── response.py │ └── routes.py ├── conf │ ├── __init__.py │ └── easyfut-template.conf ├── main.py ├── tests │ └── test.py └── server.py ├── MANIFEST.in ├── setup.py ├── README.md ├── .gitignore └── LICENSE /easyfut/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /easyfut/web/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /easyfut/conf/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /easyfut/web/handlers/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include easyfut/conf/*.conf -------------------------------------------------------------------------------- /easyfut/web/handlers/position.py: -------------------------------------------------------------------------------- 1 | from easyfut.web.handlers.base import BaseHandler 2 | 3 | # 获取仓位相关 4 | class PositionHandler(BaseHandler): 5 | def get(self): 6 | self.suc(self.share_dict['position']) -------------------------------------------------------------------------------- /easyfut/web/handlers/account.py: -------------------------------------------------------------------------------- 1 | from easyfut.web.handlers.base import BaseHandler 2 | 3 | 4 | # 获取账户相关 5 | class AccountHandler(BaseHandler): 6 | def get(self): 7 | self.suc(self.share_dict['account']) -------------------------------------------------------------------------------- /easyfut/conf/easyfut-template.conf: -------------------------------------------------------------------------------- 1 | [webserver] 2 | ;必填,监听地址,建议127.0.0.1,不可把服务暴露在公网(安全性考虑) 3 | host = 127.0.0.1 4 | ;必填,监听端口 5 | port = 8888 6 | 7 | [tqsdk] 8 | ;必填,当前环境,模拟:test 实盘:prod , 实盘需要设置对应的broker_id,account_id,account_password 9 | env = test 10 | ;必填,信易账户 11 | username = 12 | ;必填,信易密码 13 | password = 14 | ;选填,期货公司,支持的期货公司列表 https://www.shinnytech.com/blog/tq-support-broker/,举例:H海通期货 15 | broker_id = 16 | ;选填,期货公司帐号 17 | account_id = 18 | ;选填,期货公司密码 19 | account_password = 20 | ;选填,用于指定账户连接的交易服务器地址,一般不填 21 | td_url = -------------------------------------------------------------------------------- /easyfut/web/response.py: -------------------------------------------------------------------------------- 1 | 2 | rcodes = { 3 | 'suc' : {'code': 10000, 'msg': '操作成功!'}, 4 | 'tq_error' : {'code': 10001, 'msg': '服务异常,需要重启EasyFut!' }, 5 | 'tq_wait' : {'code': 10002, 'msg': '底层TqSdk服务正在启动,请耐心等待几秒钟!' }, 6 | 'request_param_error' : {'code': 10003, 'msg': '传参错误,请检查您的传参!' }, 7 | 'operate_timeout' : {'code': 10004, 'msg': '操作超时,请确保传参正确后重试!' }, 8 | 'order_not_exists' : {'code': 10005, 'msg': '该委托单不存在,请检查传入参数是否正确!' }, 9 | 'order_finished' : {'code': 10006, 'msg': '该委托单已完成,无法取消!' }, 10 | 'order_unique_error' : {'code': 10007, 'msg': '委托单ID重复提交!' } 11 | } -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | with open("README.md", "r", encoding="utf-8") as fh: 4 | long_description = fh.read() 5 | 6 | setuptools.setup( 7 | name="easyfut", 8 | version="1.0.4", 9 | author="hanwanhe", 10 | author_email="hanwanhe@foxmail.com", 11 | description="简单期货行情&交易HTTP接口API,基于TqSdk", 12 | long_description=long_description, 13 | long_description_content_type="text/markdown", 14 | url="https://github.com/hanwanhe/easyfut-python", 15 | packages=setuptools.find_packages(), 16 | classifiers=[ 17 | "Programming Language :: Python :: 3", 18 | "License :: OSI Approved :: MIT License", 19 | "Operating System :: OS Independent", 20 | ], 21 | python_requires='>=3.6.4', 22 | install_requires=["tornado", "tqsdk"], 23 | entry_points={ 24 | 'console_scripts': [ 25 | 'easyfut = easyfut.main:run' 26 | ] 27 | }, 28 | include_package_data=True 29 | ) -------------------------------------------------------------------------------- /easyfut/web/routes.py: -------------------------------------------------------------------------------- 1 | from easyfut.web.handlers.account import AccountHandler 2 | from easyfut.web.handlers.order import OrderHandler 3 | from easyfut.web.handlers.quote import QuotesHandler 4 | from easyfut.web.handlers.position import PositionHandler 5 | from easyfut.web.handlers.klines import KlinesHandler 6 | from easyfut.web.handlers.ticks import TicksHandler 7 | 8 | #创建路由 9 | def createRoutes(share_dict, message_queue): 10 | routes = [] 11 | url2handler = { 12 | r"/account" : AccountHandler, 13 | r"/quote([\/a-zA-Z0-9\.\,@\-]*)" : QuotesHandler, 14 | r"/klines([\/a-zA-Z0-9\.\,\_@\-]*)" : KlinesHandler, 15 | r"/ticks([\/a-zA-Z0-9\.\,\_@\-]*)" : TicksHandler, 16 | r"/order([\/a-zA-Z0-9\,]*)" : OrderHandler, 17 | r"/position" : PositionHandler, 18 | 19 | } 20 | for url, handler, in url2handler.items(): 21 | routes.append((url, handler, {'share_dict': share_dict, 'message_queue': message_queue})) 22 | return routes 23 | 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EasyFut 2 | 3 | #### 介绍 4 | 5 | 简单期货行情&交易HTTP接口API,基于TqSdk。 6 | 7 | #### 安装&启动教程 8 | 9 | 1.pip install easyfut 10 | 11 | 2.创建配置文件 easyfut -n easyfut.conf 12 | 13 | 3.修改 easyfut.conf 配置文件内容 14 | 15 | 4.命令行启动 easyfut -c easyfut.conf 16 | 17 | #### 使用说明(curl演示) 18 | 19 | #获取账户信息 20 | 21 | curl http://127.0.0.1:8888/account 22 | 23 | #获取当前持仓 24 | 25 | curl http://127.0.0.1:8888/position 26 | 27 | #获取实时行情 28 | 29 | curl http://127.0.0.1:8888/quote/SHFE.rb2210 30 | 31 | #获取K线行情 32 | 33 | curl http://127.0.0.1:8888/klines/SHFE.rb2210_60_20 34 | 35 | #获取Tick序列 36 | 37 | curl http://127.0.0.1:8888/ticks/SHFE.rb2210_20 38 | 39 | #委托下单 40 | 41 | curl -X POST -H "Content-type: application/json" -d '{"symbol":"SHFE.rb2210", "direction":"BUY","offset":"OPEN","volume":1,"limit_price":"UPPER_LIMIT"}' http://127.0.0.1:8888/order 42 | 43 | #取消委托单 44 | 45 | curl -X POST -H "Content-type: application/json" -d '{"order_id":"f1786bea1ad045199925deea3cd6f1c7"}' http://127.0.0.1:8888/order/cancel 46 | 47 | #获取委托单信息 48 | 49 | curl http://127.0.0.1:8888/order/fbcce9326a3a4f8c80295b0e6e07434a 50 | 51 | #获取当日可撤委托 52 | 53 | curl http://127.0.0.1:8888/order/alive 54 | 55 | 56 | #更多详见官方文档 [https://easyfut.iweiai.com/doc](https://easyfut.iweiai.com/doc) 57 | 58 | -------------------------------------------------------------------------------- /easyfut/web/handlers/quote.py: -------------------------------------------------------------------------------- 1 | from easyfut.web.handlers.base import BaseHandler 2 | from easyfut.web.response import rcodes 3 | import time 4 | import re 5 | 6 | 7 | # 获取行情相关 8 | class QuotesHandler(BaseHandler): 9 | def get(self, quote_symbol): 10 | quote_symbols = self.parse_symbol(quote_symbol) 11 | quote_symbols_len = len(quote_symbols) 12 | if(quote_symbols_len == 0): 13 | self.suc(self.share_dict['quote']) 14 | else: 15 | for quote_symbol in quote_symbols: 16 | self.message_queue['quote'].put(quote_symbol) 17 | current_timestamp = int(time.time()*1000) 18 | # 超时时间(毫秒) 19 | timeout_ms = 3000+1000*quote_symbols_len 20 | while True: 21 | # 默认处理完成 22 | flag = True 23 | for quote_symbol in quote_symbols: 24 | if(quote_symbol not in self.share_dict['quote']): 25 | # 还有未完成,需要继续等待 26 | flag = False 27 | break 28 | if(flag == True): 29 | break 30 | if(int(time.time()*1000) - current_timestamp >= timeout_ms): 31 | return self.error(rcodes['operate_timeout']['code'], rcodes['operate_timeout']['msg']) 32 | time.sleep(0.01) 33 | ret_data = {} 34 | for quote_symbol in quote_symbols: 35 | ret_data[quote_symbol] = self.share_dict['quote'][quote_symbol] 36 | return self.suc(ret_data) 37 | 38 | -------------------------------------------------------------------------------- /easyfut/web/handlers/ticks.py: -------------------------------------------------------------------------------- 1 | from easyfut.web.handlers.base import BaseHandler 2 | from easyfut.web.response import rcodes 3 | import re, time 4 | 5 | # 获取Tick相关 6 | class TicksHandler(BaseHandler): 7 | def get(self, ticks_symbol): 8 | ticks_symbols = self.parse_symbol(ticks_symbol) 9 | ticks_symbol_len = len(ticks_symbols) 10 | if(ticks_symbol_len == 0): 11 | self.suc(self.share_dict['ticks']) 12 | else: 13 | for ticks_symbol in ticks_symbols: 14 | if (ticks_symbol.count('_') != 1): 15 | return self.error(rcodes['request_param_error']['code'], rcodes['request_param_error']['msg']) 16 | self.message_queue['ticks'].put(ticks_symbol) 17 | current_timestamp = int(time.time()*1000) 18 | # 超时时间(毫秒) 19 | timeout_ms = 3000+1000*ticks_symbol_len 20 | while True: 21 | # 默认处理完成 22 | flag = True 23 | for ticks_symbol in ticks_symbols: 24 | if(ticks_symbol not in self.share_dict['ticks']): 25 | # 还有未完成,需要继续等待 26 | flag = False 27 | break 28 | if(flag == True): 29 | break 30 | if(int(time.time()*1000) - current_timestamp >= timeout_ms): 31 | return self.error(rcodes['operate_timeout']['code'], rcodes['operate_timeout']['msg']) 32 | time.sleep(0.01) 33 | ret_data = {} 34 | for ticks_symbol in ticks_symbols: 35 | ret_data[ticks_symbol] = self.share_dict['ticks'][ticks_symbol] 36 | return self.suc(ret_data) -------------------------------------------------------------------------------- /easyfut/web/handlers/klines.py: -------------------------------------------------------------------------------- 1 | from easyfut.web.handlers.base import BaseHandler 2 | from easyfut.web.response import rcodes 3 | import re, time 4 | 5 | # 获取k线相关 6 | class KlinesHandler(BaseHandler): 7 | def get(self, klines_symbol): 8 | klines_symbols = self.parse_symbol(klines_symbol) 9 | klines_symbols_len = len(klines_symbols) 10 | if(klines_symbols_len == 0): 11 | self.suc(self.share_dict['klines']) 12 | else: 13 | for klines_symbol in klines_symbols: 14 | if (klines_symbol.count('_') != 2): 15 | return self.error(rcodes['request_param_error']['code'], rcodes['request_param_error']['msg']) 16 | self.message_queue['klines'].put(klines_symbol) 17 | current_timestamp = int(time.time()*1000) 18 | # 超时时间(毫秒) 19 | timeout_ms = 3000+1000*klines_symbols_len 20 | while True: 21 | # 默认处理完成 22 | flag = True 23 | for klines_symbol in klines_symbols: 24 | if(klines_symbol not in self.share_dict['klines']): 25 | # 还有未完成,需要继续等待 26 | flag = False 27 | break 28 | if(flag == True): 29 | break 30 | if(int(time.time()*1000) - current_timestamp >= timeout_ms): 31 | return self.error(rcodes['operate_timeout']['code'], rcodes['operate_timeout']['msg']) 32 | time.sleep(0.01) 33 | ret_data = {} 34 | for klines_symbol in klines_symbols: 35 | ret_data[klines_symbol] = self.share_dict['klines'][klines_symbol] 36 | return self.suc(ret_data) -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # test module 个人习惯,测试目录去掉 10 | /test/ 11 | 12 | # Distribution / packaging 13 | .Python 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | wheels/ 26 | pip-wheel-metadata/ 27 | share/python-wheels/ 28 | *.egg-info/ 29 | .installed.cfg 30 | *.egg 31 | MANIFEST 32 | 33 | # PyInstaller 34 | # Usually these files are written by a python script from a template 35 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 36 | *.manifest 37 | *.spec 38 | .idea/ 39 | 40 | # Installer logs 41 | pip-log.txt 42 | pip-delete-this-directory.txt 43 | 44 | # Unit test / coverage reports 45 | htmlcov/ 46 | .tox/ 47 | .nox/ 48 | .coverage 49 | .coverage.* 50 | .cache 51 | nosetests.xml 52 | coverage.xml 53 | *.cover 54 | .hypothesis/ 55 | .pytest_cache/ 56 | 57 | # Translations 58 | *.mo 59 | *.pot 60 | 61 | # Django stuff: 62 | *.log 63 | local_settings.py 64 | db.sqlite3 65 | 66 | # Flask stuff: 67 | instance/ 68 | .webassets-cache 69 | 70 | # Scrapy stuff: 71 | .scrapy 72 | 73 | # Sphinx documentation 74 | docs/_build/ 75 | 76 | # PyBuilder 77 | target/ 78 | 79 | # Jupyter Notebook 80 | .ipynb_checkpoints 81 | 82 | # IPython 83 | profile_default/ 84 | ipython_config.py 85 | 86 | # pyenv 87 | .python-version 88 | 89 | # celery beat schedule file 90 | celerybeat-schedule 91 | 92 | # SageMath parsed files 93 | *.sage.py 94 | 95 | # Environments 96 | .env 97 | .venv 98 | env/ 99 | venv/ 100 | ENV/ 101 | env.bak/ 102 | venv.bak/ 103 | 104 | # Spyder project settings 105 | .spyderproject 106 | .spyproject 107 | 108 | # Rope project settings 109 | .ropeproject 110 | 111 | # mkdocs documentation 112 | /site 113 | 114 | # mypy 115 | .mypy_cache/ 116 | .dmypy.json 117 | dmypy.json 118 | 119 | # Pyre type checker 120 | .pyre/ -------------------------------------------------------------------------------- /easyfut/web/handlers/base.py: -------------------------------------------------------------------------------- 1 | import tornado.web 2 | import time 3 | from easyfut.web.response import rcodes 4 | 5 | # 基础handler 6 | class BaseHandler(tornado.web.RequestHandler): 7 | 8 | #错误信息 9 | last_error_msg = '' 10 | 11 | #初始化 12 | def initialize(self, share_dict, message_queue): 13 | #共享变量 14 | self.share_dict = share_dict 15 | #消息队列 16 | self.message_queue = message_queue 17 | 18 | #解析传过来的symbol 19 | def parse_symbol(self, symbol): 20 | return list(filter(None, map(str.strip, symbol.strip('/').split(',')))) 21 | 22 | 23 | #initialize后调用 24 | def prepare(self): 25 | if(self.share_dict['tqsdkserver_alive'] == False): 26 | return self.error(rcodes['tq_error']['code'], rcodes['tq_error']['msg']) 27 | #判断底层TqsdkServer是否已经启动完成 28 | if(self.share_dict['tqsdkserver_ready'] == False): 29 | return self.error(rcodes['tq_wait']['code'], rcodes['tq_wait']['msg']) 30 | #判断TqsdkServer是否正常(30秒内有过更新) 或者 进程已经挂掉 31 | if(int(time.time()) - self.share_dict['last_update'] > 30): 32 | return self.error(rcodes['tq_error']['code'], rcodes['tq_error']['msg']) 33 | #日志格式 34 | def _request_summary(self): 35 | params = '' 36 | err_msg = '' 37 | if(self.request.method == 'POST'): 38 | params = self.request.body 39 | if(self.last_error_msg != ''): 40 | err_msg = self.last_error_msg 41 | return "%s %s %s %s" % (self.request.method, self.request.uri, 42 | params, err_msg) 43 | 44 | #返回正确响应 45 | def suc(self, data): 46 | self.finish({ 47 | 'code' : rcodes['suc']['code'], 48 | 'data': data, 49 | 'msg': rcodes['suc']['msg'], 50 | }) 51 | 52 | # 返回错误响应 53 | def error(self, code, errmsg, data = {}): 54 | self.set_status(400) 55 | self.last_error_msg = '错误信息:'+str(code) + " "+errmsg 56 | self.finish({ 57 | 'code' : code, 58 | 'data': data, 59 | 'msg': errmsg 60 | }) 61 | -------------------------------------------------------------------------------- /easyfut/main.py: -------------------------------------------------------------------------------- 1 | from multiprocessing import Manager, Queue 2 | import argparse, configparser 3 | from easyfut.server import TqsdkServer, Webserver 4 | import signal 5 | import sys 6 | import os 7 | 8 | 9 | def run(): 10 | # 传参解析 11 | parser = argparse.ArgumentParser() 12 | group = parser.add_mutually_exclusive_group(required=True) 13 | # 启动使用的配置文件 14 | group.add_argument('-c', metavar="configuration file", help="Specify the configuration file required to start EasyFut") 15 | # 生成配置文件的地址 16 | group.add_argument('-n', metavar="configuration file",help="Generate a new configuration file") 17 | # 解析传参 18 | args = parser.parse_args() 19 | # 创建模板配置文件 20 | if(args.n is not None): 21 | if (os.path.exists(args.n) == True): 22 | print("配置文件 " + args.n + " 已存在!") 23 | sys.exit(-1) 24 | source = open(os.path.join(os.path.dirname(__file__), 'conf', 'easyfut-template.conf'), "r", encoding="utf-8") 25 | dest = open(args.n, "w", encoding="utf-8") 26 | line = source.readline() 27 | while line: 28 | dest.write(line) 29 | line = source.readline() 30 | source.close() 31 | dest.close() 32 | print("配置文件 " + args.n + " 创建成功!") 33 | return 34 | 35 | #判断配置文件存在 36 | if(os.path.exists(args.c) == False): 37 | print("配置文件 "+args.c+" 不存在!") 38 | sys.exit(-1) 39 | # 解析配置文件 40 | app_config = configparser.ConfigParser() 41 | app_config.read(args.c, encoding="utf-8") 42 | # 进程间共享变量 43 | manager = Manager() 44 | share_dict = manager.dict() 45 | share_dict['tqsdkserver_alive'] = True 46 | share_dict['webserver_ready'] = False 47 | share_dict['tqsdkserver_ready'] = False 48 | # 进程间消息队列 49 | message_queue = { 50 | 'order' : Queue(), 51 | 'quote' : Queue(), 52 | 'klines' : Queue(), 53 | 'ticks' : Queue() 54 | } 55 | # tqsdk 服务进程启动 56 | tqsdkserver = TqsdkServer(app_config, share_dict, message_queue) 57 | tqsdkserver.start() 58 | # http 服务进程启动 59 | webserver = Webserver(app_config, share_dict, message_queue) 60 | webserver.start() 61 | # 监听kill信号 62 | def signal_handler(signal, frame): 63 | tqsdkserver.terminate() 64 | webserver.terminate() 65 | manager.shutdown() 66 | sys.exit(0) 67 | signal.signal(signal.SIGTERM, signal_handler) 68 | # 等待子进程完成 69 | tqsdkserver.join() 70 | # 标记进程死掉 71 | share_dict['tqsdkserver_alive'] = False 72 | webserver.join() 73 | 74 | 75 | -------------------------------------------------------------------------------- /easyfut/web/handlers/order.py: -------------------------------------------------------------------------------- 1 | from easyfut.web.handlers.base import BaseHandler 2 | from easyfut.web.response import rcodes 3 | import tornado 4 | import time 5 | import re 6 | import random 7 | import hashlib 8 | 9 | # 获取订单相关 10 | class OrderHandler(BaseHandler): 11 | 12 | #查询订单 13 | def get(self, order_symbol): 14 | order_symbols = self.parse_symbol(order_symbol) 15 | order_symbols_len = len(order_symbols) 16 | if(order_symbols_len == 0): 17 | #获取全部的订单 18 | return self.suc(self.share_dict['orders']) 19 | elif(order_symbols_len == 1 and order_symbols[0] == 'alive'): 20 | #获取当前委托 21 | order_alive = {} 22 | for order_id in self.share_dict['orders']: 23 | if(self.share_dict['orders'][order_id]['status'] == 'ALIVE'): 24 | order_alive[order_id] = self.share_dict['orders'][order_id] 25 | return self.suc(order_alive) 26 | else: 27 | #获取订单详情 28 | order_detail = {} 29 | for order_id in order_symbols: 30 | if(order_id in self.share_dict['orders']): 31 | order_detail[order_id] = self.share_dict['orders'][order_id] 32 | return self.suc(order_detail) 33 | 34 | #下单或取消委托单 35 | def post(self, operate): 36 | operate = operate.strip('/') 37 | if(operate == 'cancel'): 38 | #取消委托单 39 | req_param = tornado.escape.json_decode(self.request.body) 40 | if('order_id' not in req_param or req_param['order_id'] not in self.share_dict['orders']): 41 | return self.error(rcodes['order_not_exists']['code'], rcodes['order_not_exists']['msg']) 42 | if(self.share_dict['orders'][req_param['order_id']]['status'] != 'ALIVE'): 43 | return self.error(rcodes['order_finished']['code'], rcodes['order_finished']['msg']) 44 | #加入消息队列,要取消的委托单 45 | self.message_queue['order'].put({'operate':'cancel', 'params':{'order_id':req_param['order_id']}}) 46 | # 超时时间(毫秒) 47 | timeout_ms = 3000 48 | current_timestamp = int(time.time()*1000) 49 | while self.share_dict['orders'][req_param['order_id']]['status'] == 'ALIVE': 50 | if(int(time.time()*1000) - current_timestamp >= timeout_ms): 51 | return self.error(rcodes['operate_timeout']['code'], rcodes['operate_timeout']['msg']) 52 | time.sleep(0.01) 53 | return self.suc(self.share_dict['orders'][req_param['order_id']]) 54 | else: 55 | #创建委托单 56 | req_param = tornado.escape.json_decode(self.request.body) 57 | #校验委托单ID 58 | if('order_id' in req_param and req_param['order_id'] != ''): 59 | if(re.match(r'^[a-zA-Z0-9]{32}$', req_param['order_id']) is None): 60 | return self.error(rcodes['request_param_error']['code'], 'order_id '+rcodes['request_param_error']['msg']) 61 | if(req_param['order_id'] in self.share_dict['orders']): 62 | return self.error(rcodes['order_unique_error']['code'], rcodes['order_unique_error']['msg']) 63 | order_id = req_param['order_id'] 64 | else: 65 | random_str = str(time.time())+str(random.randint(1, 100)) 66 | order_id = hashlib.md5(random_str.encode(encoding='UTF-8')).hexdigest() 67 | #symbol 合约ID 68 | if('symbol' not in req_param or re.match(r'^[a-zA-Z0-9]+\.[a-zA-Z0-9]+$', req_param['symbol']) is None): 69 | return self.error(rcodes['request_param_error']['code'], 'symbol '+rcodes['request_param_error']['msg']) 70 | #direction 71 | if('direction' not in req_param or req_param['direction'] not in ("BUY", "SELL")): 72 | return self.error(rcodes['request_param_error']['code'], 'direction '+rcodes['request_param_error']['msg']) 73 | #offset 74 | if('offset' not in req_param or req_param['offset'] not in ("CLOSE", "OPEN", "CLOSETODAY")): 75 | return self.error(rcodes['request_param_error']['code'], 'offset '+rcodes['request_param_error']['msg']) 76 | #limit_price 77 | if('limit_price' not in req_param): 78 | return self.error(rcodes['request_param_error']['code'], 'limit_price '+rcodes['request_param_error']['msg']) 79 | if(req_param['limit_price'] in ('UPPER_LIMIT', 'LOWER_LIMIT', 'MARKET', 'BEST', 'FIVELEVEL')): 80 | limit_price = req_param['limit_price'] 81 | else: 82 | try: 83 | limit_price = float(req_param['limit_price']) 84 | except Exception as e: 85 | return self.error(rcodes['request_param_error']['code'], 'limit_price '+rcodes['request_param_error']['msg']) 86 | #volume 87 | if('volume' not in req_param): 88 | return self.error(rcodes['request_param_error']['code'], 'volume '+rcodes['request_param_error']['msg']) 89 | try: 90 | volume = int(req_param['volume']) 91 | except Exception as e: 92 | return self.error(rcodes['request_param_error']['code'], 'limit_price '+rcodes['request_param_error']['msg']) 93 | if(volume < 1): 94 | return self.error(rcodes['request_param_error']['code'], 'limit_price '+rcodes['request_param_error']['msg']) 95 | #advanced 96 | if('advanced' in req_param and req_param['advanced']!='' and req_param['advanced'] not in ("FAK", "FOK")): 97 | return self.error(rcodes['request_param_error']['code'], 'advanced '+rcodes['request_param_error']['msg']) 98 | #写入队列 99 | self.message_queue['order'].put( 100 | { 101 | 'operate':'insert', 102 | 'params':{ 103 | 'order_id' : order_id, 104 | 'symbol' : req_param['symbol'], 105 | 'direction' : req_param['direction'], 106 | 'offset' : req_param['offset'], 107 | 'volume' : volume, 108 | 'limit_price' : limit_price, 109 | 'advanced' : req_param['advanced'] if ('advanced' in req_param and req_param['advanced']!='') else None 110 | } 111 | } 112 | ) 113 | # 超时时间(毫秒) 114 | timeout_ms = 3000 115 | current_timestamp = int(time.time()*1000) 116 | while order_id not in self.share_dict['orders']: 117 | if(int(time.time()*1000) - current_timestamp >= timeout_ms): 118 | return self.error(rcodes['operate_timeout']['code'], rcodes['operate_timeout']['msg']) 119 | time.sleep(0.01) 120 | self.suc(self.share_dict['orders'][order_id]) -------------------------------------------------------------------------------- /easyfut/tests/test.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import hashlib 3 | import time 4 | import sys 5 | 6 | 7 | #服务 8 | host_url = 'http://127.0.0.1:8888' 9 | 10 | #测试获取账户信息 11 | def test_account(): 12 | account = requests.get(host_url+'/account').json() 13 | assert(account['code'] == 10000 and len(account['data']) > 0 and isinstance(account['data']['balance'], float)) 14 | print("账户权益:"+str(account['data']['balance'])) 15 | #测试获取当前持仓 16 | def test_position(): 17 | position = requests.get(host_url+'/position').json() 18 | assert(position['code'] == 10000) 19 | pos_num = 0 20 | for quote_symbol, position_info in position['data'].items(): 21 | if(position_info['pos_short'] > 0 or position_info['pos_long'] > 0): 22 | pos_num+=1 23 | print('持仓品种数:'+str(pos_num)) 24 | 25 | 26 | #获取主力合约对应的标的合约 27 | def test_kqm_quote(): 28 | #获取螺纹钢和铁矿石当前主力合约 29 | quote = requests.get(host_url+'/quote/KQ.m@SHFE.rb,KQ.m@DCE.i').json() 30 | assert(quote['code'] == 10000 and 'KQ.m@SHFE.rb' in quote['data'] and 'KQ.m@DCE.i' in quote['data']) 31 | rb_underlying_symbol = quote['data']['KQ.m@SHFE.rb']['underlying_symbol'] 32 | i_underlying_symbol = quote['data']['KQ.m@DCE.i']['underlying_symbol'] 33 | assert(rb_underlying_symbol != '') 34 | assert(i_underlying_symbol != '') 35 | print("螺纹钢主力合约:"+rb_underlying_symbol) 36 | print("铁矿石主力合约:"+i_underlying_symbol) 37 | return rb_underlying_symbol, i_underlying_symbol 38 | 39 | #测试实时行情 40 | def test_quote(): 41 | rb_underlying_symbol, i_underlying_symbol = test_kqm_quote() 42 | #获取实时行情 43 | quote = requests.get(host_url+'/quote/'+rb_underlying_symbol+','+i_underlying_symbol).json() 44 | assert(quote['code'] == 10000 and rb_underlying_symbol in quote['data'] and i_underlying_symbol in quote['data']) 45 | print(rb_underlying_symbol+" 最新价:"+str(quote['data'][rb_underlying_symbol]['last_price'])) 46 | print(i_underlying_symbol+" 最新价:"+str(quote['data'][i_underlying_symbol]['last_price'])) 47 | 48 | #测试k线行情 49 | def test_klines(): 50 | rb_underlying_symbol, i_underlying_symbol = test_kqm_quote() 51 | klines = requests.get(host_url+'/klines/'+rb_underlying_symbol+'_60_5,'+i_underlying_symbol+'_60_5').json() 52 | assert(klines['code'] == 10000 and rb_underlying_symbol+'_60_5' in klines['data'] and i_underlying_symbol+'_60_5' in klines['data']) 53 | print(rb_underlying_symbol+'_60_5 k线最新收盘价:'+str(klines['data'][rb_underlying_symbol+'_60_5'][-1]['close'])) 54 | print(i_underlying_symbol+'_60_5 k线最新收盘价:'+str(klines['data'][i_underlying_symbol+'_60_5'][-1]['close'])) 55 | 56 | #测试ticks 57 | def test_ticks(): 58 | rb_underlying_symbol, i_underlying_symbol = test_kqm_quote() 59 | ticks = requests.get(host_url+'/ticks/'+rb_underlying_symbol+'_5,'+i_underlying_symbol+'_5').json() 60 | assert(ticks['code'] == 10000 and rb_underlying_symbol+'_5' in ticks['data'] and i_underlying_symbol+'_5' in ticks['data']) 61 | print(rb_underlying_symbol+'_5 ticks最新价:'+str(ticks['data'][rb_underlying_symbol+'_5'][-1]['last_price'])) 62 | print(i_underlying_symbol+'_5 ticks最新价:'+str(ticks['data'][i_underlying_symbol+'_5'][-1]['last_price'])) 63 | 64 | #测试下单,撤单等 65 | def test_order(): 66 | rb_underlying_symbol, i_underlying_symbol = test_kqm_quote() 67 | my_order_id = hashlib.md5(str(time.time()).encode('utf-8')).hexdigest() 68 | # 涨停买入 69 | order = requests.post(host_url+'/order', json={ 70 | 'order_id': my_order_id, 71 | 'symbol' : rb_underlying_symbol, 72 | 'direction' : 'BUY', 73 | 'offset': 'OPEN', 74 | 'volume': 1, 75 | 'limit_price': 'UPPER_LIMIT' 76 | }).json() 77 | assert(order['code'] == 10000 and order['data']['order_id'] == my_order_id) 78 | while True: 79 | order_info = requests.get(host_url+'/order/'+my_order_id).json() 80 | if order_info['data'][my_order_id]['status'] == 'FINISHED': 81 | print("涨停买入成交价格:"+str(order_info['data'][my_order_id]['trade_price'])) 82 | break 83 | time.sleep(1) 84 | #跌停买入 85 | my_order_id = hashlib.md5(str(time.time()).encode('utf-8')).hexdigest() 86 | order = requests.post(host_url+'/order', json={ 87 | 'order_id': my_order_id, 88 | 'symbol' : rb_underlying_symbol, 89 | 'direction' : 'BUY', 90 | 'offset': 'OPEN', 91 | 'volume': 2, 92 | 'limit_price': 'LOWER_LIMIT' 93 | }).json() 94 | assert(order['code'] == 10000 and order['data']['order_id'] == my_order_id) 95 | print("跌停买入成功,委托ID:"+str(order['data']['order_id'])) 96 | #获取单个委托单 97 | order = requests.get(host_url+'/order/'+my_order_id).json() 98 | assert(order['code'] == 10000 and my_order_id in order['data'] and order['data'][my_order_id]['status'] == 'ALIVE') 99 | print("当前委托价格:"+str(order['data'][my_order_id]['limit_price'])) 100 | #获取当前可撤委托单 101 | order = requests.get(host_url+'/order/alive').json() 102 | assert(order['code'] == 10000 and my_order_id in order['data'] and order['data'][my_order_id]['status'] == 'ALIVE') 103 | print("当前可撤数量:"+str(len(order['data']))) 104 | #取消跌停买入的单子 105 | order = requests.post(host_url+'/order/cancel', json={ 106 | 'order_id': my_order_id, 107 | }).json() 108 | assert(order['code'] == 10000 and order['data']['order_id'] == my_order_id) 109 | print("取消成功,委托ID:"+str(order['data']['order_id'])) 110 | 111 | #市价卖出 112 | my_order_id = hashlib.md5(str(time.time()).encode('utf-8')).hexdigest() 113 | order = requests.post(host_url+'/order', json={ 114 | 'order_id': my_order_id, 115 | 'symbol' : rb_underlying_symbol, 116 | 'direction' : 'SELL', 117 | 'offset': 'OPEN', 118 | 'volume': 3, 119 | 'limit_price':'LOWER_LIMIT' 120 | }).json() 121 | assert(order['code'] == 10000 and order['data']['order_id'] == my_order_id) 122 | 123 | #测试清除所有今仓 124 | def test_clear_position(): 125 | position = requests.get(host_url+'/position').json() 126 | assert(position['code'] == 10000) 127 | pos_num = 0 128 | print('持仓品种数:'+str(pos_num)) 129 | for quote_symbol, position_info in position['data'].items(): 130 | if(position_info['pos_short'] > 0 or position_info['pos_long'] > 0): 131 | pos_num+=1 132 | for quote_symbol, position_info in position['data'].items(): 133 | if(position_info['pos_short_today'] > 0): 134 | offset = 'CLOSE' 135 | if('SHFE' in quote_symbol): 136 | offset = 'CLOSETODAY' 137 | order = requests.post(host_url+'/order', json={ 138 | 'symbol' : quote_symbol, 139 | 'direction' : 'BUY', 140 | 'offset': offset, 141 | 'volume': position_info['pos_short_today'], 142 | 'limit_price':'UPPER_LIMIT' 143 | }).json() 144 | 145 | if(position_info['pos_long_today'] > 0): 146 | offset = 'CLOSE' 147 | if('SHFE' in quote_symbol): 148 | offset = 'CLOSETODAY' 149 | order = requests.post(host_url+'/order', json={ 150 | 'symbol' : quote_symbol, 151 | 'direction' : 'SELL', 152 | 'offset': offset, 153 | 'volume': position_info['pos_long_today'], 154 | 'limit_price':'LOWER_LIMIT' 155 | }).json() 156 | time.sleep(3) 157 | position = requests.get(host_url+'/position').json() 158 | assert(position['code'] == 10000) 159 | pos_num = 0 160 | for quote_symbol, position_info in position['data'].items(): 161 | if(position_info['pos_short'] > 0 or position_info['pos_long'] > 0): 162 | pos_num+=1 163 | print('持仓品种数:'+str(pos_num)) 164 | 165 | def main(): 166 | if(len(sys.argv) > 1): 167 | func = sys.argv[1] 168 | eval(func)() 169 | else: 170 | test_account() 171 | test_position() 172 | test_kqm_quote() 173 | test_quote() 174 | test_klines() 175 | test_ticks() 176 | test_order() 177 | time.sleep(3) 178 | test_clear_position() 179 | 180 | 181 | if __name__ == '__main__': 182 | main() -------------------------------------------------------------------------------- /easyfut/server.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from multiprocessing import Process 3 | import tornado.ioloop 4 | import tornado.web 5 | import tornado.options 6 | from easyfut.web.routes import createRoutes 7 | import time,math 8 | 9 | 10 | # 服务基类 11 | class BaseServer(Process): 12 | #程序配置 13 | app_config = None 14 | # 共享变量 15 | share_dict = None 16 | # 消息队列 17 | message_queue = None 18 | 19 | def __init__(self, app_config, share_dict, message_queue): 20 | Process.__init__(self) 21 | # 程序配置 22 | self.app_config = app_config 23 | # 共享变量 24 | self.share_dict = share_dict 25 | # 消息队列 26 | self.message_queue = message_queue 27 | # 共享变量初始化 28 | self.share_dict['account'] = {} 29 | self.share_dict['position'] = {} 30 | self.share_dict['orders'] = {} 31 | self.share_dict['quote'] = {} 32 | self.share_dict['klines'] = {} 33 | self.share_dict['ticks'] = {} 34 | self.share_dict['last_update'] = 0 35 | 36 | # 启动tqsdk 37 | class TqsdkServer(BaseServer): 38 | 39 | # tqsdk api 句柄 40 | api = None 41 | 42 | # 当前所处环境 43 | env = None 44 | 45 | def run(self): 46 | # 日志格式 47 | logging.basicConfig( 48 | level=logging.INFO, 49 | format='%(asctime)s - %(levelname)s - 通知: %(message)s', 50 | datefmt='%Y-%m-%d %H:%M:%S' 51 | ) 52 | # 导入tqsdk相关 53 | from tqsdk import TqApi, TqAuth, TqKq, TqSim, TqAccount 54 | # 连接tqsdk 55 | tq_username = self.app_config.get('tqsdk', 'username') 56 | tq_password = self.app_config.get('tqsdk', 'password') 57 | auth = TqAuth(tq_username, tq_password) 58 | # 连接tqsdk 59 | self.env = self.app_config.get('tqsdk', 'env') 60 | if(self.env == 'prod'): 61 | # 实盘 62 | broker_id = self.app_config.get('tqsdk', 'broker_id') 63 | account_id = self.app_config.get('tqsdk', 'account_id') 64 | account_password = self.app_config.get('tqsdk', 'account_password') 65 | td_url = None 66 | if (self.app_config.has_option('tqsdk', 'td_url') and self.app_config.get('tqsdk', 'td_url') != ''): 67 | td_url = self.app_config.get('tqsdk', 'td_url') 68 | self.api = TqApi(TqAccount(broker_id, account_id, account_password, td_url = td_url), auth=auth) 69 | else: 70 | # 模拟 71 | self.api = TqApi(TqKq(), auth=auth) 72 | # 获取账户 73 | account = self.api.get_account() 74 | # 获取订单 75 | orders = self.api.get_order() 76 | # quote信息 77 | all_quotes = {} 78 | # 隐含的quotes 79 | all_hidden_quotes = {} 80 | # klines信息 81 | all_klines = {} 82 | # ticks信息 83 | all_ticks = {} 84 | # 获取仓位信息 85 | position = self.api.get_position() 86 | # 首次tqsdk信息同步到共享变量 87 | self.sync2sharedict(account, orders, all_quotes, position, all_klines, all_ticks) 88 | # 是否启动 89 | is_start = False 90 | # 主逻辑 91 | while True: 92 | # 等待数据更新截止事件 93 | self.api.wait_update(int(time.time())+3) 94 | # 首次启动提示 95 | if(is_start == False): 96 | is_start = True 97 | self.share_dict['tqsdkserver_ready'] = True 98 | # 服务启动成功 99 | logging.info("TqSdkServer 启动完成") 100 | host = self.app_config.get('webserver', 'host') 101 | port = self.app_config.get('webserver', 'port') 102 | while(self.share_dict['webserver_ready'] == False): 103 | time.sleep(1) 104 | logging.info("等待 Tornado WebServer 启动完成...") 105 | logging.info("Tornado WebServer 启动完成,正在监听:" + str(host) + ':' + str(port)) 106 | # 输出免责 107 | logging.warning("因交易过程中存在各种不可抗拒因素(断网,程序Bug...),用户在使用EasyFut过程中产生的任何亏损(损失),用户需自行承担,EasyFut不承担任何责任,如果不同意请立即停止使用。") 108 | # 输出当前交易环境 109 | if(self.env == 'prod'): 110 | logging.warning("您当前正处于实盘交易中,请注意...") 111 | else: 112 | logging.info("您当前正处于模拟交易中") 113 | # 新的委托单处理 114 | while (self.message_queue['order'].empty() == False): 115 | queue_order = self.message_queue['order'].get() 116 | if(queue_order['operate'] == 'cancel'): 117 | self.api.cancel_order(queue_order['params']['order_id']) 118 | elif(queue_order['operate'] == 'insert'): 119 | #处理涨停和跌停价格 120 | if(queue_order['params']['limit_price'] in ('UPPER_LIMIT', 'LOWER_LIMIT')): 121 | if(queue_order['params']['symbol'] not in all_hidden_quotes): 122 | if(queue_order['params']['symbol'] in all_quotes): 123 | all_hidden_quotes[queue_order['params']['symbol']] = all_quotes[queue_order['params']['symbol']] 124 | else: 125 | all_hidden_quotes[queue_order['params']['symbol']] = self.api.get_quote(queue_order['params']['symbol']) 126 | if(queue_order['params']['limit_price'] == 'UPPER_LIMIT'): 127 | queue_order['params']['limit_price'] = all_hidden_quotes[queue_order['params']['symbol']]['upper_limit'] 128 | else: 129 | queue_order['params']['limit_price'] = all_hidden_quotes[queue_order['params']['symbol']]['lower_limit'] 130 | elif(queue_order['params']['limit_price'] == 'MARKET'): 131 | queue_order['params']['limit_price'] = None 132 | self.api.insert_order(**queue_order['params']) 133 | # 立即发送下单 134 | self.api.wait_update(int(time.time())+3) 135 | # 是否有新的quote需要订阅 136 | while (self.message_queue['quote'].empty() == False): 137 | quote_symbol = self.message_queue['quote'].get() 138 | if(quote_symbol in all_quotes): 139 | continue 140 | # 之前隐形获取过,涨跌停开仓的时候 141 | if(quote_symbol in all_hidden_quotes): 142 | all_quotes[quote_symbol] = all_hidden_quotes[quote_symbol] 143 | else: 144 | all_quotes[quote_symbol] = self.api.get_quote(quote_symbol) 145 | 146 | # 是否有新的klines需要订阅 147 | while (self.message_queue['klines'].empty() == False): 148 | klines_symbol = self.message_queue['klines'].get() 149 | if(klines_symbol in all_klines): 150 | continue 151 | klines_symbol_arr = klines_symbol.split('_') 152 | all_klines[klines_symbol] = self.api.get_kline_serial(klines_symbol_arr[0], klines_symbol_arr[1], klines_symbol_arr[2]) 153 | 154 | # 是否有新的ticks需要订阅 155 | while (self.message_queue['ticks'].empty() == False): 156 | ticks_symbol = self.message_queue['ticks'].get() 157 | if(ticks_symbol in all_ticks): 158 | continue 159 | ticks_symbol_arr = ticks_symbol.split('_') 160 | all_ticks[ticks_symbol] = self.api.get_tick_serial(ticks_symbol_arr[0], ticks_symbol_arr[1]) 161 | # tqsdk信息同步到共享变量 162 | self.sync2sharedict(account, orders, all_quotes, position, all_klines, all_ticks) 163 | self.api.close() 164 | 165 | 166 | # 抽取tqsdk变量中的键值对 167 | def extract_kv(self, tqsdk_variable): 168 | from tqsdk import objs 169 | kv = {} 170 | it = iter(tqsdk_variable) 171 | while True: 172 | try: 173 | k = next(it) 174 | if ( 175 | isinstance(tqsdk_variable[k], str) or 176 | isinstance(tqsdk_variable[k], float) or 177 | isinstance(tqsdk_variable[k], int) or 178 | isinstance(tqsdk_variable[k], list) or 179 | isinstance(tqsdk_variable[k], bool) or 180 | isinstance(tqsdk_variable[k], objs.TradingTime) 181 | ): 182 | if(isinstance(tqsdk_variable[k], float)): 183 | if(math.isnan(tqsdk_variable[k]) == True): 184 | kv[k] = 0.0 185 | else: 186 | kv[k] = round(tqsdk_variable[k], 6) 187 | elif(isinstance(tqsdk_variable[k], objs.TradingTime)): 188 | kv[k] = {} 189 | kv[k]['day'] = tqsdk_variable[k].day 190 | kv[k]['night'] = tqsdk_variable[k].night 191 | else: 192 | kv[k] = tqsdk_variable[k] 193 | except StopIteration: 194 | break 195 | return kv 196 | 197 | 198 | # 更新tqsdk当前信息到共享变量 199 | def sync2sharedict(self, account, orders, all_quotes, position, all_klines, all_ticks): 200 | # 同步账户 201 | self.share_dict['account'] = self.extract_kv(account) 202 | # 同步订单 203 | my_orderes = {} 204 | for order_id in orders: 205 | my_orderes[order_id] = self.extract_kv(orders[order_id]) 206 | self.share_dict['orders'] = my_orderes 207 | # 同步quote 208 | my_quotes = {} 209 | for quote_symbol in all_quotes: 210 | my_quotes[quote_symbol] = self.extract_kv(all_quotes[quote_symbol]) 211 | self.share_dict['quote'] = my_quotes 212 | # 同步position 213 | my_position = {} 214 | for quote_symbol in position: 215 | my_position[quote_symbol] = self.extract_kv(position[quote_symbol]) 216 | self.share_dict['position'] = my_position 217 | # 同步klines 218 | my_klines = {} 219 | for quote_symbol in all_klines: 220 | records = all_klines[quote_symbol].to_dict('records') 221 | for i in range(len(records)): 222 | records[i] = self.extract_kv(records[i]) 223 | my_klines[quote_symbol] = records 224 | self.share_dict['klines'] = my_klines 225 | # 同步ticks 226 | my_ticks = {} 227 | for quote_symbol in all_ticks: 228 | records = all_ticks[quote_symbol].to_dict('records') 229 | for i in range(len(records)): 230 | records[i] = self.extract_kv(records[i]) 231 | my_ticks[quote_symbol] = records 232 | self.share_dict['ticks'] = my_ticks 233 | # 标记最近一次更新的时间戳 234 | self.share_dict['last_update'] = int(time.time()) 235 | return True 236 | 237 | 238 | 239 | # 启动http服务 240 | class Webserver(BaseServer): 241 | 242 | def run(self): 243 | app = tornado.web.Application(createRoutes(self.share_dict, self.message_queue)) 244 | host = self.app_config.get('webserver', 'host') 245 | port = self.app_config.get('webserver', 'port') 246 | app.listen(port, host) 247 | logging.basicConfig( 248 | level=logging.INFO, 249 | format='%(asctime)s - %(levelname)s - 通知: %(message)s', 250 | datefmt='%Y-%m-%d %H:%M:%S' 251 | ) 252 | self.share_dict['webserver_ready'] = True 253 | tornado.ioloop.IOLoop.current().start() 254 | 255 | 256 | 257 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. --------------------------------------------------------------------------------