Exemple #1
0
    def find_strong_daliy(self, start_id, dklines):
        self.resistance_hh = 0
        self.support_ll = 0
        std = tafunc.std(dklines.high, 4)  # 收盘价序列每5项计算一个标准差
        for i in range(start_id, start_id+1):
            if (list(std)[-i] < 15):
                print(self.TAG, i, time_to_str(dklines.iloc[-i].datetime), dklines.iloc[-i].high)
                avg_high = pplib.get_average_in_series(dklines.high, i, 3)
                self.debug("get resistance hh = %d"%(avg_high))
                self.resistance_hh = avg_high
                break

        #print("过滤 low 离散性小的bar")
        std = tafunc.std(dklines.low, 4)  # 收盘价序列每5项计算一个标准差
        #print(type(std))
        #print(list(std))
        for i in range(start_id, start_id+1):
            if (list(std)[-i] < 15):
                print(i, time_to_str(dklines.iloc[-i].datetime), dklines.iloc[-i].low)
                avg_low = pplib.get_average_in_series(dklines.low, i, 3)
                self.debug("get support ll = %d"%(avg_low))
                self.support_ll = avg_low
                break
        
        if (self.resistance_hh != 0 or self.support_ll != 0):
            return True
        else:
            return False
Exemple #2
0
    def 查询当日成交订单(self, 品种名=None, 保存csv地址="成交记录导出.csv"):
        f = open(保存csv地址, 'w')
        f.write("成交时间,成交品种,下单方向,开平标志,委托价格,成交价格,成交手数,委托单号,成交单号\n")
        #f.write()
        if 品种名:
            for x in self.trade:
                b = self.get_trade(x)
                c = self.get_order(b.order_id)
                print(b)
                if b["instrument_id"] == 品种名.split(".")[1]:
                    f.write(','.join([
                        time_to_str(b.trade_date_time), b.instrument_id,
                        b.direction, b.offset,
                        str(c.limit_price),
                        str(b.price),
                        str(b.volume), b.order_id, b.trade_id
                    ]) + '\n')

        else:
            for x in self.trade:
                b = self.get_trade(x)
                #获取成交的订单信息
                c = self.get_order(b.order_id)
                f.write(','.join([
                    time_to_str(b.trade_date_time), b.instrument_id,
                    b.direction, b.offset,
                    str(c.limit_price),
                    str(b.price),
                    str(b.volume), b.order_id, b.trade_id
                ]) + '\n')
        f.close()
Exemple #3
0
def 查询最近成交价格(api, 买卖, 开平):
    总成交 = api.get_trade()
    l = []
    for x in 总成交:
        成交信息 = api.get_trade(x)
        l.append((time_to_str(成交信息.trade_date_time), 成交信息.direction,
                  成交信息.offset, 成交信息.price))
    l = sorted(l, key=lambda x: x[0], reverse=True)
    for x in l:
        if 买卖 == "买" and 开平 == "开":
            for x in l:
                if x[1] == "BUY" and x[2] == "OPEN":
                    return x[3]
        if 买卖 == "买" and 开平 == "平":
            for x in l:
                if x[1] == "BUY" and x[2] in ("CLOSE", "CLOSETODAY"):
                    return x[3]

        if 买卖 == "卖" and 开平 == "开":
            for x in l:
                if x[1] == "SELL" and x[2] == "OPEN":
                    return x[3]
        if 买卖 == "卖" and 开平 == "平":
            for x in l:
                if x[1] == "SELL" and x[2] in ("CLOSE", "CLOSETODAY"):
                    return x[3]
Exemple #4
0
def ea_break(api, 成交记录文件地址):
    struct_time = time.localtime()
    时间 = time.strftime("%H:%M:%S", struct_time)
    if "02:30:00" <= 时间 < "08:30:00":
        return 1
    if "15:15:00" <= 时间 < "20:30:00":
        try:
            f = open(成交记录文件地址, "r")
            data = f.read()
            f.close()
        except:
            data = ""
        f = open(成交记录文件地址, 'a+')
        a = api.get_trade()
        if not data:
            f.write("成交时间,成交品种,下单方向,开平标志,委托价格,成交价格,成交手数,委托单号,成交单号,成交手续费\n")
        for x in a:
            b = api.get_trade(x)
            #获取成交的订单信息
            c = api.get_order(b.order_id)
            f.write(','.join([
                time_to_str(b.trade_date_time), b.exchange_id +
                b.instrument_id, b.direction, b.offset,
                str(c.limit_price),
                str(b.price),
                str(b.volume), b.order_id, b.trade_id,
                str(b.commission)
            ]) + '\n')
        f.close()
        return 1
    return 0
