Beispiel #1
0
def deal_single_ins(item):
    r = False
    if item['ins'] == 'down_sell':
        df = ts.get_realtime_quotes(item['code'])
        b3_price = float(df.at[0, 'b3_p'])
        if b3_price <= item['price'] and b3_price > 0:
            item['ins'] = 'sell_order'
            send_instruction(item)
            r = True
    if item['ins'] == 'up_warn':
        df = ts.get_realtime_quotes(item['code'])
        b3_price = float(df.at[0, 'b3_p'])
        if b3_price >= item['price']:
            to_log('reach price by up_warn ins ')
            send_email(dss, 'up_warn', str(item))
            r = True
    if item['ins'] == 'down_warn':
        df = ts.get_realtime_quotes(item['code'])
        b3_price = float(df.at[0, 'b3_p'])
        if b3_price <= item['price'] and b3_price > 0:
            send_email(dss, 'down_warn', str(item))
            r = True
    if item['ins'] in ['sell_order', 'buy_order']:
        send_instruction(item)
        r = True

    return r
    def get_tick_service(self):
        print('in get_tick_service ')

        while True:
            try:
                with Listener(address, authkey=b'secret password') as listener:
                    with listener.accept() as conn:
                        s = conn.recv()
                        tick = ''
                        if self.q is not None:
                            if s in self.q.ticks_dict:
                                tick = self.q.ticks_dict[s][-1]
                                cols = [
                                    'Localtime', 'Instrument', 'LastPrice',
                                    'Volume', 'OpenInterest', 'AveragePrice',
                                    'UpperLimitPrice', 'LowerLimitPrice',
                                    'PreSettlementPrice', 'AskPrice',
                                    'AskVolume', 'BidPrice', 'BidVolume',
                                    'UpdateDate', 'UpdateTime'
                                ]
                                tick = dict(zip(cols, tick))
                        else:
                            now = datetime.now()
                            today = now.strftime('%Y%m%d')
                            fn = self.dss + 'fut/tick/tick_' + today + '_' + s + '.csv'
                            if os.path.exists(fn):
                                df = pd.read_csv(fn)
                                rec = df.iloc[-1, :]
                                tick = dict(rec)

                        conn.send(str(tick))
            except Exception as e:
                # print(e)
                s = traceback.format_exc()
                to_log(s)
Beispiel #3
0
def compass(date):
    listfile = os.listdir(dirname)
    for fn in listfile:
        os.remove(dirname + fn)

    d2 = get_dss() + 'info/hold/img/'
    listfile = os.listdir(d2)
    for fn in listfile:
        os.remove(d2 + fn)

    fn = get_dss() + 'fut/cfg/opt_mature.csv'
    df2 = pd.read_csv(fn)
    df2 = df2[pd.notnull(df2.flag)]

    fn_list = []
    for func in [CF, m, RM, al, IO]:
        # for func in [m]:
        try:
            fn_list += func(date, df2)
        except Exception as e:
            s = traceback.format_exc()
            to_log(s)

    # print(fn_list)
    send_email(get_dss(), 'compass', '', fn_list)
Beispiel #4
0
def df_hv(code, date):
    try:
        now = datetime.now()
        start_day = now - timedelta(days=480)
        start_day = start_day.strftime('%Y-%m-%d')

        if code[:2] == 'IO':
            df = get_inx('000300', start_day)
        else:
            fn = get_dss() + 'fut/bar/day_' + code + '.csv'
            df = pd.read_csv(fn)
        df = df[(df.date >= start_day) & (df.date <= date)]
        df = df.set_index('date')
        df = df.sort_index()

        df['ln'] = np.log(df.close)
        df['rt'] = df['ln'].diff(1)
        df['hv'] = df['rt'].rolling(20).std()
        df['hv'] *= np.sqrt(242) * 100

        df = df.iloc[-242:, ]
        df['value'] = df['hv']
        df = df[['value']]
        df.index.name = code + '_hv'
        return df
    except Exception as e:
        s = traceback.format_exc()
        to_log(s)

        return None
