Example #1
0
    def prgCheck(self, _shcode=""):
        dbInstance = dbManager.dbManager()
        res = dbInstance.selectGubunRecommendList(_shcode)
        if len(res) != 0:
            gubun = res[0]["gubun"] == "KOSPI" and "0" or "1"
        else:
            print("no info exists in recommendList")
            return False

        df = orderManager.t1636(구분=gubun, 종목코드=_shcode)
        tmpDf = df['종목코드'] == _shcode
        df = df[tmpDf]
        if df.shape[0] == 0:
            print("프로그램 추세 정보 알 수 없음(%s)" % _shcode)
            return False
        # for i in range(0, df.shape[0]):
        #     if df["종목코드"].values[i] == _shcode:
        print("종목명:", df["종목명"].values[0], "종목코드:", _shcode)
        print("순위:", df["순위"].values[0], "종목명:", df["종목명"].values[0], "현재가:", df["현재가"].values[0], \
              "대비구분:", df["대비구분"].values[0], "대비:", df["대비"].values[0], "등락률:", df["등락률"].values[0], \
              "거래량:", df["거래량"].values[0], "순매수수량:", df["순매수수량"].values[0], "비중:",
              df["비중"].values[0],
              "순매수금액", df["순매수금액"].values[0], "매수금액", df["매수금액"].values[0])
        if float(df["순매수금액"].values[0]) <= 0:
            return True  # 매도
        else:
            return False
Example #2
0
	def __init__(self):
		super(Character, self).__init__()
		self.ui=Ui_Dialog()
		self.ui.setupUi	(self)
		self.dbm=dbManager("data.db")
		self.dbm.connect()
		self.signals()
 def getOneUnderHoga(self, shcode, price):  # 1: KOPSI, 2:KOSDAQ
     price = int(price)
     ret = price
     dbInstance = dbManager.dbManager()
     res = dbInstance.selectGubunRecommendList(shcode)
     if len(res) == 0:
         print("unknown code yet in recommend list")
         return ret
     print("[호가조정] 종목명: ", res[0]['hname'], " 구분: ", res[0]['gubun'])
     gubun = res[0]['gubun']
     if price < 1000:
         ret -= 1
     elif price >= 1000 and price < 5000:
         ret -= 5
     elif price >= 5000 and price < 10000:
         ret -= 10
     elif price >= 10000 and price < 50000:
         ret -= 50
     elif price >= 50000 and price < 100000:
         ret -= 100
     elif price >= 100000 and price < 500000:
         temp = gubun == 1 and 500 or 100
         ret -= temp
     elif price >= 500000:
         temp = gubun == 1 and 1000 or 100
         ret -= temp
     else:
         print("호가 알 수 없음")
     return str(ret)
Example #4
0
 def handle_request(self, req):
     db = dbManager.dbManager()
     if req.path == '/users': #and req.method == 'POST':
         return self.create_user(req, db)
     if req.path == '/user':
         return self.checkUser(req, db)
     #return Response(200, 'OK')
     raise Exception('Not found')
Example #5
0
    def __init__(self, config_file):
        with open(config_file) as file:
            self.config = json.load(file)

        self.taxcode_index = self.config['taxcode_index']
        self.kind = self.config['kind']

        self.dbManager = dbManager(self.config['db_config'])
Example #6
0
    def __init__(self, rootPath, schema):
        """Load the config yaml"""

        self.__yamlPath = os.path.join(os.path.abspath(rootPath), "dataset/")
        self.__schema = schema
        self.__sqlPath = os.path.join(self.__yamlPath, "sql")
        self.conf = yaml.load(open(self.__yamlPath + "config.yaml"))
        self.db_manager = dbManager.dbManager(os.path.join(rootPath, 'testspec/metadata/analyticstool.xml'))

        self.__log = {}
Example #7
0
	def __init__(self):
		super(Elenco, self).__init__()
		self.ui=Ui_Dialog()
		self.ui.setupUi	(self)
		self.dbm=dbManager("data.db")
		self.dbm.connect()
		self.signals()
		self.character=Character()
		
		self.setWindowTitle("Administrar elencos")
Example #8
0
    def __init__(self, rootPath, schema):
        """Load the config yaml"""

        self.__yamlPath = os.path.join(os.path.abspath(rootPath), "dataset/")
        self.__schema = schema
        self.__sqlPath = os.path.join(self.__yamlPath, "sql")
        self.conf = yaml.load(open(self.__yamlPath + "config.yaml"))
        self.db_manager = dbManager.dbManager(
            os.path.join(rootPath, 'testspec/metadata/analyticstool.xml'))

        self.__log = {}
Example #9
0
    def rollout():
        now = time.localtime()
        start = time.time()
        tempDate = "%04d%02d%02d" % (now.tm_year, now.tm_mon, now.tm_mday)
        dbInstance = dbManager.dbManager()
        res = dbInstance.selectDailyRecommendList("KOSPI", tempDate)
        for idx, row in enumerate(res):
            print(">>>", idx, "shcode", row["shcode"])
            # strategy1(row["shcode"], tempDate, '', '', '', '',skip=False, refname=row["hname"])
            strategy2(row["shcode"], tempDate, row["hname"])

            # time.sleep(3)
        print("rollout 수행 시간: ", time.time() - start)
Example #10
0
def T1471_SearchBuyCandidates(_shcode):
    df1471o, df1471ob = orderManager.t1471(종목코드=_shcode, 자료개수="001")

    now = time.localtime()
    tempDate = "%04d%02d%02d" % (now.tm_year, now.tm_mon, now.tm_mday)

    if df1471o.shape[0] == 0 :
        print("종목코드 ",_shcode, " 잔량 조회 결과 없음")
        return None
    rtime = df1471o["시간CTS"].values[0]
    price = df1471o["현재가"].values[0]
    sign = df1471o["전일대비구분"].values[0]
    change = df1471o["전일대비"].values[0]
    diff = df1471o["등락율"].values[0]
    volume = df1471o["누적거래량"].values[0]
    dbInstance = dbManager.dbManager()
    dbInstance.insert1471OB(_shcode, tempDate, rtime, price, sign, change, diff, volume)

    if df1471ob.shape[0] == 0 :
        print("종목코드 ",_shcode, " 잔량 조회 상세 결과 없음")
        return None
    for i in range(0, df1471ob.shape[0]):
        strTempTime = df1471ob["체결시간"].values[i]
        preoffercha1 = df1471ob["매도증감"].values[i]
        offerrem1 = df1471ob["매도우선잔량"].values[i]
        offerho1 = df1471ob["매도우선호가"].values[i]
        bidho1 = df1471ob["매수우선호가"].values[i]
        bidrem1 = df1471ob["매수우선잔량"].values[i]
        prebidcha1 = df1471ob["매수증감"].values[i]
        totofferrem = df1471ob["총매도"].values[i]
        totbidrem = df1471ob["총매수"].values[i]
        totsun = df1471ob["순매수"].values[i]
        msrate = df1471ob["매수비율"].values[i]
        close = df1471ob["종가"].values[i]

        #print(_shcode+" "+strTempTime+" "+preoffercha1+" "+offerrem1+" "+offerho1+" "+bidrem1+" "+prebidcha1+" "+totofferrem+" "+totbidrem+" "+totsun+" "+msrate+" "+close)

        dbInstance.insert1471OB_Occurs(_shcode, tempDate, strTempTime, preoffercha1, offerrem1, offerho1, bidho1,
                                       bidrem1, prebidcha1, totofferrem, totbidrem, totsun, msrate, close)
        if float(msrate) > 150 and float(bidrem1) < (float(offerrem1) * 2) :
            print("watch list",_shcode,tempDate,strTempTime,msrate,bidrem1,offerrem1,price)
            return (_shcode,tempDate,strTempTime,msrate,bidrem1,offerrem1,price)
            #dbInstance.insertObserverList(_shcode,tempDate,strTempTime,msrate,bidrem1,offerrem1,price)
        else :
            return None
