From 7a13aec4ecec431b7a86f6fe3a9e90d147912e91 Mon Sep 17 00:00:00 2001 From: cclauss Date: Mon, 14 May 2018 15:47:19 +0200 Subject: [PATCH 1/4] Modernize vnpy/trader/app --- vnpy/trader/app/ctaStrategy/ctaBacktesting.py | 7 ++-- vnpy/trader/app/ctaStrategy/ctaHistoryData.py | 39 ++++++++++--------- .../app/ctaStrategy/language/__init__.py | 3 +- .../app/ctaStrategy/strategy/__init__.py | 1 + vnpy/trader/app/dataRecorder/__init__.py | 5 ++- .../app/dataRecorder/language/__init__.py | 5 ++- vnpy/trader/app/jaqsService/__init__.py | 5 ++- vnpy/trader/app/jaqsService/jrpc_server.py | 23 +++++------ vnpy/trader/app/jaqsService/jsEngine.py | 3 +- vnpy/trader/app/jaqsService/service.py | 10 +++-- vnpy/trader/app/optionMaster/omDate.py | 10 +++-- .../app/optionMaster/strategy/__init__.py | 1 + .../app/optionMaster/uiOmManualTrader.py | 3 +- vnpy/trader/app/optionMaster/uiOmWidget.py | 4 +- vnpy/trader/app/riskManager/__init__.py | 3 +- .../app/riskManager/language/__init__.py | 3 +- vnpy/trader/app/spreadTrading/uiStWidget.py | 6 ++- 17 files changed, 76 insertions(+), 55 deletions(-) diff --git a/vnpy/trader/app/ctaStrategy/ctaBacktesting.py b/vnpy/trader/app/ctaStrategy/ctaBacktesting.py index c0bb5c6d..8adffc5d 100644 --- a/vnpy/trader/app/ctaStrategy/ctaBacktesting.py +++ b/vnpy/trader/app/ctaStrategy/ctaBacktesting.py @@ -5,6 +5,7 @@ 可以使用和实盘相同的代码进行回测。 ''' from __future__ import division +from __future__ import print_function from datetime import datetime, timedelta from collections import OrderedDict @@ -112,7 +113,7 @@ class BacktestingEngine(object): #---------------------------------------------------------------------- def output(self, content): """输出内容""" - print str(datetime.now()) + "\t" + content + print(str(datetime.now()) + "\t" + content) #------------------------------------------------ # 参数设置相关 @@ -1213,11 +1214,11 @@ class OptimizationSetting(object): return if end < start: - print u'参数起始点必须不大于终止点' + print(u'参数起始点必须不大于终止点') return if step <= 0: - print u'参数布进必须大于0' + print(u'参数布进必须大于0') return l = [] diff --git a/vnpy/trader/app/ctaStrategy/ctaHistoryData.py b/vnpy/trader/app/ctaStrategy/ctaHistoryData.py index aa49d82e..362a66e2 100644 --- a/vnpy/trader/app/ctaStrategy/ctaHistoryData.py +++ b/vnpy/trader/app/ctaStrategy/ctaHistoryData.py @@ -7,6 +7,7 @@ 3. 将交易开拓者导出的历史数据载入到MongoDB中的函数 4. 将OKEX下载的历史数据载入到MongoDB中的函数 """ +from __future__ import print_function import csv from datetime import datetime, timedelta @@ -26,7 +27,7 @@ def downloadEquityDailyBarts(self, symbol): """ 下载股票的日行情,symbol是股票代码 """ - print u'开始下载%s日行情' %symbol + print(u'开始下载%s日行情' %symbol) # 查询数据库中已有数据的最后日期 cl = self.dbClient[DAILY_DB_NAME][symbol] @@ -62,20 +63,20 @@ def downloadEquityDailyBarts(self, symbol): bar.datetime = datetime.strptime(bar.date, '%Y%m%d') bar.volume = d.get('volume') except KeyError: - print d + print(d) flt = {'datetime': bar.datetime} self.dbClient[DAILY_DB_NAME][symbol].update_one(flt, {'$set':bar.__dict__}, upsert=True) - print u'%s下载完成' %symbol + print(u'%s下载完成' %symbol) else: - print u'找不到合约%s' %symbol + print(u'找不到合约%s' %symbol) #---------------------------------------------------------------------- def loadMcCsv(fileName, dbName, symbol): """将Multicharts导出的csv格式的历史数据插入到Mongo数据库中""" start = time() - print u'开始读取CSV文件%s中的数据插入到%s的%s中' %(fileName, dbName, symbol) + print(u'开始读取CSV文件%s中的数据插入到%s的%s中' %(fileName, dbName, symbol)) # 锁定集合,并创建索引 client = pymongo.MongoClient(globalSetting['mongoHost'], globalSetting['mongoPort']) @@ -99,15 +100,15 @@ def loadMcCsv(fileName, dbName, symbol): flt = {'datetime': bar.datetime} collection.update_one(flt, {'$set':bar.__dict__}, upsert=True) - print bar.date, bar.time + print(bar.date, bar.time) - print u'插入完毕,耗时:%s' % (time()-start) + print(u'插入完毕,耗时:%s' % (time()-start)) #---------------------------------------------------------------------- def loadTbCsv(fileName, dbName, symbol): """将TradeBlazer导出的csv格式的历史分钟数据插入到Mongo数据库中""" start = time() - print u'开始读取CSV文件%s中的数据插入到%s的%s中' %(fileName, dbName, symbol) + print(u'开始读取CSV文件%s中的数据插入到%s的%s中' %(fileName, dbName, symbol)) # 锁定集合,并创建索引 client = pymongo.MongoClient(globalSetting['mongoHost'], globalSetting['mongoPort']) @@ -132,15 +133,15 @@ def loadTbCsv(fileName, dbName, symbol): flt = {'datetime': bar.datetime} collection.update_one(flt, {'$set':bar.__dict__}, upsert=True) - print bar.date, bar.time + print(bar.date, bar.time) - print u'插入完毕,耗时:%s' % (time()-start) + print(u'插入完毕,耗时:%s' % (time()-start)) #---------------------------------------------------------------------- def loadTbPlusCsv(fileName, dbName, symbol): """将TB极速版导出的csv格式的历史分钟数据插入到Mongo数据库中""" start = time() - print u'开始读取CSV文件%s中的数据插入到%s的%s中' %(fileName, dbName, symbol) + print(u'开始读取CSV文件%s中的数据插入到%s的%s中' %(fileName, dbName, symbol)) # 锁定集合,并创建索引 client = pymongo.MongoClient(globalSetting['mongoHost'], globalSetting['mongoPort']) @@ -167,9 +168,9 @@ def loadTbPlusCsv(fileName, dbName, symbol): bar.openInterest = d[7] flt = {'datetime': bar.datetime} collection.update_one(flt, {'$set':bar.__dict__}, upsert=True) - print bar.date, bar.time + print(bar.date, bar.time) - print u'插入完毕,耗时:%s' % (time()-start) + print(u'插入完毕,耗时:%s' % (time()-start)) #---------------------------------------------------------------------- """ @@ -186,7 +187,7 @@ def loadTdxCsv(fileName, dbName, symbol): """将通达信导出的csv格式的历史分钟数据插入到Mongo数据库中""" start = time() date_correct = "" - print u'开始读取CSV文件%s中的数据插入到%s的%s中' %(fileName, dbName, symbol) + print(u'开始读取CSV文件%s中的数据插入到%s的%s中' %(fileName, dbName, symbol)) # 锁定集合,并创建索引 client = pymongo.MongoClient(globalSetting['mongoHost'], globalSetting['mongoPort']) @@ -218,7 +219,7 @@ def loadTdxCsv(fileName, dbName, symbol): flt = {'datetime': bar.datetime} collection.update_one(flt, {'$set':bar.__dict__}, upsert=True) - print u'插入完毕,耗时:%s' % (time()-start) + print(u'插入完毕,耗时:%s' % (time()-start)) #---------------------------------------------------------------------- """ @@ -231,7 +232,7 @@ def loadTdxLc1(fileName, dbName, symbol): """将通达信导出的lc1格式的历史分钟数据插入到Mongo数据库中""" start = time() - print u'开始读取通达信Lc1文件%s中的数据插入到%s的%s中' %(fileName, dbName, symbol) + print(u'开始读取通达信Lc1文件%s中的数据插入到%s的%s中' %(fileName, dbName, symbol)) # 锁定集合,并创建索引 client = pymongo.MongoClient(globalSetting['mongoHost'], globalSetting['mongoPort']) @@ -267,13 +268,13 @@ def loadTdxLc1(fileName, dbName, symbol): flt = {'datetime': bar.datetime} collection.update_one(flt, {'$set':bar.__dict__}, upsert=True) - print u'插入完毕,耗时:%s' % (time()-start) + print(u'插入完毕,耗时:%s' % (time()-start)) #---------------------------------------------------------------------- def loadOKEXCsv(fileName, dbName, symbol): """将OKEX导出的csv格式的历史分钟数据插入到Mongo数据库中""" start = time() - print u'开始读取CSV文件%s中的数据插入到%s的%s中' %(fileName, dbName, symbol) + print(u'开始读取CSV文件%s中的数据插入到%s的%s中' %(fileName, dbName, symbol)) # 锁定集合,并创建索引 client = pymongo.MongoClient(globalSetting['mongoHost'], globalSetting['mongoPort']) @@ -304,5 +305,5 @@ def loadOKEXCsv(fileName, dbName, symbol): collection.update_one(flt, {'$set':bar.__dict__}, upsert=True) print('%s \t %s' % (bar.date, bar.time)) - print u'插入完毕,耗时:%s' % (time()-start) + print(u'插入完毕,耗时:%s' % (time()-start)) diff --git a/vnpy/trader/app/ctaStrategy/language/__init__.py b/vnpy/trader/app/ctaStrategy/language/__init__.py index f5c4ca18..e402c4f5 100644 --- a/vnpy/trader/app/ctaStrategy/language/__init__.py +++ b/vnpy/trader/app/ctaStrategy/language/__init__.py @@ -1,5 +1,6 @@ # encoding: UTF-8 +from __future__ import absolute_import import json import os import traceback @@ -10,4 +11,4 @@ from .chinese import text # 是否要使用英文 from vnpy.trader.vtGlobal import globalSetting if globalSetting['language'] == 'english': - from english import text + from .english import text diff --git a/vnpy/trader/app/ctaStrategy/strategy/__init__.py b/vnpy/trader/app/ctaStrategy/strategy/__init__.py index 7a14afa9..5b10bc02 100644 --- a/vnpy/trader/app/ctaStrategy/strategy/__init__.py +++ b/vnpy/trader/app/ctaStrategy/strategy/__init__.py @@ -3,6 +3,7 @@ ''' 动态载入所有的策略类 ''' +from __future__ import print_function import os import importlib diff --git a/vnpy/trader/app/dataRecorder/__init__.py b/vnpy/trader/app/dataRecorder/__init__.py index 84020dfe..8d3ddf78 100644 --- a/vnpy/trader/app/dataRecorder/__init__.py +++ b/vnpy/trader/app/dataRecorder/__init__.py @@ -1,7 +1,8 @@ # encoding: UTF-8 -from drEngine import DrEngine -from uiDrWidget import DrEngineManager +from __future__ import absolute_import +from .drEngine import DrEngine +from .uiDrWidget import DrEngineManager appName = 'DataRecorder' appDisplayName = u'行情记录' diff --git a/vnpy/trader/app/dataRecorder/language/__init__.py b/vnpy/trader/app/dataRecorder/language/__init__.py index ecf72358..09d8fba7 100644 --- a/vnpy/trader/app/dataRecorder/language/__init__.py +++ b/vnpy/trader/app/dataRecorder/language/__init__.py @@ -1,13 +1,14 @@ # encoding: UTF-8 +from __future__ import absolute_import import json import os import traceback # 默认设置 -from chinese import text +from .chinese import text # 是否要使用英文 from vnpy.trader.vtGlobal import globalSetting if globalSetting['language'] == 'english': - from english import text \ No newline at end of file + from .english import text \ No newline at end of file diff --git a/vnpy/trader/app/jaqsService/__init__.py b/vnpy/trader/app/jaqsService/__init__.py index f0bf3d26..4f7abcdd 100644 --- a/vnpy/trader/app/jaqsService/__init__.py +++ b/vnpy/trader/app/jaqsService/__init__.py @@ -1,7 +1,8 @@ # encoding: UTF-8 -from jsEngine import JsEngine -from uiJsWidget import JsEngineManager +from __future__ import absolute_import +from .jsEngine import JsEngine +from .uiJsWidget import JsEngineManager appName = 'JaqsService' appDisplayName = u'Jaqs服务' diff --git a/vnpy/trader/app/jaqsService/jrpc_server.py b/vnpy/trader/app/jaqsService/jrpc_server.py index d49037c1..a80edda3 100644 --- a/vnpy/trader/app/jaqsService/jrpc_server.py +++ b/vnpy/trader/app/jaqsService/jrpc_server.py @@ -1,3 +1,4 @@ +from __future__ import print_function import zmq import Queue import threading @@ -108,11 +109,11 @@ class JRpcServer : #client_addr_map[client_id] = identity self._on_data_arrived(identity, data) - except zmq.error.Again, e: + except zmq.error.Again as e: #print "RECV timeout: ", e pass - except Exception, e: - print("_recv_run:", e) + except Exception as e: + print(("_recv_run:", e)) def _callback_run(self): while not self._should_close: @@ -120,12 +121,12 @@ class JRpcServer : r = self._callback_queue.get(timeout = 1) if r : r() - except Queue.Empty, e: + except Queue.Empty as e: pass - except Exception, e: + except Exception as e: traceback.print_exc(e) - print "_callback_run", type(e), e + print("_callback_run", type(e), e) def _async_call(self, func): self._callback_queue.put( func ) @@ -164,12 +165,12 @@ class JRpcServer : #print "RECV", msg if not msg: - print "wrong message format" + print("wrong message format") return - method = msg['method'] if msg.has_key('method') else None + method = msg['method'] if 'method' in msg else None - call_id = msg['id'] if msg.has_key('id') and msg['id'] else None + call_id = msg['id'] if 'id' in msg and msg['id'] else None if call_id and method: if method == ".sys.heartbeat": @@ -183,8 +184,8 @@ class JRpcServer : if self.on_call : self._async_call( lambda : self.on_call(identity, msg)) - except Exception, e: - print( "_on_data_arrived:", e) + except Exception as e: + print(( "_on_data_arrived:", e)) pass diff --git a/vnpy/trader/app/jaqsService/jsEngine.py b/vnpy/trader/app/jaqsService/jsEngine.py index 8a072b57..15c6265c 100644 --- a/vnpy/trader/app/jaqsService/jsEngine.py +++ b/vnpy/trader/app/jaqsService/jsEngine.py @@ -1,9 +1,10 @@ # encoding: UTF-8 +from __future__ import absolute_import import json from collections import defaultdict -import jrpc_server +from . import jrpc_server from vnpy.event import Event from vnpy.trader.vtFunction import getJsonPath diff --git a/vnpy/trader/app/jaqsService/service.py b/vnpy/trader/app/jaqsService/service.py index 39bf6485..38cbae97 100644 --- a/vnpy/trader/app/jaqsService/service.py +++ b/vnpy/trader/app/jaqsService/service.py @@ -1,6 +1,8 @@ # -*- coding: utf-8 -*- -import jrpc_server +from __future__ import print_function +from __future__ import absolute_import +from . import jrpc_server import time import pandas as pd from qdata.database import DatabaseConn @@ -15,7 +17,7 @@ db = None def on_call(client_id, req): if req['method'] != '.sys.heartbeat': - print "on_call", req + print("on_call", req) if req['method'] == 'auth.login': server.send_rsp(client_id, req, result = { "username" : "fixme", "name": "fixme" }) @@ -25,7 +27,7 @@ def on_call(client_id, req): server.send_rsp(client_id, req, error=[-1, "unknown method"]) return - if not req.has_key('params'): + if 'params' not in req: server.send_rsp(client_id, req, error=[-1, "missing params"]) return @@ -55,7 +57,7 @@ def run(): server = jrpc_server.JRpcServer() server.on_call = on_call addr = "tcp://%s:%s"%(st.HOST, st.PORT) - print "listen at " + addr + print("listen at " + addr) server.listen(addr) while True: diff --git a/vnpy/trader/app/optionMaster/omDate.py b/vnpy/trader/app/optionMaster/omDate.py index 1211c166..795f3068 100644 --- a/vnpy/trader/app/optionMaster/omDate.py +++ b/vnpy/trader/app/optionMaster/omDate.py @@ -159,9 +159,11 @@ class CalendarManager(QtWidgets.QWidget): #---------------------------------------------------------------------- def runCalendarEditor(): """运行日历编辑器""" - reload(sys) - sys.setdefaultencoding('utf8') - + try: # Python 2 + reload(sys) + sys.setdefaultencoding('utf8') + except NameError: # Python 3 + pass app = QtWidgets.QApplication(sys.argv) app.setFont(QtGui.QFont(u'微软雅黑', 12)) @@ -249,4 +251,4 @@ def getTimeToMaturity(expiryDate): if __name__ == '__main__': - runCalendarEditor() \ No newline at end of file + runCalendarEditor() diff --git a/vnpy/trader/app/optionMaster/strategy/__init__.py b/vnpy/trader/app/optionMaster/strategy/__init__.py index 5e349490..0035381d 100644 --- a/vnpy/trader/app/optionMaster/strategy/__init__.py +++ b/vnpy/trader/app/optionMaster/strategy/__init__.py @@ -3,6 +3,7 @@ ''' 动态载入所有的策略类 ''' +from __future__ import print_function import os import importlib diff --git a/vnpy/trader/app/optionMaster/uiOmManualTrader.py b/vnpy/trader/app/optionMaster/uiOmManualTrader.py index 1652be06..d29743f9 100644 --- a/vnpy/trader/app/optionMaster/uiOmManualTrader.py +++ b/vnpy/trader/app/optionMaster/uiOmManualTrader.py @@ -1,5 +1,6 @@ # encoding: UTF-8 +from __future__ import absolute_import from vnpy.event import Event from vnpy.trader.vtConstant import DIRECTION_LONG, DIRECTION_SHORT, OFFSET_OPEN, OFFSET_CLOSE, PRICETYPE_LIMITPRICE @@ -7,7 +8,7 @@ from vnpy.trader.vtObject import VtOrderReq from vnpy.trader.vtEvent import EVENT_TICK, EVENT_TRADE from vnpy.trader.uiBasicWidget import WorkingOrderMonitor, PositionMonitor -from uiOmBase import * +from .uiOmBase import * diff --git a/vnpy/trader/app/optionMaster/uiOmWidget.py b/vnpy/trader/app/optionMaster/uiOmWidget.py index ea770808..956a6372 100644 --- a/vnpy/trader/app/optionMaster/uiOmWidget.py +++ b/vnpy/trader/app/optionMaster/uiOmWidget.py @@ -5,6 +5,8 @@ from __future__ import division import os from datetime import datetime +from six import text_type + from vnpy.event import Event from .omBase import EVENT_OM_LOG @@ -113,7 +115,7 @@ class OmManager(QtWidgets.QWidget): def initOmEngine(self): """初始化引擎""" path = os.getcwd() - fileName = unicode(self.comboSettingFile.currentText()) + fileName = text_type(self.comboSettingFile.currentText()) fileName = os.path.join(path, fileName) result = self.omEngine.initEngine(fileName) diff --git a/vnpy/trader/app/riskManager/__init__.py b/vnpy/trader/app/riskManager/__init__.py index 04e66bc5..daa917c0 100644 --- a/vnpy/trader/app/riskManager/__init__.py +++ b/vnpy/trader/app/riskManager/__init__.py @@ -1,5 +1,6 @@ # encoding: UTF-8 +from __future__ import absolute_import from .rmEngine import RmEngine from .uiRmWidget import RmEngineManager @@ -7,4 +8,4 @@ appName = 'RiskManager' appDisplayName = u'风险管理' appEngine = RmEngine appWidget = RmEngineManager -appIco = 'rm.ico' \ No newline at end of file +appIco = 'rm.ico' diff --git a/vnpy/trader/app/riskManager/language/__init__.py b/vnpy/trader/app/riskManager/language/__init__.py index f5c4ca18..e402c4f5 100644 --- a/vnpy/trader/app/riskManager/language/__init__.py +++ b/vnpy/trader/app/riskManager/language/__init__.py @@ -1,5 +1,6 @@ # encoding: UTF-8 +from __future__ import absolute_import import json import os import traceback @@ -10,4 +11,4 @@ from .chinese import text # 是否要使用英文 from vnpy.trader.vtGlobal import globalSetting if globalSetting['language'] == 'english': - from english import text + from .english import text diff --git a/vnpy/trader/app/spreadTrading/uiStWidget.py b/vnpy/trader/app/spreadTrading/uiStWidget.py index 7f505c8b..76b932fd 100644 --- a/vnpy/trader/app/spreadTrading/uiStWidget.py +++ b/vnpy/trader/app/spreadTrading/uiStWidget.py @@ -2,6 +2,8 @@ from collections import OrderedDict +from six import text_type + from vnpy.event import Event from vnpy.trader.uiQt import QtWidgets, QtCore from vnpy.trader.uiBasicWidget import (BasicMonitor, BasicCell, PnlCell, @@ -338,7 +340,7 @@ class StModeComboBox(QtWidgets.QComboBox): #---------------------------------------------------------------------- def setMode(self): """设置模式""" - mode = unicode(self.currentText()) + mode = text_type(self.currentText()) self.algoEngine.setAlgoMode(self.spreadName, mode) #---------------------------------------------------------------------- @@ -582,4 +584,4 @@ class StManager(QtWidgets.QWidget): - \ No newline at end of file + From 314dece44b8864d4f61b460a516692f83720e703 Mon Sep 17 00:00:00 2001 From: cclauss Date: Mon, 14 May 2018 16:02:15 +0200 Subject: [PATCH 2/4] Modernize vnpy/trader/gateway --- .../trader/gateway/cshshlpGateway/__init__.py | 3 ++- vnpy/trader/gateway/ctpGateway/__init__.py | 3 ++- .../gateway/ctpGateway/language/__init__.py | 5 +++-- vnpy/trader/gateway/femasGateway/__init__.py | 3 ++- .../gateway/femasGateway/femasGateway.py | 5 +++-- vnpy/trader/gateway/futuGateway/__init__.py | 1 + vnpy/trader/gateway/fxcmGateway/__init__.py | 3 ++- .../trader/gateway/fxcmGateway/fxcmGateway.py | 9 ++++---- vnpy/trader/gateway/huobiGateway/__init__.py | 3 ++- .../gateway/huobiGateway/huobiGateway.py | 21 ++++++++----------- vnpy/trader/gateway/ibGateway/__init__.py | 3 ++- vnpy/trader/gateway/ibGateway/ibGateway.py | 5 +++-- .../gateway/ibGateway/language/__init__.py | 12 +++++------ vnpy/trader/gateway/ksgoldGateway/__init__.py | 3 ++- vnpy/trader/gateway/ksotpGateway/__init__.py | 3 ++- vnpy/trader/gateway/lbankGateway/__init__.py | 3 ++- .../gateway/lbankGateway/lbankGateway.py | 5 +++-- vnpy/trader/gateway/ltsGateway/__init__.py | 3 ++- vnpy/trader/gateway/ltsGateway/ltsGateway.py | 3 ++- vnpy/trader/gateway/oandaGateway/__init__.py | 3 ++- vnpy/trader/gateway/qdpGateway/__init__.py | 3 ++- vnpy/trader/gateway/secGateway/__init__.py | 3 ++- vnpy/trader/gateway/secGateway/secGateway.py | 5 +++-- vnpy/trader/gateway/sgitGateway/__init__.py | 3 ++- vnpy/trader/gateway/shzdGateway/__init__.py | 3 ++- .../trader/gateway/shzdGateway/shzdGateway.py | 5 +++-- .../gateway/tkproGateway/tkproGateway.py | 2 +- vnpy/trader/gateway/windGateway/__init__.py | 3 ++- .../trader/gateway/windGateway/windGateway.py | 3 ++- vnpy/trader/gateway/xspeedGateway/__init__.py | 3 ++- vnpy/trader/gateway/xtpGateway/__init__.py | 3 ++- 31 files changed, 80 insertions(+), 55 deletions(-) diff --git a/vnpy/trader/gateway/cshshlpGateway/__init__.py b/vnpy/trader/gateway/cshshlpGateway/__init__.py index ff1cd68e..e340ebe5 100644 --- a/vnpy/trader/gateway/cshshlpGateway/__init__.py +++ b/vnpy/trader/gateway/cshshlpGateway/__init__.py @@ -1,7 +1,8 @@ # encoding: UTF-8 +from __future__ import absolute_import from vnpy.trader import vtConstant -from cshshlpGateway import CshshlpGateway +from .cshshlpGateway import CshshlpGateway gatewayClass = CshshlpGateway gatewayName = 'CSHSHLP' diff --git a/vnpy/trader/gateway/ctpGateway/__init__.py b/vnpy/trader/gateway/ctpGateway/__init__.py index 3078d854..8a8d5827 100644 --- a/vnpy/trader/gateway/ctpGateway/__init__.py +++ b/vnpy/trader/gateway/ctpGateway/__init__.py @@ -1,7 +1,8 @@ # encoding: UTF-8 +from __future__ import absolute_import from vnpy.trader import vtConstant -from ctpGateway import CtpGateway +from .ctpGateway import CtpGateway gatewayClass = CtpGateway gatewayName = 'CTP' diff --git a/vnpy/trader/gateway/ctpGateway/language/__init__.py b/vnpy/trader/gateway/ctpGateway/language/__init__.py index 2ca0ef80..8f68ed7f 100644 --- a/vnpy/trader/gateway/ctpGateway/language/__init__.py +++ b/vnpy/trader/gateway/ctpGateway/language/__init__.py @@ -1,15 +1,16 @@ # encoding: UTF-8 +from __future__ import absolute_import import json import os import traceback # 默认设置 -from chinese import text +from .chinese import text # 获取全局配置 from vnpy.trader.vtGlobal import globalSetting # 打开配置文件,读取语言配置 if globalSetting['language'] == 'english': - from english import text + from .english import text diff --git a/vnpy/trader/gateway/femasGateway/__init__.py b/vnpy/trader/gateway/femasGateway/__init__.py index 646b363e..e6897beb 100644 --- a/vnpy/trader/gateway/femasGateway/__init__.py +++ b/vnpy/trader/gateway/femasGateway/__init__.py @@ -1,7 +1,8 @@ # encoding: UTF-8 +from __future__ import absolute_import from vnpy.trader import vtConstant -from femasGateway import FemasGateway +from .femasGateway import FemasGateway gatewayClass = FemasGateway gatewayName = 'FEMAS' diff --git a/vnpy/trader/gateway/femasGateway/femasGateway.py b/vnpy/trader/gateway/femasGateway/femasGateway.py index c5962a49..88ba3d42 100644 --- a/vnpy/trader/gateway/femasGateway/femasGateway.py +++ b/vnpy/trader/gateway/femasGateway/femasGateway.py @@ -5,6 +5,7 @@ vn.femas的gateway接入 考虑到飞马只对接期货(目前只有中金所), vtSymbol直接使用symbol ''' +from __future__ import print_function import os @@ -599,10 +600,10 @@ class FemasTdApi(TdApi): # 如果登录成功,推送日志信息 if error['ErrorID'] == 0: for k, v in data.items(): - print k, ':', v + print(k, ':', v) if data['MaxOrderLocalID']: self.localID = int(data['MaxOrderLocalID']) # 目前最大本地报单号 - print 'id now', self.localID + print('id now', self.localID) self.loginStatus = True self.gateway.mdConnected = True diff --git a/vnpy/trader/gateway/futuGateway/__init__.py b/vnpy/trader/gateway/futuGateway/__init__.py index 827c2b6c..3778ebc6 100644 --- a/vnpy/trader/gateway/futuGateway/__init__.py +++ b/vnpy/trader/gateway/futuGateway/__init__.py @@ -1,5 +1,6 @@ # encoding: UTF-8 +from __future__ import absolute_import from vnpy.trader import vtConstant from .futuGateway import FutuGateway diff --git a/vnpy/trader/gateway/fxcmGateway/__init__.py b/vnpy/trader/gateway/fxcmGateway/__init__.py index 26e36c12..53254b47 100644 --- a/vnpy/trader/gateway/fxcmGateway/__init__.py +++ b/vnpy/trader/gateway/fxcmGateway/__init__.py @@ -1,7 +1,8 @@ # encoding: UTF-8 +from __future__ import absolute_import from vnpy.trader import vtConstant -from fxcmGateway import FxcmGateway +from .fxcmGateway import FxcmGateway gatewayClass = FxcmGateway gatewayName = 'FXCM' diff --git a/vnpy/trader/gateway/fxcmGateway/fxcmGateway.py b/vnpy/trader/gateway/fxcmGateway/fxcmGateway.py index 712b0692..fc5f323f 100644 --- a/vnpy/trader/gateway/fxcmGateway/fxcmGateway.py +++ b/vnpy/trader/gateway/fxcmGateway/fxcmGateway.py @@ -1,5 +1,6 @@ # encoding: UTF-8 +from __future__ import print_function import os import json from datetime import datetime @@ -434,22 +435,22 @@ class Api(FxcmApi): #---------------------------------------------------------------------- def onOpenTrade(self, data, reqid): """开仓回调""" - print data, reqid + print(data, reqid) #---------------------------------------------------------------------- def onCloseTrade(self, data, reqid): """平仓回调""" - print data, reqid + print(data, reqid) #---------------------------------------------------------------------- def onChangeOrder(self, data, reqid): """改单回调""" - print data, reqid + print(data, reqid) #---------------------------------------------------------------------- def onDeleteOrder(self, data, reqid): """撤单回调""" - print data, reqid + print(data, reqid) #---------------------------------------------------------------------- def onPriceUpdate(self, data): diff --git a/vnpy/trader/gateway/huobiGateway/__init__.py b/vnpy/trader/gateway/huobiGateway/__init__.py index b6bb6efe..34044316 100644 --- a/vnpy/trader/gateway/huobiGateway/__init__.py +++ b/vnpy/trader/gateway/huobiGateway/__init__.py @@ -1,7 +1,8 @@ # encoding: UTF-8 +from __future__ import absolute_import from vnpy.trader import vtConstant -from huobiGateway import HuobiGateway +from .huobiGateway import HuobiGateway gatewayClass = HuobiGateway gatewayName = 'HUOBI' diff --git a/vnpy/trader/gateway/huobiGateway/huobiGateway.py b/vnpy/trader/gateway/huobiGateway/huobiGateway.py index b3fc31d4..b84cf580 100644 --- a/vnpy/trader/gateway/huobiGateway/huobiGateway.py +++ b/vnpy/trader/gateway/huobiGateway/huobiGateway.py @@ -3,8 +3,8 @@ ''' vn.sec的gateway接入 ''' +from __future__ import print_function -import os import json from datetime import datetime, timedelta from copy import copy @@ -12,7 +12,7 @@ from math import pow from vnpy.api.huobi import TradeApi, DataApi from vnpy.trader.vtGateway import * -from vnpy.trader.vtFunction import getJsonPath, getTempPath +from vnpy.trader.vtFunction import getJsonPath # 委托状态类型映射 @@ -29,11 +29,9 @@ statusMapReverse['canceled'] = STATUS_CANCELLED #---------------------------------------------------------------------- def print_dict(d): """""" - print '-' * 30 - l = d.keys() - l.sort() - for k in l: - print '%s:%s' %(k, d[k]) + print('-' * 30) + for key in sorted(d): + print('%s:%s' % (key, d[key])) ######################################################################## @@ -60,7 +58,7 @@ class HuobiGateway(VtGateway): def connect(self): """连接""" try: - f = file(self.filePath) + f = open(self.filePath) except IOError: log = VtLogData() log.gatewayName = self.gatewayName @@ -294,7 +292,7 @@ class HuobiDataApi(DataApi): #---------------------------------------------------------------------- def onTradeDetail(self, data): """成交细节推送""" - print data + print(data) #---------------------------------------------------------------------- def onMarketDetail(self, data): @@ -322,7 +320,6 @@ class HuobiDataApi(DataApi): self.gateway.onTick(tick) - ######################################################################## class HuobiTradeApi(TradeApi): """交易API实现""" @@ -693,7 +690,7 @@ class HuobiTradeApi(TradeApi): #---------------------------------------------------------------------- def onGetMatchResult(self, data, reqid): """查询单一成交回调""" - print reqid, data + print(reqid, data) #---------------------------------------------------------------------- def onPlaceOrder(self, data, reqid): @@ -717,4 +714,4 @@ class HuobiTradeApi(TradeApi): #---------------------------------------------------------------------- def onBatchCancel(self, data, reqid): """批量撤单回调""" - print reqid, data + print(reqid, data) diff --git a/vnpy/trader/gateway/ibGateway/__init__.py b/vnpy/trader/gateway/ibGateway/__init__.py index c7be4fdd..8d6335a4 100644 --- a/vnpy/trader/gateway/ibGateway/__init__.py +++ b/vnpy/trader/gateway/ibGateway/__init__.py @@ -1,7 +1,8 @@ # encoding: UTF-8 +from __future__ import absolute_import from vnpy.trader import vtConstant -from ibGateway import IbGateway +from .ibGateway import IbGateway gatewayClass = IbGateway gatewayName = 'IB' diff --git a/vnpy/trader/gateway/ibGateway/ibGateway.py b/vnpy/trader/gateway/ibGateway/ibGateway.py index 9c6c251e..3f70826b 100644 --- a/vnpy/trader/gateway/ibGateway/ibGateway.py +++ b/vnpy/trader/gateway/ibGateway/ibGateway.py @@ -10,6 +10,7 @@ Interactive Brokers的gateway接入,已经替换为vn.ib封装。 4. 目前只支持股票和期货交易,ib api里期权合约的确定是基于Contract对象的多个字段,比较复杂暂时没做 5. 海外市场的交易规则和国内有很多细节上的不同,所以一些字段类型的映射可能不合理,如果发现问题欢迎指出 ''' +from __future__ import print_function import os import json @@ -375,7 +376,7 @@ class IbWrapper(IbApi): newtick = copy(tick) self.gateway.onTick(newtick) else: - print field + print(field) #---------------------------------------------------------------------- def tickSize(self, tickerId, field, size): @@ -385,7 +386,7 @@ class IbWrapper(IbApi): key = tickFieldMap[field] tick.__setattr__(key, size) else: - print field + print(field) #---------------------------------------------------------------------- def tickOptionComputation(self, tickerId, tickType, impliedVol, delta, optPrice, pvDividend, gamma, vega, theta, undPrice): diff --git a/vnpy/trader/gateway/ibGateway/language/__init__.py b/vnpy/trader/gateway/ibGateway/language/__init__.py index 8325ae0c..e9efec4b 100644 --- a/vnpy/trader/gateway/ibGateway/language/__init__.py +++ b/vnpy/trader/gateway/ibGateway/language/__init__.py @@ -1,11 +1,12 @@ # encoding: UTF-8 +from __future__ import absolute_import import json import os import traceback # 默认设置 -from chinese import text +from .chinese import text # 获取目录上级路径 path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')) @@ -14,10 +15,9 @@ SETTING_FILENAME = os.path.join(path, SETTING_FILENAME) # 打开配置文件,读取语言配置 try: - f = file(SETTING_FILENAME) - setting = json.load(f) + with open(SETTING_FILENAME) as f: + setting = json.load(f) if setting['language'] == 'english': - from english import text - f.close() -except: + from .english import text +except Exception: traceback.print_exc() diff --git a/vnpy/trader/gateway/ksgoldGateway/__init__.py b/vnpy/trader/gateway/ksgoldGateway/__init__.py index b81b6ef3..cc9ef208 100644 --- a/vnpy/trader/gateway/ksgoldGateway/__init__.py +++ b/vnpy/trader/gateway/ksgoldGateway/__init__.py @@ -1,7 +1,8 @@ # encoding: UTF-8 +from __future__ import absolute_import from vnpy.trader import vtConstant -from ksgoldGateway import KsgoldGateway +from .ksgoldGateway import KsgoldGateway gatewayClass = KsgoldGateway gatewayName = 'KSGOLD' diff --git a/vnpy/trader/gateway/ksotpGateway/__init__.py b/vnpy/trader/gateway/ksotpGateway/__init__.py index cf9c5dbb..d18f121a 100644 --- a/vnpy/trader/gateway/ksotpGateway/__init__.py +++ b/vnpy/trader/gateway/ksotpGateway/__init__.py @@ -1,7 +1,8 @@ # encoding: UTF-8 +from __future__ import absolute_import from vnpy.trader import vtConstant -from ksotpGateway import KsotpGateway +from .ksotpGateway import KsotpGateway gatewayClass = KsotpGateway gatewayName = 'KSOTP' diff --git a/vnpy/trader/gateway/lbankGateway/__init__.py b/vnpy/trader/gateway/lbankGateway/__init__.py index 4d5d6e00..72ba49d8 100644 --- a/vnpy/trader/gateway/lbankGateway/__init__.py +++ b/vnpy/trader/gateway/lbankGateway/__init__.py @@ -1,7 +1,8 @@ # encoding: UTF-8 +from __future__ import absolute_import from vnpy.trader import vtConstant -from lbankGateway import LbankGateway +from .lbankGateway import LbankGateway gatewayClass = LbankGateway gatewayName = 'LBANK' diff --git a/vnpy/trader/gateway/lbankGateway/lbankGateway.py b/vnpy/trader/gateway/lbankGateway/lbankGateway.py index 85f82ae3..3cade80e 100644 --- a/vnpy/trader/gateway/lbankGateway/lbankGateway.py +++ b/vnpy/trader/gateway/lbankGateway/lbankGateway.py @@ -3,6 +3,7 @@ ''' vn.lhang的gateway接入 ''' +from __future__ import print_function import os @@ -244,11 +245,11 @@ class LbankApi(LbankApi): # ---------------------------------------------------------------------- def onGetTrades(self, data, req, reqID): """查询历史成交""" - print data, reqID + print(data, reqID) # ---------------------------------------------------------------------- def onGetKline(self, data, req, reqID): - print data, reqID + print(data, reqID) # ---------------------------------------------------------------------- def onGetUserInfo(self, data, req, reqID): diff --git a/vnpy/trader/gateway/ltsGateway/__init__.py b/vnpy/trader/gateway/ltsGateway/__init__.py index cbb88696..72306493 100644 --- a/vnpy/trader/gateway/ltsGateway/__init__.py +++ b/vnpy/trader/gateway/ltsGateway/__init__.py @@ -1,7 +1,8 @@ # encoding: UTF-8 +from __future__ import absolute_import from vnpy.trader import vtConstant -from ltsGateway import LtsGateway +from .ltsGateway import LtsGateway gatewayClass = LtsGateway gatewayName = 'LTS' diff --git a/vnpy/trader/gateway/ltsGateway/ltsGateway.py b/vnpy/trader/gateway/ltsGateway/ltsGateway.py index 83610ac2..00942059 100644 --- a/vnpy/trader/gateway/ltsGateway/ltsGateway.py +++ b/vnpy/trader/gateway/ltsGateway/ltsGateway.py @@ -3,6 +3,7 @@ ''' vn.lts的gateway接入 ''' +from __future__ import print_function import os import json @@ -980,7 +981,7 @@ class LtsQryApi(QryApi): elif data['ProductClass'] == '8': contract.productClass = PRODUCT_EQUITY else: - print data['ProductClass'] + print(data['ProductClass']) # 期权类型 if data['InstrumentType'] == '1': diff --git a/vnpy/trader/gateway/oandaGateway/__init__.py b/vnpy/trader/gateway/oandaGateway/__init__.py index 0ce2fb0d..7ba3dbdb 100644 --- a/vnpy/trader/gateway/oandaGateway/__init__.py +++ b/vnpy/trader/gateway/oandaGateway/__init__.py @@ -1,7 +1,8 @@ # encoding: UTF-8 +from __future__ import absolute_import from vnpy.trader import vtConstant -from oandaGateway import OandaGateway +from .oandaGateway import OandaGateway gatewayClass = OandaGateway gatewayName = 'OANDA' diff --git a/vnpy/trader/gateway/qdpGateway/__init__.py b/vnpy/trader/gateway/qdpGateway/__init__.py index 4fb85e9b..2c8b6685 100644 --- a/vnpy/trader/gateway/qdpGateway/__init__.py +++ b/vnpy/trader/gateway/qdpGateway/__init__.py @@ -1,7 +1,8 @@ # encoding: UTF-8 +from __future__ import absolute_import from vnpy.trader import vtConstant -from qdpGateway import QdpGateway +from .qdpGateway import QdpGateway gatewayClass = QdpGateway gatewayName = 'QDP' diff --git a/vnpy/trader/gateway/secGateway/__init__.py b/vnpy/trader/gateway/secGateway/__init__.py index c919bb29..ba50b638 100644 --- a/vnpy/trader/gateway/secGateway/__init__.py +++ b/vnpy/trader/gateway/secGateway/__init__.py @@ -1,7 +1,8 @@ # encoding: UTF-8 +from __future__ import absolute_import from vnpy.trader import vtConstant -from secGateway import SecGateway +from .secGateway import SecGateway gatewayClass = SecGateway gatewayName = 'SEC' diff --git a/vnpy/trader/gateway/secGateway/secGateway.py b/vnpy/trader/gateway/secGateway/secGateway.py index 095341b8..a5ff3d01 100644 --- a/vnpy/trader/gateway/secGateway/secGateway.py +++ b/vnpy/trader/gateway/secGateway/secGateway.py @@ -3,6 +3,7 @@ ''' vn.sec的gateway接入 ''' +from __future__ import print_function import os import json @@ -50,11 +51,11 @@ exchangeMapReverse = {v:k for k,v in exchangeMap.items()} #---------------------------------------------------------------------- def print_dict(d): """""" - print '-' * 30 + print('-' * 30) l = d.keys() l.sort() for k in l: - print '%s:%s' %(k, d[k]) + print('%s:%s' %(k, d[k])) ######################################################################## diff --git a/vnpy/trader/gateway/sgitGateway/__init__.py b/vnpy/trader/gateway/sgitGateway/__init__.py index 2be6983b..52c55412 100644 --- a/vnpy/trader/gateway/sgitGateway/__init__.py +++ b/vnpy/trader/gateway/sgitGateway/__init__.py @@ -1,7 +1,8 @@ # encoding: UTF-8 +from __future__ import absolute_import from vnpy.trader import vtConstant -from sgitGateway import SgitGateway +from .sgitGateway import SgitGateway gatewayClass = SgitGateway gatewayName = 'SGIT' diff --git a/vnpy/trader/gateway/shzdGateway/__init__.py b/vnpy/trader/gateway/shzdGateway/__init__.py index 7f5d3497..fd10bb58 100644 --- a/vnpy/trader/gateway/shzdGateway/__init__.py +++ b/vnpy/trader/gateway/shzdGateway/__init__.py @@ -1,7 +1,8 @@ # encoding: UTF-8 +from __future__ import absolute_import from vnpy.trader import vtConstant -from shzdGateway import ShzdGateway +from .shzdGateway import ShzdGateway gatewayClass = ShzdGateway gatewayName = 'SHZD' diff --git a/vnpy/trader/gateway/shzdGateway/shzdGateway.py b/vnpy/trader/gateway/shzdGateway/shzdGateway.py index 3ed9f305..d49ba6b0 100644 --- a/vnpy/trader/gateway/shzdGateway/shzdGateway.py +++ b/vnpy/trader/gateway/shzdGateway/shzdGateway.py @@ -8,6 +8,7 @@ vn.shzd的gateway接入 3. 持仓全部平光后,再次查询时会没有该合约的推送(和CTP不同),为了避免最后平仓 不更新的情况,使用缓存机制来处理 ''' +from __future__ import print_function import os @@ -721,9 +722,9 @@ class ShzdGatewayApi(ShzdApi): #---------------------------------------------------------------------- def printDict(d): """打印字典""" - print '-' * 50 + print('-' * 50) l = d.keys() l.sort() for k in l: - print k, ':', d[k] + print(k, ':', d[k]) \ No newline at end of file diff --git a/vnpy/trader/gateway/tkproGateway/tkproGateway.py b/vnpy/trader/gateway/tkproGateway/tkproGateway.py index 85d406cc..ddd53e4a 100644 --- a/vnpy/trader/gateway/tkproGateway/tkproGateway.py +++ b/vnpy/trader/gateway/tkproGateway/tkproGateway.py @@ -570,7 +570,7 @@ class TkproDataApi(object): tick.lowerLimit = data['limit_down'] self.gateway.onTick(tick) - except Exception, e: + except Exception as e: self.writeLog(u'行情更新失败,错误信息:%s' % str(e)) #---------------------------------------------------------------------- diff --git a/vnpy/trader/gateway/windGateway/__init__.py b/vnpy/trader/gateway/windGateway/__init__.py index f2508aee..fc9949b4 100644 --- a/vnpy/trader/gateway/windGateway/__init__.py +++ b/vnpy/trader/gateway/windGateway/__init__.py @@ -1,7 +1,8 @@ # encoding: UTF-8 +from __future__ import absolute_import from vnpy.trader import vtConstant -from windGateway import WindGateway +from .windGateway import WindGateway gatewayClass = WindGateway gatewayName = 'WIND' diff --git a/vnpy/trader/gateway/windGateway/windGateway.py b/vnpy/trader/gateway/windGateway/windGateway.py index 1a872cdf..e244b6c5 100644 --- a/vnpy/trader/gateway/windGateway/windGateway.py +++ b/vnpy/trader/gateway/windGateway/windGateway.py @@ -3,6 +3,7 @@ ''' Wind Python API的gateway接入 ''' +from __future__ import print_function from copy import copy @@ -11,7 +12,7 @@ w = None try: from WindPy import w except ImportError: - print u'请先安装WindPy接口' + print(u'请先安装WindPy接口') from vnpy.trader.vtGateway import * diff --git a/vnpy/trader/gateway/xspeedGateway/__init__.py b/vnpy/trader/gateway/xspeedGateway/__init__.py index 50d26714..ee1f848b 100644 --- a/vnpy/trader/gateway/xspeedGateway/__init__.py +++ b/vnpy/trader/gateway/xspeedGateway/__init__.py @@ -1,7 +1,8 @@ # encoding: UTF-8 +from __future__ import absolute_import from vnpy.trader import vtConstant -from xspeedGateway import XspeedGateway +from .xspeedGateway import XspeedGateway gatewayClass = XspeedGateway gatewayName = 'XSPEED' diff --git a/vnpy/trader/gateway/xtpGateway/__init__.py b/vnpy/trader/gateway/xtpGateway/__init__.py index bd4dfe6d..b9ea0af4 100644 --- a/vnpy/trader/gateway/xtpGateway/__init__.py +++ b/vnpy/trader/gateway/xtpGateway/__init__.py @@ -1,7 +1,8 @@ # encoding: UTF-8 +from __future__ import absolute_import from vnpy.trader import vtConstant -from xtpGateway import XtpGateway +from .xtpGateway import XtpGateway gatewayClass = XtpGateway gatewayName = 'XTP' From 49d22b47beed8d94043e4667f1bf5a3ce27b9c66 Mon Sep 17 00:00:00 2001 From: "vn.py" Date: Mon, 11 Jun 2018 13:06:41 +0800 Subject: [PATCH 3/4] =?UTF-8?q?[Mod]=E5=A2=9E=E5=8A=A0BitfinexGateway?= =?UTF-8?q?=E8=A1=8C=E6=83=85=E6=95=B0=E6=8D=AE=E7=9A=84=E5=BC=BA=E5=88=B6?= =?UTF-8?q?=E6=95=B0=E5=AD=97=E7=B1=BB=E5=9E=8B=E8=BD=AC=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../gateway/bitfinexGateway/bitfinexGateway.py | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/vnpy/trader/gateway/bitfinexGateway/bitfinexGateway.py b/vnpy/trader/gateway/bitfinexGateway/bitfinexGateway.py index 5aef41be..31c9cf52 100644 --- a/vnpy/trader/gateway/bitfinexGateway/bitfinexGateway.py +++ b/vnpy/trader/gateway/bitfinexGateway/bitfinexGateway.py @@ -350,11 +350,11 @@ class GatewayApi(BitfinexApi): # 常规行情更新 if channel == 'ticker': - tick.volume = l[-3] - tick.highPrice = l[-2] - tick.lowPrice = l[-1] - tick.lastPrice = l[-4] - tick.openPrice = tick.lastPrice - l[4] + tick.volume = float(l[-3]) + tick.highPrice = float(l[-2]) + tick.lowPrice = float(l[-1]) + tick.lastPrice = float(l[-4]) + tick.openPrice = float(tick.lastPrice - l[4]) # 深度报价更新 elif channel == 'book': bid = self.bidDict.setdefault(symbol, {}) @@ -362,12 +362,20 @@ class GatewayApi(BitfinexApi): if len(l) > 3: for price, count, amount in l: + price = float(price) + count = int(count) + amount = float(amount) + if amount > 0: bid[price] = amount else: ask[price] = -amount else: price, count, amount = l + price = float(price) + count = int(count) + amount = float(amount) + if not count: if price in bid: del bid[price] From 920ee7fbb1ab6f609ed31160fafc2e2c440b05ed Mon Sep 17 00:00:00 2001 From: "vn.py" Date: Mon, 11 Jun 2018 14:09:16 +0800 Subject: [PATCH 4/4] =?UTF-8?q?[Add]=E6=96=B0=E5=A2=9E=E4=BB=8ECSV?= =?UTF-8?q?=E5=90=AF=E5=8A=A8=E7=AF=AE=E5=AD=90=E7=AE=97=E6=B3=95=E6=88=96?= =?UTF-8?q?=E8=80=85=E5=8A=A0=E8=BD=BD=E7=AE=97=E6=B3=95=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E5=88=B0=E6=95=B0=E6=8D=AE=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/CryptoTrader/algoBasket.csv | 3 + vnpy/trader/app/algoTrading/twapAlgo.py | 18 ++--- vnpy/trader/app/algoTrading/uiAlgoManager.py | 74 +++++++++++++++++--- vnpy/trader/uiBasicWidget.py | 2 +- 4 files changed, 79 insertions(+), 18 deletions(-) create mode 100644 examples/CryptoTrader/algoBasket.csv diff --git a/examples/CryptoTrader/algoBasket.csv b/examples/CryptoTrader/algoBasket.csv new file mode 100644 index 00000000..dfecd5b2 --- /dev/null +++ b/examples/CryptoTrader/algoBasket.csv @@ -0,0 +1,3 @@ +templateName,settingName,vtSymbol,direction,targetPrice,totalVolume,time,interval,priceLevel,minVolume +TWAP,BUY_BTC_TWAP,BTCUSD.BITFINEX,多,4000,10,200,10,3,1 +TWAP,SELL_BTC_TWAP,BTCUSD.BITFINEX,空,9000,10,200,10,3,1 diff --git a/vnpy/trader/app/algoTrading/twapAlgo.py b/vnpy/trader/app/algoTrading/twapAlgo.py index b4bc9f7d..d3727136 100644 --- a/vnpy/trader/app/algoTrading/twapAlgo.py +++ b/vnpy/trader/app/algoTrading/twapAlgo.py @@ -21,15 +21,15 @@ class TwapAlgo(AlgoTemplate): """Constructor""" super(TwapAlgo, self).__init__(engine, setting, algoName) - # 参数 - self.vtSymbol = setting['vtSymbol'] # 合约代码 - self.direction = setting['direction'] # 买卖 - self.targetPrice = setting['targetPrice'] # 目标价格 - self.totalVolume = setting['totalVolume'] # 总数量 - self.time = setting['time'] # 执行时间 - self.interval = setting['interval'] # 执行间隔 - self.minVolume = setting['minVolume'] # 最小委托数量 - self.priceLevel = setting['priceLevel'] # 使用第几档价格委托 + # 参数,强制类型转换,保证从CSV加载的配置正确 + self.vtSymbol = str(setting['vtSymbol']) # 合约代码 + self.direction = unicode(setting['direction']) # 买卖 + self.targetPrice = float(setting['targetPrice']) # 目标价格 + self.totalVolume = float(setting['totalVolume']) # 总数量 + self.time = int(setting['time']) # 执行时间 + self.interval = int(setting['interval']) # 执行间隔 + self.minVolume = float(setting['minVolume']) # 最小委托数量 + self.priceLevel = int(setting['priceLevel']) # 使用第几档价格委托 # 变量 self.orderSize = self.totalVolume / (self.time / self.interval) diff --git a/vnpy/trader/app/algoTrading/uiAlgoManager.py b/vnpy/trader/app/algoTrading/uiAlgoManager.py index fa92fae3..811d1b08 100644 --- a/vnpy/trader/app/algoTrading/uiAlgoManager.py +++ b/vnpy/trader/app/algoTrading/uiAlgoManager.py @@ -1,5 +1,9 @@ # encoding: UTF-8 +import csv +import traceback +from collections import OrderedDict + from vnpy.event import Event from vnpy.trader.uiQt import QtCore, QtWidgets @@ -26,7 +30,7 @@ class StopButton(QtWidgets.QPushButton): self.setText(u'停止') self.clicked.connect(self.stopAlgo) else: - self.setText(u'全部停止') + self.setText(u'停止全部算法') self.clicked.connect(self.stopAll) #---------------------------------------------------------------------- @@ -388,17 +392,32 @@ class AlgoManager(QtWidgets.QWidget): """""" self.setWindowTitle(u'算法交易') - self.tab = QtWidgets.QTabWidget() - self.buttonStop = StopButton(self.algoEngine) + buttonWidth = 400 + buttonHeight = 60 - self.tab.setMaximumWidth(400) - self.buttonStop.setMaximumWidth(400) - self.buttonStop.setFixedHeight(100) + self.tab = QtWidgets.QTabWidget() + self.tab.setMaximumWidth(buttonWidth) + + self.buttonStop = StopButton(self.algoEngine) + self.buttonStop.setMaximumWidth(buttonWidth) + self.buttonStop.setFixedHeight(buttonHeight) + + self.buttonAddAlgo = QtWidgets.QPushButton(u'启动篮子算法') + self.buttonAddAlgo.setStyleSheet("color:white;background-color:green") + self.buttonAddAlgo.clicked.connect(self.addAlgoFromCsv) + self.buttonAddAlgo.setFixedHeight(buttonHeight) + + self.buttonSaveSetting = QtWidgets.QPushButton(u'加载算法配置') + self.buttonSaveSetting.setStyleSheet("color:white;background-color:blue") + self.buttonSaveSetting.clicked.connect(self.saveSettingFromCsv) + self.buttonSaveSetting.setFixedHeight(buttonHeight) vbox1 = QtWidgets.QVBoxLayout() vbox1.addWidget(self.tab) vbox1.addStretch() vbox1.addWidget(self.buttonStop) + vbox1.addWidget(self.buttonAddAlgo) + vbox1.addWidget(self.buttonSaveSetting) workingMonitor = AlgoStatusMonitor(self.algoEngine, AlgoStatusMonitor.MODE_WORKING) historyMonitor = AlgoStatusMonitor(self.algoEngine, AlgoStatusMonitor.MODE_HISTORY) @@ -431,6 +450,45 @@ class AlgoManager(QtWidgets.QWidget): #---------------------------------------------------------------------- def addAlgoWidget(self, widgetClass): - """""" + """添加算法控制组件 """ w = widgetClass(self.algoEngine) - self.tab.addTab(w, w.templateName) \ No newline at end of file + self.tab.addTab(w, w.templateName) + + #---------------------------------------------------------------------- + def loadCsv(self, path): + """读取CSV配置文件""" + try: + with open(unicode(path)) as f: + buf = [line.encode('UTF-8') for line in f] + + reader = csv.DictReader(buf) + l = [] + + for d in reader: + setting = OrderedDict() + for name in reader.fieldnames: + setting[str(name)] = d[name] + l.append(setting) + + return l + + except: + msg = traceback.format_exc() + self.algoEngine.writeLog(u'读取CSV文件失败:\n' + msg) + return [] + + #---------------------------------------------------------------------- + def saveSettingFromCsv(self): + """从CSV加载配置到数据库""" + path, fileType = QtWidgets.QFileDialog.getOpenFileName(self, u'加载算法配置', '', 'CSV(*.csv)') + l = self.loadCsv(path) + for setting in l: + self.algoEngine.saveAlgoSetting(setting) + + #---------------------------------------------------------------------- + def addAlgoFromCsv(self): + """从CSV启动一篮子算法""" + path, fileType = QtWidgets.QFileDialog.getOpenFileName(self, u'启动篮子算法', '', 'CSV(*.csv) ') + l = self.loadCsv(path) + for setting in l: + self.algoEngine.addAlgo(setting) \ No newline at end of file diff --git a/vnpy/trader/uiBasicWidget.py b/vnpy/trader/uiBasicWidget.py index 6ef2dcee..4cde79f1 100644 --- a/vnpy/trader/uiBasicWidget.py +++ b/vnpy/trader/uiBasicWidget.py @@ -375,7 +375,7 @@ class BasicMonitor(QtWidgets.QTableWidget): self.menu.close() # 获取想要保存的文件名 - path = QtWidgets.QFileDialog.getSaveFileName(self, vtText.SAVE_DATA, '', 'CSV(*.csv)') + path, fileType = QtWidgets.QFileDialog.getSaveFileName(self, vtText.SAVE_DATA, '', 'CSV(*.csv)') try: #if not path.isEmpty():