Exemple #5
0
def 启动():
    while True:
        #获取合约
        while True:
            try:
                api=tqsdk.TqApi(auth="[email protected],24729220a")
            except:
                continue
            break

        合约=api.query_quotes(ins_class="FUTURE",expired=False)
        api.close()

        #建立一个原版行情API实例
        mduserapi=mdapi.CThostFtdcMdApi_CreateFtdcMdApi()
        #建立一个自定义的行情类()的连接实例
        red=redis.Redis(db=14)
        mduserspi=CFtdcMdSpi(mduserapi,red,合约)
        #为连接实例设置连接地址
        mduserapi.RegisterFront(行情地址)
        mduserapi.RegisterSpi(mduserspi)
        #启动连接线程
        mduserapi.Init()    
        #进行线程阻塞
        while True:
            if time_to_str(time.time())[11:16]=="15:30":
                mduserapi.Release()
                转存(red)
                while True:
                    time.sleep(10)
                    if time_to_str(time.time())[11:16]=="20:30":
                        break
                break

            if time_to_str(time.time())[11:16]=="02:35":
                mduserapi.Release()
                while True:
                    time.sleep(10)
                    if time_to_str(time.time())[11:16]=="08:30":
                        break
                break
            time.sleep(10)
Exemple #6
0
    def print_opens(self, str_name, o_df):
        o_size = len(o_df)
        if (str_name == "w_open" and o_size > 0):
            print('%-5s%-10s%-10s%-10s%-10s%-10s' %
                  ("id", "lcount", "rcount", "close", "low", "datetime"))
            for i in range(0, o_size):
                #print(i, o_df.iloc[-i].lcount, o_df.iloc[-i].rcount, o_df.iloc[-i].close, o_df.iloc[-i].low, time_to_str(o_df.iloc[-i].time))
                print('%-5s%-10s%-10s%-10s%-10s%-10s' %
                      (i, o_df.loc[i].lcount, o_df.loc[i].rcount,
                       o_df.loc[i].close, o_df.loc[i].low,
                       time_to_str(o_df.loc[i].time)))
        if (str_name == "m_open" and o_size > 0):
            print('%-5s%-10s%-10s%-10s%-10s%-10s' %
                  ("id", "lcount", "rcount", "close", "high", "datetime"))
            for i in range(0, o_size):
                print('%-5s%-10s%-10s%-10s%-10s%-10s' %
                      (i, o_df.loc[i].lcount, o_df.loc[i].rcount,
                       o_df.loc[i].close, o_df.loc[i].high,
                       time_to_str(o_df.loc[i].time)))

        print("hh=%d, ll=%d" % (self.hh, self.ll))
        print("w_check=%d, m_check=%d" % (self.w_checksum, self.m_checksum))
Exemple #7
0
def 启动行情记录(symbol_list,
           list_duration_seconds,
           行情类型="TQ",
           redis_con=None,
           天勤连接=None,
           通达信连接=None,
           data_length=2000,
           行情地址="tcp://101.230.209.178:53313",
           md_subscription_name="gaoctp"):
    while True:
        当前时间 = time_to_str(time.time())[11:16]
        if 当前时间 > "20:30" or "00:00" < 当前时间 < "02:30" or "08:30" < 当前时间 < "15:30":
            启动行情记录2(symbol_list, list_duration_seconds, 行情类型, redis_con, 天勤连接,
                    通达信连接, data_length, 行情地址, md_subscription_name)
        time.sleep(1)
Exemple #8
0
def 转存(red):
    a=red.keys("*")
    当天日期="".join(time_to_str(time.time())[:10].split("-"))
    if 当天日期 !=当前交易日:
        return
    if 当天日期 not in os.listdir():
        os.mkdir(当天日期)

    #循环遍历写一下
    for x in a:
        x=x.decode()
        b= red.lrange(x,0,-1)[::-1]
        f=open(".\\"+当天日期+"\\"+x+".csv",'w')
        f.write("\n".join([ y.decode() for y in b ]))
        f.close()
        red.delete(x)

    az=zipfile.ZipFile(".\\"+当天日期+'.zip', mode='w', compression=0, allowZip64=True, compresslevel=None)
    for name_file in os.listdir(".\\"+当天日期): 
        az.write(filename=".\\"+当天日期+"\\"+name_file,compress_type=zipfile.ZIP_BZIP2,compresslevel=None)
        os.remove(".\\"+当天日期+"\\"+name_file)
    az.close()
Exemple #9
0
async def 启动程序(账户data):
    global CTP用户名对应实例和登陆名,myqueue
    CTP用户名对应实例和登陆名={}
    myqueue=janus.Queue()
    while True:
        #每个CTP账户实例遍历,建立spi和api实例
        for x in 账户data:
            if 账户data[x] is None:
                账户data[x]=[list(x[1:3])+[0]]
            #登陆交易实例
            tradeapi=api.CThostFtdcTraderApi_CreateFtdcTraderApi()
            BROKERID,USERID,PASSWORD,AppID,AuthCode,FrontAddr=x
            tradespi=CTradeSpi(tradeapi,BROKERID,USERID,PASSWORD,AppID,AuthCode,myqueue.sync_q)
            tradeapi.RegisterFront(FrontAddr)
            tradeapi.RegisterSpi(tradespi)
            tradeapi.SubscribePrivateTopic(api.THOST_TERT_RESTART)
            tradeapi.SubscribePublicTopic(api.THOST_TERT_RESTART)
            tradeapi.Init()
            while True:
                if tradespi.init_start is None:
                    time.sleep(1)
                else:
                    break

            if x[1] not in CTP用户名对应实例和登陆名:
                CTP用户名对应实例和登陆名[x[1]]={"td_obj":tradespi,'td_user_pass':账户data[x],"td_websockets":[],"td_api":tradeapi}
            else:
                CTP用户名对应实例和登陆名[x[1]]["td_obj"]=tradespi
                CTP用户名对应实例和登陆名[x[1]]["td_api"]=tradeapi
        await asyncio.sleep(100)
        #进行无限延迟,到达重连时间,去释放原来的api
        while True:
            await asyncio.sleep(10)
            if time_to_str(time.time())[11:16] in ("08:35","20:35"):
                for x in 账户data:
                    CTP用户名对应实例和登陆名[x[1]]["td_api"].Release()
                break