Beispiel #5
0
 def _OnFrontDisConnected(self, reason: int):
     """"""
     to_log('in CtpQuote._OnFrontDisConnected')
     # 确保隔夜或重新登录时的第1个tick不被发送到客户端
     self.inst_tick.clear()
     self.logined = False
     self.OnDisConnected(self, reason)
    def worker_close(self):
        """盘后保存及展示数据"""
        try:
            if self.working == False:
                return

            # 保存信号参数
            for p in self.portfolio_list:
                p.daily_close()
            self.portfolio_list = []  # 组合
            self.working = False

            # print('seq_tm: ', self.seq_tm)
            # if self.seq_tm == 'morning':
            #     print('begin pandian_run')
            #     pandian_run()
            #     print('end pandian_run')

            print('begin gateway release ')
            if self.gateway is not None:
                self.gateway.release()
            self.gateway = None  # 路由
            self.vtSymbol_list = []

            now = datetime.now()
            print('in worker close, now time is: ', now)

        except Exception as e:
            s = traceback.format_exc()
            to_log(s)
Beispiel #7
0
def mail_1515():
    to_log('in mail_1515')
    try:
        now = datetime.now()
        today = now.strftime('%Y-%m-%d')
        weekday = int(now.strftime('%w'))
        if 1 <= weekday <= 5:
            r = []
            logfile = dss + 'log/autotrade.log'
            df = pd.read_csv(logfile, sep=' ', header=None, encoding='ansi')
            df = df[df[0] == today]
            for i, row in df.iterrows():
                r.append(str(list(row)[:7]))
            send_email(dss, 'show log', '\n'.join(r))

            r = []
            txtfile = dss + 'csv/ins.txt'
            with open(txtfile, 'r', encoding='utf-8') as f:
                line = f.readline()
                while line:
                    if line[0] == '{':
                        #line_dict = eval(line)
                        r.append(line)
                    line = f.readline()
            send_email(dss, 'show ins ', '\n'.join(r))

    except Exception as e:
        print('error')
        print(e)
Beispiel #8
0
    def ReqSubscribeMarketData(self, pInstrument: str):
        """订阅合约行情

        :param pInstrument:
        """
        to_log('in CtpQuote.ReqSubscribeMarketData')
        self.q.SubscribeMarketData(pInstrument)
def run_down_opt():
    try:
        now = datetime.datetime.now()
        weekday = int(now.strftime('%w'))
        if 1 <= weekday <= 5 and is_market_date():
            print('\n' + str(now) + " down_opt begin...")
            down_opt()
            print(" down_opt end ")
            time.sleep(180)

            now = datetime.datetime.now()
            print('\n' + str(now) + " calc_greeks begin...")
            calc_greeks()
            print(" calc_greeks end ")

            now = datetime.datetime.now()
            print('\n' + str(now) + " calc_sigma begin...")
            calc_sigma()
            print(" calc_sigma end ")

            now = datetime.datetime.now()
            print('\n' + str(now) + " calc_skew begin...")
            calc_skew()
            print(" calc_skew end ")

    except Exception as e:
        s = traceback.format_exc()
        to_log(s)
Beispiel #10
0
def kqgj_short(code, price, num):
    """卖开仓"""
    r = True
    try:
        to_log('in kqgj_short')
        time.sleep(0.1)

        dlg_spec.Edit1.set_text(code)  #合约
        time.sleep(0.1)

        dlg_spec['买入'].uncheck()
        time.sleep(0.1)
        dlg_spec['卖出'].check()  #买卖
        time.sleep(0.1)

        dlg_spec['平仓'].uncheck()
        time.sleep(0.1)
        dlg_spec['平今'].uncheck()
        time.sleep(0.1)
        dlg_spec['开仓'].check()  #开平
        time.sleep(0.1)

        dlg_spec.Edit2.set_text(num)  #手数
        time.sleep(0.1)
        dlg_spec.Edit3.set_text(price)  #价格
        time.sleep(0.1)

        dlg_spec['下单'].click()
    except:
        r = False
        print('error, 下单异常')

    return r
