Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions TradeInterface/HistoryTrading.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import os
import time
import json
import urllib2
import urllib.request
import urllib
import hashlib
import sys
Expand Down Expand Up @@ -167,7 +167,7 @@ def get_stock_dic():
def md5encryption(password):
if password.strip() != '':
md = hashlib.md5()
md.update(password)
md.update(password.encode("utf8"))
return md.hexdigest()
else:
return ''
Expand All @@ -176,8 +176,8 @@ def md5encryption(password):
@staticmethod
def http_post(send_dic, urlencode_name, url):
jdata = json.dumps(send_dic) # json格式化编码
jdata = urllib.urlencode({urlencode_name: jdata}) # urlencode编码
req = urllib2.Request(url, jdata) # 生成页面请求的完整数据
res = urllib2.urlopen(req) # 发送页面请求
jdata = urllib.parse.urlencode({urlencode_name: jdata}).encode(encoding='UTF8') # urlencode编码
req = urllib.request.Request(url, jdata) # 生成页面请求的完整数据
res = urllib.request.urlopen(req) # 发送页面请求
temp_res = res.read() # 返回结果,把list结果处理为字符串显示
return temp_res
15 changes: 6 additions & 9 deletions TradeInterface/RealTimeTrading.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,12 @@
import os
import time
import json
import urllib2
import urllib.request
import urllib
import hashlib
import sys
import pandas as pd
import importlib,sys

if sys.getdefaultencoding() != 'utf-8':
reload(sys)
sys.setdefaultencoding('utf-8')


class RealTimeTrading(object):
Expand Down Expand Up @@ -107,7 +104,7 @@ def get_stock_dic():
def md5encryption(password):
if password.strip() != '':
md = hashlib.md5()
md.update(password)
md.update(password.encode("utf8"))
return md.hexdigest()
else:
return ''
Expand All @@ -118,9 +115,9 @@ def http_post(send_dic, urlencode_name, url):
jdata = json.dumps(send_dic) # json格式化编码
# print(jdata)
# exit()
jdata = urllib.urlencode({urlencode_name: jdata}) # urlencode编码
req = urllib2.Request(url, jdata) # 生成页面请求的完整数据
res = urllib2.urlopen(req) # 发送页面请求
jdata = urllib.parse.urlencode({urlencode_name: jdata}).encode(encoding='UTF8') # urlencode编码
req = urllib.request.Request(url, jdata) # 生成页面请求的完整数据
res = urllib.request.urlopen(req) # 发送页面请求
temp_res = res.read() # 返回结果,把list结果处理为字符串显示
return temp_res

172 changes: 92 additions & 80 deletions TradeInterface/TestEngine.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
#coding:utf-8
# coding:utf-8

import datetime
import json
from HistoryTrading import HistoryTrading
from RealTimeTrading import RealTimeTrading
from .HistoryTrading import HistoryTrading
from .RealTimeTrading import RealTimeTrading

'''装饰器'''


def input_checker(func):
'''
用于监测函数输入是否合法,code,volume均转化为str
:param func:
:return:
'''
def _input_checker(self,**kwargs):

def _input_checker(self, **kwargs):
# 股票代码检查
if isinstance(kwargs['code'], str):
pass
Expand All @@ -21,34 +24,35 @@ def _input_checker(self,**kwargs):
while len(kwargs['code']) < 6:
kwargs['code'] = '0' + kwargs['code']
else:
raise TypeError, 'code must be str or int'
raise TypeError('code must be str or int')
# 股票交易量检查
if isinstance(kwargs['volume'], str):
pass
elif isinstance(kwargs['volume'], int):
kwargs['volume'] = str(kwargs['volume'])
else:
raise TypeError, 'volume must be str or int'
#回测日期检查
if isinstance(self._core,HistoryTrading):
raise TypeError('volume must be str or int')
# 回测日期检查
if isinstance(self._core, HistoryTrading):
if 'date' not in kwargs:
kwargs['date'] = self._current_time.strftime('%Y-%m-%d')
elif isinstance(kwargs['date'],datetime.datetime):
elif isinstance(kwargs['date'], datetime.datetime):
kwargs['date'] = datetime.datetime.strftime('%Y-%m-%d')
elif isinstance(kwargs['date'],str):
elif isinstance(kwargs['date'], str):
pass
else:
raise TypeError,'date must be str or datetime object'
#返回函数
print kwargs
raise TypeError('date must be str or datetime object')
# 返回函数
print(kwargs)
res = func(self, **kwargs)
return res