Exemple #10
0
import tqsdk
import time
from sdk.gaoapi2 import GaoApi
from tqsdk.tafunc import time_to_str
api = GaoApi("040123", "123456")

行情 = api.get_tick_serial("CFFEX.IC2011")

while True:
    api.wait_update()
    print(行情.datetime.iloc[-1], 行情.last_price.iloc[-1],
          time_to_str(time.time()))
Exemple #11
0
    def find_inrange_daily(self, start_id, dklines):
        hhv = tafunc.hhv(dklines.high, 3)
        llv = tafunc.llv(dklines.low, 3)
        hclose = tafunc.hhv(dklines.close, 3)
        lclose = tafunc.llv(dklines.close, 3)

        range_h = 0
        range_l = 0
        for i in range(start_id, start_id+1):
            close_height = list(hclose)[-i] - list(lclose)[-i]
            hl_height = list(hhv)[-i] - list(llv)[-i]
            if (close_height < 25 or hl_height < 60):
                range_l = pplib.get_average_in_series(dklines.low, i, 3)
                range_h = pplib.get_average_in_series(dklines.high, i, 3)
        
            
            print(i, close_height, hl_height,list(hhv)[-i], list(llv)[-i],dklines.iloc[-i].open, dklines.iloc[-i].close, time_to_str(dklines.iloc[-i].datetime))
        
        self.debug("range_l=%d range_h=%d"%(range_l, range_h))
        self.range_ll = range_l
        self.range_h = range_h

        if (range_h !=0 and range_l != 0):
            return True
        else:
            return False
Exemple #12
0
from sdk.gaoapi2 import GaoApi
from tqsdk.tafunc import time_to_str, ma
import time
api = GaoApi("086515", "123456")

行情 = api.获取_K线("DCE.i2101", 10, 5)
print(行情)
行情2 = api.获取_tick("SHFE.rb2101")
print(行情2.last_price)
while True:
    # print(行情)
    # 行情['ma']=ma(行情.close,5)
    # #print(time_to_str(行情.datetime.iloc[-1]))
    # print(time_to_str(time.time()))
    api.wait_update()
    if api.is_changing(行情.id.iloc[-1], "id"):
        print(行情)
        print(time_to_str(行情.datetime.iloc[-1]))