Beispiel #11
0
    def on_bar_minx(self, bar):
        self.am.updateBar(bar)
        if not self.am.inited:
            return

        # 涨跌停时暂停交易
        if bar.close == bar.UpperLimitPrice:
            self.pause = True
            to_log(self.vtSymbol + ' 已涨停,该品种dali策略暂停交易')

        if bar.close == bar.LowerLimitPrice:
            self.pause = True
            to_log(self.vtSymbol + ' 已跌停,该品种dali策略暂停交易')

        if self.paused == True and self.backtest == False:
            self.counter += 1
            if self.counter == 3:
                filename = get_dss() +  'gateway_closed.csv'
                if os.path.exists(filename):
                    pass
                else:
                    send_email(get_dss(), self.vtSymbol + ' 挂单未成交!!!', '')
            return

        self.calculateIndicator()     # 计算指标
        self.generateSignal(bar)      # 触发信号,产生交易指令
def send_email(dss, subject, content, attach_list=[]):
    try:

        # # 第三方 SMTP 服务
        # mail_host = 'smtp.yeah.net'              # 设置服务器
        # mail_username = '******'   # 用户名
        # mail_auth_password = "******"       # 授权密码

        # 加载配置
        config = open(dss + 'csv/config.json')
        setting = json.load(config)
        mail_host = setting['mail_host']  # 设置服务器
        mail_username = setting['mail_username']  # 用户名
        mail_auth_password = setting['mail_auth_password']  # 授权密码
        # print(mail_host, mail_username, mail_auth_password)

        # # 第三方 SMTP 服务
        # mail_host = 'smtp.qq.com'              # 设置服务器
        # mail_username = '******'   # 用户名
        # mail_auth_password = "******"       # 授权密码

        sender = setting['sender']
        receivers = setting['receivers']
        #receivers = '[email protected], [email protected]' # 多个收件人

        message = MIMEMultipart()
        message['From'] = sender
        message['To'] = receivers
        message['Subject'] = str(subject)
        message.attach(MIMEText(content, 'plain', 'utf-8'))

        if attach_list == []:
            pass
        else:
            # 构造附件
            now = datetime.now()
            today = now.strftime("%Y%m%d_")
            for i, attach in enumerate(attach_list):
                att = MIMEText(open(attach, "rb").read(), "base64", "utf-8")
                att["Content-Type"] = "application/octet-stream"
                # 附件名称非中文时的写法
                att["Content-Disposition"] = 'attachment; filename=' + today + str(
                    i) + attach[-4:]
                # 附件名称为中文时的写法
                # att.add_header("Content-Disposition", "attachment", filename=("gbk", "", "测试结果.txt"))
                # att.add_header("Content-Disposition", "attachment", filename="测试结果.txt")
                message.attach(att)

        #smtpObj = smtplib.SMTP(mail_host, 25)                               # 生成smtpObj对象,使用非SSL协议端口号25
        smtpObj = smtplib.SMTP_SSL(mail_host, 465)  # 生成smtpObj对象,使用SSL协议端口号465
        smtpObj.login(mail_username, mail_auth_password)  # 登录邮箱
        smtpObj.sendmail(sender, receivers, message.as_string())  # 发送给一人
        # smtpObj.sendmail(sender, receivers.split(','), message.as_string()) # 发送给多人
        print("邮件发送成功")

    except smtplib.SMTPException as e:
        print("Error: 无法发送邮件")
        print(e)
        s = traceback.format_exc()
        to_log(s)