Example #11
0
    def T1471(_self, _shcode):
        instXAQueryT1471 = win32com.client.DispatchWithEvents("XA_DataSet.XAQuery", XAQueryEventsT1471)
        instXAQueryT1471.ResFileName = "C:\\eBEST\\xingAPI\\Res\\t1471.res"
        instXAQueryT1471.SetFieldData("t1471InBlock", "shcode", 0, _shcode)
        instXAQueryT1471.SetFieldData("t1471InBlock", "gubun", 0, "01") # 00:30sec, 01: 1min
        instXAQueryT1471.SetFieldData("t1471InBlock", "time", 0, "")
        instXAQueryT1471.SetFieldData("t1471InBlock", "cnt", 0, "500")
        instXAQueryT1471.Request(0)

        while instXAQueryT1471.query_state == 0:
            pythoncom.PumpWaitingMessages()
        XAQueryEventsT1471.query_state = 0  # 중요

        # sql = "insert into TB_TRADE_MIN(shcode, chetime,close,sign,change,diff,chdegree,mdvolume,msvolume,revolume,mdchecnt,mschecnt,rechecnt,volume,open,high,low,cvolume,mdchecnttm,mschecnttm,totofferrem,totbidrem,mdvolumetm,msvolumetm,ymd) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
        now = time.localtime()
        tempDate = "%04d%02d%02d" % (now.tm_year, now.tm_mon, now.tm_mday)

        rtime = instXAQueryT1471.GetFieldData("t1471OutBlock", "time", 0)
        price = instXAQueryT1471.GetFieldData("t1471OutBlock", "price", 0)
        sign = instXAQueryT1471.GetFieldData("t1471OutBlock", "sign", 0)
        change = instXAQueryT1471.GetFieldData("t1471OutBlock", "change", 0)
        diff = instXAQueryT1471.GetFieldData("t1471OutBlock", "diff", 0)
        volume  = instXAQueryT1471.GetFieldData("t1471OutBlock", "volume", 0)
        dbInstance = dbManager.dbManager()
        dbInstance.insert1471OB(_shcode, tempDate, rtime, price, sign, change, diff, volume)

        count = instXAQueryT1471.GetBlockCount("t1471OutBlock1")

        for i in range(count):
            strTempTime = instXAQueryT1471.GetFieldData("t1471OutBlock1", "time", i)
            preoffercha1 = instXAQueryT1471.GetFieldData("t1471OutBlock1", "preoffercha1", i)
            offerrem1 = instXAQueryT1471.GetFieldData("t1471OutBlock1", "offerrem1", i)
            offerho1 = instXAQueryT1471.GetFieldData("t1471OutBlock1", "offerho1", i)
            bidho1 = instXAQueryT1471.GetFieldData("t1471OutBlock1", "bidho1", i)
            bidrem1 = instXAQueryT1471.GetFieldData("t1471OutBlock1", "bidrem1", i)
            prebidcha1 = instXAQueryT1471.GetFieldData("t1471OutBlock1", "prebidcha1", i)
            totofferrem = instXAQueryT1471.GetFieldData("t1471OutBlock1", "totofferrem", i)
            totbidrem = instXAQueryT1471.GetFieldData("t1471OutBlock1", "totbidrem", i)
            totsun = instXAQueryT1471.GetFieldData("t1471OutBlock1", "totsun", i)
            msrate = instXAQueryT1471.GetFieldData("t1471OutBlock1", "msrate", i)
            close = instXAQueryT1471.GetFieldData("t1471OutBlock1", "close", i)
            dbInstance.insert1471OB_Occurs(_shcode, tempDate, strTempTime, preoffercha1, offerrem1, offerho1, bidho1,
                                           bidrem1, \
                                           prebidcha1, totofferrem, totbidrem, totsun, msrate, close)
Example #12
0
    def testconfig(self):
        """Parse logger database connection to store result."""
        try:
            configuration       =   Parser.getNodeTag(self, self.xmlDoc, "configuration")
            metadatadb          =   Parser.getNodeTag(self, configuration, "metadatadb")        
            self.user                =   Parser.getNodeVal(self, metadatadb, "user")
            self.host                =   Parser.getNodeVal(self, metadatadb, "host")
            self.port                =   Parser.getNodeVal(self, metadatadb, "port")
            self.database            =   Parser.getNodeVal(self, metadatadb, "database")
            self.resultDBSchema      =   Parser.getNodeVal(self, metadatadb, "schema")

            self.resultDBconf = {'username':self.user, 'host':self.host, 'port':self.port, \
                       'database':self.database, 'schema':self.resultDBSchema, 'name':'resultDB'}
            self.dbmanager = dbManager.dbManager(self.resultDBconf)
 
        except Exception, exp:
            print str(exp)
            print "Error when parsing testConfig"
            sys.exit()
    def do(self, modules=None, overwritten=False, overload=False, initdb=False):
        """Read yaml files, download, unzip, convert and load"""
        yaml_list = self.__loadYaml(modules)
        self.__convert(yaml_list, overwritten)

        db_manager = dbManager.dbManager(self.testdbs_conf)
        # db_manager.start()

        if initdb is True:
            db_manager.initDB()

        self.__load(db_manager, yaml_list, overload)
        # db_manager.stop()
        total_time = 0.0
        for id, attris in self.__log.items():
            info = ''
            for key, value in attris.items():
                if key in ('load', 'convert', 'download'):
                    total_time += value
                info += key + ':' + str(value) + '\t'
            print id + '\t' + info
        print "Total Time Spent:", total_time