Exemple #13
0
def 启动行情记录2(symbol_list,
            list_duration_seconds,
            行情类型="TQ",
            redis_con=None,
            天勤连接=None,
            通达信连接=None,
            data_length=2000,
            行情地址="tcp://101.230.209.178:53313",
            md_subscription_name="gaoctp"):

    存储tick队列 = queue.Queue()
    if not redis_con:
        redis_con = redis.Redis(db=15)
    while True:

        天勤连接 = tqsdk.TqApi(auth="[email protected],24729220a")

        if 行情类型 == "TQ":
            单symbol_dict = set()
            需要订阅的CTPsymbol = []
            订阅中的主连合约 = {}
            订阅中的主连合约_反向 = {}
            订阅中的指数合约 = {}
            天勤需要添加的合约 = []
            for x in symbol_list:
                if "KQ.m" in x:
                    订阅中的主连合约[x] = 天勤连接.get_quote(x).underlying_symbol
                    需要订阅的CTPsymbol.append(订阅中的主连合约[x])
                    天勤需要添加的合约.append(订阅中的主连合约[x])
                elif "KQ.i" in x:
                    symbol = x.split("@")[1]
                    订阅中的指数合约[x] = [
                        y for y in 天勤连接._data['quotes']
                        if 天勤连接._data['quotes'][y]["expired"] == False
                        and re.findall("^" + symbol + "[0-9]{3,4}$", y)
                    ]
                    需要订阅的CTPsymbol += 订阅中的指数合约[x]
                    天勤需要添加的合约 += 订阅中的指数合约[x]
                    list_duration_seconds.append(86400)
                else:
                    需要订阅的CTPsymbol.append(x)
                    单symbol_dict.add(x)

            symbol_list = list(set(symbol_list + 天勤需要添加的合约))

            订阅中的主连合约_反向 = {订阅中的主连合约[x]: x for x in 订阅中的主连合约}
            list_duration_seconds = list(set(list_duration_seconds))
            天勤 = TQ_md_class(symbol_list, list_duration_seconds, 天勤连接,
                             redis_con, data_length, md_subscription_name)

        #建立一个原版行情API实例
        mduserapi = mdapi.CThostFtdcMdApi_CreateFtdcMdApi()
        #建立一个自定义的行情类()的连接实例
        mduserspi = CFtdcMdSpi(mduserapi, 存储tick队列, 需要订阅的CTPsymbol)
        #为连接实例设置连接地址
        mduserapi.RegisterFront(行情地址)
        mduserapi.RegisterSpi(mduserspi)
        #启动连接线程
        mduserapi.Init()
        #进行线程阻塞

        单symbol_dict映射 = {x.split('.')[1]: x for x in 需要订阅的CTPsymbol}
        while True:
            try:
                symbol,UpdateTime, UpdateMillisec, TradingDay,ActionDay,LastPrice, Volume, AskPrice1,AskVolume1, BidPrice1,BidVolume1,OpenInterest,\
                    PreSettlementPrice,PreClosePrice, PreOpenInterest,OpenPrice,HighestPrice,LowestPrice,Turnover,ClosePrice,SettlementPrice,UpperLimitPrice,LowerLimitPrice,BidPrice2,BidVolume2,AskPrice2,AskVolume2,\
                        BidPrice3,BidVolume3,AskPrice3,AskVolume3,BidPrice4,BidVolume4,AskPrice4,AskVolume4,BidPrice5,BidVolume5,AskPrice5,AskVolume5,AveragePrice=存储tick队列.get(timeout=30)
            except:
                当前时间 = time_to_str(time.time())[11:16]
                if 当前时间 > "20:30" or "00:00" < 当前时间 < "02:30" or "08:30" < 当前时间 < "15:30":
                    continue
                else:
                    time.sleep(1)
                    mduserapi.Release()
                    print("哥哥我释放了")
                    break
            # if time_to_str(time.time())[11:13] in ("16","03") or time_to_str(time.time())[11:16]=="10:11" :
            #     mduserapi.Release()
            #     print("哥哥我释放了2")
            #     # for x in range(1000):
            #     #     print(x)
            #     #     time.sleep(1)
            #     break

            if 行情类型 == "TQ":
                #处理本条data
                天勤.updata(单symbol_dict映射[symbol], UpdateTime, UpdateMillisec,
                          TradingDay, ActionDay, LastPrice, Volume, AskPrice1,
                          AskVolume1, BidPrice1, BidVolume1, OpenInterest,
                          PreSettlementPrice, PreClosePrice, PreOpenInterest,
                          OpenPrice, HighestPrice, LowestPrice, Turnover,
                          ClosePrice, SettlementPrice, UpperLimitPrice,
                          LowerLimitPrice, BidPrice2, BidVolume2, AskPrice2,
                          AskVolume2, BidPrice3, BidVolume3, AskPrice3,
                          AskVolume3, BidPrice4, BidVolume4, AskPrice4,
                          AskVolume4, BidPrice5, BidVolume5, AskPrice5,
                          AskVolume5, AveragePrice)

                #处理主连
                if 单symbol_dict映射[symbol] in 订阅中的主连合约_反向:
                    天勤.updata(订阅中的主连合约_反向[单symbol_dict映射[symbol]], UpdateTime,
                              UpdateMillisec, TradingDay, ActionDay, LastPrice,
                              Volume, AskPrice1, AskVolume1, BidPrice1,
                              BidVolume1, OpenInterest, PreSettlementPrice,
                              PreClosePrice, PreOpenInterest, OpenPrice,
                              HighestPrice, LowestPrice, Turnover, ClosePrice,
                              SettlementPrice, UpperLimitPrice,
                              LowerLimitPrice, BidPrice2, BidVolume2,
                              AskPrice2, AskVolume2, BidPrice3, BidVolume3,
                              AskPrice3, AskVolume3, BidPrice4, BidVolume4,
                              AskPrice4, AskVolume4, BidPrice5, BidVolume5,
                              AskPrice5, AskVolume5, AveragePrice)

                #如果处理data后,为空列表,change_i_data
                if 存储tick队列.empty():
                    time.sleep(0.003)
                    if 存储tick队列.empty():
                        #print(time_to_str(time.time()))
                        天勤.change_i_data(订阅中的指数合约)
                        #整体处理后,全部推送
                        天勤.all_push()
                    else:
                        #print("我错了")
                        pass
        while True:
            当前时间 = time_to_str(time.time())[11:16]
            if 当前时间 > "20:30" or "00:00" < 当前时间 < "02:30" or "08:30" < 当前时间 < "15:30":
                break
            else:
                time.sleep(1)
