def test(self): if request.method == 'POST': id = request.args.get('id') model = Model.query.get(id) modelName = model.nick_name f = request.files['file'] uploadPath = '' config = Config.get() if f.filename: uploadPath = config[ 'appRoot'] + '/src/py/web/static/test_data/' + modelName + '.csv' f.save(uploadPath) @flask.stream_with_context def generate(): id = request.args.get('id') model = Model.query.get(id) cmd = 'CTP_CONFIG_PATH=%s python %s/src/py/test.py %s %s' % ( os.environ.get('CTP_CONFIG_PATH'), config['appRoot'], modelName, uploadPath) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) while p.poll() is None: line = p.stdout.read() if not line: continue yield line + '\n' return self.render('admin/runner_test.html', logs=generate()) else: return self.render('admin/runner_test.html', logs=[])
def getData(self): if not os.path.exists(self.dataPath): config = Config.get() self.dataPath = config[ 'appRoot'] + '/src/py/web/static/test_data/test.csv' data = csv.reader(open(self.dataPath, 'r')) isTitle = True title = [] tickData = [] for line in data: if isTitle: for t in line: title.append(t) isTitle = False continue tick = {} for i, t in enumerate(line): tick[title[i]] = t tickData.append(tick) self.over = True return tickData
def __init__(self, name, isToFile=False): self.logger = logging.getLogger(name) self.isToFile = isToFile if self.isToFile: config = Config.get() today = datetime.datetime.now().strftime("%Y%m%d") path = "%s/src/py/web/static/logs/online/%s_%s.log" % ( config['appRoot'], name, today) print path, name self.logger.addHandler(logging.FileHandler(path))
def index(self): config = Config.get() app = config['app'] appStr = json.dumps(app, indent=4) if request.method == 'POST': content = request.form.get('config') newApp = json.loads(content) config['app'] = newApp Config.write(config) return redirect('admin/config') return self.render('admin/config.html', appStr = appStr)
def lbtest(self): config = Config.get() if request.method == 'GET': id = request.args.get('id') model = Model.query.get(id) modelName = model.nick_name else: id = request.form.get('id') testVersion = request.form.get('testVersion') iids = request.form.get('iids') startDate = request.form.get('startDate') endDate = request.form.get('endDate') isRandom = request.form.get('isRandom') maxSlippage = request.form.get('maxSlippage') optional = '' if isRandom: optional += ' -r ' if isRandom and maxSlippage: optional += ' -s ' + maxSlippage + ' ' model = Model.query.get(id) modelName = model.nick_name cmd = 'CTP_CONFIG_PATH=%s python %s/src/py/lbtest.py %s %s %s %s %s %s' \ % (os.environ.get('CTP_CONFIG_PATH'), config['appRoot'], optional, modelName, testVersion, iids, startDate, endDate) now = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") fd = open( '%s/src/py/web/static/logs/lbtest/%s_%s_%s.log' % (config['appRoot'], modelName, testVersion, now), 'w') subprocess.Popen(cmd, shell=True, stdout=fd) locking = Locker.getLocking('TEST_SERVICE_RUNNING_' + modelName) files = [] for file in os.listdir('%s/src/py/web/static/logs/lbtest/' % (config['appRoot'])): if file.find(modelName) >= 0: files.append(file) return self.render('admin/runner_lbtest.html', locking=locking, id=id, logs=files)
def __init__(self, modelName, iids, version): self.server = Redis.get() self.sender = Redis.get() self.cache = Redis.get() self.config = Config.get() self.modelName = modelName self.srvChannel = version self.appConfig = self.config['app'][modelName] self.iids = iids # 获取模型 m = Model.query.filter(Model.nick_name==modelName).first() if not m: print 'Error: model not exist' exit() className = m.class_name moduleName = 'model.' + className moduleMeta = __import__(moduleName, globals(), locals(), [className]) classMeta = getattr(moduleMeta, className) self.model = classMeta(modelName, self)
from common.MySQL import MySQL from common.Config import Config from common.Redis import Redis import time as timeer import hashlib import demjson as JSON import datetime def format_price(num): num = float('{:.2f}'.format(num)) return 0 if num > 10000000.0 else num db = MySQL() rds = Redis.get() config = Config.get() iids = config['iids'] runningKey = 'CTP.QUEUE.RUNNING.CNT' rds.incr(runningKey) for i in xrange(1,10000): runningCnt = int(rds.get(runningKey)) if runningCnt > 5: break data = rds.rpop(config['queueKey']) if not data: timeer.sleep(1) continue
def build(self): config = Config.get() appRoot = config['appRoot'] self.cmd = "CTP_CONFIG_PATH=%s python %s/%s %s" % (os.environ.get('CTP_CONFIG_PATH'), appRoot, self.cmd, self.globalId)
def build(self): config = Config.get() appRoot = config['appRoot'] ctpConfig = config['ctpConfig'] self.cmd = "%s/%s %s/%s" % (appRoot, self.cmd, appRoot, ctpConfig)
def __init__(self, modelName, tradeSrv): self.modelName = modelName self.tradeSrv = tradeSrv self.appConfig = Config.get()['app'][modelName]
def index(self): if request.method == 'POST': iid = request.form.get('iid') if not iid: return jsonify(code=10002, msg="IID Name cannot be empty") config = Config.get() tick = filter(lambda x: x not in '0123456789', iid) # add tick table if tick not in config['iids']: config['iids'].append(tick) Config.write(config) mysql = MySQL() sql = ''' CREATE TABLE IF NOT EXISTS `tick_%s` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `token` char(32) NOT NULL DEFAULT '', `iid` varchar(50) NOT NULL DEFAULT '', `time` char(17) NOT NULL DEFAULT '', `msec` int(11) NOT NULL DEFAULT '0', `price` decimal(10,2) NOT NULL DEFAULT '0.00', `volume` int(11) NOT NULL DEFAULT '0', `bid_price1` decimal(10,2) NOT NULL DEFAULT '0.00', `bid_volume1` int(11) NOT NULL DEFAULT '0', `ask_price1` decimal(10,2) NOT NULL DEFAULT '0.00', `ask_volume1` int(11) NOT NULL DEFAULT '0', `mtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY idx_token(`token`), KEY idx_time(`time`) ) ENGINE=InnoDB CHARSET=utf8;''' % (tick) mysql.insert(sql) tickModel = createTickModel(tick) tmp_val = app._got_first_request app._got_first_request = False admin.add_view(TickView(tickModel, db.session, category='Tick')) app._got_first_request = tmp_val f = request.files['csv'] if not f: return jsonify(code=0, msg="create iid success") tmpPath = '/tmp/%s' % (f.filename) f.save(tmpPath) csv_reader = csv.reader(open(tmpPath)) isTitle = True total = succ = 0 mysql = MySQL() for row in csv_reader: if isTitle: if not self.checkTitle(row): return jsonify( code=10001, msg= "Error, title should be ['time', 'msec', 'price', 'volume', 'bid_price1', 'bid_volume1', 'ask_price1', 'ask_volume1']" ) isTitle = False continue total += 1 if self.insertTickData(mysql, iid, row): succ += 1 return jsonify(code=0, msg='ok', data={ 'total': total, 'succ': succ }) return self.render('admin/tick_upload.html')
def __init__(self): self.db = MySQL() self.rds = Redis.get() self.config = Config.get()
def edit_view(self): id = request.args.get('id') return_url = get_redirect_target() or self.get_url('.index_view') model = self.get_one(id) if model is None: flash('Record does not exist.', 'error') return redirect(return_url) form = self.edit_form(obj=model) if self.validate_form(form): if self.update_model(form, model): config = Config.get() filename = '%s/src/py/model/%s.py' % (config['appRoot'], form.class_name.data) with open(filename, 'w') as f: f.write(form.source.data) flash('Record was successfully saved.', 'success') return redirect(request.url) if request.method == 'GET': self.on_form_prefill(form, id) if not form.source.data: form.source.data = ''' #!/usr/bin/env python # -*- encoding:utf-8 -*- # from .ModelBase import ModelBase class %s(ModelBase): """ 模型类: 编写算法时,需要重写onTick、tradeSuccess以及tradeCancel方法 onTick:当有Tick信号时触发 tradeSuccess:下单成功时触发 tradeCancel:订单撤销时触发 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 可用变量: self.appConfig: 应用配置,在Config配置中,appKey所对应的配置项 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 可用方法: self.tradeNormal(iid='', price=3690, volume=2, isOpen=True, isBuy=True, isToday=True) 该方法用于下普通单,直到成交,触发tradeSuccess方法, 可手动撤单,撤单成功后会触发tradeCancel方法 self.tradeFAK(iid='', price=3690, volume=2, isOpen=True, isBuy=True, isToday=True) 该方法用于下FAK单,触发tradeSuccess或tradeCancel方法 self.tradeFOK(iid='', price=3690, volume=2, isOpen=True, isBuy=True, isToday=True) 该方法用于下FOK单,触发tradeSuccess或tradeCancel方法 self.tradeIOC(iid='', price=3690, volume=2, isOpen=True, isBuy=True, isToday=True) 该方法用于下市价单,涨跌停情况外,触发tradeSuccess方法 以上全部方法均返回tradeId,tradeId为此次交易的唯一订单ID, 可用于追踪订单 self.cancel(iid, tradeId) 该方法用于撤单 """ def __init__(self, appKey, tradeSrv): super(%s, self).__init__(appKey, tradeSrv) def onTick(self, tick): """ tick:Dict { 'iid': 'hc1808', // 合约 'price': 3400, // 最新价 'volume': 340, // 数量 'bidPrice1': 3333, 'bidVolume1': 300, 'askPrice1': 3322, 'askVolume1': 33, 'time': '20180312 11:23:44', // 时间 'msec': 500, // 毫秒 } """ pass def tradeSuccess(self, tradeId, dealPrice, dealVolume): """ tradeId: String 订单号 dealPrice: Float 成交价 dealVolume: Int 成交量 """ pass def tradeCancel(self, tradeId): pass ''' % (form.class_name.data, form.class_name.data) template = self.edit_template return self.render(template, id=id, model=model, form=form, return_url=return_url)