async def queryProfit(tempDate='', isToday=True):

    pythoncom.CoInitialize()
    orderManager.Login(id=user_id, pwd=user_pass, cert=user_certificate_pass)

    print("queryProfit called")
    dbInstance = dbManager.dbManager()
    res = dbInstance.selectOrderListByDate(tempDate)
    if len(res) == 0:
        print("There is no ordered list yet")
        return

    if isToday == True:
        df = orderManager.t0150(accountNumber)
    else:
        df = orderManager.t0151(tempDate, accountNumber)

    if df.shape[0] == 0:
        print("매매내역 조회 실패")
        sendTeleMsg("매매내역 조회 실패")
        pythoncom.CoUninitialize()
        return
    totmdsum = 0
    totmssum = 0
    totStr = '[당일매매 수익현황]\n'
    for i in res:
        tmpdf = df[(df['종목번호'] == i["shcode"]) & (df['매매구분'] == '매도')]
        if tmpdf.shape[0] == 0:
            print("해당 종목 해당일 매도 내역 없음")
            pythoncom.CoUninitialize()
            continue
        mdsum = tmpdf['정산금액'].apply(pd.to_numeric).sum()
        totmdsum += mdsum
        mssum = 0
        tmpdf = df[(df['종목번호'] == i["shcode"]) & (df['매매구분'] == '매수')]
        if tmpdf.shape[0] == 0:
            print("금일 매수 내역 없음, 전일 조회 시작")
            innerRes = dbInstance.selectBoughtDateFromOrderList(
                i["shcode"], tempDate)
            if len(innerRes) == 0:
                print("매수 조회 실패")
                continue
            print("매수 일자: ", innerRes[0]['orderdate'])
            df1 = orderManager.t0151(innerRes[0]['orderdate'], accountNumber)
            df1 = df1[(df1['종목번호'] == i["shcode"]) & (df1['매매구분'] == '매수')]
            mssum = df1['정산금액'].apply(pd.to_numeric).sum()
            totmssum += mssum
        else:
            mssum = tmpdf['정산금액'].apply(pd.to_numeric).sum()
            totmssum += mssum

        if mssum == 0:
            print("매수금액 계산 오류")
            continue
        profitRate = (((float(mdsum) * 0.9974 - float(mssum))) / float(mssum))
        profitRate = format(profitRate, "3.2%")  # '{:.3%}".format(0.25666)
        tmpStr = i['isunm'] + ' 매수금액: ' + str(mssum) + ' 매도금액: ' + str(
            mdsum) + ' 수익률: ' + str(profitRate) + '\n'
        print(tmpStr, end='')
        totStr += tmpStr

    sendTeleMsg(totStr)

    if totmssum == 0:
        print("정산 대상 총매수금액 : 0")
        pythoncom.CoUninitialize()
        return
    tmpStr = '총매수: ' + str(totmssum) + ' 총매도: ' + str(
        totmdsum) + ' 총수익: ' + format(
            (float(totmdsum) * 0.9974 - float(totmssum)) / float(totmssum),
            "10.2%")
    print(tmpStr)
    sendTeleMsg(tmpStr)
    pythoncom.CoUninitialize()
Example #15
0
import dbManager

dbmanager = dbManager.dbManager()

index = "forensic_db"
doc_type = "prova inserimento"
body = {
    "filePath": "/home/prova",
    "size": "123456"
}

dbmanager.push(index,doc_type,body)
Example #16
0
    myPrint.fDebug = open(myPrint.fnDebug, 'a')  # , buffering=1)
    server_addr = "hts.ebestsec.co.kr"
    server_port = 20001
    server_type = 0
    user_id = "your id"
    user_pass = "******"
    user_certificate_pass = "******"
    g_rsiTgt = 0
    g_simpleMA9Tgt = 0
    inXASession = win32com.client.DispatchWithEvents("XA_Session.XASession",
                                                     XASessionEvents)
    inXASession.ConnectServer(server_addr, server_port)
    inXASession.Login(user_id, user_pass, user_certificate_pass, server_type,
                      0)

    dbInstance = dbManager.dbManager()
    while XASessionEvents.logInState == 0:
        pythoncom.PumpWaitingMessages()

    num_account = inXASession.GetAccountListCount()
    for i in range(num_account):
        account = inXASession.GetAccountList(i)
        print(account)

    #listT1452=[["null" for col in range(5)] for row in range(120)]
    listT1452 = [["null" for col in range(1)] for row in range(280)]

    # 전날 데이터 수신 (1: today 2: yesterday)
    def T1452(idx=0, isToday=1):
        # Exit Condition
        idxTemp = int(idx)
Example #17
0
def on_message(client, userdata, message):
    db = dbManager(os.path.dirname(os.path.realpath(__file__)) + "/emonv3.db")
    db.setup()
    mes = str(message.payload.decode("utf-8"))
    parsed_js = (json.loads(mes))
    if 'id' in parsed_js:
        message_id = str(parsed_js['id'])
    elif 'MeterGuid' in parsed_js:
        message_id = str(parsed_js['MeterGuid'])
    elif 'name' in parsed_js:
        message_id = str(parsed_js['name'])

    if message_id == "TIMDB_PATJON_EMON":
        logging.info("Received data from: %s", message_id)
        result = db.retrieve_iskra_energie_last()
        energymeter_name = str((parsed_js['identification']))
        watt = parsed_js['watt']
        signature = str((parsed_js['signature']))
        dateTimeObj = datetime.now()
        timestamp = dateTimeObj.strftime("%d-%b-%Y %H:%M:%S")
        if result == None:
            wattHour = watt / 30
            totalkwh = wattHour / 1000
            db.insert_iskra_energie(message_id, energymeter_name, watt,
                                    wattHour, totalkwh, signature, timestamp)
        else:
            wattHour = watt / 30
            totalkwh = (wattHour / 1000) + result[5]
            db.insert_iskra_energie(message_id, energymeter_name, watt,
                                    wattHour, totalkwh, signature, timestamp)

    if message_id == "TIMDB_PAJTON_EMON_TEMP":
        logging.info("Received data from: %s", message_id)
        temperature = parsed_js['temperature']
        signature = str((parsed_js['signature']))
        dateTimeObj = datetime.now()
        timestamp = dateTimeObj.strftime("%d-%b-%Y %H:%M:%S")
        db.insert_iskra_temperature(message_id, temperature, signature,
                                    timestamp)

    # Om de minuut
    if message_id == "858A559A-58E7-4429-8753-AC239E49C489":
        logging.info("Received data from: %s",
                     "858A559A-58E7-4429-8753-AC239E49C489")
        result = db.retrieve_tom_energy_last()
        wattHour = parsed_js["wattHour"] / 17
        meterguid = message_id
        dateTimeObj = datetime.now()
        timestamp = dateTimeObj.strftime("%d-%b-%Y %H:%M:%S")
        if result == None:
            watt = wattHour * 30
            total = wattHour / 2000
            db.insert_tom_energiemeter(meterguid, watt, wattHour, total,
                                       timestamp)
        else:
            watt = wattHour * 30
            total = (wattHour / 2000) + result[4]
            db.insert_tom_energiemeter(meterguid, watt, wattHour, total,
                                       timestamp)

    # om de 5 minuten
    if message_id == "AngstHuisMeter":
        logging.info("Received data from: %s", "AngstHuisMeter")
        result = db.retrieve_simon_energie_last()
        name = message_id
        watt = parsed_js["watt"]
        wattHour = watt / 12
        signature = parsed_js["signature"]
        dateTimeObj = datetime.now()
        timestamp = dateTimeObj.strftime("%d-%b-%Y %H:%M:%S")

        if result == None:
            total = wattHour / 1000
            db.insert_simon_energiemeter(name, watt, wattHour, total,
                                         signature, timestamp)
        else:
            total = (wattHour / 1000) + result[4]
            db.insert_simon_energiemeter(name, watt, wattHour, total,
                                         signature, timestamp)
Example #18
0
    print('mouse clicked:', x, y)