Exemple #14
0
    def on_self_bar(self, klines, UPS_COUNT, DOWNS_COUNT, start, end):
        tmp_position = self.position

        tmp_bar, ups = pplib.get_count_of_greater2(klines, start, end)
        tmp_bar, downs = pplib.get_count_of_less2(klines, start, end)
        checksum = pplib.get_checksum2(klines, start, self.count_for_checksum,
                                       1)

        cur_bar_id = klines.iloc[-(start)].id
        if (self.cur_bar < 10):
            return

        if (cur_bar_id % 5 == 0):
            self.on_bar5(klines)

        if (ups > UPS_COUNT):
            self.last_uper_bar = cur_bar_id
            self.last_uper_count = ups
            self.debug(
                "datetime:%s ups:%d downs:%d checksum=%d" % (time_to_str(
                    klines.iloc[-start].datetime), ups, downs, checksum))
            self.debug("datetime:%s up_mark_bar=%d" %
                       (time_to_str(klines.iloc[-start].datetime), cur_bar_id))

        if (downs > DOWNS_COUNT):
            self.last_downer_bar = cur_bar_id
            self.last_downer_count = downs
            self.debug(
                "datetime:%s ups:%d downs:%d checksum=%d" % (time_to_str(
                    klines.iloc[-start].datetime), ups, downs, checksum))
            self.debug("datetime:%s down_mark_bar=%d" %
                       (time_to_str(klines.iloc[-start].datetime), cur_bar_id))
        #开
        #if (cur_bar_id % 3 == 0):
        #    print(time_to_str(klines.iloc[-start].datetime), ups, downs, checksum)
        if (abs(checksum) < 5 and cur_bar_id - self.last_downer_bar < 16
                and self.position <= 0):
            self.debug("ups=%d, downs=%d, lst_downer_count=%d checksum=%d" %
                       (ups, downs, self.last_downer_count, checksum))
            score_inday = self.get_kpi_inday()
            #if (score_inday < -50 and self.last_downer_bar > 110):
            if (score_inday < 0 and self.last_downer_bar > self.std_downs_max):
                if (self.position < 0
                        and self.entry_price - self.ask_price > 35):
                    tmp_position = 0
                    self.debug("空平(p=%d time=%s) 强降到价格 " %
                               (klines.iloc[-start].close,
                                time_to_str(klines.iloc[-start].datetime)))
            if (self.last_downer_count > self.std_downs_max and ups > 5):
                if (self.position < 0):
                    tmp_position = 0
                    self.debug("空平(p=%d time=%s) 条件1 " %
                               (klines.iloc[-start].close,
                                time_to_str(klines.iloc[-start].datetime)))
            elif (self.last_downer_count < self.std_downs_max and ups > 2):
                if (self.low_range_flag == True):
                    if (ups < 8):
                        tmp_position = 1
                        self.debug("多开(p=%d time=%s) 条件1 " %
                                   (klines.iloc[-start].close,
                                    time_to_str(klines.iloc[-start].datetime)))
                else:
                    tmp_position = 1
                    self.debug("多开(p=%d time=%s) 条件1 " %
                               (klines.iloc[-start].close,
                                time_to_str(klines.iloc[-start].datetime)))
        elif (abs(checksum) < 3 and cur_bar_id - self.last_uper_bar < 16
              and self.position >= 0):
            self.debug("ups=%d, downs=%d, lst_uper_count=%d checksum=%d" %
                       (ups, downs, self.last_uper_count, checksum))
            score_inday = self.get_kpi_inday()
            if (score_inday > 0 and self.last_uper_count > self.std_overs_max):
                if (self.position > 0
                        and self.ask_price - self.entry_price > 35):
                    tmp_position = 0
                    self.debug("多平(p=%d time=%s) 强升到价格 " %
                               (klines.iloc[-start].close,
                                time_to_str(klines.iloc[-start].datetime)))
            elif (self.last_uper_count > self.std_overs_max):
                if (self.position > 0 and downs > 5):
                    tmp_position = 0
                    self.debug("多平(p=%d time=%s) 条件1 " %
                               (klines.iloc[-start].close,
                                time_to_str(klines.iloc[-start].datetime)))
            elif (self.last_uper_count < self.std_overs_max and downs > 3):
                if (self.low_range_flag == True):
                    if (downs < 8):
                        tmp_position = -1
                        self.debug("空开(p=%d time=%s) 条件1 " %
                                   (klines.iloc[-start].close,
                                    time_to_str(klines.iloc[-start].datetime)))
                else:
                    tmp_position = -1
                    self.debug("空开(p=%d time=%s) 条件1 " %
                               (klines.iloc[-start].close,
                                time_to_str(klines.iloc[-start].datetime)))
        #止平
        if (self.position < 0 and self.last_uper_count > self.std_overs_max
                and abs(checksum) < 5):
            tmp_position = 0
            self.cond_up_count = self.cond_up_count + 10
            self.cond_down_count = self.cond_down_count - 10
            self.debug("空止平(p=%d time=%s) 条件1 " %
                       (klines.iloc[-start].close,
                        time_to_str(klines.iloc[-start].datetime)))
        if (self.position > 0 and self.last_downer_count > self.std_downs_max
                and abs(checksum) < 5):
            self.cond_up_count = self.cond_up_count - 10
            self.cond_down_count = self.cond_down_count + 10
            tmp_position = 0
            self.debug("多止平(p=%d time=%s) 条件1 " %
                       (klines.iloc[-start].close,
                        time_to_str(klines.iloc[-start].datetime)))
        '''
        if (cur_bar_id - self.last_downer_bar == 10):

        '''
        if (tmp_position != self.position):
            if (self.check_open_position(tmp_position) == True):
                self.set_position(tmp_position)
Exemple #15
0
 def backtest(self, klines):
     for i in range(1, 10):
         print("==========[%s]===============" %
               (tafunc.time_to_str(klines.iloc[-i].datetime)))
         self.get_daybar_score(klines, i)