return _input_checker


class TestEngine(object):

def __init__(self,user_id='',password = '',type = 'RealTimeTrading'):
def __init__(self, user_id='', password='', type='RealTimeTrading'):
'''
{'buy_sell': 'sell', 'code': '000006', 'volume': '100', 'price': '1', 'price_type': 'now_price', 'effect_term': '2'}
:param user_id:用户id
Expand All @@ -60,93 +64,97 @@ def __init__(self,user_id='',password = '',type = 'RealTimeTrading'):
self._core = RealTimeTrading(userid=user_id, password=password)
elif type == 'HistoryTrading':
stratagy_name = user_id
self._current_time = datetime.datetime.today()-datetime.timedelta(days=1)
self._core = HistoryTrading(userid=user_id,password=password,strategy_name = stratagy_name)
self._current_time = datetime.datetime.today() - datetime.timedelta(days=1)
self._core = HistoryTrading(userid=user_id, password=password, strategy_name=stratagy_name)
self._core.create_strategy(stratagy_name)
else:
raise ValueError,'type must be "RealTimeTrading" or "HistoryTrading"'
#显示当前的交易引擎类型
raise ValueError('type must be "RealTimeTrading" or "HistoryTrading"')

# 显示当前的交易引擎类型
@property
def core(self):
'''
返回当前的引擎类型
:return:
'''
return self._core.__class__
#显示当前回测引擎时间

# 显示当前回测引擎时间
@property
def current_time(self):
'''
返回当前的引擎时间,主要用于回测
:return:
'''
if isinstance(self._core,RealTimeTrading):
if isinstance(self._core, RealTimeTrading):
return datetime.datetime.now().strftime('%Y-%m-%d,%H:%M:%S')
elif isinstance(self._core,HistoryTrading):
elif isinstance(self._core, HistoryTrading):
return self._current_time.strftime('%Y-%m-%d')

@current_time.setter
def current_time(self,date):
def current_time(self, date):
'''
自由设定引擎时间
:param date:
:return:
'''
if isinstance(self._core,HistoryTrading):
if isinstance(date,str):
self._current_time = datetime.datetime.strptime(date,'%Y-%m-%d')
elif isinstance(date,datetime.datetime):
if isinstance(self._core, HistoryTrading):
if isinstance(date, str):
self._current_time = datetime.datetime.strptime(date, '%Y-%m-%d')
elif isinstance(date, datetime.datetime):
pass
else:
raise TypeError, '%s can not operate on current_time' % (self._core.__class__)
raise TypeError('%s can not operate on current_time' % (self._core.__class__))

def shift_current_time(self,days):
def shift_current_time(self, days):
'''
按时间步长调整时间
:param days:
:return:
'''
if isinstance(self._core,RealTimeTrading):
raise TypeError,'RealTimeTrading can not operate on current_time'
elif isinstance(self._core,HistoryTrading):
if isinstance(self._core, RealTimeTrading):
raise TypeError('RealTimeTrading can not operate on current_time')
elif isinstance(self._core, HistoryTrading):
self._current_time += datetime.timedelta(days=days)
return self._current_time.strftime('%Y-%m-%d')
#购买

# 购买
@input_checker
def buy(self,code,volume,price_type='now_price',price=None,date=None,effect_term = 1):
if isinstance(self._core,RealTimeTrading):
dic = {'code':code,
'volume':volume,
def buy(self, code, volume, price_type='now_price', price=None, date=None, effect_term=1):
if isinstance(self._core, RealTimeTrading):
dic = {'code': code,
'volume': volume,
'price_type': price_type,
'price': price,
'effect_term':str(effect_term)}
'effect_term': str(effect_term)}
self._core.set_stock_dic(dic)
res = self._core.buy()
return json.loads(res)
elif isinstance(self._core,HistoryTrading):
elif isinstance(self._core, HistoryTrading):
if not date:
date = self._current_time.strftime("%Y-%m-%d")
dic = {'date':date,
dic = {'date': date,
'code': code,
'volume': volume,
'price_type': 'average_price',
}
self._core.set_stock_dic(dic)
res = self._core.bt_buy()
return json.loads(res)
#卖出

# 卖出
@input_checker
def sell(self,code,volume,price_type='now_price',price=None,date=None,effect_term = 1):
if isinstance(self._core,RealTimeTrading):
dic = {'code':code,
'volume':volume,
def sell(self, code, volume, price_type='now_price', price=None, date=None, effect_term=1):
if isinstance(self._core, RealTimeTrading):
dic = {'code': code,
'volume': volume,
'price_type': price_type,
'price': price,
'effect_term':str(effect_term)}
'effect_term': str(effect_term)}
self._core.set_stock_dic(dic)
res = self._core.sell()
return json.loads(res)
elif isinstance(self._core,HistoryTrading):
elif isinstance(self._core, HistoryTrading):
if not date:
date = self._current_time.strftime("%Y-%m-%d")
dic = {'date': date,
Expand All @@ -157,60 +165,64 @@ def sell(self,code,volume,price_type='now_price',price=None,date=None,effect_ter
self._core.set_stock_dic(dic)
res = self._core.bt_sell()
return json.loads(res)
#撤单
def cancel_order(self,pre_id):
if isinstance(self._core,RealTimeTrading):

# 撤单
def cancel_order(self, pre_id):
if isinstance(self._core, RealTimeTrading):
return self._core.cancel_order(pre_id)
else:
raise TypeError
#资产和持仓情况

# 资产和持仓情况
def query_profit(self):
if isinstance(self._core, RealTimeTrading):
return json.loads(self._core.query_profit())
elif isinstance(self._core,HistoryTrading):
elif isinstance(self._core, HistoryTrading):
pass
#委托查询
def query_records(self,start="2018-4-4", end="2018-04-05"):
if isinstance(self._core,RealTimeTrading):
return json.loads(self._core.query_records(start,end))
#历史交割查询
def query_history_records(self,start='',end=''):
if isinstance(self._core,RealTimeTrading):
return json.loads(self._core.query_history_records(start,end))
elif isinstance(self._core,HistoryTrading):

# 委托查询
def query_records(self, start="2018-4-4", end="2018-04-05"):
if isinstance(self._core, RealTimeTrading):
return json.loads(self._core.query_records(start, end))

# 历史交割查询
def query_history_records(self, start='', end=''):
if isinstance(self._core, RealTimeTrading):
return json.loads(self._core.query_history_records(start, end))
elif isinstance(self._core, HistoryTrading):
return json.loads(self._core.bt_query_history_records(start, end))
#历史交割单输出到csv文件
def history_to_csv(self,path='history_record'):
if isinstance(self._core,RealTimeTrading):

# 历史交割单输出到csv文件
def history_to_csv(self, path='history_record'):
if isinstance(self._core, RealTimeTrading):
pass
elif isinstance(self._core,HistoryTrading):
elif isinstance(self._core, HistoryTrading):
return self._core.get_history_csv(path)
#查询策略

# 查询策略
def list_stratagy(self):
if isinstance(self._core,HistoryTrading):
if isinstance(self._core, HistoryTrading):
return json.loads(self._core.get_strategy())
else:
raise AttributeError, '%s has no attribute stratagy_name' % (self._core.__class__)
raise AttributeError('%s has no attribute stratagy_name' % (self._core.__class__))

# 设置策略名称
def set_stratagy(self, stratagy_name):
if isinstance(self._core, HistoryTrading):
self._core.set_strategy_name(stratagy_name)
else:
raise AttributeError, '%s has no attribute stratagy_name' % (self._core.__class__)
#创建策略
def create_stratagy(self,stratagy_name):
if isinstance(self._core,HistoryTrading):
raise AttributeError('%s has no attribute stratagy_name' % (self._core.__class__))

# 创建策略
def create_stratagy(self, stratagy_name):
if isinstance(self._core, HistoryTrading):
return self._core.create_strategy(stratagy_name)
else:
raise AttributeError
#删除策略
def del_stratagy(self,stratagy_name):
if isinstance(self._core,HistoryTrading):

# 删除策略
def del_stratagy(self, stratagy_name):
if isinstance(self._core, HistoryTrading):
return self._core.del_strategy(stratagy_name)
else:
raise AttributeError, '%s has no attribute stratagy_name' % (self._core.__class__)





raise AttributeError('%s has no attribute stratagy_name' % (self._core.__class__))
Loading