if __name__ == "__main__":
    args = sys.argv
    qml_doc_path = None
    if len(args) > 1:
        qml_doc_path = args[1]
        print('qml doc path:', qml_doc_path)
    else:
        print('no qml doc path :(')
        exit()
    if not os.path.isfile(qml_doc_path):
        print('qml doc is not a file :(')
        exit()
    app = QApplication([])
    engine = QQmlApplicationEngine()

    db = dbManager(SqliteDatabase('resources.db'))
    model = RouteModel(db)
    engine.rootContext().setContextProperty('routeModel', model)
    engine.rootContext().setContextProperty('dbManager', db)

    engine.load(qml_doc_path)
    #    qml_root = engine.rootObjects()[0]

    #    qml_root.clicked.connect(on_qml_mouse_clicked)

    sys.exit(app.exec_())
#    del db
Example #19
0
def main(argv):
	#getting the inputfile name and ouputfolder path 
	input_file = ''
	output_folder = ''
	try:
		opts, args = getopt.getopt(argv,"i:o:")
	except getopt.GetoptError:
		print 'usage: run.py -i <inputfile> -o <outputfolder>'
		sys.exit(2)
	for opt, arg in opts:
		if opt in ("-i"):
			input_file = arg
		elif opt in("-o"):
			output_folder = arg
	if (len(input_file) == 0):
		print "usage: run.py -i <inputfile> -o <outputfolder>"
		sys.exit(2)

	# Check to see if the folder you are writing to exists or not, and creates it
	if not os.path.exists("./"+output_folder):
		print 'Directory not found, creating...'
		os.makedirs("./"+output_folder)	

	#connecting to the  main database
	print 'Forming database connection..."
	database = dbManager.dbManager()
	database.connect()

	# connecting to the email database
	emails = email_db.email_db()
	emails.connect()
	# A dictionary that returns the servers that belong to a given ip

	servDict = readServers.readServers("/home/cmanker/HOSTS.csv", "/home/cmanker/ag_list.csv")
	
	# opening file to be parsed 
	
	whole_file = open(input_file,"r")
	text = whole_file.read()
	
	#selecting html portion of file as html_part
	js, css, html_part = text.split("</script>",2)

	#instantiating a parser and feeding it the html part of the file
	print 'Parsing file, this may take some time...'
	aParser = parser.MyHTMLParser()
	aParser.feed(html_part)
	
	servers = aParser.server_list
	print str(len(servers))+' machines in scan.'

	database.updateDb(servers)
	
	print 'Do you wish to send out notification emails for this scan?'
	emailflag = -1
	while (emailflag == -1):
		email = raw_input()
		if (email == 'yes') or (email == 'y'):
			emailflag = 1
		elif (email == 'no') or (email == 'n'):
			emailflag = 0
		else:
			print 'Did not understand input, please use yes/y or no/n.'
	departments = dict()
	print 'Generating output...'
	for server in servers:
		for departs in servDict[server.getIp()]:
			if departs in departments:
				departments[departs].addServer(server)
			else:
				departments[departs] = Department.Department(database,server,output_folder,departs, emails,emailflag) 
			# ADD EMAIL STUFF 
	for departs in departments:
		departments[departs].writeFile()
Example #20
0
import os
import sys
import json

project_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, project_dir)

from dbManager import dbManager

config_file = project_dir + '/config.json'
with open(config_file) as file:
    config = json.load(file)

group_list = {}
for year in range(2013, 2014):
    file_name = "groupName_{}.json".format(year)
    file_path = os.path.join(config['groupInfo_folder'], file_name)
    file_handler = open(file_path)
    group_list[year] = json.load(file_handler)

dbManager = dbManager(config['db_config'])
Example #21
0
import flask
from flask import Flask, request, redirect, url_for
import dbManager
import htmlMaker
from datetime import *
app = Flask(__name__)
app.debug = True
db = dbManager.dbManager()


def checkCookie():
    try:
        cookie = request.headers["Cookie"].split("=")[1]
        userID = db.checkCookie(cookie)
        return userID
    except:
        return None


def isNotLoggedIn():
    # not logged in return error page
    errorString = "You must be logged in"
    html += htmlMaker.loginFailMSG(errorString)
    return html, 200


# url routes from here on
@app.route("/", methods=["GET"])
def loginPage():

    if (checkCookie()):
Example #22
0
import flask
import dash
import dash_html_components as html

from dbManager import dbManager

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

server = flask.Flask(__name__)
app = dash.Dash(__name__,
                server=server,
                external_stylesheets=external_stylesheets)
app.config.suppress_callback_exceptions = True

db_manager = dbManager()

millnames = ["", " K", " M", " B", " T"]  # used to convert numbers


# return html Table with dataframe values
def df_to_table(df):
    return html.Table(
        # Header
        [html.Tr([html.Th(col) for col in df.columns])] +

        # Body
        [
            html.Tr([html.Td(df.iloc[i][col]) for col in df.columns])
            for i in range(len(df))
        ])
Example #23
0
		return

	if '. - ' in message:
		show_lyriqs(message[5:], chat_id)
		return
	req = generate_string(message)
	song_names, meta_infos, artist_names, song_links, keyboard, found = get_data(req)

	if not found:
		hide_keyboard = {'hide_keyboard' : True}
		text = 'Unfortunately, your search returned *no result*.\n Try to _check spelling_ or _compose less restrictive search query_'
		bot.sendMessage(chat_id, text, reply_markup=hide_keyboard, parse_mode="markdown")
		return
		

	show_keyboard = {'keyboard' : keyboard}
	bot.sendMessage(chat_id, 'Choose the lyriqs you need, from below',reply_markup=show_keyboard)

ACCESS_TOKEN = '226162312:AAFCLYFSBaMwaHsV5LWsmkNIDDNKKlP4yeM'

bot = telepot.Bot(ACCESS_TOKEN)
bot.message_loop(handle)
print ('Listening ...')

connection = sqlite3.connect('lyriqs.db', check_same_thread=False)
db = dbManager(connection)