Exemple #16
0
 def OnRtnDepthMarketData(self, pDepthMarketData: 'CThostFtdcDepthMarketDataField') -> "void":
     global 当前交易日
     #print(pDepthMarketData)
     当前交易日=pDepthMarketData.TradingDay
     #print(pDepthMarketData.InstrumentID)
     l=[
     pDepthMarketData.InstrumentID,
     pDepthMarketData.UpdateTime,
     pDepthMarketData.UpdateMillisec,
     pDepthMarketData.TradingDay,
     pDepthMarketData.ActionDay,
     pDepthMarketData.LastPrice,
     pDepthMarketData.Volume,
     pDepthMarketData.AskPrice1,
     pDepthMarketData.AskVolume1,
     pDepthMarketData.BidPrice1,
     pDepthMarketData.BidVolume1,
     pDepthMarketData.OpenInterest,
     #PreSettlementPrice
     pDepthMarketData.PreSettlementPrice,
     #PreClosePrice
     pDepthMarketData.PreClosePrice,
     #PreOpenInterest
     pDepthMarketData.PreOpenInterest,
     #OpenPrice
     pDepthMarketData.OpenPrice,
     #HighestPrice
     pDepthMarketData.HighestPrice,
     #LowestPrice
     pDepthMarketData.LowestPrice,
     #Turnover
     pDepthMarketData.Turnover,
     #ClosePrice
     pDepthMarketData.ClosePrice,
     #SettlementPrice
     pDepthMarketData.SettlementPrice,
     #UpperLimitPrice
     pDepthMarketData.UpperLimitPrice,
     #LowerLimitPrice
     pDepthMarketData.LowerLimitPrice,
     # ///BidPrice2
     pDepthMarketData.BidPrice2,
     # ///BidVolume2
     pDepthMarketData.BidVolume2,
     # ///AskPrice2
     pDepthMarketData.AskPrice2,
     # ///AskVolume2
     pDepthMarketData.AskVolume2,
     # ///BidPrice3
     pDepthMarketData.BidPrice3,
     # ///BidVolume3
     pDepthMarketData.BidVolume3,
     # ///AskPrice3
     pDepthMarketData.AskPrice3,
     # ///AskVolume3
     pDepthMarketData.AskVolume3,
     # ///BidPrice4
     pDepthMarketData.BidPrice4,
     # ///BidVolume4
     pDepthMarketData.BidVolume4,
     # ///AskPrice4
     pDepthMarketData.AskPrice4,
     # ///AskVolume4
     pDepthMarketData.AskVolume4,
     # ///BidPrice5
     pDepthMarketData.BidPrice5,
     # ///BidVolume5
     pDepthMarketData.BidVolume5,
     # ///AskPrice5
     pDepthMarketData.AskPrice5,
     # ///AskVolume5
     pDepthMarketData.AskVolume5,
     # ///AveragePrice
     pDepthMarketData.AveragePrice,
     time_to_str(time.time())
     ]
     self.red.lpush(pDepthMarketData.InstrumentID,','.join( [str(x) for x in l ]))
Exemple #17
0
import redis
import time
from tqsdk.tafunc import time_to_str

red = redis.Redis(db=15)
n = 0
t2 = 0
while True:
    a = red.lrange("DCE.i210110", 0, 5)
    if n != eval(a[0].decode())[1]:
        t1 = time.time()
        print(t1 - t2)
        t2 = t1
        n = eval(a[0].decode())[1]
        print("----------")
        for x in a:
            print(time_to_str(eval(x.decode())[0]))