Beispiel #13
0
    def _record_buy_order(self, ins_dict):

        df = pd.read_csv(self.holdFilename, dtype={'code': 'str'})

        portfolio_index = df[(df.portfolio == ins_dict['portfolio'])
                             & (df.code == 'profit') &
                             (df.agent == ins_dict['agent'])].index.tolist()
        if len(portfolio_index) == 1:  #已开组合
            #获得原来的cash, 并减少cash
            pre_cash_index = df[(df.portfolio == 'cash') & (
                df.agent == ins_dict['agent'])].index.tolist()
            df.loc[pre_cash_index[0], 'cost'] -= ins_dict['cost']

            #文件中不需要保存这两个字段
            if 'ins' in ins_dict:
                ins_dict.pop('ins')
            if 'price' in ins_dict:
                ins_dict.pop('price')

            #新增一条记录
            df_dict = pd.DataFrame([ins_dict])
            df = df.append(df_dict, sort=False)
            #print(df)

            df = df[['portfolio', 'code', 'cost', 'num', 'agent']]
            df.to_csv(self.holdFilename, index=False)
        else:
            to_log('error, 组合未开,buy_order无法处理')
Beispiel #14
0
    def loadPortfolio(self, PortfolioClass, name):
        """每日重新加载投资组合"""
        to_log('in TradeEngine.loadPortfolio')

        p = PortfolioClass(self, name)
        p.init()
        self.portfolio_list.append(p)
    def _bc_sendOrder(self, vtSymbol, direction, offset, price, volume,
                      pfName):
        """记录交易数据(由portfolio调用)"""

        # 记录成交数据
        dt = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
        time.sleep(0.01)
        order_id = str(int(time.time()))

        r = [[
            dt, pfName, order_id, 'minx', vtSymbol, direction, offset, price,
            volume
        ]]
        #print('send order: ', r)
        to_log(str(r)[3:-2])
        fn = 'fut/engine/engine_deal.csv'
        a_file(fn, str(r)[2:-2])

        priceTick = get_contract(vtSymbol).price_tick
        price = int(round(price / priceTick, 0)) * priceTick

        if self.gateway is not None:
            # self.gateway._bc_sendOrder(dt, vtSymbol, direction, offset, price_deal, volume, pfName)
            threading.Thread(target=self.gateway._bc_sendOrder,
                             args=(dt, vtSymbol, direction, offset, price,
                                   volume, pfName)).start()
Beispiel #16
0
def send_email(dss, subject, content):
    to_log('in send_email')
    # # 第三方 SMTP 服务
    # mail_host = 'smtp.yeah.net'              # 设置服务器
    # mail_username = '******'   # 用户名
    # mail_auth_password = "******"       # 授权密码

    # 加载配置
    config = open(dss + 'csv/config.json')
    setting = json.load(config)
    mail_host = setting['mail_host']  # 设置服务器
    mail_username = setting['mail_username']  # 用户名
    mail_auth_password = setting['mail_auth_password']  # 授权密码
    # print(mail_host, mail_username, mail_auth_password)

    sender = setting['sender']
    receivers = setting['receivers']  # 一个收件人
    #receivers = '[email protected], [email protected]' # 多个收件人

    try:
        message = MIMEText(content, 'plain', 'utf-8')
        message['From'] = sender
        message['To'] = receivers
        message['Subject'] = str(subject)
        #smtpObj = smtplib.SMTP(mail_host, 25)                               # 生成smtpObj对象,使用非SSL协议端口号25
        smtpObj = smtplib.SMTP_SSL(mail_host, 465)  # 生成smtpObj对象,使用SSL协议端口号465
        smtpObj.login(mail_username, mail_auth_password)  # 登录邮箱
        # smtpObj.sendmail(sender, receivers, message.as_string())          # 发送给一人
        smtpObj.sendmail(sender, receivers.split(','),
                         message.as_string())  # 发送给多人
        print("邮件发送成功")
    except smtplib.SMTPException as e:
        print("Error: 无法发送邮件")
        print(e)
    def worker_open(self):
        """盘前加载配置及数据"""
        try:
            if is_market_date() == False:
                self.working = False
                return

            now = datetime.now()
            tm = now.strftime('%H:%M:%S')
            print('-' * 60)
            print('in worker open, now time is: ', now)
            print('\n')
            if tm > '08:30:00' and tm < '14:30:00':
                self.seq_tm = 'morning'
            if tm > '20:30:00' and tm < '22:30:00':
                self.seq_tm = 'night'

            self.init_daily()
            self.working = True
            time.sleep(600)
            if self.gateway is not None:
                self.gateway.check_risk()

        except Exception as e:
            s = traceback.format_exc()
            to_log(s)