while 1:
	time.sleep(10)
    def checkAccount(self):
        # [START] 자산 조회 로직 0424는 추정단계, 12300은 확정단계
        orderInstance = orderManager.t0424(BuyAgent.accountNumber,
                                           BuyAgent.accountPwd)  # 계좌번호, 비밀번호
        if orderInstance[0].shape[0] == 0:
            print("0424 account record info error")
            return False
        df1, df2 = orderManager.CSPAQ12200(레코드갯수='1',
                                           관리지점번호='',
                                           계좌번호=BuyAgent.accountNumber,
                                           비밀번호=BuyAgent.accountPwd,
                                           잔고생성구분='0')
        # BuyAgent.balanced2 = orderInstance[0]["추정D2예수금"].values[0]
        BuyAgent.netAssest = orderInstance[0]["추정순자산"].values[0]
        if df2.shape[0] == 0:
            print("CSPAQ12200 info error")
            return False
        BuyAgent.balanced2 = df2['D2예수금'].values[0]

        print("예수금(D2) : ", BuyAgent.balanced2, "추정순자산 : ", BuyAgent.netAssest)
        # [END] 자산 조회 로직
        # [START] 미체결 주문금액을 반영한 자산 반영 로직 -> 13700 오동작
        # res1, res2, res3 = orderManager.CSPAQ13700(계좌번호=BuyAgent.accountNumber, 입력비밀번호=BuyAgent.password)

        # balanced2 에서 미체결 주문금액을 빼야 함
        # db 조회 후, 확인한 종목코드, 주문수량, 주문총액 - 해당 종목의 t0425 totrem
        now = time.localtime()
        tempDate = "%04d%02d%02d" % (now.tm_year, now.tm_mon, now.tm_mday)
        dbInstance = dbManager.dbManager()
        res = dbInstance.selectbuylistford2(tempDate, '2')

        tempAmount = 0
        for i in res:
            time.sleep(2)
            shcode = i["shcode"]
            ordqty = i["ordqty"]
            ordprc = i["ordprc"]
            df, df1 = orderManager.t0425(계좌번호=BuyAgent.accountNumber,
                                         비밀번호=BuyAgent.accountPwd,
                                         종목번호=shcode,
                                         체결구분='2',
                                         매매구분='2',
                                         정렬순서='2',
                                         주문번호='')
            tmpCnt = 0

            while df.shape[0] == 0:
                #if df.shape[0] == 0 :
                time.sleep(2)
                df, df1 = orderManager.t0425(계좌번호=BuyAgent.accountNumber,
                                             비밀번호=BuyAgent.accountPwd,
                                             종목번호=shcode,
                                             체결구분='2',
                                             매매구분='2',
                                             정렬순서='2',
                                             주문번호='')
                tmpCnt += 1
                if tmpCnt > 2:
                    dbInstance.updateBuyListford2(shcode,
                                                  tempDate)  # 미체결 수량 없음
                    break
            # else:
            #
            now = time.localtime()
            for i in range(0, df1.shape[0]):
                tmpOrderTime = df1['주문시간'].values[i]
                print("주문번호:", df1['주문번호'].values[i], " 종목번호:",
                      df1['종목번호'].values[i], "주문시간", tmpOrderTime, " 주문수량:",
                      df1['주문수량'].values[i])
                print("현재 시각: ", now.tm_hour, ":", now.tm_min)

                delayedCancel = False
                if now.tm_hour - int(tmpOrderTime[:2]) == 1:
                    print(int(now.tm_min) + 60 - int(tmpOrderTime[2:4]))
                    if int(now.tm_min) + 60 - int(tmpOrderTime[2:4]) >= 2:
                        delayedCancel = True
                elif now.tm_hour - int(tmpOrderTime[:2]) > 1:
                    delayedCancel = True
                elif int(tmpOrderTime[:2]) == now.tm_hour and int(
                        now.tm_min) != int(tmpOrderTime[2:4]):
                    if int(now.tm_min) - int(tmpOrderTime[2:4]) >= 2:
                        delayedCancel = True
                else:
                    tempAmount += ((int(ordprc) / int(ordqty)) *
                                   int(df['총미체결수량'].values[0]))
                    print('[미체결 정보] 종목번호', shcode, '주문수량', ordqty, '주문가격',
                          ordprc, '미체결수량', df['총미체결수량'].values[0])
                    print('누적 미체결 금액 : ', tempAmount)

                if delayedCancel == True:
                    now = time.localtime()
                    print("매수취소 시도: ", now.tm_hour, ":", now.tm_min)
                    calcelRes = orderManager.CSPAT00800(
                        df1['주문번호'].values[i], BuyAgent.accountNumber,
                        BuyAgent.accountPwd, df1['종목번호'].values[i],
                        df['총미체결수량'].values[0])  #df1['주문수량'].values[i])

                    if calcelRes[1]["주문번호"].values[0] == 0:
                        print("매수취소 주문접수 불가")
                        tempAmount += ((int(ordprc) / int(ordqty)) *
                                       int(df['총미체결수량'].values[0]))
                        print('[미체결 정보] 종목번호', shcode, '주문수량', ordqty, '주문가격',
                              ordprc, '미체결수량', df['총미체결수량'].values[0])
                        print('누적 미체결 금액 : ', tempAmount)
                    else:
                        print("매수취소 주문접수 완료")
                        print(df1['종목번호'].values[i], df1['주문수량'].values[i],
                              "0", df1['주문번호'].values[i], tempDate,
                              calcelRes[1]["주문시각"].values[0],
                              calcelRes[1]["종목명"].values[0], "3", "0")
                        # `shcode`, `ordqty`, `ordprc`, `ordno`, `orderdate`, `ordtime`, `isunm`,`bnstpcode`,`strategy`)
                        #dbInstance.insertOrderList(str(df1['종목번호'].values[i]), str(df1['주문수량'].values[i]), "0", str(df1['주문번호'].values[i]), tempDate,  str(calcelRes[1]["주문시각"].values[0]),  str(calcelRes[1]["종목명"].values[0]), "3","0") # 취소
                        dbInstance.deleteOrderList(tempDate,
                                                   df1['종목번호'].values[i])
        BuyAgent.balanced2 -= tempAmount
        print("미체결금액 반영한 D2 : ", BuyAgent.balanced2)
        # [END] 미체결 주문금액을 반영한 자산 반영 로직
        return True
