code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
if is_str(codelist):
codelist = codelist.split(',')
elif isinstance(codelist, list):
pass
else:
return RET_ERROR, "code list must be like ['HK.00001', 'HK.00700'] or 'HK.00001,HK.00700'"
result = []
for code in codelist:
ret, data = self.get_history_kline(code, start, end, ktype, autype)
if ret != RET_OK:
return RET_ERROR, 'get history kline error: {}, {},{},{},{}'.format(data, code, start, end, ktype)
result.append(data)
return 0, result | def get_multiple_history_kline(self,
codelist,
start=None,
end=None,
ktype=KLType.K_DAY,
autype=AuType.QFQ) | 获取多只股票的本地历史k线数据
:param codelist: 股票代码列表,list或str。例如:['HK.00700', 'HK.00001'],'HK.00700,HK.00001'
:param start: 起始时间,例如'2017-06-20'
:param end: 结束时间, 例如'2017-07-20',start与end组合关系参见 get_history_kline_
:param ktype: k线类型,参见KLType
:param autype: 复权类型,参见AuType
:return: 成功时返回(RET_OK, [data]),data是DataFrame数据, 数据列格式如下
================= =========== ==============================================================================
参数 类型 说明
================= =========== ==============================================================================
code str 股票代码
time_key str k线时间
open float 开盘价
close float 收盘价
high float 最高价
low float 最低价
pe_ratio float 市盈率(该字段为比例字段,默认不展示%)
turnover_rate float 换手率
volume int 成交量
turnover float 成交额
change_rate float 涨跌幅
last_close float 昨收价
================= =========== ==============================================================================
失败时返回(RET_ERROR, data),其中data是错误描述字符串 | 2.43101 | 2.264702 | 1.073435 |
return self._get_history_kline_impl(GetHistoryKlineQuery, code, start=start, end=end,
ktype=ktype, autype=autype, fields=fields) | def get_history_kline(self,
code,
start=None,
end=None,
ktype=KLType.K_DAY,
autype=AuType.QFQ,
fields=[KL_FIELD.ALL]) | 得到本地历史k线,需先参照帮助文档下载k线
:param code: 股票代码
:param start: 开始时间,例如'2017-06-20'
:param end: 结束时间,例如'2017-06-30'
start和end的组合如下:
========== ========== ========================================
start类型 end类型 说明
========== ========== ========================================
str str start和end分别为指定的日期
None str start为end往前365天
str None end为start往后365天
None None end为当前日期,start为end往前365天
========== ========== ========================================
:param ktype: k线类型, 参见 KLType 定义
:param autype: 复权类型, 参见 AuType 定义
:param fields: 需返回的字段列表,参见 KL_FIELD 定义 KL_FIELD.ALL KL_FIELD.OPEN ....
:return: (ret, data)
ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下
ret != RET_OK 返回错误字符串
================= =========== ==============================================================================
参数 类型 说明
================= =========== ==============================================================================
code str 股票代码
time_key str k线时间
open float 开盘价
close float 收盘价
high float 最高价
low float 最低价
pe_ratio float 市盈率(该字段为比例字段,默认不展示%)
turnover_rate float 换手率
volume int 成交量
turnover float 成交额
change_rate float 涨跌幅
last_close float 昨收价
================= =========== ==============================================================================
:example:
.. code:: python
from futuquant import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
print(quote_ctx.get_history_kline('HK.00700', start='2017-06-20', end='2017-06-22'))
quote_ctx.close() | 3.467582 | 3.738527 | 0.927526 |
code_list = unique_and_normalize_list(code_list)
for code in code_list:
if code is None or is_str(code) is False:
error_str = ERROR_STR_PREFIX + "the type of param in code_list is wrong"
return RET_ERROR, error_str
query_processor = self._get_sync_query_processor(
ExrightQuery.pack_req, ExrightQuery.unpack_rsp)
kargs = {
"stock_list": code_list,
"conn_id": self.get_sync_conn_id()
}
ret_code, msg, exr_record = query_processor(**kargs)
if ret_code == RET_ERROR:
return ret_code, msg
col_list = [
'code', 'ex_div_date', 'split_ratio', 'per_cash_div',
'per_share_div_ratio', 'per_share_trans_ratio', 'allotment_ratio',
'allotment_price', 'stk_spo_ratio', 'stk_spo_price',
'forward_adj_factorA', 'forward_adj_factorB',
'backward_adj_factorA', 'backward_adj_factorB'
]
exr_frame_table = pd.DataFrame(exr_record, columns=col_list)
return RET_OK, exr_frame_table | def get_autype_list(self, code_list) | 获取给定股票列表的复权因子
:param code_list: 股票列表,例如['HK.00700']
:return: (ret, data)
ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下
ret != RET_OK 返回错误字符串
===================== =========== =================================================================================
参数 类型 说明
===================== =========== =================================================================================
code str 股票代码
ex_div_date str 除权除息日
split_ratio float 拆合股比例(该字段为比例字段,默认不展示%),例如,对于5股合1股为1/5,对于1股拆5股为5/1
per_cash_div float 每股派现
per_share_div_ratio float 每股送股比例(该字段为比例字段,默认不展示%)
per_share_trans_ratio float 每股转增股比例(该字段为比例字段,默认不展示%)
allotment_ratio float 每股配股比例(该字段为比例字段,默认不展示%)
allotment_price float 配股价
stk_spo_ratio float 增发比例(该字段为比例字段,默认不展示%)
stk_spo_price float 增发价格
forward_adj_factorA float 前复权因子A
forward_adj_factorB float 前复权因子B
backward_adj_factorA float 后复权因子A
backward_adj_factorB float 后复权因子B
===================== =========== ================================================================================= | 4.026952 | 2.479525 | 1.624082 |
if code is None or is_str(code) is False:
error_str = ERROR_STR_PREFIX + "the type of param in code is wrong"
return RET_ERROR, error_str
query_processor = self._get_sync_query_processor(
RtDataQuery.pack_req, RtDataQuery.unpack_rsp)
kargs = {
"code": code,
"conn_id": self.get_sync_conn_id()
}
ret_code, msg, rt_data_list = query_processor(**kargs)
if ret_code == RET_ERROR:
return ret_code, msg
for x in rt_data_list:
x['code'] = code
col_list = [
'code', 'time', 'is_blank', 'opened_mins', 'cur_price',
'last_close', 'avg_price', 'volume', 'turnover'
]
rt_data_table = pd.DataFrame(rt_data_list, columns=col_list)
return RET_OK, rt_data_table | def get_rt_data(self, code) | 获取指定股票的分时数据
:param code: 股票代码,例如,HK.00700,US.APPL
:return: (ret, data)
ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下
ret != RET_OK 返回错误字符串
===================== =========== ==========================================================================
参数 类型 说明
===================== =========== ==========================================================================
code str 股票代码
time str 时间(yyyy-MM-dd HH:mm:ss)(美股默认是美东时间,港股A股默认是北京时间)
is_blank bool 数据状态;正常数据为False,伪造数据为True
opened_mins int 零点到当前多少分钟
cur_price float 当前价格
last_close float 昨天收盘的价格
avg_price float 平均价格
volume float 成交量
turnover float 成交金额
===================== =========== ========================================================================== | 3.550553 | 2.756841 | 1.287906 |
param_table = {'market': market, 'plate_class': plate_class}
for x in param_table:
param = param_table[x]
if param is None or is_str(market) is False:
error_str = ERROR_STR_PREFIX + "the type of market param is wrong"
return RET_ERROR, error_str
if market not in MKT_MAP:
error_str = ERROR_STR_PREFIX + "the value of market param is wrong "
return RET_ERROR, error_str
if plate_class not in PLATE_CLASS_MAP:
error_str = ERROR_STR_PREFIX + "the class of plate is wrong"
return RET_ERROR, error_str
query_processor = self._get_sync_query_processor(
SubplateQuery.pack_req, SubplateQuery.unpack_rsp)
kargs = {
'market': market,
'plate_class': plate_class,
'conn_id': self.get_sync_conn_id()
}
ret_code, msg, subplate_list = query_processor(**kargs)
if ret_code == RET_ERROR:
return ret_code, msg
col_list = ['code', 'plate_name', 'plate_id']
subplate_frame_table = pd.DataFrame(subplate_list, columns=col_list)
return RET_OK, subplate_frame_table | def get_plate_list(self, market, plate_class) | 获取板块集合下的子板块列表
:param market: 市场标识,注意这里不区分沪,深,输入沪或者深都会返回沪深市场的子板块(这个是和客户端保持一致的)参见Market
:param plate_class: 板块分类,参见Plate
:return: ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下
ret != RET_OK 返回错误字符串
===================== =========== ==============================================================
参数 类型 说明
===================== =========== ==============================================================
code str 股票代码
plate_name str 板块名字
plate_id str 板块id
===================== =========== ============================================================== | 2.942764 | 2.667144 | 1.103339 |
if plate_code is None or is_str(plate_code) is False:
error_str = ERROR_STR_PREFIX + "the type of code is wrong"
return RET_ERROR, error_str
query_processor = self._get_sync_query_processor(
PlateStockQuery.pack_req, PlateStockQuery.unpack_rsp)
kargs = {
"plate_code": plate_code,
"conn_id": self.get_sync_conn_id()
}
ret_code, msg, plate_stock_list = query_processor(**kargs)
if ret_code == RET_ERROR:
return ret_code, msg
col_list = [
'code', 'lot_size', 'stock_name', 'stock_owner',
'stock_child_type', 'stock_type', 'list_time', 'stock_id',
]
plate_stock_table = pd.DataFrame(plate_stock_list, columns=col_list)
return RET_OK, plate_stock_table | def get_plate_stock(self, plate_code) | 获取特定板块下的股票列表
:param plate_code: 板块代码, string, 例如,”SH.BK0001”,”SH.BK0002”,先利用获取子版块列表函数获取子版块代码
:return: (ret, data)
ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下
ret != RET_OK 返回错误字符串
===================== =========== ==============================================================
参数 类型 说明
===================== =========== ==============================================================
code str 股票代码
lot_size int 每手股数
stock_name str 股票名称
stock_owner str 所属正股的代码
stock_child_type str 股票子类型,参见WrtType
stock_type str 股票类型,参见SecurityType
list_time str 上市时间(美股默认是美东时间,港股A股默认是北京时间)
stock_id int 股票id
===================== =========== ============================================================== | 3.478951 | 2.615363 | 1.330198 |
if code is None or is_str(code) is False:
error_str = ERROR_STR_PREFIX + "the type of param in code is wrong"
return RET_ERROR, error_str
query_processor = self._get_sync_query_processor(
BrokerQueueQuery.pack_req, BrokerQueueQuery.unpack_rsp)
kargs = {
"code": code,
"conn_id": self.get_sync_conn_id()
}
ret_code, ret_msg, content = query_processor(**kargs)
if ret_code != RET_OK:
return ret_code, ret_msg, ret_msg
(_, bid_list, ask_list) = content
col_bid_list = [
'code', 'bid_broker_id', 'bid_broker_name', 'bid_broker_pos'
]
col_ask_list = [
'code', 'ask_broker_id', 'ask_broker_name', 'ask_broker_pos'
]
bid_frame_table = pd.DataFrame(bid_list, columns=col_bid_list)
ask_frame_table = pd.DataFrame(ask_list, columns=col_ask_list)
return RET_OK, bid_frame_table, ask_frame_table | def get_broker_queue(self, code) | 获取股票的经纪队列
:param code: 股票代码
:return: (ret, bid_frame_table, ask_frame_table)或(ret, err_message)
ret == RET_OK 返回pd dataframe数据,数据列格式如下
ret != RET_OK 后面两项为错误字符串
bid_frame_table 经纪买盘数据
===================== =========== ==============================================================
参数 类型 说明
===================== =========== ==============================================================
code str 股票代码
bid_broker_id int 经纪买盘id
bid_broker_name str 经纪买盘名称
bid_broker_pos int 经纪档位
===================== =========== ==============================================================
ask_frame_table 经纪卖盘数据
===================== =========== ==============================================================
参数 类型 说明
===================== =========== ==============================================================
code str 股票代码
ask_broker_id int 经纪卖盘id
ask_broker_name str 经纪卖盘名称
ask_broker_pos int 经纪档位
===================== =========== ============================================================== | 2.866831 | 2.317961 | 1.23679 |
return self._subscribe_impl(code_list, subtype_list, is_first_push) | def subscribe(self, code_list, subtype_list, is_first_push=True) | 订阅注册需要的实时信息,指定股票和订阅的数据类型即可
注意:len(code_list) * 订阅的K线类型的数量 <= 100
:param code_list: 需要订阅的股票代码列表
:param subtype_list: 需要订阅的数据类型列表,参见SubType
:param is_first_push: 订阅成功后是否马上推送一次数据
:return: (ret, err_message)
ret == RET_OK err_message为None
ret != RET_OK err_message为错误描述字符串
:example:
.. code:: python
from futuquant import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
print(quote_ctx.subscribe(['HK.00700'], [SubType.QUOTE)])
quote_ctx.close() | 3.263302 | 6.653006 | 0.4905 |
ret, msg, code_list, subtype_list = self._check_subscribe_param(code_list, subtype_list)
if ret != RET_OK:
return ret, msg
query_processor = self._get_sync_query_processor(SubscriptionQuery.pack_unsubscribe_req,
SubscriptionQuery.unpack_unsubscribe_rsp)
kargs = {
'code_list': code_list,
'subtype_list': subtype_list,
"conn_id": self.get_sync_conn_id()
}
for subtype in subtype_list:
if subtype not in self._ctx_subscribe:
continue
code_set = self._ctx_subscribe[subtype]
for code in code_list:
if code not in code_set:
continue
code_set.remove(code)
ret_code, msg, _ = query_processor(**kargs)
if ret_code != RET_OK:
return RET_ERROR, msg
ret_code, msg, unpush_req_str = SubscriptionQuery.pack_unpush_req(code_list, subtype_list, self.get_async_conn_id())
if ret_code != RET_OK:
return RET_ERROR, msg
ret_code, msg = self._send_async_req(unpush_req_str)
if ret_code != RET_OK:
return RET_ERROR, msg
return RET_OK, None | def unsubscribe(self, code_list, subtype_list) | 取消订阅
:param code_list: 取消订阅的股票代码列表
:param subtype_list: 取消订阅的类型,参见SubType
:return: (ret, err_message)
ret == RET_OK err_message为None
ret != RET_OK err_message为错误描述字符串 | 2.439428 | 2.396402 | 1.017955 |
is_all_conn = bool(is_all_conn)
query_processor = self._get_sync_query_processor(
SubscriptionQuery.pack_subscription_query_req,
SubscriptionQuery.unpack_subscription_query_rsp)
kargs = {
"is_all_conn": is_all_conn,
"conn_id": self.get_sync_conn_id()
}
ret_code, msg, sub_table = query_processor(**kargs)
if ret_code == RET_ERROR:
return ret_code, msg
ret_dict = {}
ret_dict['total_used'] = sub_table['total_used']
ret_dict['remain'] = sub_table['remain']
ret_dict['own_used'] = 0
ret_dict['sub_list'] = {}
for conn_sub in sub_table['conn_sub_list']:
is_own_conn = conn_sub['is_own_conn']
if is_own_conn:
ret_dict['own_used'] = conn_sub['used']
if not is_all_conn and not is_own_conn:
continue
for sub_info in conn_sub['sub_list']:
subtype = sub_info['subtype']
if subtype not in ret_dict['sub_list']:
ret_dict['sub_list'][subtype] = []
code_list = ret_dict['sub_list'][subtype]
for code in sub_info['code_list']:
if code not in code_list:
code_list.append(code)
return RET_OK, ret_dict | def query_subscription(self, is_all_conn=True) | 查询已订阅的实时信息
:param is_all_conn: 是否返回所有连接的订阅状态,不传或者传False只返回当前连接数据
:return: (ret, data)
ret != RET_OK 返回错误字符串
ret == RET_OK 返回 定阅信息的字典数据 ,格式如下:
{
'total_used': 4, # 所有连接已使用的定阅额度
'own_used': 0, # 当前连接已使用的定阅额度
'remain': 496, # 剩余的定阅额度
'sub_list': # 每种定阅类型对应的股票列表
{
'BROKER': ['HK.00700', 'HK.02318'],
'RT_DATA': ['HK.00700', 'HK.02318']
}
} | 2.505586 | 2.212219 | 1.132612 |
code_list = unique_and_normalize_list(code_list)
if not code_list:
error_str = ERROR_STR_PREFIX + "the type of code_list param is wrong"
return RET_ERROR, error_str
query_processor = self._get_sync_query_processor(
StockQuoteQuery.pack_req,
StockQuoteQuery.unpack_rsp,
)
kargs = {
"stock_list": code_list,
"conn_id": self.get_sync_conn_id()
}
ret_code, msg, quote_list = query_processor(**kargs)
if ret_code == RET_ERROR:
return ret_code, msg
col_list = [
'code', 'data_date', 'data_time', 'last_price', 'open_price',
'high_price', 'low_price', 'prev_close_price', 'volume',
'turnover', 'turnover_rate', 'amplitude', 'suspension',
'listing_date', 'price_spread', 'dark_status', 'strike_price',
'contract_size', 'open_interest', 'implied_volatility',
'premium', 'delta', 'gamma', 'vega', 'theta', 'rho'
]
quote_frame_table = pd.DataFrame(quote_list, columns=col_list)
return RET_OK, quote_frame_table | def get_stock_quote(self, code_list) | 获取订阅股票报价的实时数据,有订阅要求限制。
对于异步推送,参见StockQuoteHandlerBase
:param code_list: 股票代码列表,必须确保code_list中的股票均订阅成功后才能够执行
:return: (ret, data)
ret == RET_OK 返回pd dataframe数据,数据列格式如下
ret != RET_OK 返回错误字符串
===================== =========== ==============================================================
参数 类型 说明
===================== =========== ==============================================================
code str 股票代码
data_date str 日期
data_time str 时间(美股默认是美东时间,港股A股默认是北京时间)
last_price float 最新价格
open_price float 今日开盘价
high_price float 最高价格
low_price float 最低价格
prev_close_price float 昨收盘价格
volume int 成交数量
turnover float 成交金额
turnover_rate float 换手率
amplitude int 振幅
suspension bool 是否停牌(True表示停牌)
listing_date str 上市日期 (yyyy-MM-dd)
price_spread float 当前价差,亦即摆盘数据的买档或卖档的相邻档位的报价差
dark_status str 暗盘交易状态,见DarkStatus
strike_price float 行权价
contract_size int 每份合约数
open_interest int 未平仓合约数
implied_volatility float 隐含波动率
premium float 溢价
delta float 希腊值 Delta
gamma float 希腊值 Gamma
vega float 希腊值 Vega
theta float 希腊值 Theta
rho float 希腊值 Rho
===================== =========== ============================================================== | 3.180295 | 2.170569 | 1.46519 |
if code is None or is_str(code) is False:
error_str = ERROR_STR_PREFIX + "the type of code param is wrong"
return RET_ERROR, error_str
if num is None or isinstance(num, int) is False:
error_str = ERROR_STR_PREFIX + "the type of num param is wrong"
return RET_ERROR, error_str
query_processor = self._get_sync_query_processor(
TickerQuery.pack_req,
TickerQuery.unpack_rsp,
)
kargs = {
"code": code,
"num": num,
"conn_id": self.get_sync_conn_id()
}
ret_code, msg, ticker_list = query_processor(**kargs)
if ret_code == RET_ERROR:
return ret_code, msg
col_list = [
'code', 'time', 'price', 'volume', 'turnover', "ticker_direction",
'sequence', 'type'
]
ticker_frame_table = pd.DataFrame(ticker_list, columns=col_list)
return RET_OK, ticker_frame_table | def get_rt_ticker(self, code, num=500) | 获取指定股票的实时逐笔。取最近num个逐笔
:param code: 股票代码
:param num: 最近ticker个数(有最大个数限制,最近1000个)
:return: (ret, data)
ret == RET_OK 返回pd dataframe数据,数据列格式如下
ret != RET_OK 返回错误字符串
===================== =========== ==============================================================
参数 类型 说明
===================== =========== ==============================================================
stock_code str 股票代码
sequence int 逐笔序号
time str 成交时间(美股默认是美东时间,港股A股默认是北京时间)
price float 成交价格
volume int 成交数量(股数)
turnover float 成交金额
ticker_direction str 逐笔方向
type str 逐笔类型,参见TickerType
===================== =========== ============================================================== | 2.852355 | 2.43496 | 1.171418 |
param_table = {'code': code, 'ktype': ktype}
for x in param_table:
param = param_table[x]
if param is None or is_str(param) is False:
error_str = ERROR_STR_PREFIX + "the type of %s param is wrong" % x
return RET_ERROR, error_str
if num is None or isinstance(num, int) is False:
error_str = ERROR_STR_PREFIX + "the type of num param is wrong"
return RET_ERROR, error_str
if autype is not None and is_str(autype) is False:
error_str = ERROR_STR_PREFIX + "the type of autype param is wrong"
return RET_ERROR, error_str
query_processor = self._get_sync_query_processor(
CurKlineQuery.pack_req,
CurKlineQuery.unpack_rsp,
)
kargs = {
"code": code,
"num": num,
"ktype": ktype,
"autype": autype,
"conn_id": self.get_sync_conn_id()
}
ret_code, msg, kline_list = query_processor(**kargs)
if ret_code == RET_ERROR:
return ret_code, msg
col_list = [
'code', 'time_key', 'open', 'close', 'high', 'low', 'volume',
'turnover', 'pe_ratio', 'turnover_rate', 'last_close'
]
kline_frame_table = pd.DataFrame(kline_list, columns=col_list)
return RET_OK, kline_frame_table | def get_cur_kline(self, code, num, ktype=SubType.K_DAY, autype=AuType.QFQ) | 实时获取指定股票最近num个K线数据,最多1000根
:param code: 股票代码
:param num: k线数据个数
:param ktype: k线类型,参见KLType
:param autype: 复权类型,参见AuType
:return: (ret, data)
ret == RET_OK 返回pd dataframe数据,数据列格式如下
ret != RET_OK 返回错误字符串
===================== =========== ==============================================================
参数 类型 说明
===================== =========== ==============================================================
code str 股票代码
time_key str 时间(美股默认是美东时间,港股A股默认是北京时间)
open float 开盘价
close float 收盘价
high float 最高价
low float 最低价
volume int 成交量
turnover float 成交额
pe_ratio float 市盈率(该字段为比例字段,默认不展示%)
turnover_rate float 换手率
last_close float 昨收价
===================== =========== ============================================================== | 2.288502 | 2.133649 | 1.072577 |
if code is None or is_str(code) is False:
error_str = ERROR_STR_PREFIX + "the type of code param is wrong"
return RET_ERROR, error_str
query_processor = self._get_sync_query_processor(
OrderBookQuery.pack_req,
OrderBookQuery.unpack_rsp,
)
kargs = {
"code": code,
"conn_id": self.get_sync_conn_id()
}
ret_code, msg, orderbook = query_processor(**kargs)
if ret_code == RET_ERROR:
return ret_code, msg
return RET_OK, orderbook | def get_order_book(self, code) | 获取实时摆盘数据
:param code: 股票代码
:return: (ret, data)
ret == RET_OK 返回字典,数据格式如下
ret != RET_OK 返回错误字符串
{‘code’: 股票代码
‘Ask’:[ (ask_price1, ask_volume1,order_num), (ask_price2, ask_volume2, order_num),…]
‘Bid’: [ (bid_price1, bid_volume1, order_num), (bid_price2, bid_volume2, order_num),…]
}
'Ask':卖盘, 'Bid'买盘。每个元组的含义是(委托价格,委托数量,委托订单数) | 3.343067 | 3.444634 | 0.970514 |
if code is None or is_str(code) is False:
error_str = ERROR_STR_PREFIX + "the type of code param is wrong"
return RET_ERROR, error_str
query_processor = self._get_sync_query_processor(
StockReferenceList.pack_req,
StockReferenceList.unpack_rsp,
)
kargs = {
"code": code,
'ref_type': reference_type,
"conn_id": self.get_sync_conn_id()
}
ret_code, msg, data_list = query_processor(**kargs)
if ret_code == RET_ERROR:
return ret_code, msg
col_list = [
'code', 'lot_size', 'stock_type', 'stock_name', 'list_time', 'wrt_valid', 'wrt_type', 'wrt_code'
]
pd_frame = pd.DataFrame(data_list, columns=col_list)
return RET_OK, pd_frame | def get_referencestock_list(self, code, reference_type) | 获取证券的关联数据
:param code: 证券id,str,例如HK.00700
:param reference_type: 要获得的相关数据,参见SecurityReferenceType。例如WARRANT,表示获取正股相关的涡轮
:return: (ret, data)
ret == RET_OK 返回pd dataframe数据,数据列格式如下
ret != RET_OK 返回错误字符串
================= =========== ==============================================================================
参数 类型 说明
================= =========== ==============================================================================
code str 证券代码
lot_size int 每手数量
stock_type str 证券类型,参见SecurityType
stock_name str 证券名字
list_time str 上市时间(美股默认是美东时间,港股A股默认是北京时间)
wrt_valid bool 是否是涡轮,如果为True,下面wrt开头的字段有效
wrt_type str 涡轮类型,参见WrtType
wrt_code str 所属正股
================= =========== ============================================================================== | 3.707133 | 2.643709 | 1.402247 |
if is_str(code_list):
code_list = code_list.split(',')
elif isinstance(code_list, list):
pass
else:
return RET_ERROR, "code list must be like ['HK.00001', 'HK.00700'] or 'HK.00001,HK.00700'"
code_list = unique_and_normalize_list(code_list)
for code in code_list:
if code is None or is_str(code) is False:
error_str = ERROR_STR_PREFIX + "the type of param in code_list is wrong"
return RET_ERROR, error_str
query_processor = self._get_sync_query_processor(
OwnerPlateQuery.pack_req, OwnerPlateQuery.unpack_rsp)
kargs = {
"code_list": code_list,
"conn_id": self.get_sync_conn_id()
}
ret_code, msg, owner_plate_list = query_processor(**kargs)
if ret_code == RET_ERROR:
return ret_code, msg
col_list = [
'code', 'plate_code', 'plate_name', 'plate_type'
]
owner_plate_table = pd.DataFrame(owner_plate_list, columns=col_list)
return RET_OK, owner_plate_table | def get_owner_plate(self, code_list) | 获取单支或多支股票的所属板块信息列表
:param code_list: 股票代码列表,仅支持正股、指数。list或str。例如:['HK.00700', 'HK.00001']或者'HK.00700,HK.00001'。
:return: (ret, data)
ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下
ret != RET_OK 返回错误字符串
===================== =========== ==============================================================
参数 类型 说明
===================== =========== ==============================================================
code str 证券代码
plate_code str 板块代码
plate_name str 板块名字
plate_type str 板块类型(行业板块或概念板块),futuquant.common.constant.Plate
===================== =========== ============================================================== | 2.86773 | 2.436142 | 1.17716 |
holder_type = STOCK_HOLDER_CLASS_MAP[holder_type]
if code is None or is_str(code) is False:
msg = ERROR_STR_PREFIX + "the type of code param is wrong"
return RET_ERROR, msg
if holder_type < 1 or holder_type > len(STOCK_HOLDER_CLASS_MAP):
msg = ERROR_STR_PREFIX + "the type {0} is wrong, total number of types is {1}".format(holder_type, len(STOCK_HOLDER_CLASS_MAP))
return RET_ERROR, msg
ret_code, msg, start, end = normalize_start_end_date(start, end, delta_days=365)
if ret_code != RET_OK:
return ret_code, msg
query_processor = self._get_sync_query_processor(
HoldingChangeList.pack_req, HoldingChangeList.unpack_rsp)
kargs = {
"code": code,
"holder_type": holder_type,
"conn_id": self.get_sync_conn_id(),
"start_date": start,
"end_date": end
}
ret_code, msg, owner_plate_list = query_processor(**kargs)
if ret_code == RET_ERROR:
return ret_code, msg
col_list = [
'holder_name', 'holding_qty', 'holding_ratio', 'change_qty', 'change_ratio', 'time'
]
holding_change_list = pd.DataFrame(owner_plate_list, columns=col_list)
return RET_OK, holding_change_list | def get_holding_change_list(self, code, holder_type, start=None, end=None) | 获取大股东持股变动列表,只提供美股数据
:param code: 股票代码. 例如:'US.AAPL'
:param holder_type: 持有者类别,StockHolder_
:param start: 开始时间. 例如:'2016-10-01'
:param end: 结束时间,例如:'2017-10-01'。
start与end的组合如下:
========== ========== ========================================
start类型 end类型 说明
========== ========== ========================================
str str start和end分别为指定的日期
None str start为end往前365天
str None end为start往后365天
None None end为当前日期,start为end往前365天
========== ========== ========================================
:return: (ret, data)
ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下
ret != RET_OK 返回错误字符串
===================== =========== ==============================================================
参数 类型 说明
===================== =========== ==============================================================
holder_name str 高管名称
holding_qty float 持股数
holding_ratio float 持股比例(该字段为比例字段,默认不展示%)
change_qty float 变动数
change_ratio float 变动比例(该字段为比例字段,默认不展示%)
time str 发布时间(美股的时间默认是美东)
===================== =========== ============================================================== | 2.944136 | 2.666822 | 1.103987 |
if code is None or is_str(code) is False:
error_str = ERROR_STR_PREFIX + "the type of code param is wrong"
return RET_ERROR, error_str
ret_code, msg, start, end = normalize_start_end_date(start, end, delta_days=29, default_time_end='00:00:00', prefer_end_now=False)
if ret_code != RET_OK:
return ret_code, msg
query_processor = self._get_sync_query_processor(
OptionChain.pack_req, OptionChain.unpack_rsp)
kargs = {
"code": code,
"conn_id": self.get_sync_conn_id(),
"start_date": start,
"end_date": end,
"option_cond_type": option_cond_type,
"option_type": option_type
}
ret_code, msg, option_chain_list = query_processor(**kargs)
if ret_code == RET_ERROR:
return ret_code, msg
col_list = [
'code', 'name', 'lot_size', 'stock_type',
'option_type', 'stock_owner', 'strike_time', 'strike_price', 'suspension',
'stock_id'
]
option_chain = pd.DataFrame(option_chain_list, columns=col_list)
option_chain.sort_values(by=["strike_time", "strike_price"], axis=0, ascending=True, inplace=True)
option_chain.index = range(len(option_chain))
return RET_OK, option_chain | def get_option_chain(self, code, start=None, end=None, option_type=OptionType.ALL, option_cond_type=OptionCondType.ALL) | 通过标的股查询期权
:param code: 股票代码,例如:'HK.02318'
:param start: 开始日期,该日期指到期日,例如'2017-08-01'
:param end: 结束日期(包括这一天),该日期指到期日,例如'2017-08-30'。 注意,时间范围最多30天
start和end的组合如下:
========== ========== ========================================
start类型 end类型 说明
========== ========== ========================================
str str start和end分别为指定的日期
None str start为end往前30天
str None end为start往后30天
None None start为当前日期,end往后30天
========== ========== ========================================
:param option_type: 期权类型,默认全部,全部/看涨/看跌,futuquant.common.constant.OptionType
:param option_cond_type: 默认全部,全部/价内/价外,futuquant.common.constant.OptionCondType
:return: (ret, data)
ret == RET_OK 返回pd dataframe数据,数据列格式如下
ret != RET_OK 返回错误字符串
================== =========== ==============================================================
参数 类型 说明
================== =========== ==============================================================
code str 股票代码
name str 名字
lot_size int 每手数量
stock_type str 股票类型,参见SecurityType
option_type str 期权类型,Qot_Common.OptionType
stock_owner str 标的股
strike_time str 行权日(美股默认是美东时间,港股A股默认是北京时间)
strike_price float 行权价
suspension bool 是否停牌(True表示停牌)
stock_id int 股票id
================== =========== ============================================================== | 2.959546 | 2.369012 | 1.249274 |
if code is None or is_str(code) is False:
error_str = ERROR_STR_PREFIX + "the type of code param is wrong"
return RET_ERROR, error_str
query_processor = self._get_sync_query_processor(
OrderDetail.pack_req, OrderDetail.unpack_rsp)
kargs = {
"code": code,
"conn_id": self.get_sync_conn_id()
}
ret_code, msg, order_detail = query_processor(**kargs)
if ret_code == RET_ERROR:
return ret_code, msg
return RET_OK, order_detail | def get_order_detail(self, code) | 查询A股Level 2权限下提供的委托明细
:param code: 股票代码,例如:'HK.02318'
:return: (ret, data)
ret == RET_OK data为1个dict,包含以下数据
ret != RET_OK data为错误字符串
{‘code’: 股票代码
‘Ask’:[ order_num, [order_volume1, order_volume2] ]
‘Bid’: [ order_num, [order_volume1, order_volume2] ]
}
'Ask':卖盘, 'Bid'买盘。order_num指委托订单数量,order_volume是每笔委托的委托量,当前最多返回前50笔委托的委托数量。即order_num有可能多于后面的order_volume | 3.40765 | 3.323558 | 1.025302 |
'''
订阅多只股票的行情数据
:return:
'''
logger = Logs().getNewLogger('allStockQoutation', QoutationAsynPush.dir)
markets= [Market.HK,Market.US,Market.SH,Market.SZ] #,Market.HK_FUTURE,Market.US_OPTION
stockTypes = [SecurityType.STOCK,SecurityType.WARRANT,SecurityType.IDX,SecurityType.BOND,SecurityType.ETF]
for stockType in stockTypes:
for market in markets:
ret_code_stock_basicinfo ,ret_data_stock_basicinfo = self.quote_ctx.get_stock_basicinfo(market,stockType)
codes = ret_data_stock_basicinfo['code'].tolist()
codes_len = len(codes)
code_sub = 0
code_sub_succ = 0
for code in codes:
ret_code = self.aStockQoutation(code)
code_sub += 1
if ret_code is RET_OK:
code_sub_succ += 1
logger.info('市场 = %s,股票类型 = %s, 股票总数 = %d, 已发起订阅 = %d,订阅成功 = %d' % (market, stockType, codes_len, code_sub,code_sub_succ)) # 记录
logger.info('end-------->市场 = %s,股票类型 = %s, 股票总数 = %d, 已发起订阅 = %d,订阅成功 = %d' % ( market, stockType, codes_len, code_sub,code_sub_succ)) # 记录
time.sleep(5)
self.quote_ctx.stop()
self.quote_ctx.close() | def allStockQoutation(self) | 订阅多只股票的行情数据
:return: | 3.27142 | 3.14146 | 1.041369 |
'''
订阅一只股票的实时行情数据,接收推送
:param code: 股票代码
:return:
'''
#设置监听-->订阅-->调用接口
# 分时
self.quote_ctx.set_handler(RTDataTest())
self.quote_ctx.subscribe(code, SubType.RT_DATA)
ret_code_rt_data, ret_data_rt_data = self.quote_ctx.get_rt_data(code)
# 逐笔
self.quote_ctx.set_handler(TickerTest())
self.quote_ctx.subscribe(code, SubType.TICKER)
ret_code_rt_ticker, ret_data_rt_ticker = self.quote_ctx.get_rt_ticker(code)
# 报价
self.quote_ctx.set_handler(StockQuoteTest())
self.quote_ctx.subscribe(code, SubType.QUOTE)
ret_code_stock_quote, ret_data_stock_quote = self.quote_ctx.get_stock_quote([code])
# 实时K线
self.quote_ctx.set_handler(CurKlineTest())
kTypes = [SubType.K_1M, SubType.K_5M, SubType.K_15M, SubType.K_30M, SubType.K_60M, SubType.K_DAY,
SubType.K_WEEK, SubType.K_MON]
auTypes = [AuType.NONE, AuType.QFQ, AuType.HFQ]
num = 10
ret_code_cur_kline = RET_OK
for kType in kTypes:
self.quote_ctx.subscribe(code, kType)
for auType in auTypes:
ret_code_cur_kline_temp, ret_data_cur_kline = self.quote_ctx.get_cur_kline(code, num, kType, auType)
if ret_code_cur_kline_temp is RET_ERROR:
ret_code_cur_kline = RET_ERROR
# 摆盘
self.quote_ctx.set_handler(OrderBookTest())
self.quote_ctx.subscribe(code, SubType.ORDER_BOOK)
ret_code_order_book, ret_data_order_book = self.quote_ctx.get_order_book(code)
# 经纪队列
self.quote_ctx.set_handler(BrokerTest())
self.quote_ctx.subscribe(code, SubType.BROKER)
ret_code_broker_queue, bid_frame_table, ask_frame_table = self.quote_ctx.get_broker_queue(code)
return ret_code_rt_data+ret_code_rt_ticker+ret_code_stock_quote+ret_code_cur_kline+ret_code_order_book+ret_code_broker_queue | def aStockQoutation(self,code) | 订阅一只股票的实时行情数据,接收推送
:param code: 股票代码
:return: | 2.107579 | 2.014681 | 1.04611 |
bar = tiny_bar
symbol = bar.symbol
price = bar.open
up, down = self.track(symbol)
now = datetime.datetime.now()
work_time = now.replace(hour=9, minute=30, second=0)
if now == work_time:
self.before_minute_price = price
return
if self.before_minute_price == 0:
self.before_minute_price = price
return
if self.before_minute_price < up and price > up:
self.do_trade(symbol, price, "buy")
elif self.before_minute_price > down and price < down:
self.do_trade(symbol, price, "sell")
self.before_minute_price = price | def on_bar_min1(self, tiny_bar) | 每一分钟触发一次回调 | 2.836279 | 2.804505 | 1.01133 |
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
now = datetime.datetime.now()
end_str = now.strftime('%Y-%m-%d')
start = now - datetime.timedelta(days=365)
start_str = start.strftime('%Y-%m-%d')
_, temp = quote_ctx.get_history_kline(symbol, start=start_str, end=end_str)
#print(temp)
high = temp['high'].values
low = temp['low'].values
open = temp['open'].values
'''
y_amplitude = []
for i in range(len(high)):
temp = high[i] - low[i]
y_amplitude.append(temp)
'''
y_amplitude = high - low
print(y_amplitude)
y_a_r = y_amplitude[-1] / open[-2]
if y_a_r > 0.05:
up_ = open[-1] + 0.5 * y_amplitude[-1]
down_ = open[-1] - 0.5 * y_amplitude[-1]
else:
up_ = open[-1] + 2 / 3 * y_amplitude[-1]
down_ = open[-1] - 2 / 3 * y_amplitude[-1]
#print(up_, down_)
return up_, down_ | def track(self, symbol) | 确定上下轨 | 2.489028 | 2.390671 | 1.041142 |
with self._mgr_lock:
with self._lock:
self._use_count += 1
if self._thread is None:
self._create_all()
self._thread = threading.Thread(target=self._thread_func)
self._thread.setDaemon(SysConfig.get_all_thread_daemon())
self._thread.start() | def start(self) | Should be called from main thread
:return: | 4.679489 | 4.811219 | 0.97262 |
obj = cls()
for field in obj.DESCRIPTOR.fields:
if not field.label == field.LABEL_REQUIRED:
continue
if not field.has_default_value:
continue
if not field.name in adict:
raise ConvertException('Field "%s" missing from descriptor dictionary.'
% field.name)
field_names = set([field.name for field in obj.DESCRIPTOR.fields])
if strict:
for key in adict.keys():
if key not in field_names:
raise ConvertException(
'Key "%s" can not be mapped to field in %s class.'
% (key, type(obj)))
for field in obj.DESCRIPTOR.fields:
if not field.name in adict:
continue
msg_type = field.message_type
if field.label == FD.LABEL_REPEATED:
if field.type == FD.TYPE_MESSAGE:
for sub_dict in adict[field.name]:
item = getattr(obj, field.name).add()
item.CopyFrom(dict2pb(msg_type._concrete_class, sub_dict))
else:
# fix python3 map用法变更
list(map(getattr(obj, field.name).append, adict[field.name]))
else:
if field.type == FD.TYPE_MESSAGE:
value = dict2pb(msg_type._concrete_class, adict[field.name])
getattr(obj, field.name).CopyFrom(value)
elif field.type in [FD.TYPE_UINT64, FD.TYPE_INT64, FD.TYPE_SINT64]:
setattr(obj, field.name, int(adict[field.name]))
else:
setattr(obj, field.name, adict[field.name])
return obj | def dict2pb(cls, adict, strict=False) | Takes a class representing the ProtoBuf Message and fills it with data from
the dict. | 2.280597 | 2.252966 | 1.012264 |
adict = {}
if not obj.IsInitialized():
return None
for field in obj.DESCRIPTOR.fields:
if not getattr(obj, field.name):
continue
if not field.label == FD.LABEL_REPEATED:
if not field.type == FD.TYPE_MESSAGE:
adict[field.name] = getattr(obj, field.name)
else:
value = pb2dict(getattr(obj, field.name))
if value:
adict[field.name] = value
else:
if field.type == FD.TYPE_MESSAGE:
adict[field.name] = \
[pb2dict(v) for v in getattr(obj, field.name)]
else:
adict[field.name] = [v for v in getattr(obj, field.name)]
return adict | def pb2dict(obj) | Takes a ProtoBuf Message obj and convertes it to a dict. | 1.775545 | 1.688292 | 1.051681 |
return dict2pb(cls, simplejson.loads(json), strict) | def json2pb(cls, json, strict=False) | Takes a class representing the Protobuf Message and fills it with data from
the json string. | 8.744045 | 12.213 | 0.715962 |
'''pre handler push
return: ret_error or ret_ok
'''
set_flag = False
for protoc in self._pre_handler_table:
if isinstance(handler, self._pre_handler_table[protoc]["type"]):
self._pre_handler_table[protoc]["obj"] = handler
return RET_OK
if set_flag is False:
return RET_ERROR | def set_pre_handler(self, handler) | pre handler push
return: ret_error or ret_ok | 6.844096 | 4.327336 | 1.581596 |
set_flag = False
for protoc in self._handler_table:
if isinstance(handler, self._handler_table[protoc]["type"]):
self._handler_table[protoc]["obj"] = handler
return RET_OK
if set_flag is False:
return RET_ERROR | def set_handler(self, handler) | set the callback processing object to be used by the receiving thread after receiving the data.User should set
their own callback object setting in order to achieve event driven.
:param handler:the object in callback handler base
:return: ret_error or ret_ok | 5.864461 | 5.071631 | 1.156326 |
if self.cb_check_recv is not None and not self.cb_check_recv() and ProtoId.is_proto_id_push(proto_id):
return
handler = self._default_handler
pre_handler = None
if proto_id in self._handler_table:
handler = self._handler_table[proto_id]['obj']
if proto_id in self._pre_handler_table:
pre_handler = self._pre_handler_table[proto_id]['obj']
if pre_handler is not None:
pre_handler.on_recv_rsp(rsp_pb)
handler.on_recv_rsp(rsp_pb) | def recv_func(self, rsp_pb, proto_id) | receive response callback function | 2.836078 | 2.802464 | 1.011995 |
if rsp_pb.retType != RET_OK:
return RET_ERROR, rsp_pb.retMsg, None
raw_acc_list = rsp_pb.s2c.accList
acc_list = [{
'acc_id': record.accID,
'trd_env': TRADE.REV_TRD_ENV_MAP[record.trdEnv] if record.trdEnv in TRADE.REV_TRD_ENV_MAP else "",
'trdMarket_list': [(TRADE.REV_TRD_MKT_MAP[trdMkt] if trdMkt in TRADE.REV_TRD_MKT_MAP else TrdMarket.NONE) for trdMkt in record.trdMarketAuthList]
} for record in raw_acc_list]
return RET_OK, "", acc_list | def unpack_rsp(cls, rsp_pb) | Convert from PLS response to user response | 3.6114 | 3.581545 | 1.008336 |
from futuquant.common.pb.Trd_UnlockTrade_pb2 import Request
req = Request()
req.c2s.unlock = is_unlock
req.c2s.pwdMD5 = password_md5
return pack_pb_req(req, ProtoId.Trd_UnlockTrade, conn_id) | def pack_req(cls, is_unlock, password_md5, conn_id) | Convert from user request for trading days to PLS request | 3.484351 | 3.48436 | 0.999997 |
if rsp_pb.retType != RET_OK:
return RET_ERROR, rsp_pb.retMsg, None
if rsp_pb.HasField('retMsg'):
return RET_OK, rsp_pb.retMsg, None
return RET_OK, "", None | def unpack_rsp(cls, rsp_pb) | Convert from PLS response to user response | 4.002852 | 3.767695 | 1.062414 |
if rsp_pb.retType != RET_OK:
return RET_ERROR, rsp_pb.retMsg, None
return RET_OK, "", None | def unpack_rsp(cls, rsp_pb) | Convert from PLS response to user response | 5.64997 | 5.395726 | 1.047119 |
if rsp_pb.retType != RET_OK:
return RET_ERROR, rsp_pb.retMsg, None
raw_funds = rsp_pb.s2c.funds
accinfo_list = [{
'power': raw_funds.power,
'total_assets': raw_funds.totalAssets,
'cash': raw_funds.cash,
'market_val': raw_funds.marketVal,
'frozen_cash': raw_funds.frozenCash,
'avl_withdrawal_cash': raw_funds.avlWithdrawalCash,
}]
return RET_OK, "", accinfo_list | def unpack_rsp(cls, rsp_pb) | Convert from PLS response to user response | 3.210912 | 3.193005 | 1.005608 |
from futuquant.common.pb.Trd_GetPositionList_pb2 import Request
req = Request()
req.c2s.header.trdEnv = TRD_ENV_MAP[trd_env]
req.c2s.header.accID = acc_id
req.c2s.header.trdMarket = TRD_MKT_MAP[trd_mkt]
if code:
req.c2s.filterConditions.codeList.append(code)
if pl_ratio_min is not None:
req.c2s.filterPLRatioMin = float(pl_ratio_min) / 100.0
if pl_ratio_max is not None:
req.c2s.filterPLRatioMax = float(pl_ratio_max) / 100.0
return pack_pb_req(req, ProtoId.Trd_GetPositionList, conn_id) | def pack_req(cls, code, pl_ratio_min,
pl_ratio_max, trd_env, acc_id, trd_mkt, conn_id) | Convert from user request for trading days to PLS request | 2.087986 | 2.193773 | 0.951779 |
if rsp_pb.retType != RET_OK:
return RET_ERROR, rsp_pb.retMsg, None
raw_position_list = rsp_pb.s2c.positionList
position_list = [{
"code": merge_trd_mkt_stock_str(rsp_pb.s2c.header.trdMarket, position.code),
"stock_name": position.name,
"qty": position.qty,
"can_sell_qty": position.canSellQty,
"cost_price": position.costPrice if position.HasField('costPrice') else 0,
"cost_price_valid": 1 if position.HasField('costPrice') else 0,
"market_val": position.val,
"nominal_price": position.price,
"pl_ratio": 100 * position.plRatio if position.HasField('plRatio') else 0,
"pl_ratio_valid": 1 if position.HasField('plRatio') else 0,
"pl_val": position.plVal if position.HasField('plVal') else 0,
"pl_val_valid": 1 if position.HasField('plVal') else 0,
"today_buy_qty": position.td_buyQty if position.HasField('td_buyQty') else 0,
"today_buy_val": position.td_buyVal if position.HasField('td_buyVal') else 0,
"today_pl_val": position.td_plVal if position.HasField('td_plVal') else 0,
"today_sell_qty": position.td_sellQty if position.HasField('td_sellQty') else 0,
"today_sell_val": position.td_sellVal if position.HasField('td_sellVal') else 0,
"position_side": TRADE.REV_POSITION_SIDE_MAP[position.positionSide]
if position.positionSide in TRADE.REV_POSITION_SIDE_MAP else PositionSide.NONE,
} for position in raw_position_list]
return RET_OK, "", position_list | def unpack_rsp(cls, rsp_pb) | Convert from PLS response to user response | 2.307099 | 2.291486 | 1.006814 |
from futuquant.common.pb.Trd_GetOrderList_pb2 import Request
req = Request()
req.c2s.header.trdEnv = TRD_ENV_MAP[trd_env]
req.c2s.header.accID = acc_id
req.c2s.header.trdMarket = TRD_MKT_MAP[trd_mkt]
if code:
req.c2s.filterConditions.codeList.append(code)
if order_id:
req.c2s.filterConditions.idList.append(int(order_id))
if start:
req.c2s.filterConditions.beginTime = start
if end:
req.c2s.filterConditions.endTime = end
if len(status_filter_list):
for order_status in status_filter_list:
req.c2s.filterStatusList.append(ORDER_STATUS_MAP[order_status])
return pack_pb_req(req, ProtoId.Trd_GetOrderList, conn_id) | def pack_req(cls, order_id, status_filter_list, code, start, end,
trd_env, acc_id, trd_mkt, conn_id) | Convert from user request for trading days to PLS request | 2.029709 | 2.117067 | 0.958737 |
if rsp_pb.retType != RET_OK:
return RET_ERROR, rsp_pb.retMsg, None
raw_order_list = rsp_pb.s2c.orderList
order_list = [OrderListQuery.parse_order(rsp_pb, order) for order in raw_order_list]
return RET_OK, "", order_list | def unpack_rsp(cls, rsp_pb) | Convert from PLS response to user response | 4.02063 | 4.043612 | 0.994316 |
from futuquant.common.pb.Trd_PlaceOrder_pb2 import Request
req = Request()
serial_no = get_unique_id32()
req.c2s.packetID.serialNo = serial_no
req.c2s.packetID.connID = conn_id
req.c2s.header.trdEnv = TRD_ENV_MAP[trd_env]
req.c2s.header.accID = acc_id
req.c2s.header.trdMarket = TRD_MKT_MAP[trd_mkt]
req.c2s.trdSide = TRD_SIDE_MAP[trd_side]
req.c2s.orderType = ORDER_TYPE_MAP[order_type]
req.c2s.code = code
req.c2s.qty = qty
req.c2s.price = price
req.c2s.adjustPrice = adjust_limit != 0
req.c2s.adjustSideAndLimit = adjust_limit
proto_qot_mkt = MKT_MAP.get(sec_mkt_str, Qot_Common_pb2.QotMarket_Unknown)
proto_trd_sec_mkt = QOT_MARKET_TO_TRD_SEC_MARKET_MAP.get(proto_qot_mkt,
Trd_Common_pb2.TrdSecMarket_Unknown)
req.c2s.secMarket = proto_trd_sec_mkt
return pack_pb_req(req, ProtoId.Trd_PlaceOrder, conn_id, serial_no) | def pack_req(cls, trd_side, order_type, price, qty,
code, adjust_limit, trd_env, sec_mkt_str, acc_id, trd_mkt, conn_id) | Convert from user request for place order to PLS request | 2.419263 | 2.49448 | 0.969847 |
if rsp_pb.retType != RET_OK:
return RET_ERROR, rsp_pb.retMsg, None
order_id = str(rsp_pb.s2c.orderID)
return RET_OK, "", order_id | def unpack_rsp(cls, rsp_pb) | Convert from PLS response to user response | 4.826351 | 4.851107 | 0.994897 |
from futuquant.common.pb.Trd_ModifyOrder_pb2 import Request
req = Request()
serial_no = get_unique_id32()
req.c2s.packetID.serialNo = serial_no
req.c2s.packetID.connID = conn_id
req.c2s.header.trdEnv = TRD_ENV_MAP[trd_env]
req.c2s.header.accID = acc_id
req.c2s.header.trdMarket = TRD_MKT_MAP[trd_mkt]
req.c2s.orderID = int(order_id)
req.c2s.modifyOrderOp = MODIFY_ORDER_OP_MAP[modify_order_op]
req.c2s.forAll = False
if modify_order_op == ModifyOrderOp.NORMAL:
req.c2s.qty = qty
req.c2s.price = price
req.c2s.adjustPrice = adjust_limit != 0
req.c2s.adjustSideAndLimit = adjust_limit
return pack_pb_req(req, ProtoId.Trd_ModifyOrder, conn_id, serial_no) | def pack_req(cls, modify_order_op, order_id, price, qty,
adjust_limit, trd_env, acc_id, trd_mkt, conn_id) | Convert from user request for place order to PLS request | 2.592449 | 2.715654 | 0.954632 |
if rsp_pb.retType != RET_OK:
return RET_ERROR, rsp_pb.retMsg, None
order_id = str(rsp_pb.s2c.orderID)
modify_order_list = [{
'trd_env': TRADE.REV_TRD_ENV_MAP[rsp_pb.s2c.header.trdEnv],
'order_id': order_id
}]
return RET_OK, "", modify_order_list | def unpack_rsp(cls, rsp_pb) | Convert from PLS response to user response | 5.044299 | 5.076322 | 0.993692 |
from futuquant.common.pb.Trd_GetOrderFillList_pb2 import Request
req = Request()
req.c2s.header.trdEnv = TRD_ENV_MAP[trd_env]
req.c2s.header.accID = acc_id
req.c2s.header.trdMarket = TRD_MKT_MAP[trd_mkt]
if code:
req.c2s.filterConditions.codeList.append(code)
return pack_pb_req(req, ProtoId.Trd_GetOrderFillList, conn_id) | def pack_req(cls, code, trd_env, acc_id, trd_mkt, conn_id) | Convert from user request for place order to PLS request | 2.510081 | 2.561817 | 0.979805 |
if rsp_pb.retType != RET_OK:
return RET_ERROR, rsp_pb.retMsg, None
raw_deal_list = rsp_pb.s2c.orderFillList
deal_list = [DealListQuery.parse_deal(rsp_pb, deal) for deal in raw_deal_list]
return RET_OK, "", deal_list | def unpack_rsp(cls, rsp_pb) | Convert from PLS response to user response | 5.204016 | 5.091423 | 1.022114 |
ret_code, content = self.parse_rsp_pb(rsp_pb)
return ret_code, content | def on_recv_rsp(self, rsp_pb) | 在收到实摆盘数据推送后会回调到该函数,使用者需要在派生类中覆盖此方法
注意该回调是在独立子线程中
:param rsp_pb: 派生类中不需要直接处理该参数
:return: 参见get_order_book的返回值 | 5.116454 | 5.881272 | 0.869957 |
ret_code, content = self.parse_rsp_pb(rsp_pb)
if ret_code != RET_OK:
return ret_code, content
else:
col_list = [
'code', 'time', 'price', 'volume', 'turnover',
"ticker_direction", 'sequence', 'type', 'push_data_type',
]
ticker_frame_table = pd.DataFrame(content, columns=col_list)
return RET_OK, ticker_frame_table | def on_recv_rsp(self, rsp_pb) | 在收到实时逐笔数据推送后会回调到该函数,使用者需要在派生类中覆盖此方法
注意该回调是在独立子线程中
:param rsp_pb: 派生类中不需要直接处理该参数
:return: 参见get_rt_ticker的返回值 | 4.819226 | 4.115706 | 1.170935 |
ret_code, content = self.parse_rsp_pb(rsp_pb)
if ret_code != RET_OK:
return ret_code, content, None
else:
stock_code, bid_content, ask_content = content
bid_list = [
'code', 'bid_broker_id', 'bid_broker_name', 'bid_broker_pos'
]
ask_list = [
'code', 'ask_broker_id', 'ask_broker_name', 'ask_broker_pos'
]
bid_frame_table = pd.DataFrame(bid_content, columns=bid_list)
ask_frame_table = pd.DataFrame(ask_content, columns=ask_list)
return RET_OK, stock_code, [bid_frame_table, ask_frame_table] | def on_recv_rsp(self, rsp_pb) | 在收到实时经纪数据推送后会回调到该函数,使用者需要在派生类中覆盖此方法
注意该回调是在独立子线程中
:param rsp_pb: 派生类中不需要直接处理该参数
:return: 成功时返回(RET_OK, stock_code, [bid_frame_table, ask_frame_table]), 相关frame table含义见 get_broker_queue_ 的返回值说明
失败时返回(RET_ERROR, ERR_MSG, None) | 2.511085 | 1.942123 | 1.292959 |
ret_code, msg, conn_info_map = InitConnect.unpack_rsp(rsp_pb)
if self._notify_obj is not None:
self._notify_obj.on_async_init_connect(ret_code, msg, conn_info_map)
return ret_code, msg | def on_recv_rsp(self, rsp_pb) | receive response callback function | 5.186047 | 5.244874 | 0.988784 |
ret_code, msg, data = OrderDetail.unpack_rsp(rsp_pb)
if ret_code != RET_OK:
return ret_code, msg
else:
return RET_OK, data | def on_recv_rsp(self, rsp_pb) | receive response callback function | 4.515915 | 4.390602 | 1.028541 |
# TinyQuoteData
data = tiny_quote
str_log = "on_quote_changed symbol=%s open=%s high=%s close=%s low=%s" % (data.symbol, data.openPrice, data.highPrice, data.lastPrice, data.lowPrice)
self.log(str_log) | def on_quote_changed(self, tiny_quote) | 报价、摆盘实时数据变化时,会触发该回调 | 4.181411 | 3.672106 | 1.138696 |
return self._quant_frame.buy(price, volume, symbol, order_type, adjust_limit, acc_id) | def buy(self, price, volume, symbol, order_type=ft.OrderType.NORMAL, adjust_limit=0, acc_id=0) | 买入
:param price: 报价,浮点数 精度0.001
:param volume: 数量(股)
:param symbol: 股票 eg: 'HK.00700'
:param order_type: 订单类型
:param adjust_limit: 当非0时,会自动调整报价,以符合价位表要求, 但不会超过指定的幅度, 为0时不调整报价
:param acc_id: int, 交易账户id, 为0时取第1个可交易账户
:return: (ret, data)
ret == 0 , data = order_id
ret != 0 , data = 错误字符串 | 4.049726 | 5.678869 | 0.713122 |
if type(self._quant_frame) is not int:
return True
self._quant_frame = quant_frame
self._event_engine = event_engine
init_ret = self.__loadSetting(global_setting)
# 注册事件
self._event_engine.register(EVENT_BEFORE_TRADING, self.__event_before_trading)
self._event_engine.register(EVENT_AFTER_TRADING, self.__event_after_trading)
self._event_engine.register(EVENT_QUOTE_CHANGE, self.__event_quote_change)
self._event_engine.register(EVENT_CUR_KLINE_BAR, self.__event_cur_kline_bar)
self.log("init_strate '%s' ret = %s" % (self.name, init_ret))
# 对外通知初始化事件
self.on_init_strate()
return init_ret | def init_strate(self, global_setting, quant_frame, event_engine) | TinyQuantFrame 初始化策略的接口 | 2.866311 | 2.827935 | 1.01357 |
# 添加必要的股票,以便能得到相应的股票行情数据
self.symbol_pools.append(self.symbol_ref)
if self.cta_call["enable"]:
self.symbol_pools.append(self.cta_call["symbol"])
if self.cta_put["enable"]:
self.symbol_pools.append(self.cta_put["symbol"])
# call put 的持仓量以及持仓天数
self.cta_call['pos'] = 0
self.cta_call['days'] = 0
self.cta_put['pos'] = 0
self.cta_put['days'] = 0
# call put 一天只操作一次,记录当天是否已经操作过
self.cta_call['done'] = False
self.cta_put['done'] = False
# 记录当天操作的订单id
self.cta_call['order_id'] = ''
self.cta_put['order_id'] = ''
# 检查参数: 下单的滑点 / 下单的数量
if self.trade_price_idx < 1 or self.trade_price_idx > 5:
raise Exception("conifg trade_price_idx error!")
if self.trade_qty < 0:
raise Exception("conifg trade_qty error!") | def on_init_strate(self) | 策略加载完配置 | 4.005172 | 3.959468 | 1.011543 |
# 读取用户现有帐户持仓信息, 数量不超过config中指定的交易数量 'trade_qty'
for cta in [self.cta_call, self.cta_put]:
pos = self.get_tiny_position(cta['symbol'])
if pos is not None:
valid_pos = pos.position - pos.frozen
valid_pos = valid_pos if valid_pos > 0 else 0
valid_pos = self.trade_qty if valid_pos > self.trade_qty else valid_pos
cta['pos'] = valid_pos
self.log("on_start") | def on_start(self) | 策略启动入口 | 6.416731 | 6.189519 | 1.036709 |
# TinyQuoteData
if tiny_quote.symbol != self.symbol_ref:
return
# 减少计算频率,每x秒一次
dt_now = time.time()
if dt_now - self._last_dt_process < 2:
return
self._last_dt_process = dt_now
# 执行策略
self._process_cta(self.cta_call)
self._process_cta(self.cta_put) | def on_quote_changed(self, tiny_quote) | 报价、摆盘实时数据变化时,会触发该回调 | 6.475973 | 6.063475 | 1.06803 |
if self.cta_call['pos'] > 0:
self.cta_call['days'] += 1
if self.cta_put['pos'] > 0:
self.cta_put['days'] += 1
self.cta_call['done'] = False
self.cta_put['done'] = False | def on_before_trading(self, date_time) | 开盘的时候检查,如果有持仓,就把持有天数 + 1 | 3.21601 | 2.829041 | 1.136785 |
self._update_cta_pos(self.cta_call)
self._update_cta_pos(self.cta_put) | def on_after_trading(self, date_time) | 收盘的时候更新持仓信息 | 6.682808 | 5.693149 | 1.173833 |
if n < 2:
result = np_array
else:
result = talib.EMA(np_array, n)
if array:
return result
return result[-1] | def ema(self, np_array, n, array=False) | 移动均线 | 2.8284 | 2.466107 | 1.146909 |
self.__is_acc_sub_push = False
self.__last_acc_list = []
ret, msg = RET_OK, ''
# auto unlock trade
if self._ctx_unlock is not None:
password, password_md5 = self._ctx_unlock
ret, data = self.unlock_trade(password, password_md5)
logger.debug('auto unlock trade ret={},data={}'.format(ret, data))
if ret != RET_OK:
msg = data
# 定阅交易帐号推送
if ret == RET_OK:
self.__check_acc_sub_push()
return ret, msg | def on_api_socket_reconnected(self) | for API socket reconnected | 6.489609 | 6.310537 | 1.028377 |
query_processor = self._get_sync_query_processor(
GetAccountList.pack_req, GetAccountList.unpack_rsp)
kargs = {
'user_id': self.get_login_user_id(),
'conn_id': self.get_sync_conn_id()
}
ret_code, msg, acc_list = query_processor(**kargs)
if ret_code != RET_OK:
return RET_ERROR, msg
# 记录当前市场的帐号列表
self.__last_acc_list = []
for record in acc_list:
trdMkt_list = record["trdMarket_list"]
if self.__trd_mkt in trdMkt_list:
self.__last_acc_list.append({
"trd_env": record["trd_env"],
"acc_id": record["acc_id"]})
col_list = ["acc_id", "trd_env"]
acc_table = pd.DataFrame(copy(self.__last_acc_list), columns=col_list)
return RET_OK, acc_table | def get_acc_list(self) | :return: (ret, data) | 3.769234 | 3.617306 | 1.042 |
# 仅支持真实交易的市场可以解锁,模拟交易不需要解锁
md5_val = ''
if is_unlock:
ret = TRADE.check_mkt_envtype(self.__trd_mkt, TrdEnv.REAL)
if not ret:
return RET_OK, Err.NoNeedUnlock.text
if password is None and password_md5 is None:
return RET_ERROR, make_msg(Err.ParamErr, password=password, password_md5=password_md5)
md5_val = str(password_md5) if password_md5 else md5_transform(str(password))
# 解锁要求先拉一次帐户列表, 目前仅真实环境需要解锁
ret, msg, acc_id = self._check_acc_id(TrdEnv.REAL, 0)
if ret != RET_OK:
return ret, msg
query_processor = self._get_sync_query_processor(
UnlockTrade.pack_req, UnlockTrade.unpack_rsp)
kargs = {
'is_unlock': is_unlock,
'password_md5': md5_val,
'conn_id': self.get_sync_conn_id()
}
ret_code, msg, _ = query_processor(**kargs)
if ret_code != RET_OK:
return RET_ERROR, msg
# reconnected to auto unlock
if RET_OK == ret_code:
self._ctx_unlock = (password, password_md5) if is_unlock else None
# 定阅交易帐号推送
if is_unlock and ret_code == RET_OK:
self.__check_acc_sub_push()
if msg is not None and len(msg) > 0:
return RET_OK, msg
return RET_OK, None | def unlock_trade(self, password=None, password_md5=None, is_unlock=True) | 交易解锁,安全考虑,所有的交易api,需成功解锁后才可操作
:param password: 明文密码字符串 (二选一)
:param password_md5: 密码的md5字符串(二选一)
:param is_unlock: 解锁 = True, 锁定 = False
:return:(ret, data) ret == RET_OK时, data为None,如果之前已经解锁过了,data为提示字符串,指示出已经解锁
ret != RET_OK时, data为错误字符串 | 5.255801 | 5.168529 | 1.016885 |
kargs = {
'acc_id_list': acc_id_list,
'conn_id': self.get_async_conn_id(),
}
ret_code, msg, push_req_str = SubAccPush.pack_req(**kargs)
if ret_code == RET_OK:
self._send_async_req(push_req_str)
return RET_OK, None | def _async_sub_acc_push(self, acc_id_list) | 异步连接指定要接收送的acc id
:param acc_id:
:return: | 4.853071 | 4.409248 | 1.100657 |
ret, msg = self._check_trd_env(trd_env)
if ret != RET_OK:
return ret, msg
ret, msg, acc_id = self._check_acc_id_and_acc_index(trd_env, acc_id, acc_index)
if ret != RET_OK:
return ret, msg
query_processor = self._get_sync_query_processor(
AccInfoQuery.pack_req, AccInfoQuery.unpack_rsp)
kargs = {
'acc_id': int(acc_id),
'trd_env': trd_env,
'trd_market': self.__trd_mkt,
'conn_id': self.get_sync_conn_id()
}
ret_code, msg, accinfo_list = query_processor(**kargs)
if ret_code != RET_OK:
return RET_ERROR, msg
col_list = [
'power', 'total_assets', 'cash', 'market_val', 'frozen_cash', 'avl_withdrawal_cash'
]
accinfo_frame_table = pd.DataFrame(accinfo_list, columns=col_list)
return RET_OK, accinfo_frame_table | def accinfo_query(self, trd_env=TrdEnv.REAL, acc_id=0, acc_index=0) | :param trd_env:
:param acc_id:
:param acc_index:
:return: | 2.927935 | 2.942591 | 0.995019 |
stock_str = str(code)
split_loc = stock_str.find(".")
'''do not use the built-in split function in python.
The built-in function cannot handle some stock strings correctly.
for instance, US..DJI, where the dot . itself is a part of original code'''
if 0 <= split_loc < len(
stock_str) - 1 and stock_str[0:split_loc] in MKT_MAP:
market_str = stock_str[0:split_loc]
partial_stock_str = stock_str[split_loc + 1:]
return RET_OK, (market_str, partial_stock_str)
else:
error_str = ERROR_STR_PREFIX + "format of %s is wrong. (US.AAPL, HK.00700, SZ.000001)" % stock_str
return RET_ERROR, error_str | def _split_stock_code(self, code) | do not use the built-in split function in python.
The built-in function cannot handle some stock strings correctly.
for instance, US..DJI, where the dot . itself is a part of original code | 5.214606 | 2.82579 | 1.845362 |
ret, msg = self._check_trd_env(trd_env)
if ret != RET_OK:
return ret, msg
ret, msg, acc_id = self._check_acc_id_and_acc_index(trd_env, acc_id, acc_index)
if ret != RET_OK:
return ret, msg
ret, msg, stock_code = self._check_stock_code(code)
if ret != RET_OK:
return ret, msg
query_processor = self._get_sync_query_processor(
PositionListQuery.pack_req, PositionListQuery.unpack_rsp)
kargs = {
'code': str(stock_code),
'pl_ratio_min': pl_ratio_min,
'pl_ratio_max': pl_ratio_max,
'trd_mkt': self.__trd_mkt,
'trd_env': trd_env,
'acc_id': acc_id,
'conn_id': self.get_sync_conn_id()
}
ret_code, msg, position_list = query_processor(**kargs)
if ret_code != RET_OK:
return RET_ERROR, msg
col_list = [
"code", "stock_name", "qty", "can_sell_qty", "cost_price",
"cost_price_valid", "market_val", "nominal_price", "pl_ratio",
"pl_ratio_valid", "pl_val", "pl_val_valid", "today_buy_qty",
"today_buy_val", "today_pl_val", "today_sell_qty", "today_sell_val",
"position_side"
]
position_list_table = pd.DataFrame(position_list, columns=col_list)
return RET_OK, position_list_table | def position_list_query(self, code='', pl_ratio_min=None,
pl_ratio_max=None, trd_env=TrdEnv.REAL, acc_id=0, acc_index=0) | for querying the position list | 2.290987 | 2.308026 | 0.992618 |
# ret, msg = self._check_trd_env(trd_env)
# if ret != RET_OK:
# return ret, msg
ret, msg, acc_id = self._check_acc_id_and_acc_index(trd_env, acc_id, acc_index)
if ret != RET_OK:
return ret, msg
ret, content = self._split_stock_code(code)
if ret != RET_OK:
return ret, content
market_str, stock_code = content
query_processor = self._get_sync_query_processor(
PlaceOrder.pack_req, PlaceOrder.unpack_rsp)
# the keys of kargs should be corresponding to the actual function arguments
kargs = {
'trd_side': trd_side,
'order_type': order_type,
'price': float(price),
'qty': float(qty),
'code': stock_code,
'adjust_limit': float(adjust_limit),
'trd_mkt': self.__trd_mkt,
'sec_mkt_str': market_str,
'trd_env': trd_env,
'acc_id': acc_id,
'conn_id': self.get_sync_conn_id()
}
ret_code, msg, order_id = query_processor(**kargs)
if ret_code != RET_OK:
return RET_ERROR, msg
order_item = {'trd_env': trd_env, 'order_id': order_id}
# 保持跟v2.0兼容, 增加必要的订单字段
for x in range(3):
ret_code, ret_data = self._order_list_query_impl(order_id=order_id,status_filter_list=[],
code="", start="", end="", trd_env=trd_env, acc_id=acc_id)
if ret_code == RET_OK and len(ret_data) > 0:
order_item = ret_data[0]
order_item['trd_env'] = trd_env
break
col_list = [
"code", "stock_name", "trd_side", "order_type", "order_status",
"order_id", "qty", "price", "create_time", "updated_time",
"dealt_qty", "dealt_avg_price", "last_err_msg"
]
order_list = [order_item]
order_table = pd.DataFrame(order_list, columns=col_list)
return RET_OK, order_table | def place_order(self, price, qty, code, trd_side, order_type=OrderType.NORMAL,
adjust_limit=0, trd_env=TrdEnv.REAL, acc_id=0, acc_index=0) | place order
use set_handle(HKTradeOrderHandlerBase) to recv order push ! | 3.004401 | 2.990206 | 1.004747 |
ret, msg = self._check_trd_env(trd_env)
if ret != RET_OK:
return ret, msg
ret, msg, acc_id = self._check_acc_id_and_acc_index(trd_env, acc_id, acc_index)
if ret != RET_OK:
return ret, msg
ret, msg, stock_code = self._check_stock_code(code)
if ret != RET_OK:
return ret, msg
query_processor = self._get_sync_query_processor(
DealListQuery.pack_req, DealListQuery.unpack_rsp)
kargs = {
'code': stock_code,
'trd_mkt': self.__trd_mkt,
'trd_env': trd_env,
'acc_id': acc_id,
'conn_id': self.get_sync_conn_id()
}
ret_code, msg, deal_list = query_processor(**kargs)
if ret_code != RET_OK:
return RET_ERROR, msg
col_list = [
"code", "stock_name", "deal_id", "order_id", "qty", "price",
"trd_side", "create_time", "counter_broker_id", "counter_broker_name"
]
deal_list_table = pd.DataFrame(deal_list, columns=col_list)
return RET_OK, deal_list_table | def deal_list_query(self, code="", trd_env=TrdEnv.REAL, acc_id=0, acc_index=0) | for querying deal list | 2.450918 | 2.462568 | 0.995269 |
ret, msg = self._check_trd_env(trd_env)
if ret != RET_OK:
return ret, msg
ret, msg, acc_id = self._check_acc_id_and_acc_index(trd_env, acc_id, acc_index)
if ret != RET_OK:
return ret, msg
ret, content = self._split_stock_code(code)
if ret != RET_OK:
return ret, content
market_str, stock_code = content
query_processor = self._get_sync_query_processor(
AccTradingInfoQuery.pack_req,
AccTradingInfoQuery.unpack_rsp)
kargs = {
'order_type': order_type,
'code': str(stock_code),
'price': price,
'order_id': order_id,
'adjust_limit': adjust_limit,
'trd_mkt': self.__trd_mkt,
'sec_mkt_str': market_str,
'trd_env': trd_env,
'acc_id': acc_id,
'conn_id': self.get_sync_conn_id()
}
ret_code, msg, data = query_processor(**kargs)
if ret_code != RET_OK:
return RET_ERROR, msg
col_list = ['max_cash_buy', 'max_cash_and_margin_buy', 'max_position_sell', 'max_sell_short', 'max_buy_back']
acctradinginfo_table = pd.DataFrame(data, columns=col_list)
return RET_OK, acctradinginfo_table | def acctradinginfo_query(self, order_type, code, price, order_id=None, adjust_limit=0, trd_env=TrdEnv.REAL, acc_id=0, acc_index=0) | 查询账户下最大可买卖数量
:param order_type: 订单类型,参见OrderType
:param code: 证券代码,例如'HK.00700'
:param price: 报价,3位精度
:param order_id: 订单号。如果是新下单,则可以传None。如果是改单则要传单号。
:param adjust_limit: 调整方向和调整幅度百分比限制,正数代表向上调整,负数代表向下调整,具体值代表调整幅度限制,如:0.015代表向上调整且幅度不超过1.5%;-0.01代表向下调整且幅度不超过1%。默认0表示不调整
:param trd_env: 交易环境,参见TrdEnv
:param acc_id: 业务账号,默认0表示第1个
:param acc_index: int,交易业务子账户ID列表所对应的下标,默认0,表示第1个业务ID
:return: (ret, data)
ret == RET_OK, data为pd.DataFrame,数据列如下
ret != RET_OK, data为错误信息
======================= =========== ======================================================================================
参数 类型 说明
======================= =========== ======================================================================================
max_cash_buy float 不使用融资,仅自己的现金最大可买整手股数
max_cash_and_margin_buy float 使用融资,自己的现金 + 融资资金总共的最大可买整手股数
max_position_sell float 不使用融券(卖空),仅自己的持仓最大可卖整手股数
max_sell_short float 使用融券(卖空),最大可卖空整手股数,不包括多仓
max_buy_back float 卖空后,需要买回的最大整手股数。因为卖空后,必须先买回已卖空的股数,还掉股票,才能再继续买多。
======================= =========== ====================================================================================== | 2.79876 | 2.353986 | 1.188945 |
return super(OpenHKCCTradeContext, self).order_list_query(order_id, status_filter_list, code, start, end, trd_env, acc_id, acc_index) | def order_list_query(self, order_id="", status_filter_list=[], code='', start='', end='',
trd_env=TrdEnv.REAL, acc_id=0, acc_index=0) | :param order_id:
:param status_filter_list:
:param code:
:param start:
:param end:
:param trd_env:
:param acc_id:
:return: 返回值见基类及接口文档,但order_type仅有OrderType.NORMAL, order_status没有OrderStatus.DISABLED | 2.905732 | 3.462579 | 0.839181 |
return super(OpenHKCCTradeContext, self).modify_order(modify_order_op=modify_order_op,
order_id=order_id,
qty=qty,
price=price,
adjust_limit=adjust_limit,
trd_env=trd_env,
acc_id=acc_id,
acc_index=acc_index) | def modify_order(self, modify_order_op, order_id, qty, price, adjust_limit=0, trd_env=TrdEnv.REAL, acc_id=0, acc_index=0) | 详细说明见基类接口说明,但有以下不同:不支持改单。 可撤单。删除订单是本地操作。
:param modify_order_op:
:param order_id:
:param qty:
:param price:
:param adjust_limit:
:param trd_env:
:param acc_id:
:return: | 2.064162 | 2.334654 | 0.884141 |
# TinyQuoteData
data = tiny_quote
symbol = data.symbol
str_dt = data.datetime.strftime("%Y%m%d %H:%M:%S")
# 得到日k数据的ArrayManager(vnpy)对象
am = self.get_kl_day_am(data.symbol)
array_high = am.high
array_low = am.low
array_open = am.open
array_close = am.close
array_vol = am.volume
n = 5
ma_high = self.sma(array_high, n)
ma_low = self.sma(array_low, n)
ma_open = self.sma(array_open, n)
ma_close = self.sma(array_close, n)
ma_vol = self.sma(array_vol, n)
str_log = "on_quote_changed symbol=%s dt=%s sma(%s) open=%s high=%s close=%s low=%s vol=%s" % (
symbol, str_dt, n, ma_open, ma_high, ma_close, ma_low, ma_vol)
self.log(str_log) | def on_quote_changed(self, tiny_quote) | 报价、摆盘实时数据变化时,会触发该回调 | 2.785714 | 2.656111 | 1.048794 |
bar = tiny_bar
symbol = bar.symbol
str_dt = bar.datetime.strftime("%Y%m%d %H:%M:%S")
# 得到分k数据的ArrayManager(vnpy)对象
am = self.get_kl_min1_am(symbol)
array_high = am.high
array_low = am.low
array_open = am.open
array_close = am.close
array_vol = am.volume
n = 5
ma_high = self.ema(array_high, n)
ma_low = self.ema(array_low, n)
ma_open = self.ema(array_open, n)
ma_close = self.ema(array_close, n)
ma_vol = self.ema(array_vol, n)
str_log = "on_bar_min1 symbol=%s dt=%s ema(%s) open=%s high=%s close=%s low=%s vol=%s" % (
symbol, str_dt, n, ma_open, ma_high, ma_close, ma_low, ma_vol)
self.log(str_log) | def on_bar_min1(self, tiny_bar) | 每一分钟触发一次回调 | 2.608114 | 2.570297 | 1.014713 |
bar = tiny_bar
symbol = bar.symbol
str_dt = bar.datetime.strftime("%Y%m%d %H:%M:%S")
str_log = "on_bar_day symbol=%s dt=%s open=%s high=%s close=%s low=%s vol=%s" % (
symbol, str_dt, bar.open, bar.high, bar.close, bar.low, bar.volume)
self.log(str_log) | def on_bar_day(self, tiny_bar) | 收盘时会触发一次日k回调 | 2.389414 | 2.284781 | 1.045795 |
if n < 2:
result = np_array
else:
result = talib.SMA(np_array, n)
if array:
return result
return result[-1] | def sma(self, np_array, n, array=False) | 简单均线 | 2.491733 | 2.392501 | 1.041476 |
data = tiny_quote
symbol = data.symbol
price = data.open
#print(price)
now = datetime.datetime.now()
work_time = now.replace(hour=15, minute=55, second=0)
if now >= work_time:
ma_20 = self.get_sma(20, symbol)
ma_60 = self.get_sma(60, symbol)
if ma_20 >= ma_60 and self.flag==0:
#金叉买入
self.do_trade(symbol, price, "buy")
self.flag = 1
elif ma_20 < ma_60 and self.flag==1:
#死叉卖出
self.do_trade(symbol, price, "sell")
self.flag = 0 | def on_bar_min1(self, tiny_quote) | 每一分钟触发一次回调 | 2.733975 | 2.70877 | 1.009305 |
while self.__active == True:
try:
event = self.__queue.get(block = True, timeout = 1) # 获取事件的阻塞时间设为1秒
self.__process(event)
except Empty:
pass | def __run(self) | 引擎运行 | 4.397663 | 3.868042 | 1.136922 |
# 检查是否存在对该事件进行监听的处理函数
if event.type_ in self.__handlers:
# 若存在,则按顺序将事件传递给处理函数执行
[handler(event) for handler in self.__handlers[event.type_]]
# 以上语句为Python列表解析方式的写法,对应的常规循环写法为:
#for handler in self.__handlers[event.type_]:
#handler(event)
# 调用通用处理函数进行处理
if self.__generalHandlers:
[handler(event) for handler in self.__generalHandlers] | def __process(self, event) | 处理事件 | 5.535668 | 5.195815 | 1.065409 |
# 将引擎设为启动
self.__active = True
# 启动事件处理线程
self.__thread.start()
# 启动计时器,计时器事件间隔默认设定为1秒
if timer:
self.__timer.start(1000) | def start(self, timer=True) | 引擎启动
timer:是否要启动计时器 | 5.633195 | 5.089653 | 1.106793 |
# 将引擎设为停止
self.__active = False
# 停止计时器
self.__timer.stop()
# 等待事件处理线程退出
self.__thread.join() | def stop(self) | 停止引擎 | 7.656974 | 6.145598 | 1.245928 |
# 尝试获取该事件类型对应的处理函数列表,若无defaultDict会自动创建新的list
handlerList = self.__handlers[type_]
# 若要注册的处理器不在该事件的处理器列表中,则注册该事件
if handler not in handlerList:
handlerList.append(handler) | def register(self, type_, handler) | 注册事件处理函数监听 | 7.107449 | 6.588154 | 1.078823 |
# 尝试获取该事件类型对应的处理函数列表,若无则忽略该次注销请求
handlerList = self.__handlers[type_]
# 如果该函数存在于列表中,则移除
if handler in handlerList:
handlerList.remove(handler)
# 如果函数列表为空,则从引擎中移除该事件类型
if not handlerList:
del self.__handlers[type_] | def unregister(self, type_, handler) | 注销事件处理函数监听 | 5.147274 | 4.696007 | 1.096096 |
if handler not in self.__generalHandlers:
self.__generalHandlers.append(handler) | def registerGeneralHandler(self, handler) | 注册通用事件处理函数监听 | 3.553724 | 3.506304 | 1.013524 |
if handler in self.__generalHandlers:
self.__generalHandlers.remove(handler) | def unregisterGeneralHandler(self, handler) | 注销通用事件处理函数监听 | 3.458196 | 3.369162 | 1.026426 |
while self.__timerActive:
# 创建计时器事件
event = Event(type_=EVENT_TIMER)
# 向队列中存入计时器事件
self.put(event)
# 等待
sleep(self.__timerSleep) | def __runTimer(self) | 运行在计时器线程中的循环函数 | 6.767612 | 6.083864 | 1.112387 |
# 将引擎设为停止
self.__active = False
# 停止计时器
self.__timerActive = False
self.__timer.join()
# 等待事件处理线程退出
self.__thread.join() | def stop(self) | 停止引擎 | 7.843931 | 6.528083 | 1.201567 |
stock_code_list = ["US.AAPL", "HK.00700"]
# subscribe "QUOTE"
ret_status, ret_data = quote_ctx.subscribe(stock_code_list, ft.SubType.QUOTE)
if ret_status != ft.RET_OK:
print("%s %s: %s" % (stock_code_list, "QUOTE", ret_data))
exit()
ret_status, ret_data = quote_ctx.query_subscription()
if ret_status != ft.RET_OK:
print(ret_status)
exit()
print(ret_data)
ret_status, ret_data = quote_ctx.get_stock_quote(stock_code_list)
if ret_status != ft.RET_OK:
print(ret_data)
exit()
quote_table = ret_data
print("QUOTE_TABLE")
print(quote_table) | def _example_stock_quote(quote_ctx) | 获取批量报价,输出 股票名称,时间,当前价,开盘价,最高价,最低价,昨天收盘价,成交量,成交额,换手率,振幅,股票状态 | 2.633357 | 2.547395 | 1.033745 |
# subscribe Kline
stock_code_list = ["US.AAPL", "HK.00700"]
sub_type_list = [ft.SubType.K_1M, ft.SubType.K_5M, ft.SubType.K_15M, ft.SubType.K_30M, ft.SubType.K_60M,
ft.SubType.K_DAY, ft.SubType.K_WEEK, ft.SubType.K_MON]
ret_status, ret_data = quote_ctx.subscribe(stock_code_list, sub_type_list)
if ret_status != ft.RET_OK:
print(ret_data)
exit()
ret_status, ret_data = quote_ctx.query_subscription()
if ret_status == ft.RET_ERROR:
print(ret_data)
exit()
print(ret_data)
for code in stock_code_list:
for ktype in [ft.SubType.K_DAY, ft.SubType.K_1M, ft.SubType.K_5M]:
ret_code, ret_data = quote_ctx.get_cur_kline(code, 5, ktype)
if ret_code == ft.RET_ERROR:
print(code, ktype, ret_data)
exit()
kline_table = ret_data
print("%s KLINE %s" % (code, ktype))
print(kline_table)
print("\n\n") | def _example_cur_kline(quote_ctx) | 获取当前K线,输出 股票代码,时间,开盘价,收盘价,最高价,最低价,成交量,成交额 | 2.10855 | 2.074856 | 1.016239 |
stock_code_list = ["HK.00700", "US.AAPL"]
# subscribe "TICKER"
ret_status, ret_data = quote_ctx.subscribe(stock_code_list, ft.SubType.TICKER)
if ret_status != ft.RET_OK:
print(ret_data)
exit()
for stk_code in stock_code_list:
ret_status, ret_data = quote_ctx.get_rt_ticker(stk_code, 3)
if ret_status != ft.RET_OK:
print(stk_code, ret_data)
exit()
print("%s TICKER" % stk_code)
print(ret_data)
print("\n\n") | def _example_rt_ticker(quote_ctx) | 获取逐笔,输出 股票代码,时间,价格,成交量,成交金额,暂时没什么意义的序列号 | 2.667921 | 2.550959 | 1.04585 |
stock_code_list = ["US.AAPL", "HK.00700"]
# subscribe "ORDER_BOOK"
ret_status, ret_data = quote_ctx.subscribe(stock_code_list, ft.SubType.ORDER_BOOK)
if ret_status != ft.RET_OK:
print(ret_data)
exit()
for stk_code in stock_code_list:
ret_status, ret_data = quote_ctx.get_order_book(stk_code)
if ret_status != ft.RET_OK:
print(stk_code, ret_data)
exit()
print("%s ORDER_BOOK" % stk_code)
print(ret_data)
print("\n\n") | def _example_order_book(quote_ctx) | 获取摆盘数据,输出 买价,买量,买盘经纪个数,卖价,卖量,卖盘经纪个数 | 2.693496 | 2.625995 | 1.025705 |
ret_status, ret_data = quote_ctx.get_trading_days("US", None, None)
if ret_status != ft.RET_OK:
print(ret_data)
exit()
print("TRADING DAYS")
for x in ret_data:
print(x) | def _example_get_trade_days(quote_ctx) | 获取交易日列表,输出 交易日列表 | 4.342785 | 4.206146 | 1.032486 |
ret_status, ret_data = quote_ctx.get_stock_basicinfo(ft.Market.HK, ft.SecurityType.STOCK)
if ret_status != ft.RET_OK:
print(ret_data)
exit()
print("stock_basic")
print(ret_data) | def _example_stock_basic(quote_ctx) | 获取股票信息,输出 股票代码,股票名,每手数量,股票类型,子类型所属正股 | 3.540186 | 3.330098 | 1.063088 |
ret_status, ret_data = quote_ctx.get_market_snapshot(["US.AAPL", "HK.00700"])
if ret_status != ft.RET_OK:
print(ret_data)
exit()
print("market_snapshot")
print(ret_data) | def _example_get_market_snapshot(quote_ctx) | 获取市场快照,输出 股票代码,更新时间,按盘价,开盘价,最高价,最低价,昨天收盘价,成交量,成交额,换手率,
停牌状态,上市日期,流通市值,总市值,是否涡轮,换股比例,窝轮类型,行使价格,格式化窝轮到期时间,
格式化窝轮最后到期时间,窝轮对应的正股,窝轮回收价,窝轮街货量,窝轮发行量,窝轮街货占比,窝轮对冲值,窝轮引伸波幅,
窝轮溢价 | 3.814023 | 3.766618 | 1.012585 |
stock_code_list = ["US.AAPL", "HK.00700"]
ret_status, ret_data = quote_ctx.subscribe(stock_code_list, ft.SubType.RT_DATA)
if ret_status != ft.RET_OK:
print(ret_data)
exit()
for stk_code in stock_code_list:
ret_status, ret_data = quote_ctx.get_rt_data(stk_code)
if ret_status != ft.RET_OK:
print(stk_code, ret_data)
exit()
print("%s RT_DATA" % stk_code)
print(ret_data)
print("\n\n") | def _example_rt_data(quote_ctx) | 获取分时数据,输出 时间,数据状态,开盘多少分钟,目前价,昨收价,平均价,成交量,成交额 | 2.487564 | 2.451915 | 1.014539 |
ret_status, ret_data = quote_ctx.get_plate_list(ft.Market.SZ, ft.Plate.ALL)
if ret_status != ft.RET_OK:
print(ret_data)
exit()
print("plate_subplate")
print(ret_data) | def _example_plate_subplate(quote_ctx) | 获取板块集合下的子板块列表,输出 市场,板块分类,板块代码,名称,ID | 4.327622 | 3.911717 | 1.106323 |
ret_status, ret_data = quote_ctx.get_plate_stock("SH.BK0531")
if ret_status != ft.RET_OK:
print(ret_data)
exit()
print("plate_stock")
print(ret_data) | def _example_plate_stock(quote_ctx) | 获取板块下的股票列表,输出 市场,股票每手,股票名称,所属市场,子类型,股票类型 | 4.630606 | 4.69921 | 0.985401 |
stock_code_list = ["HK.00700"]
for stk_code in stock_code_list:
ret_status, ret_data = quote_ctx.subscribe(stk_code, ft.SubType.BROKER)
if ret_status != ft.RET_OK:
print(ret_data)
exit()
for stk_code in stock_code_list:
ret_status, bid_data, ask_data = quote_ctx.get_broker_queue(stk_code)
if ret_status != ft.RET_OK:
print(bid_data)
exit()
print("%s BROKER" % stk_code)
print(ask_data)
print("\n\n")
print(bid_data)
print("\n\n") | def _example_broker_queue(quote_ctx) | 获取经纪队列,输出 买盘卖盘的经纪ID,经纪名称,经纪档位 | 2.713614 | 2.564039 | 1.058335 |
self._socket_lock.acquire()
self._force_close_session()
self._socket_lock.release() | def close_socket(self) | close socket | 6.205824 | 5.462142 | 1.136152 |
self._socket_lock.acquire()
try:
ret = self._is_socket_ok(timeout_select)
finally:
self._socket_lock.release()
return ret | def is_sock_ok(self, timeout_select) | check if socket is OK | 2.554516 | 2.313234 | 1.104305 |
req_proto_id = 0
try:
is_socket_lock = False
ret, msg = self._create_session(is_create_socket)
if ret != RET_OK:
return ret, msg, None
self._socket_lock.acquire()
if not self.s:
self._socket_lock.release()
return RET_ERROR, "socket is closed"
is_socket_lock = True
head_len = get_message_head_len()
req_head_dict = parse_head(req_str[:head_len])
req_proto_id = req_head_dict['proto_id']
req_serial_no = req_head_dict['serial_no']
s_cnt = self.s.send(req_str)
is_rsp_body = False
left_buf = b''
rsp_body = b''
head_dict = []
while not is_rsp_body:
if len(left_buf) < head_len:
recv_buf = self.s.recv(5 * 1024 * 1024)
if recv_buf == b'':
raise Exception("_SyncNetworkQueryCtx : head recv error, remote server close")
left_buf += recv_buf
head_dict = parse_head(left_buf[:head_len])
rsp_body = left_buf[head_len:]
while head_dict['body_len'] > len(rsp_body):
try:
recv_buf = self.s.recv(5 * 1024 * 1024)
rsp_body += recv_buf
if recv_buf == b'':
raise Exception("_SyncNetworkQueryCtx : body recv error, remote server close")
except Exception as e:
traceback.print_exc()
err = sys.exc_info()[1]
error_str = ERROR_STR_PREFIX + str(
err) + ' when receiving after sending %s bytes.' % s_cnt + ""
self._force_close_session()
return RET_ERROR, error_str, None
if head_dict["proto_id"] == req_proto_id and head_dict["serial_no"] == req_serial_no:
is_rsp_body = True
else:
left_buf = rsp_body[head_dict['body_len']:]
logger.debug("recv dirty response: req protoID={} serial={}, recv protoID={} serial={} conn_id={}".format(
req_proto_id, req_serial_no, head_dict["proto_id"], head_dict["serial_no"], self._conn_id))
ret_decrypt, msg_decrypt, rsp_body = decrypt_rsp_body(rsp_body, head_dict, self._conn_id)
if ret_decrypt != RET_OK:
return ret_decrypt, msg_decrypt, None
rsp_pb = binary2pb(rsp_body, head_dict['proto_id'], head_dict['proto_fmt_type'])
if rsp_pb is None:
return RET_ERROR, "parse error", None
self._close_session()
except Exception as e:
traceback.print_exc()
err = sys.exc_info()[1]
str_proto = ' when req proto:{} conn_id:{}, host:{} port:{}'.format(req_proto_id, self._conn_id, self.__host, self.__port)
error_str = ERROR_STR_PREFIX + str(err) + str_proto
logger.error(error_str)
return RET_ERROR, error_str, None
finally:
if is_socket_lock:
self._socket_lock.release()
return RET_OK, "", rsp_pb | def network_query(self, req_str, is_create_socket=True) | the function sends req_str to FUTU client and try to get response from the client.
:param req_str
:return: rsp_str | 2.74155 | 2.747017 | 0.99801 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.