Beispiel #18
0
    def control_in_p(self, bar):
        try:
            for k in self.spread_dict.keys():
                s0 = self.spread_dict[k][0]
                s1 = self.spread_dict[k][1]
                if s0 not in self.got_dict or s1 not in self.got_dict:
                    continue
                if self.got_dict[s0] and self.got_dict[
                        s1] and self.process_dict[k] == False:
                    self.process_dict[k] = True
                    s0 = self.signalDict[s0][0]
                    s1 = self.signalDict[s1][0]

                    bar_s = VtBarData()
                    bar_s.vtSymbol = k
                    bar_s.symbol = k
                    bar_s.exchange = s0.bar.exchange
                    bar_s.date = s0.bar.date
                    bar_s.time = s0.bar.time

                    bar_s.close = s0.bar.close - s1.bar.close
                    bar_s.AskPrice = s0.bar.AskPrice - s1.bar.BidPrice
                    bar_s.BidPrice = s0.bar.BidPrice - s1.bar.AskPrice

                    # print(bar_s.time, bar_s.vtSymbol, bar_s.close, bar_s.AskPrice, bar_s.BidPrice)

                    self.engine.lock.acquire()
                    self.engine.bar_list.append(bar_s)
                    self.engine.lock.release()

        except Exception as e:
            s = traceback.format_exc()
            to_log(s)
Beispiel #19
0
    def _record_sell_order(self, ins_dict):
        to_log('in record_sell_order')

        df = pd.read_csv(self.holdFilename, dtype={'code': 'str'})

        #获得原来的stock
        pre_stock_index = df[(df.portfolio == ins_dict['portfolio'])
                             & (df.code == ins_dict['code']) &
                             (df.num == ins_dict['num']) &
                             (df.agent == ins_dict['agent'])].index.tolist()
        if len(pre_stock_index) > 0:
            pre_row = df.loc[pre_stock_index[0]]

            #更新组合的profit
            profit = ins_dict['cost'] * (1 - 0.0015) - pre_row['cost']
            profit_index = df[(df.portfolio == ins_dict['portfolio'])
                              & (df.code == 'profit') &
                              (df.agent == ins_dict['agent'])].index.tolist()
            df.loc[profit_index[0], 'cost'] += profit

            #获得原来的cash, 并增加cash
            pre_cash_index = df[(df.portfolio == 'cash') & (
                df.agent == ins_dict['agent'])].index.tolist()
            df.loc[pre_cash_index[0],
                   'cost'] += ins_dict['cost'] * (1 - 0.0015)

            #删除原来的记录
            df = df.drop(index=[pre_stock_index[0]])

            #print(df)
            df = df[['portfolio', 'code', 'cost', 'num', 'agent']]
            df.to_csv(self.holdFilename, index=False)
        else:
            to_log('error, 原持仓记录不存在,sell_order无法处理')
Beispiel #20
0
    def loadPortfolio(self, PortfolioClass, name):
        """加载投资组合"""
        to_log('in FutEngine.loadPortfolio')

        p = PortfolioClass(self, name)
        p.init()
        p.loadParam()
        self.portfolio_list.append(p)
Beispiel #21
0
def down_data_0100():
    to_log('in down_data_0100')

    now = datetime.now()
    weekday = int(now.strftime('%w'))
    if 2 <= weekday <= 6:
        print('\n' + str(now) + " down_data begin...")
        down_data(dss)
    def worker_open(self):
        """盘前加载配置及数据"""
        try:
            self.init_daily()

        except Exception as e:
            s = traceback.format_exc()
            to_log(s)
    def worker_close(self):
        """盘后保存及展示数据"""
        to_log('in FutEngine.worker_close')

        print('begin worker_close')

        # 保存信号参数
        for p in self.portfolio_list:
            p.saveParam()