Exemple #18
0
    def get_daybar_score(self, klines, id):
        self.debug("======analyze [%s] daybar=========" %
                   (tafunc.time_to_str(klines.iloc[-id].datetime)))
        self.debug("当日:open=%d close=%d" %
                   (klines.iloc[-1].open, klines.iloc[-1].close))
        self.debug("昨日:open=%d close=%d" %
                   (klines.iloc[-id].open, klines.iloc[-id].close))
        #突破+40
        #Bigbang30
        #连续+10
        #震荡上一个绿+10
        #底部+10
        BreakScore = 30
        BigBangScore = 20
        CheckSumScore = 20
        ContinueScore = 10
        InRangeAdjust = 10
        TopBomScore = 10
        RED_GREEN_SCORE = 10

        self.kpi = 0
        self.cur_day_bar = id
        if (self.cur_price == 0):
            self.cur_price = klines.iloc[-id].close
        #常用数据
        atr = ATR(klines, 30)
        self.ATR_day = int(atr.atr.iloc[-id])
        print("[%s] self.ATR_day=%d" % (self.TAG, self.ATR_day))

        # big bang find
        self.last_big_green_candle, self.last_big_green_candle_hight = pplib.find_big_green_candle(
            klines, 1, id, id + 20, atr.atr.iloc[-id] * 1.5)
        self.last_big_red_candle, self.last_big_red_candle_height = pplib.find_big_red_candle(
            klines, 1, id, id + 20, atr.atr.iloc[-id] * 1.5)
        # big bang score
        if (self.last_big_red_candle - id < 10
                and self.last_big_red_candle < self.last_big_green_candle):
            self.kpi = self.kpi + (11 - (self.last_big_red_candle - id)) * (
                BigBangScore / 10) + int(
                    (self.last_big_red_candle - atr.atr.iloc[-id] * 1.5) /
                    50) * 5
        if (self.last_big_green_candle - id < 10
                and self.last_big_red_candle < self.last_big_green_candle):
            self.kpi = self.kpi - (11 - (self.last_big_green_candle - 1)) * (
                BigBangScore / 10) - int(
                    (self.last_big_red_candle - atr.atr.iloc[-id] * 1.5) /
                    50) * 5
        print(
            "[%s] self.last_big_red_candle=%d, self.last_big_green_candle=%d" %
            (self.TAG, self.last_big_red_candle, self.last_big_green_candle))
        print("[%s] kpi=%d" % (self.TAG, self.kpi))

        #continue find
        self.last_continue_up_bar = 999
        self.last_continue_down_bar = 999
        for i in range(id, id + 6):
            count = 0
            for j in range(0, 3):
                if (klines.iloc[-(i + j)].open < klines.iloc[-(i + j)].close):
                    count = count + 1
                else:
                    count = count - 1
            if (count >= 3):
                self.last_continue_up_bar = i
                break
            elif (count <= -3):
                self.last_continue_down_bar = i
                break
        #连续
        if (self.last_continue_up_bar - id <= 1):
            self.kpi = self.kpi + ContinueScore
        if (self.last_continue_down_bar - id <= 1):
            self.kpi = self.kpi - ContinueScore
        print(
            "[%s] self.last_continue_up_bar=%d self.last_continue_down_bar=%d"
            %
            (self.TAG, self.last_continue_up_bar, self.last_continue_down_bar))
        print("[%s] kpi=%d after ContinueScore" % (self.TAG, self.kpi))
        #checksum
        self.day_checksum_4 = pplib.get_checksum(klines, 5, 1)
        cks_ret = abs(self.day_checksum_4) / self.ATR_day
        print("[%s] self.day_checksum_4=%d cks_ret=%f" %
              (self.TAG, self.day_checksum_4, cks_ret))
        cks_score = 0
        cks_weight = 0.2
        if (cks_ret > 1.5):
            cks_weight = 1
        elif (cks_ret > 1):
            cks_weight = 0.7
        elif (cks_ret > 0.5):
            cks_weight = 0.5
        else:
            cks_weight = 0.2
        if (self.day_checksum_4 > 0):
            cks_score = int(CheckSumScore * cks_weight)
        if (self.day_checksum_4 < 0):
            cks_score = -int(CheckSumScore * cks_weight)
        print("[%s] cks_score=%d" % (self.TAG, cks_score))
        # inrange find
        heightest = 1000
        heightest_bar = 1
        '''
        for i in range(id, id+2):
            height = pplib.get_height_in_range(klines, i, i+3)
            if (height > heightest):
                heightest = height
                heightest_bar = i
        '''
        heightest = pplib.get_height_in_range(klines, id, id + 5)
        result = heightest / atr.atr.iloc[-i]
        print("[%s] result=%f" % (self.TAG, result))
        if (result < 1.5):
            self.last_inrange_bar = heightest_bar
        self.last_inrange_height = heightest
        self.last_inrange_high = pplib.get_hest_in_range(klines, id, id + 5)
        self.last_inrange_low = pplib.get_lest_in_range(klines, id, id + 5)

        #inrange score
        if (self.last_inrange_bar - id < 2
                and self.last_continue_up_bar - id > 3
                and self.last_continue_down_bar - id > 3):
            if (klines.iloc[-id].close > klines.iloc[-id].open):
                self.kpi = self.kpi - InRangeAdjust
            else:
                self.kpi = self.kpi - InRangeAdjust
        print("[%s] last_inrange_bar=%d" % (self.TAG, self.last_inrange_bar))
        self.debug(
            "last_inrange_high=%d last_inrange_low=%d last_inrange_height=%d" %
            (self.last_inrange_high, self.last_inrange_low,
             self.last_inrange_height))
        print("[%s] kpi=%d" % (self.TAG, self.kpi))
        #===================================================#
        # break find
        self.last_break_up_bar = 999
        self.last_break_down_bar = 999
        for i in range(id, id + 6):
            tmp = pplib.get_hest_in_range(klines, i + 1, i + 1 + 4)
            if (klines.iloc[-i].close > tmp):
                self.last_break_up_bar = i
                break
        for i in range(id, id + 6):
            tmp = pplib.get_lest_in_range(klines, i + 1, i + 1 + 4)
            if (klines.iloc[-i].close < tmp):
                self.last_break_down_bar = i
                break
        #break
        if (self.last_break_up_bar - id == 0):
            self.kpi = self.kpi + BreakScore
        elif (self.last_break_up_bar - id == 1):
            self.kpi = self.kpi + int(BreakScore / 2)
        elif (self.last_break_up_bar - id == 2):
            self.kpi = self.kpi + int(BreakScore / 3)
        if (self.last_break_down_bar - id == 0):
            self.kpi = self.kpi - BreakScore
        elif (self.last_break_down_bar - id == 1):
            self.kpi = self.kpi - int(BreakScore / 2)
        elif (self.last_break_down_bar - id == 2):
            self.kpi = self.kpi - int(BreakScore / 3)
        print("[%s] self.last_break_up_bar=%d self.last_break_down_bar=%d " %
              (self.TAG, self.last_break_up_bar, self.last_break_down_bar))
        print("[%s] kpi=%d" % (self.TAG, self.kpi))
        #=====================================#
        # price pos find
        self.hh_100, self.hh_100_bar = pplib.get_hest_in_range2(
            klines, id, id + 100)
        self.ll_100, self.ll_100_bar = pplib.get_lest_in_range2(
            klines, id, id + 100)
        price_pos_ratio = (self.cur_price - self.ll_100) / (self.hh_100 -
                                                            self.ll_100)
        if (price_pos_ratio <= 0.5):
            self.kpi = self.kpi + (5 - int(price_pos_ratio * TopBomScore)) * 2
        else:
            self.kpi = self.kpi - (int(price_pos_ratio * TopBomScore) - 5) * 2
        print("[%s] price_pos_ratio=%f" % (self.TAG, price_pos_ratio))
        print("[%s] kpi=%d" % (self.TAG, self.kpi))
        #++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#

        #修正
        if (self.last_break_up_bar - id <= 2
                and self.last_big_red_candle - id < 6):
            print("last_break_up_bar=%d last_big_red_candle=%d  " %
                  (self.last_break_up_bar - id <= 2,
                   self.last_big_red_candle - id))
            self.kpi += 20
        if (self.last_break_down_bar - id <= 2
                and self.last_big_green_candle - id < 6):
            self.kpi -= 20
        if (self.last_break_up_bar - id <= 2 and price_pos_ratio < 0.6):
            self.kpi += 20
            print("last_break_up_bar=%d price_pos_ratio=%d  " %
                  (self.last_break_up_bar - id <= 2, price_pos_ratio))
        if (self.last_break_down_bar - id <= 2
                and self.last_big_green_candle - id < 6):
            self.kpi -= 20
        #print ("height=%d atr=%d wave ratio=%f "%(height, atr.atr.iloc[-i], height/atr.atr.iloc[-i]))
        print("[%s] kpi=%d" % (self.TAG, self.kpi))
        #=====================================================================#
        # 距离底、顶的距离
        self.hh_20, self.hh_20_bar = pplib.get_hest_in_range2(
            klines, id, id + 20)
        self.ll_20, self.ll_20_bar = pplib.get_lest_in_range2(
            klines, id, id + 20)
        self.hh_10, self.hh_10_bar = pplib.get_hest_in_range2(
            klines, id, id + 10)
        self.ll_10, self.ll_10_bar = pplib.get_lest_in_range2(
            klines, id, id + 10)
        self.hh_5, self.hh_5_bar = pplib.get_hest_in_range2(klines, id, id + 6)
        self.ll_5, self.ll_5_bar = pplib.get_lest_in_range2(klines, id, id + 6)
        dif = self.hh_10_bar - id
        if (dif == 0):
            self.kpi += TopBomScore
        if (dif == 1):
            self.kpi += int(TopBomScore / 2)
        elif (dif == 2):
            self.kpi -= TopBomScore
        elif (dif == 3):
            self.kpi += TopBomScore
        elif (dif > 3 and dif <= 5):
            self.kpi -= TopBomScore
        self.to_top = dif

        dif = self.ll_10_bar - id
        if (dif == 0):
            self.kpi -= TopBomScore
        if (dif == 1):
            self.kpi -= int(TopBomScore / 2)
        elif (dif == 2):
            self.kpi += TopBomScore
        elif (dif == 3):
            self.kpi -= TopBomScore
        elif (dif > 3 and dif <= 5):
            self.kpi += TopBomScore
        self.to_bottom = dif
        print("[%s] to top=%d, to bottom=%d " %
              (self.TAG, self.hh_10_bar - id, self.ll_10_bar - id))
        print("[%s] kpi=%d" % (self.TAG, self.kpi))
        #==============================================================#
        # 红绿数量
        red_gre_score = 0
        self.reds = pplib.get_reds_candle(klines, 6)
        self.greens = pplib.get_greens_candle(klines, 6)
        if (self.greens > 0):
            red_gre_score -= self.greens * 20
        if (self.reds > 0):
            red_gre_score += self.reds * 20
        self.kpi += red_gre_score * (RED_GREEN_SCORE / 100)
        #跳空
        print("[%s] greens=%d reds=%d" % (self.TAG, self.greens, self.reds))
        gap_v = klines.iloc[-id].open - klines.iloc[-(id + 1)].close
        if (gap_v > 10):
            print("[%s] 高跳" % (self.TAG))
            self.manager.drive_event(self.TAG, StgEvent.GapUp, gap_v)
            self.kpi += 10
        gap_v = klines.iloc[-(id + 1)].close - klines.iloc[-id].open
        if (gap_v > 10):
            print("[%s] 低跳" % (self.TAG))
            self.manager.drive_event(self.TAG, StgEvent.GapDown, gap_v)
            self.kpi -= 10

        print("[%s] kpi=%d" % (self.TAG, self.kpi))
Exemple #19
0
def print_klines(klines, count):
    for i in range(1, count):
        print(time_to_str(klines.loc[i].datetime), klines.iloc[i].average)