Example #25
0
    def rsiCheck(self, msprice, _shcode="", curPrice=0):

        df = orderManager.t8412(단축코드=_shcode, 단위="2", 요청건수="36")

        if df.shape[0] > 0:  # rsi 9 구하기
            upper, middle, low = ta.BBANDS(df['종가'], 20, 2, 2)
            upper = np.asarray(upper)
            # middle = np.asarray(middle)
            print("볼린저 상한:", upper[-1], "종가:", df['종가'].values[-1])
            dbInstance = dbManager.dbManager()
            now = time.localtime()
            tempDate = "%04d%02d%02d" % (now.tm_year, now.tm_mon, now.tm_mday)
            if float(upper[-1]) <= float(
                    df['종가'].values[-1]):  # mark that record
                dbInstance.updateOrdListBB(_shcode, tempDate)
                if msprice * 1.013 <= df['종가'].values[-1]:
                    print("RSI 조건(BB상단 돌파 및 1% 수익)에 의하여 50%매도")
                    return 2
            elif float(upper[-1]) > float(df['종가'].values[-1]):
                res = dbInstance.selectOrdListBB(_shcode, tempDate)
                if len(res) != 0:
                    print("BB 상한 돌파 이력 조회 결과:", res[0]['reserve2'])
                    if res[0]['reserve2'] == '1':
                        print("BB 상한 + -> - 로 매도")
                        return 1

            rsi9 = ta.RSI(np.asarray(df['종가']), 9)
            rsi9 = rsi9[~np.isnan(rsi9)]  # remove nan
            if rsi9.size == 0:
                print("rsi size exception")
                return -1
            rsiTgt = rsi9[-1]
            simpleMA9 = ta.MA(rsi9, timeperiod=9)

            simpleMA9Tgt = simpleMA9[-1]
            # print('----------[RSI SIGNAL JUDGE]----------')
            if rsiTgt < simpleMA9Tgt:
                print('rsi', rsiTgt, '<', 'signal', simpleMA9Tgt)
                #df = orderManager.t8412(단축코드=_shcode, 단위="5", 요청건수="36")
                simpleMA5 = ta.MA(np.asarray(df['종가'], dtype=np.double),
                                  timeperiod=5)
                simpleMA20 = ta.MA(np.asarray(df['종가'], dtype=np.double),
                                   timeperiod=20)
                print("종가:", df['종가'].values[-1], "5MA: ", simpleMA5[-1],
                      "20MA", simpleMA20[-1])
                taadx = ta.ADX(df['고가'], df['저가'], df['종가'], 9)
                taadxSig = ta.MA(taadx, timeperiod=9)
                taadx = np.asarray(taadx)
                taadxSig = np.asarray(taadxSig)
                if float(taadx[-1]) <= float(taadxSig[-1]):
                    if float(simpleMA5[-1]) <= float(df['종가'].values[-1]):
                        return 0
                else:
                    if float(simpleMA20[-1]) <= float(df['종가'].values[-1]):
                        return 0
                return 1  # 매도
            # elif rsiTgt >= 75 and rsiTgt <= 80: # 75
            #     df = orderManager.t8412(단축코드=_shcode, 단위="2", 요청건수="3")
            #     if df.shape[0] == 0 :
            #         print("분봉 정보 조회 불가")
            #         return False
            #     if df['종가'].values[-1] < df['종가'].values[-2] and df['종가'].values[-2] < df['종가'].values[-3] :
            #         print("RSI 75~80 에서 하락 2봉으로 매도")
            #         return True
            #     SellAgent.sleeptime = 60
            #     return False
            elif rsiTgt > 75:
                # df = orderManager.t8412(단축코드=_shcode, 단위="2", 요청건수="36")
                # check if close price > BB upper bound
                if df['종가'].values[-1] < df['종가'].values[-2] and df[
                        '종가'].values[-2] < df['종가'].values[-3]:
                    simpleMA5 = ta.MA(np.asarray(df['종가'], dtype=np.double),
                                      timeperiod=5)
                    if float(df['종가'].values[-1]) < float(simpleMA5[-1]):
                        print("RSI 75 초과에서 하락 2봉 + 5MA(2min) 이하로 매도 ",
                              simpleMA5[-1])
                        return 1
                    else:
                        return 0
                # 매수 1,2 호가 물량 체크
                # elif SellAgent.msmdVolumeCheck(self, _shcode) == True:
                #     print("총매수 잔량 조건으로 50% 매도")
                #     return 2

                simpleMA10 = ta.MA(np.asarray(df['종가'], dtype=np.double),
                                   timeperiod=10)
                print("종가:", df['종가'].values[-1], "10MA(2Min.): ",
                      simpleMA10[-1])
                if float(simpleMA10[-1]) > float(df['종가'].values[-1]):
                    return 1
                return 0
                # 장대양봉 존재할 경우, 장대양봉의 중간 지지선 붕괴 여부 검사
            elif SellAgent.checkBaseLine(self, df, float(curPrice)) == True:
                print("장대양봉의 지지선 붕괴로 매도")
                return 1
            else:
                print('rsi > ', rsiTgt, '>', 'signal', simpleMA9Tgt)
                return 0

        return 0
    def run(self):
        #pythoncom.CoInitialize()
        orderManager.Login(id=BuyAgent.accountId,
                           pwd=BuyAgent.password,
                           cert=BuyAgent.pkpwd)

        now = time.localtime()
        tempDate = "%04d%02d%02d" % (now.tm_year, now.tm_mon, now.tm_mday)
        # dbInstance = dbManager.dbManager()
        while False == buy.checkAccount():
            time.sleep(1)

        cnt = 0
        while True:
            dbInstance = dbManager.dbManager()
            res = dbInstance.selectObserverList(tempDate, '1', tempDate)
            if cnt != 0 and cnt % 3 == 0:
                BuyAgent.checkAccount(self)
            orderPrice = 0
            #print(res)
            for i in res:
                nPortfolio = BuyAgent.numberOfPortfolio
                # time.sleep(5)
                df1, df2, df3 = orderManager.CSPAQ12300(
                    레코드갯수='1',
                    계좌번호=BuyAgent.accountNumber,
                    비밀번호=BuyAgent.accountPwd,
                    잔고생성구분='0',
                    수수료적용구분='1',
                    D2잔고기준조회구분='0',
                    단가구분='0')
                tmpdf = df3[(df3['종목번호'] == i["shcode"])]
                if tmpdf.shape[0] > 0:
                    print("현재 보유 중, Skip")
                    continue

                # nPortfolio -= df3.shape[0]
                # if nPortfolio <= 0 :
                #     print("포트폴리오 초과 매수불가")
                #     continue

                tmpres = dbInstance.selectUserControlListByShcode(
                    i["shcode"], tempDate)
                if len(tmpres) != 0 and tmpres[0]['undercontrol'] == 'Lock':
                    print('수동 컨트럴 중으로 skip')
                    continue

                df8407 = orderManager.t8407(종목코드=i["shcode"])
                print(df8407["종목명"].values[0], df8407["현재가"].values[0])
                if int(df8407["현재가"].values[0]) < 1000:
                    print("동전주 skip")
                    continue
                client = texttospeech.TextToSpeechClient()
                # Set the text input to be synthesized
                synthesis_input = texttospeech.SynthesisInput(
                    text=df8407["종목명"].values[0])

                if not os.path.exists("audio"):
                    os.mkdir("audio")
                # 해당 종목코드 mp3가 존재한다면,
                if os.path.isfile("audio/" + i["shcode"] + ".mp3") == True:
                    playsound("audio/" + i["shcode"] + ".mp3")
                else:  # 해당 종목코드 mp3가 존재하지 않을경우,
                    # Build the voice request, select the language code ("en-US") and the ssml
                    # voice gender ("neutral")
                    voice = texttospeech.VoiceSelectionParams(
                        language_code="ko-KR",
                        ssml_gender=texttospeech.SsmlVoiceGender.NEUTRAL)
                    # Select the type of audio file you want returned
                    audio_config = texttospeech.AudioConfig(
                        audio_encoding=texttospeech.AudioEncoding.MP3)
                    # Perform the text-to-speech request on the text input with the selected
                    # voice parameters and audio file type
                    response = client.synthesize_speech(
                        input=synthesis_input,
                        voice=voice,
                        audio_config=audio_config)
                    with open("audio/" + i["shcode"] + ".mp3", "wb") as out:
                        # Write the response to the output file.
                        out.write(response.audio_content)
                    playsound("audio/" + i["shcode"] + ".mp3")
                    # os.remove("output.mp3") # playsound(None)

                # if BuyAgent.checkExcludedList(self, df8407["종목명"].values[0]) == True :
                #     print("인덱스 종목 제외 ",df8407["종목명"].values[0])
                #     continue

                BuyAgent.checkAccount(self)
                #BuyAgent.ordqty = int((min(BuyAgent.balanced2, BuyAgent.netAssest) / nPortfolio) / int(df8407["현재가"].values[0]))
                BuyAgent.ordqty = int(
                    (min(BuyAgent.balanced2, BuyAgent.netAssest)) /
                    int(df8407["현재가"].values[0]))
                print("[INFO] ", "포폴# ", nPortfolio, "D2추정: ",
                      BuyAgent.balanced2, "추정순자산", BuyAgent.netAssest)
                #if BuyAgent.ordqty < 1 or df2["D2예수금"].values[0] < (BuyAgent.ordqty * float(i["price"])) :
                if BuyAgent.ordqty < 1 or BuyAgent.balanced2 < (
                        BuyAgent.ordqty * float(df8407["현재가"].values[0])):
                    print(
                        "[잔고부족] ",
                        "#종목코드",
                        str(i["shcode"]),
                        "예수금 ",
                        df2["D2예수금"].values[0],
                        "VS. 물량 ",
                        str(BuyAgent.ordqty),
                        "가격",
                        str(df8407["현재가"].values[0]),
                    )
                    dbInstance.updateObserverList(i["shcode"], tempDate)
                    continue

                # 상한가 임박 or 단주 매수 필터 아웃
                if BuyAgent.upperLimitCheck(
                        self, i["shcode"]
                ) == 1 or True == BuyAgent.weirdConditionCheck(
                        self, i["shcode"]) or True == BuyAgent.msquantityCheck(
                            self, i["shcode"]):
                    print("매수 포기")
                    dbInstance.updateObserverList(i["shcode"], tempDate)
                    continue
                orderPrice = int(df8407["현재가"].values[0])
                # 이전 장대양봉 기준선(중간값)이하일 경우 매수 포기하는 로직 -> 주석 처리 210110
                # df = orderManager.t8412(단축코드=i["shcode"], 단위="2", 요청건수="36")
                # if BuyAgent.checkmsBaseLine(df,float(df8407["현재가"].values[0]) ) == True:
                #     print("장대양봉 기준선 이하로 매수 포기")
                #     dbInstance.updateObserverList(i["shcode"], tempDate)
                #     continue

                # 볼린저 밴드 상한 초과시 포기, 중상일 경우 호가를 골드라인으로 조정 -> 로직 주석 처리 210110
                df8412 = orderManager.t8412(단축코드=i["shcode"],
                                            단위="2",
                                            요청건수="36")
                upper, middle, low = ta.BBANDS(
                    df8412['종가'], 20, 2, 2)  # 2 sigma 에서 3 sigma로 변경 210118
                upper = np.asarray(upper)
                middle = np.asarray(middle)
                low = np.array(low)
                tmpUpperCheck = BuyAgent.upperBoundCheck(
                    self, df8412, upper, middle, low, df8407["현재가"].values[0])
                orderPrice = int(df8407["현재가"].values[0])
                if tmpUpperCheck == 1:
                    print("매수 호가 하향 조정 시도, 현재가:", orderPrice)
                    while (float(upper[-1]) +
                           float(middle[-1])) / 2 < orderPrice:
                        orderPrice = int(
                            BuyAgent.getOneUnderHoga(self, i["shcode"],
                                                     orderPrice))
                        print("orderPrice: ", orderPrice)
                elif tmpUpperCheck == 2:
                    print("매수 포기")
                    dbInstance.updateObserverList(i["shcode"], tempDate)
                    continue

                print("매수시도 종목코드: ", i["shcode"], " 수량: ", BuyAgent.ordqty,
                      " 가격: ", orderPrice)
                try:
                    orderRes = orderManager.CSPAT00600(BuyAgent.accountNumber,
                                                       BuyAgent.accountPwd,
                                                       i["shcode"],
                                                       BuyAgent.ordqty,
                                                       str(orderPrice), '2',
                                                       '00', '000', '0')
                    if orderRes[1]["주문번호"].values[0] == 0:  # 장 종료 등의 사유
                        # observerList 테이블에서 해당 Row의 excluded칼럼을 1로 업데이트
                        dbInstance.updateObserverList(i["shcode"], tempDate)
                        continue
                    else:
                        print(orderRes[1]["주문번호"].values[0])
                        # bnstpcode 2: 매수, strategy 1: 전략1
                        dbInstance.insertOrderList(
                            orderRes[0]["종목번호"].values[0],
                            str(BuyAgent.ordqty),
                            str(orderRes[1]["주문금액"].values[0]),
                            str(orderRes[1]["주문번호"].values[0]), tempDate,
                            str(orderRes[1]["주문시각"].values[0]),
                            str(orderRes[1]["종목명"].values[0]), "2", "1")
                        #dbInstance.deleteOrderList(tempDate,i["shcode"])

                        client = texttospeech.TextToSpeechClient()
                        # Set the text input to be synthesized
                        tmpStr = df8407["종목명"].values[0] + " 매수하겠습니다."
                        synthesis_input = texttospeech.SynthesisInput(
                            text=tmpStr)
                        # Build the voice request, select the language code ("en-US") and the ssml
                        # voice gender ("neutral")
                        voice = texttospeech.VoiceSelectionParams(
                            language_code="ko-KR",
                            ssml_gender=texttospeech.SsmlVoiceGender.NEUTRAL)
                        # Select the type of audio file you want returned
                        audio_config = texttospeech.AudioConfig(
                            audio_encoding=texttospeech.AudioEncoding.MP3)
                        # Perform the text-to-speech request on the text input with the selected
                        # voice parameters and audio file type
                        response = client.synthesize_speech(
                            input=synthesis_input,
                            voice=voice,
                            audio_config=audio_config)
                        with open("output.mp3", "wb") as out:
                            # Write the response to the output file.
                            out.write(response.audio_content)
                            print('Audio content written to file "output.mp3"')
                        playsound("output.mp3")
                        os.remove("output.mp3")
                except Exception as e:
                    print("Exception Occur : ", e)
            time.sleep(5)
            cnt += 1
            print(str(cnt), " 회전(Buy Manager)")