Beispiel #24
0
    def get_cost_cap(self):
        to_log('in Book.get_cost_cap')

        cost, cap = 0, 0
        for tactic in self.tactic_List:
            cost1, cap1 = tactic.get_cost_cap()
            cost += cost1
            cap  += cap1
        return cost, cap
Beispiel #25
0
    def ReqUserLogin(self, user: str, pwd: str, broker: str):
        """登录

        :param user:
        :param pwd:
        :param broker:
        """
        to_log('in CtpQuote.ReqUserLogin')
        self.q.ReqUserLogin(BrokerID=broker, UserID=user, Password=pwd)
Beispiel #26
0
    def ReqUserLogout(self):
        """退出接口(正常退出,不会触发OnFrontDisconnected)"""
        to_log('in CtpQuote.ReqUserLogout')

        self.q.Release()
        # 确保隔夜或重新登录时的第1个tick不被发送到客户端
        self.inst_tick.clear()
        self.logined = False
        self.OnDisConnected(self, 0)
Beispiel #27
0
    def worker_1450(self):
        """盘中推送bar"""
        to_log('in TradeEngine.worker_1450')

        for p in self.portfolio_list:
            for vtSymbol in p.vtSymbolList:
                #print(vtSymbol)
                df = None
                i = 0
                while df is None and i < 2:
                    try:
                        i += 1
                        df = ts.get_realtime_quotes(vtSymbol)
                    except Exception as e:
                        print('error get_realtime_quotes')
                        print(e)
                        time.sleep(0.1)

                if df is None:
                    continue

                code = vtSymbol
                df1 = None
                i = 0
                while df1 is None and i < 2:
                    try:
                        i += 1
                        df1 = get_adj_factor(self.dss, code)
                    except Exception as e:
                        print('error adj_factor ' + code)
                        print(e)
                        time.sleep(0.1)
                if df1 is None:
                    continue

                factor = float(df1.at[0, 'adj_factor'])
                d = df.loc[0, :]
                bar = VtBarData()
                bar.vtSymbol = vtSymbol
                bar.symbol = vtSymbol
                bar.open = float(d['open']) * factor
                bar.high = float(d['high']) * factor
                bar.low = float(d['low']) * factor
                bar.close = float(d['price']) * factor
                bar.close_bfq = float(d['price'])
                date = d['date'].split('-')  #去掉字符串中间的'-'
                date = ''.join(date)
                bar.date = date
                bar.time = '00:00:00'
                bar.datetime = datetime.strptime(bar.date + ' ' + bar.time,
                                                 '%Y%m%d %H:%M:%S')
                bar.volume = float(d['volume'])

                p.onBar(bar)

        send_email(self.dss, 'worker_1450处理完毕', '')
Beispiel #28
0
 def _OnRspUserLogin(self, pRspUserLogin: CThostFtdcRspUserLoginField,
                     pRspInfo: CThostFtdcRspInfoField, nRequestID: int,
                     bIsLast: bool):
     """"""
     to_log('in CtpQuote._OnRspUserLogin')
     info = InfoField()
     info.ErrorID = pRspInfo.getErrorID()
     info.ErrorMsg = pRspInfo.getErrorMsg()
     self.logined = True
     self.OnUserLogin(self, info)
def mail_pdf(s):
    try:
        # 将url页面转化为pdf
        url = 'http://114.116.190.167:5000/show_' + s
        fn = 'web/static/out3.pdf'
        pdfkit.from_url(url, fn)
        send_email(dss, url[33:], '', [fn])

    except Exception as e:
        s = traceback.format_exc()
        to_log(s)
    def loadPortfolio(self, PortfolioClass, symbol_list):
        """加载投资组合"""
        try:
            p = PortfolioClass(self, symbol_list, {})
            p.daily_open()
            self.portfolio_list.append(p)

        except Exception as e:
            s = traceback.format_exc()
            to_log(s)
            to_log('加载投资组合出现异常')