Example #27
0
    def run(self):
        pythoncom.CoInitialize()
        orderManager.Login(id=SellAgent.accountId,
                           pwd=SellAgent.password,
                           cert=SellAgent.pkpwd)
        # instXAQueryT1471 = win32com.client.DispatchWithEvents("XA_DataSet.XAQuery", XAQueryEventsT1471)
        # instXAQueryT1471.ResFileName = "C:\\eBEST\\xingAPI\\Res\\t1471.res"
        now = time.localtime()
        tempDate = "%04d%02d%02d" % (now.tm_year, now.tm_mon, now.tm_mday)
        dbInstance = dbManager.dbManager()

        cnt = 0
        while True:
            # print(cnt, "회전(Sell Manager)")
            # botManager.queryMine(isToday=True) # ,date='20201209')

            cnt += 1

            df1, df2 = orderManager.t0424(SellAgent.accountNumber,
                                          SellAgent.accountPwd,
                                          체결구분='2')  # 계좌번호, 비밀번호
            while df2.shape[0] == 0:
                df1, df2 = orderManager.t0424(SellAgent.accountNumber,
                                              SellAgent.accountPwd,
                                              체결구분='2')  # 계좌번호, 비밀번호
                print("보유 종목 갯수 : ", df2.shape[0])
                time.sleep(1)

            sellyn = False
            sellHalfYn = False

            for i in range(0, df2.shape[0]):
                tmpres = dbInstance.selectUserControlListByShcode(
                    df2["종목번호"].values[i], tempDate)
                if len(tmpres) != 0 and tmpres[0]['undercontrol'] == 'Lock':
                    print('수동 컨트럴 중으로 skip')
                    continue

                print("종목번호:", df2["종목번호"].values[i],"종목명:", df2["종목명"].values[i],"평균단가:", df2["평균단가"].values[i], \
                      "현재가:", df2["현재가"].values[i],"매도가능수량:", df2["매도가능수량"].values[i],"잔고수량:", df2["잔고수량"].values[i])
                if df2["매도가능수량"].values[i] != df2["잔고수량"].values[i]:
                    # 기존 매도주문 취소 및 reset (잔고수량과 매도가능수량이 다른 경우는 이미 매도주문이 들어가서 부분 매도된 경우이다.)
                    # 이러한 경우는 남은 물량을 현재가로 정정주문(매도) 한다.
                    # 잔고 수량 - 매도가능수량
                    # 모의투자 정정주문은 시장가 지정 불가능
                    ordno = dbInstance.selectOrdNo(str(df2["종목번호"].values[i]),
                                                   tempDate)
                    if len(ordno) == 0:  # HTS 등 타 시스템에서 주문한 경우 스킵
                        continue
                    print("[정정주문] 원주문번호: ", ordno[0]['ordno'])
                    orderRes = orderManager.CSPAT00700(
                        ordno[0]['ordno'], SellAgent.accountNumber,
                        SellAgent.accountPwd, str(df2["종목번호"].values[i]),
                        str(df2["잔고수량"].values[i] - df2["매도가능수량"].values[i]),
                        '00', '0',
                        SellAgent.getOneUnderHoga(self,
                                                  str(df2["종목번호"].values[i]),
                                                  str(df2["현재가"].values[i])))
                    if orderRes[1]["주문번호"].values[
                            0] == 0:  # 장 종료 또는 기존주문 미체결 상태 등의 사유
                        print("정정 주문접수 불가")
                        # 일단 취소, 상위 반복문에서 다시 매도 시도로 연결됨
                        calcelRes = orderManager.CSPAT00800(
                            ordno[0]['ordno'], SellAgent.accountNumber,
                            SellAgent.accountPwd, str(df2["종목번호"].values[i]),
                            str(
                                int(df2["잔고수량"].values[i]) -
                                int(df2["매도가능수량"].values[i])))
                        if calcelRes[1]["주문번호"].values[0] == 0:
                            print("취소 주문접수 불가")
                        else:
                            dbInstance.insertOrderList(
                                str(orderRes[0]["종목번호"].values[0]),
                                str(orderRes[0]["주문수량"].values[0]), "0",
                                str(orderRes[1]["모주문번호"].values[0]), tempDate,
                                str(orderRes[1]["주문시각"].values[0]),
                                str(orderRes[1]["종목명"].values[0]), "3",
                                "0")  # 취소

                    else:
                        print(orderRes[1]["주문번호"].values[0])

                        dbInstance.insertOrderList(
                            str(orderRes[0]["종목번호"].values[0]),
                            str(orderRes[0]["주문수량"].values[0]),
                            str(orderRes[1]["주문금액"].values[0]),
                            str(orderRes[1]["주문번호"].values[0]), tempDate,
                            str(orderRes[1]["주문시각"].values[0]),
                            str(orderRes[1]["종목명"].values[0]), "1", "4")  # 정정
                    continue
                if df2["매도가능수량"].values[i] == 0:
                    #매도가능한 수량이 없기 때문에 이후 로직을 검사할 필요가 없다.
                    continue
                # 판단1 : 평단 < 현재가 * (1.033 - tolerance) # 매도잔량: 7273 매수잔량: 23468 체결강도: 458.71
                if SellAgent.weirdConditionCheck(self, df2["종목번호"].values[i],
                                                 df2["종목명"].values[i]) == True:
                    print("!!!!!!!!!!!!!!!!매도 경고!!!!!!!!!!!!!!!!")
                if float(df2["평균단가"].values[i]) * (
                        1 - (SellAgent.principalNfee -
                             SellAgent.tolerance)) > df2["현재가"].values[i]:
                    print("한계 초과로 매도")
                    sellyn = True
                if sellyn == False and float(
                        df2["평균단가"].values[i]) * 1.013 <= float(
                            df2["현재가"].values[i]):
                    print("1% 수익 확보, 50% 매도시도")
                    sellyn = True
                    sellHalfYn = True
                # if sellyn == False and SellAgent.weirdConditionCheck(self, df2["종목번호"].values[i]) == True:
                #     sellyn = True

                if sellyn == False:
                    #if (float(totbidrem1) >= float(totofferrem1)  and float(msrate) <= SellAgent.stdmsrate) or float(msrate) <= SellAgent.stdmsrate - 50 :
                    rsiChkRet = SellAgent.rsiCheck(
                        self,
                        df2["평균단가"].values[i],
                        _shcode=df2["종목번호"].values[i],
                        curPrice=df2["현재가"].values[i])
                    if rsiChkRet == 1:
                        print("RSI 조건에 의하여 매도")
                        #dbInstance.insertObserverList(df2["종목번호"].values[i], tempDate, strTempTime, msrate, bidrem1, offerrem1, price)
                        dbInstance.updateObserverList(df2["종목번호"].values[i],
                                                      tempDate)
                        sellyn = True
                    elif rsiChkRet == 2:
                        dbInstance.updateObserverList(df2["종목번호"].values[i],
                                                      tempDate)
                        sellyn = True
                        sellHalfYn = True
                    # if sellyn == False: #and SellAgent.prgCheck(self, _shcode=df2["종목번호"].values[i]) == True  :
                    #     print("프로그램 순매도 조건으로 매도")
                    #     sellyn = True
                    # elif float(bidrem1) >= (float(offerrem1) * 3 ) :
                    #     print("매수잔량 >= 매도잔량 * 2  매도")
                    #     dbInstance.insertObserverList(df2["종목번호"].values[i], tempDate, strTempTime, msrate, bidrem1,
                    #                                   offerrem1, price)
                    #     dbInstance.updateObserverList(df2["종목번호"].values[i])
                    #     sellyn = True
                if sellyn == True:
                    # 매도
                    sellQuantity = sellHalfYn == True and str(
                        int(int(df2["매도가능수량"].values[i]) /
                            2)) or df2["매도가능수량"].values[i]
                    if sellHalfYn == True and sellQuantity == '0':  # 매도가능수량이 1인 경우 예외처리
                        sellQuantity = df2["매도가능수량"].values[i]
                    try:
                        orderRes = orderManager.CSPAT00600(
                            SellAgent.accountNumber, SellAgent.accountPwd,
                            df2["종목번호"].values[i], sellQuantity, '', '1', '03',
                            '000', '0')  # 시장가로 매도, df2["현재가"].values[i]
                        if orderRes[1]["주문번호"].values[0] == 0:  # 장 종료 등의 사유
                            print("주문접수 불가")
                        else:
                            print(orderRes[1]["주문번호"].values[0])

                            dbInstance.insertOrderList(
                                str(orderRes[0]["종목번호"].values[0]),
                                str(orderRes[1]["실물주문수량"].values[0]),
                                str(orderRes[1]["주문금액"].values[0]),
                                str(orderRes[1]["주문번호"].values[0]), tempDate,
                                str(orderRes[1]["주문시각"].values[0]),
                                str(orderRes[1]["종목명"].values[0]), "1", "0")
                    except Exception as e:
                        print("Exception Occur : ", e)

                    sellyn = False
                    sellHalfYn = False
            time.sleep(SellAgent.sleeptime)

        pythoncom.CoUninitialize()