Ejemplo n.º 1
0
def build_key_array(tradeAction, bars_15m, bars_1h, bars_1d):
    #These has to be in sequential order since insert adds rather than replace.
    cci_key = "long"
    if tradeAction == "Sell":
        cci_key = "short"
    cci_key += categories.categorize_atr15(bars_15m.atr) + categories.categorize_atr1h(bars_1h.atr) + categories.categorize_atr1d(bars_1d.atr) + \
        categories.categorize_cci_15(bars_15m.cci) + categories.categorize_cci_15_avg(bars_15m.ccia) + categories.categorize_cci_1h(bars_1h.ccia) + \
        categories.categorize_cci_1d(bars_1d.ccia) + categories.categorize_spread(bars_15m.cci_ccia_spread)
    #categories.categorize_cci_1d(bars_1d.ccia) + bars_1h.cci_over_ccia_tf + bars_1d.cci_over_ccia_tf + categories.categorize_spread(bars_15m.cci_ccia_spread)
    cci_key_no_spread = "long"
    if tradeAction == "Sell":
        cci_key_no_spread = "short"
    cci_key_no_spread += categories.categorize_atr15(bars_15m.atr) + categories.categorize_atr1h(bars_1h.atr) + categories.categorize_atr1d(bars_1d.atr) + \
        categories.categorize_cci_15(bars_15m.cci) + categories.categorize_cci_15_avg(bars_15m.ccia) + categories.categorize_cci_1h(bars_1h.ccia) + \
        categories.categorize_cci_1d(bars_1d.ccia)
    #ccibb_key = cci_key_no_spread + categories.categorize_BBW15(bars_15m.bband_width) + categories.categorize_BBb15(bars_15m.bband_b) + categories.categorize_BBW1h(bars_1h.bband_width) + \
    #    categories.categorize_BBb1h(bars_1h.bband_b) + categories.categorize_BBW1d(bars_1d.bband_width) + categories.categorize_BBb1d(bars_1d.bband_b)
    summ_key = categories.categorize_cci_15_avg(
        bars_15m.ccia) + categories.categorize_cci_1h(
            bars_1h.ccia) + categories.categorize_cci_1d(
                bars_1d.ccia) + categories.categorize_spread(
                    bars_15m.cci_ccia_spread)
    #summ_key = categories.categorize_cci_15_avg(bars_15m.ccia) + categories.categorize_cci_1h(bars_1h.ccia) + categories.categorize_cci_1d(bars_1d.ccia) + bars_1h.cci_over_ccia_tf + bars_1d.cci_over_ccia_tf + categories.categorize_spread(bars_15m.cci_ccia_spread)
    #return cci_key, cci_key_no_spread, summ_key
    return cci_key, cci_key, summ_key
Ejemplo n.º 2
0
    def run(self):
        """ Execute the algorithm """
        key_arr = [
            'blank', 'ATR15', 'ATR1', 'ATRD', 'CCI15', 'CCIA15', 'CCIA1h',
            'CCIA1d', 'BBW15', 'BBb15', 'BBW1h', 'BBb1h', 'BBW1d', 'BBb1d'
        ]
        tradenow = False
        not_finished = True
        tradenow = False
        cci_trade = False
        ccibb_trade = False
        while not_finished:
            print("top of algo run self")
            crossed = False
            self.app.crossover.update(crossed)
            contContract = get_contract(self)
            dataContract = Contract(exchange=config.EXCHANGE,
                                    secType="FUT",
                                    localSymbol=contContract.localSymbol)
            log.info("Got Contract: {}".format(dataContract.localSymbol))
            self.app.contract.update(dataContract.localSymbol)

            # my add
            nextday = datetime.now().day
            nexthour = datetime.now().hour
            # endDateTime=datetime(int(date.today().year),int(date.today().month),int(nextday),int(nexthour),int(nextqtr),int(0)),
            if datetime.now().minute < 15:
                nextqtr = 15
                getqtr = 30

            elif datetime.now().minute < 30:
                nextqtr = 30
                getqtr = 45
            elif datetime.now().minute < 45:
                nextqtr = 45
                getqtr = 0
            else:
                nexthour = nexthour + 1
                nextqtr = 0
                getqtr = 15
            test = (datetime(int(date.today().year), int(date.today().month),
                             int(nextday), int(nexthour), int(getqtr), int(0)))
            print("nextqtr and getqtr {} {}".format(nextqtr, getqtr))
            log.info(
                "next datetime for 15 minutes - should be 15 minutes ahead of desired nextqtr{}"
                .format(test))
            #
            #nextqtr = datetime.now().minute + 1
            #print ("we manually overwrote start time")
            #print (nextqtr)
            #
            self.ib.waitUntil(time(hour=nexthour, minute=nextqtr))
            # 15 Minute Data
            self.app.qtrhour.update(datetime.now())
            print(datetime.now())
            log.info(
                "requesting info for the following timeframe today: {} nexthour: {} minutes: {}"
                .format(date.today().day, nexthour + 1, getqtr))
            bars_15m = self.get_bars_data(dataContract, "2 D", "15 mins",
                                          date.today().day, nexthour + 1,
                                          getqtr)
            x = np.array(bars_15m)
            log.debug("15 min bars {}".format(bars_15m[-1]))
            #sef.app. barupdateEvent_15m(baas_15m, True)
            #aars_15m.updateEvent += self.app.barupdateEvent_15m
            log.info("Got 15m data subscription")
            cci, avg, cci_prior, averageh, cci3 = calculate_cci(bars_15m)
            atr, atrprior = calculate_atr(bars_15m)
            bband_width, bband_b, bband_width_prior, bband_b_prior = calculate_bbands(
                bars_15m)
            log.info("starting 15 minutes".format(datetime.now()))
            log.info("CCI:      {} ".format(cci))
            log.info("CCIA      {} ".format(avg))
            log.info("CCIP      {} ".format(cci_prior))
            log.info("CCIPA:    {} ".format(averageh))
            log.info("ATR:      {} ".format(atr))
            log.info("bband w:  {} ".format(bband_width))
            log.info("bband p:  {} ".format(bband_b))
            qtrtime = datetime.now()
            #key_arr = []
            if (cci > cci_prior
                    and cci_prior < cci3) or (cci < cci_prior
                                              and cci_prior > cci3):
                crossed = True
                tradenow = True
                csv_row = "'" + str(datetime.now()) + ",'long'"
                key_arr[0] = "long"
            else:
                crossed = True
                tradenow = True
                csv_row = "'" + str(datetime.now()) + ",'short'"
                key_arr[0] = "short"
            csv_row += ",'" + str(crossed) + "'," + str(cci) + "," + str(
                avg) + "," + str(cci_prior) + "," + str(averageh) + "," + str(
                    atr) + "," + str(bband_width) + "," + str(bband_b)
            print(key_arr)
            key_arr[1] = categories.categorize_atr15(atr)
            key_arr[4] = categories.categorize_cci_15(cci)
            key_arr[5] = categories.categorize_cci_15_avg(avg)
            key_arr[8] = categories.categorize_BBW15(bband_width)
            key_arr[9] = categories.categorize_BBb15(bband_b)
            stat = "check crossed status"

            #print("printing self app ********************************************")
            #print(Indicator.data)
            self.app.status1.update(stat)
            self.app.crossover.update(crossed)
            self.app.cci15.update(f"{cci:.02f}")
            self.app.cci15_av.update(f"{avg:.02f}")
            self.app.cci15p_av.update(f"{averageh:.02f}")
            self.app.cci15p.update(f"{cci_prior:.02f}")
            self.app.atr15.update(f"{atr:.02f}")
            self.app.bband15_width.update(f"{bband_width:.04f}")
            self.app.bband15_b.update(f"{bband_b:.04f}")
            self.app.qtrhour.update(qtrtime)

            #1 hour data
            test = (datetime(int(date.today().year), int(date.today().month),
                             int(nextday), int(nexthour), int(getqtr), int(0)))
            #log.info("next datetime for 1 hour - should be 1 hour behind current hour {}".format(test))
            log.info(
                "requesting info for the following timeframe today: {} nexthour: {} minutes: {} "
                .format(date.today().day, nexthour, 0))
            bars_1h = self.get_bars_data(dataContract, "5 D", "1 hour",
                                         date.today().day, nexthour, 0)
            cci, avg, cci_prior, averageh, cci3 = calculate_cci(bars_1h)
            log.debug("bars_1h {}".format(bars_1h[-1]))
            atr, atrprior = calculate_atr(bars_1h)
            bband_width, bband_b, bband_width_prior, bband_b_prior = calculate_bbands(
                bars_1h)
            csv_row += "," + str(cci) + "," + str(avg) + "," + str(
                atr) + "," + str(bband_width) + "," + str(bband_b)
            key_arr[2] = categories.categorize_atr1h(atr)
            key_arr[6] = categories.categorize_cci_1h(avg)
            key_arr[10] = categories.categorize_BBW1h(bband_width)
            key_arr[11] = categories.categorize_BBb1h(bband_b)
            log.info("starting 1H ")
            log.info("CCI       {} ".format(cci))
            log.info("CCIA:     {} ".format(avg))
            log.info("ATR:      {} ".format(atr))
            log.info("bband w:  {} ".format(bband_width))
            log.info("bband p:  {} ".format(bband_b))
            qtrtime = datetime.now()
            self.app.cci1h.update(f"{cci:.02f}")
            self.app.cci1h_av.update(f"{avg:.02f}")
            self.app.bband1h_b.update(f"{bband_b:.04f}")
            self.app.bband1h_width.update(f"{bband_width:.04f}")
            self.app.atr1h.update(f"{atr:.02f}")

            log.info(
                "requesting info for the following timeframe today: nextday: {} hour: {} minute: {} "
                .format((nextday - 1), 0, 0))
            bars_1d = self.get_bars_data(dataContract, "75 D", "1 day",
                                         nextday - 1, 0, 0)
            log.debug("1d min bars {}".format(bars_1d[-1]))
            cci, avg, cci_prior, averageh, cci3 = calculate_cci(bars_1d)
            atr, atrprior = calculate_atr(bars_1d)
            bband_width, bband_b, bband_width_prior, bband_b_prior = calculate_bbands(
                bars_1d)
            csv_row += "," + str(cci) + "," + str(avg) + "," + str(
                atr) + "," + str(bband_width) + "," + str(bband_b)
            key_arr[3] = categories.categorize_atr1d(atr)
            key_arr[7] = categories.categorize_cci_1d(avg)
            key_arr[12] = categories.categorize_BBW1d(bband_width)
            key_arr[13] = categories.categorize_BBb1d(bband_b)
            log.info("starting 1H ")
            log.info("starting 1D ")
            log.info("CCIP      {} ".format(cci))
            log.info("CCIPA:    {} ".format(avg))
            log.info("ATR:      {} ".format(atr))
            log.info("bband w:  {} ".format(bband_width))
            log.info("bband p:  {} ".format(bband_b))
            qtrtime = datetime.now()
            qtrtime = datetime.now()
            self.app.cci1d.update(f"{cci:.02f}")
            self.app.cci1d_av.update(f"{avg:.02f}")
            self.app.bband1d_b.update(f"{bband_b:.04f}")
            self.app.bband1d_width.update(f"{bband_width:.04f}")
            self.app.atr1d.update(f"{atr:.02f}")
            if tradenow:
                csv_file = csv.reader(open('data/ccibb.csv', "rt"),
                                      delimiter="'")
                for row in csv_file:
                    if (''.join(key_arr)) == row[0]:
                        print("we have a match in ccibb.csv")
                        print(row)
                        ccibb_trade = True
                csv_file = csv.reader(open('data/cci.csv', "rt"),
                                      delimiter="'")
                for row in csv_file:
                    if (''.join(key_arr[0:7])) == row[0]:
                        print("we have a match in cci.csv")
                        print(row)
                        cci_trade = True
            csv_row += "," + (''.join(key_arr)) + "," + str(
                ccibb_trade) + "," + str(ccibb_trade)
            with open('data/hist15.csv', mode='a') as hist15:
                histwriter = csv.writer(hist15,
                                        delimiter=',',
                                        quotechar='"',
                                        quoting=csv.QUOTE_MINIMAL)
                histwriter.writerow([csv_row])
            print("key array comming *************************")
            print(''.join(key_arr))
            log.info("key array {}".format(key_arr))
            #key_arr.clear()
            tradenow = False
            cci_trade = False
            ccibb_trade = False
Ejemplo n.º 3
0
    def run(self):
        """ Execute the algorithm """
        key_arr = ['blank','ATR15','ATR1','ATRD','CCI15','CCIA15','CCIA1h','CCIA1d','BBW15','BBb15','BBW1h','BBb1h','BBW1d','BBb1d']
        tradenow = False
        not_finished = True
        pendingshort = False
        pendinglong = False
        tradenow = False
        cci_trade = False
        ccibb_trade = False
        while not_finished:
            print ("top of algo run self")
            #top of logic - want to check status as we enter a new bar/hour/day/contract
            crossed = False
            self.app.crossover.update(crossed)
            contContract, contracthours = get_contract(self)
            # NEW
            tradeContract = self.ib.qualifyContracts(contContract)   # gives all the details of a contract so we can trade it
            #print("fully qualified trading Contract: ",tradeContract)
            positions = self.ib.positions()
            open = self.have_position(positions)
            open_today = helpers.is_open_today(contracthours)
            dataContract = Contract(exchange=config.EXCHANGE, secType="FUT", localSymbol=contContract.localSymbol)
            log.info("Got Contract: {}".format(dataContract.localSymbol))
            self.app.contract.update(dataContract.localSymbol)
            wait_time, datetime_15, datetime_1h, datetime_1d = self.define_times()
            log.info("next datetime for 15 minutes - should be 15 minutes ahead of desired nextqtr{}".format(wait_time))
            #
            # starting the analysis section
            #
            self.ib.waitUntil(wait_time)
            #
            # 15 Minute Data
            #
            self.app.qtrhour.update(wait_time)
            log.info("requesting info for the following timeframe today: {} ".format(wait_time))
            bars_15m = self.get_bars_data(dataContract,"2 D","15 mins",datetime_15)
            x = np.array(bars_15m)
            log.info("15 min bars {}".format(bars_15m[-1]))
            cci, avg, cci_prior, averageh, cci3 = calculate_cci(bars_15m)
            atr, atrprior =  calculate_atr(bars_15m)
            bband_width, bband_b,bband_width_prior, bband_b_prior = calculate_bbands(bars_15m)
            log.info("starting 15 minutes".format(datetime.now()))
            log.info("CCI:      {} ".format(cci))
            log.info("CCIA      {} ".format(avg))
            log.info("CCIP      {} ".format(cci_prior))
            log.info("CCIPA:    {} ".format(averageh))
            log.info("ATR:      {} ".format(atr))
            log.info("bband w:  {} ".format(bband_width))
            log.info("bband p:  {} ".format(bband_b))
            qtrtime = datetime.now()
            if cci > avg and cci_prior < averageh:
                crossed = True
                print("crossed long",crossed)
                tradenow = True
                csv_row = "'"+str(datetime.now())+",'long'"
                key_arr[0] = "long"
            elif cci < avg and cci_prior > averageh:
                crossed = True
                tradenow = True
                print("crossed short",crossed)
                csv_row = "'"+str(datetime.now())+",'short'"
                key_arr[0] = "short"
            else:
                csv_row = "'"+str(datetime.now())+",'cash'"
                crossed = False
                tradenow = False
                print("NOT CROSSED ",crossed)
            print("csv row crossed ",csv_row)
            #if abs(cci - avg) > config.SPREAD:
            #    pending = True
            csv_header = "Date,Status,Crossed,CCI15,CCIA15,CCI15P,CCIA15P,ATR15,BBw15,BBB15"
            csv_row += ",'"+str(crossed)+"',"+str(cci)+","+str(avg)+","+str(cci_prior)+","+str(averageh)+","+str(atr)+","+str(bband_width)+","+str(bband_b)
            print("csv row 15",csv_row)
            key_arr[1] = categories.categorize_atr15(atr)
            key_arr[4] = categories.categorize_cci_15(cci)
            key_arr[5] = categories.categorize_cci_15_avg(avg)
            key_arr[8] = categories.categorize_BBW15(bband_width)
            key_arr[9] = categories.categorize_BBb15(bband_b)
            stat = "check crossed status"

            self.app.status1.update(stat)
            self.app.crossover.update(crossed)
            self.app.cci15.update(f"{cci:.02f}")
            self.app.cci15_av.update(f"{avg:.02f}")
            self.app.cci15p_av.update(f"{averageh:.02f}")
            self.app.cci15p.update(f"{cci_prior:.02f}")
            self.app.atr15.update(f"{atr:.02f}")
            self.app.bband15_width.update(f"{bband_width:.04f}")
            self.app.bband15_b.update(f"{bband_b:.04f}")
            self.app.qtrhour.update(qtrtime)
            
            
            #1 hour data 
            log.info("next datetime for 1 hour - should be 1 hour behind current hour {}".format(datetime_1h))
            bars_1h = self.get_bars_data(dataContract,"5 D","1 hour",datetime_1h)
            cci, avg, cci_prior, averageh, cci3 = calculate_cci(bars_1h)
            log.info("bars_1h {}".format(bars_1h[-1]))
            atr,atrprior = calculate_atr(bars_1h)
            bband_width, bband_b,bband_width_prior, bband_b_prior = calculate_bbands(bars_1h)
            csv_row += ","+str(cci)+","+str(avg)+","+str(atr)+","+str(bband_width)+","+str(bband_b)
            print("csv row 1 hour ",csv_row)
            csv_header += ",CCI1h,CCIA1h,ATR1h,BBW1h,BBB1h"
            key_arr[2] = categories.categorize_atr1h(atr)
            key_arr[6] = categories.categorize_cci_1h(avg)
            key_arr[10] = categories.categorize_BBW1h(bband_width)
            key_arr[11] = categories.categorize_BBb1h(bband_b)
            log.info("starting 1H ")
            log.info("CCI       {} ".format(cci))
            log.info("CCIA:     {} ".format(avg))
            log.info("ATR:      {} ".format(atr))
            log.info("bband w:  {} ".format(bband_width))
            log.info("bband p:  {} ".format(bband_b))
            qtrtime = datetime.now()
            self.app.cci1h.update(f"{cci:.02f}")
            self.app.cci1h_av.update(f"{avg:.02f}")
            self.app.bband1h_b.update(f"{bband_b:.04f}")
            self.app.bband1h_width.update(f"{bband_width:.04f}")
            self.app.atr1h.update(f"{atr:.02f}")
            
            log.info("requesting info for the following timeframe today: nextday: ".format(datetime_1d))
            bars_1d = self.get_bars_data(dataContract,"75 D","1 day",datetime_1d)
            log.info("1d min bars {}".format(bars_1d[-1]))
            cci, avg, cci_prior, averageh, cci3 = calculate_cci(bars_1d)
            atr, atrprior = calculate_atr(bars_1d)
            bband_width, bband_b,bband_width_prior, bband_b_prior = calculate_bbands(bars_1d)
            csv_row += ","+str(cci)+","+str(avg)+","+str(atr)+","+str(bband_width)+","+str(bband_b)
            print("csv row daily ",csv_row)
            csv_header += ",CCI1d,CCIA1d,ATR1d,BBB1d,BBW1d"
            key_arr[3] = categories.categorize_atr1d(atr)
            key_arr[7] = categories.categorize_cci_1d(avg)
            key_arr[12] = categories.categorize_BBW1d(bband_width)
            key_arr[13] = categories.categorize_BBb1d(bband_b)
            log.info("starting 1D ")
            log.info("CCIP      {} ".format(cci))
            log.info("CCIPA:    {} ".format(avg))
            log.info("ATR:      {} ".format(atr))
            log.info("bband w:  {} ".format(bband_width))
            log.info("bband p:  {} ".format(bband_b))
            qtrtime = datetime.now()
            qtrtime = datetime.now()
            self.app.cci1d.update(f"{cci:.02f}")
            self.app.cci1d_av.update(f"{avg:.02f}")
            self.app.bband1d_b.update(f"{bband_b:.04f}")
            self.app.bband1d_width.update(f"{bband_width:.04f}")
            self.app.atr1d.update(f"{atr:.02f}")
            print("tradenow: ",tradenow)
            if tradenow:
                print("Tradeing this bar ",(''.join(key_arr))," - ",''.join(key_arr[0:8]))
                csv_file1 = csv.reader(open('data/ccibb.csv', "rt"), delimiter = ",")
                for row1 in csv_file1:
                    print("ccibb row: ",row1[0])
                    if ((''.join(key_arr)) == row1[0]):
                            log.info("we have a match in ccibb.csv")
                            print("found a match in CCIBB ",row1[0])
                            ccibb_trade = True
                            tradenow = False
                            status_done = self.row_results(row1,cci_trade,ccibb_trade)
                            break
                csv_file2 = csv.reader(open('data/cci.csv', "rt"), delimiter = ",")
                for row2 in csv_file2:
                    print("cci row: ",row2[0])
                    if ((''.join(key_arr[0:8])) == row2[0]):
                            print("we have a match in cci.csv")
                            print("found a math in CCI ",row2[0])
                            cci_trade = True
                            tradenow = False
                            status_done = self.row_results(row2,cci_trade,ccibb_trade)
                            break
            print("did we find a match?  If true than no ",tradenow)
            csv_row += ","+(''.join(key_arr))+","+(''.join(key_arr[0:8]))+","+str(cci_trade)+","+str(ccibb_trade)+","+str(pendinglong)+","+str(pendingshort)
            csv_header += ",CCIbbKey,CCIKey,CCI Trade,CCIbbTrade,Pending Long, Pending Short"
            print("csv row right before csv write ",csv_row)
            with open('data/hist15.csv', mode='a') as hist15:
                histwriter = csv.writer(hist15, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
                #histwriter.writerow([csv_header])
                #histwriter.writerow([csv_row])
            tradenow = False
            cci_trade = False
            ccibb_trade = False
            print ("end of run self **********************************************************************************************")
Ejemplo n.º 4
0
 def run(self):
     """ Execute the algorithm """
     key_arr = ['blank','ATR15','ATR1','ATRD','CCI15','CCIA15','CCIA1h','CCIA1d','BBW15','BBb15','BBW1h','BBb1h','BBW1d','BBb1d']
     tradenow = False
     not_finished = True
     pendingshort = False
     pendinglong = False      # this is when the cross over is not wide enough
     PendingLongCnt = 0
     PendingShortCnt = 0
     tradenow = False
     cci_trade = False
     ccibb_trade = False
     while not_finished:
         print ("top of algo run self*************************************************")
         #top of logic - want to check status as we enter a new bar/hour/day/contract
         crossed = False
         contContract, contracthours = get_contract(self) #basic information on continuious contact
         #i NEW
         tradeContract = self.ib.qualifyContracts(contContract)[0]   # gives all the details of a contract so we can trade it
         open_long, open_short, position_qty = self.have_position(self.ib.positions())   # do we have an open position?
         open_today = helpers.is_open_today(contracthours)
         dataContract = Contract(exchange=config.EXCHANGE, secType="FUT", localSymbol=contContract.localSymbol)
         log.debug("Got Contract: {}".format(dataContract.localSymbol))
         #pnl = self.ib.pnl()
         log.debug("account names: {}".format(self.ib.managedAccounts()))
         log.info("PNL : {PNL} ".format(PNL=self.ib.pnl("all")))
         self.app.contract.update(dataContract.localSymbol)
         wait_time, datetime_15, datetime_1h, datetime_1d = self.define_times()
         log.debug("next datetime for 15 minutes - should be 15 minutes ahead of desired nextqtr{}".format(wait_time))
         self.ib.waitUntil(wait_time)
         self.app.qtrhour.update(wait_time)
         log.debug("requesting info for the following timeframe today: {} ".format(wait_time))
         #
         #start of study
         #
         bars_15m = self.get_bars_data(dataContract,"2 D","15 mins",datetime_15)
         print("bar data close: ",bars_15m[-1].close)
         x = np.array(bars_15m)
         log.debug("15 min bars {}".format(str(bars_15m[-1])))
         cci, avg, cci_prior, averageh, cci3 = calculate_cci(bars_15m)
         atr, atrprior =  calculate_atr(bars_15m)
         bband_width, bband_b,bband_width_prior, bband_b_prior = calculate_bbands(bars_15m)
         logged_it = self.log_value("Starting 15 minutes", cci,avg,cci_prior, averageh,atr,bband_width,bband_b)
         qtrtime = datetime.now()
         print("stop loss = ",round((bars_15m[-1].close + (atr *2))*4,0)/4)
         if cci > avg and cci_prior < averageh:
             crossed = True
             tradenow = True
             csv_row = "'"+str(datetime.now())+",'long'"
             key_arr[0] = "long"
             tradeAction = "BUY"
             stoplossprice = round((bars_15m[-1].close - (atr * 2))*4,0)/4
         elif cci < avg and cci_prior > averageh:
             crossed = True
             tradenow = True
             csv_row = "'"+str(datetime.now())+",'short'"
             key_arr[0] = "short"
             tradeAction = "SELL"
             stoplossprice = round((bars_15m[-1].close + (atr * 2))*4,0)/4
         else:
             csv_row = "'"+str(datetime.now())+",'cash'"
             crossed = False
             tradenow = False
             stoplossprice = 0
             stoploss = 0
         if abs(cci - avg) > config.SPREAD:
             log.info("Pending ".format(cci-avg))
             pendinglong = True
             pendingshort = True
         csv_header = "Date,Status,Crossed,CCI15,CCIA15,CCI15P,CCIA15P,ATR15,BBw15,BBB15"
         csv_row += ",'"+str(crossed)+"',"+str(cci)+","+str(avg)+","+str(cci_prior)+","+str(averageh)+","+str(atr)+","+str(bband_width)+","+str(bband_b)
         key_arr[1] = categories.categorize_atr15(atr)
         key_arr[4] = categories.categorize_cci_15(cci)
         key_arr[5] = categories.categorize_cci_15_avg(avg)
         key_arr[8] = categories.categorize_BBW15(bband_width)
         key_arr[9] = categories.categorize_BBb15(bband_b)
         #
         #1 hour data 
         #
         log.debug("next datetime for 1 hour - should be 1 hour behind current hour {}".format(datetime_1h))
         bars_1h = self.get_bars_data(dataContract,"5 D","1 hour",datetime_1h)
         cci, avg, cci_prior, averageh, cci3 = calculate_cci(bars_1h)
         log.debug("bars_1h {}".format(str(bars_1h[-1])))
         atr,atrprior = calculate_atr(bars_1h)
         bband_width, bband_b,bband_width_prior, bband_b_prior = calculate_bbands(bars_1h)
         csv_row += ","+str(cci)+","+str(avg)+","+str(atr)+","+str(bband_width)+","+str(bband_b)
         csv_header += ",CCI1h,CCIA1h,ATR1h,BBW1h,BBB1h"
         key_arr[2] = categories.categorize_atr1h(atr)
         key_arr[6] = categories.categorize_cci_1h(avg)
         key_arr[10] = categories.categorize_BBW1h(bband_width)
         key_arr[11] = categories.categorize_BBb1h(bband_b)
         #logged_it = self.log_value("Starting 1 hour", cci,avg,cci_prior, averageh,atr,bband_width,bband_b)
         qtrtime = datetime.now()
         
         log.debug("requesting info for the following timeframe today: nextday: ".format(datetime_1d))
         bars_1d = self.get_bars_data(dataContract,"75 D","1 day",datetime_1d)
         log.debug("1d min bars {}".format(str(bars_1d[-1])))
         cci, avg, cci_prior, averageh, cci3 = calculate_cci(bars_1d)
         atr, atrprior = calculate_atr(bars_1d)
         bband_width, bband_b,bband_width_prior, bband_b_prior = calculate_bbands(bars_1d)
         csv_row += ","+str(cci)+","+str(avg)+","+str(atr)+","+str(bband_width)+","+str(bband_b)
         csv_header += ",CCI1d,CCIA1d,ATR1d,BBB1d,BBW1d"
         key_arr[3] = categories.categorize_atr1d(atr)
         key_arr[7] = categories.categorize_cci_1d(avg)
         key_arr[12] = categories.categorize_BBW1d(bband_width)
         key_arr[13] = categories.categorize_BBb1d(bband_b)
         #logged_it = self.log_value("Starting 1 Day", cci,avg,cci_prior, averageh,atr,bband_width,bband_b)
         qtrtime = datetime.now()
         setsum = self.setupsummary(key_arr)
         log.info("tradenow: {trade}".format(trade = tradenow))
         #
         # starting trade logic
         #
         # test buy
         if tradenow:
             log.info("Tradeing this bar {}".format(str(''.join(key_arr))," - ",''.join(key_arr[0:8])))
             csv_file1 = csv.reader(open('data/ccibb.csv', "rt"), delimiter = ",")
             for row1 in csv_file1:
                 print("ccibb row: ",row1[0],row1[13])
                 if ((''.join(key_arr)) == row1[0]) and row1[13] == "Y": #13 is winrisk - whether we trade or not
                         quantity = 2
                         log.info("we have a match in ccibb.csv")
                         log.info("found a match in CCIBB ".format(str(row1[0])))
                         ccibb_trade = True
                         if open_long or open_short:
                             quantity = 4
                         ParentOrderID = orders.buildOrders(self.ib,tradeContract,tradeAction,quantity,"ccibb_day",stoplossprice)
                         log.info("order placed, parentID: {}".format(ParentOrderID))
                         open_long = False
                         open_short = False
                         tradenow = False
                         status_done = self.row_results(row1,cci_trade,ccibb_trade)
                         break
             csv_file2 = csv.reader(open('data/cci.csv', "rt"), delimiter = ",")
             for row2 in csv_file2:
                 print("cci   row: ",row2[0],row2[13])
                 if ((''.join(key_arr[0:8])) == row2[0]) and row2[13] == "Y":
                         quantity = 2
                         log.info("we have a match in cci.csv - tradeAction".format(tradeAction))
                         log.info("found a math in CCI {}".format(str(row2[0])))
                         if open_long or open_short:
                             quantity = 4
                         ParentOrderID = orders.buildOrders(self.ib,tradeContract,tradeAction,quantity,"cci_day",stoplossprice)
                         open_long = False
                         open_short = False
                         tradenow = False
                         status_done = self.row_results(row2,cci_trade,ccibb_trade)
                         break
             log.info("did we find a match?  If true than no {match}".format(match = tradenow))
             if open_long or open_short:
                 quantity = 2
                 ParentOrderID = orders.buildOrders(self.ib,tradeContract,tradeAction,quantity,"ccibb_day",stoplossprice)
                 open_long =False
                 open_short = False
         csv_row += ","+(''.join(key_arr))+","+(''.join(key_arr[0:8]))+","+str(cci_trade)+","+str(ccibb_trade)+","+str(pendinglong)+","+str(pendingshort)
         csv_header += ",CCIbbKey,CCIKey,CCI Trade,CCIbbTrade,PendingLong, PendingShort"
         with open('data/hist15.csv', mode='a') as hist15:
             histwriter = csv.writer(hist15, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
             histwriter.writerow([csv_header])
             histwriter.writerow([csv_row])
         tradenow = False
         cci_trade = False
         ccibb_trade = False
Ejemplo n.º 5
0
    def run(self):
        """ Execute the algorithm """
        key_arr = [
            'blank', 'ATR15', 'ATR1', 'ATRD', 'CCI15', 'CCIA15', 'CCIA1h',
            'CCIA1d', 'BBW15', 'BBb15', 'BBW1h', 'BBb1h', 'BBW1d', 'BBb1d'
        ]
        tradenow = False
        not_finished = True
        tradenow = False
        cci_trade = False
        ccibb_trade = False
        while not_finished:
            print("top of algo run self")
            crossed = False
            self.app.crossover.update(crossed)
            contContract = get_contract(self)
            #print(contract.tradingHours.split(";"))
            #open_today = helpers.is_open_today(contract)
            #print("open today ",open_today)
            dataContract = Contract(exchange=config.EXCHANGE,
                                    secType="FUT",
                                    localSymbol=contContract.localSymbol)
            log.info("Got Contract: {}".format(dataContract.localSymbol))
            self.app.contract.update(dataContract.localSymbol)
            wait_time, datetime_15, datetime_1h, datetime_1d = self.define_times(
            )
            log.info(
                "next datetime for 15 minutes - should be 15 minutes ahead of desired nextqtr{}"
                .format(wait_time))
            #
            #nextqtr = datetime.now().minute + 1
            #print ("we manually overwrote start time")
            #print (nextqtr)
            #
            self.ib.waitUntil(wait_time)
            # 15 Minute Data
            self.app.qtrhour.update(wait_time)
            log.info("requesting info for the following timeframe today: {} ".
                     format(wait_time))
            bars_15m = self.get_bars_data(dataContract, "2 D", "15 mins",
                                          datetime_15)
            x = np.array(bars_15m)
            log.info("15 min bars {}".format(bars_15m[-1]))
            #sef.app. barupdateEvent_15m(baas_15m, True)
            #aars_15m.updateEvent += self.app.barupdateEvent_15m
            log.info("Got 15m data subscription")
            cci, avg, cci_prior, averageh, cci3 = calculate_cci(bars_15m)
            atr, atrprior = calculate_atr(bars_15m)
            bband_width, bband_b, bband_width_prior, bband_b_prior = calculate_bbands(
                bars_15m)
            log.info("starting 15 minutes".format(datetime.now()))
            log.info("CCI:      {} ".format(cci))
            log.info("CCIA      {} ".format(avg))
            log.info("CCIP      {} ".format(cci_prior))
            log.info("CCIPA:    {} ".format(averageh))
            log.info("ATR:      {} ".format(atr))
            log.info("bband w:  {} ".format(bband_width))
            log.info("bband p:  {} ".format(bband_b))
            qtrtime = datetime.now()
            #key_arr = []
            if cci > cci_prior and cci_prior < cci3:
                crossed = True
                tradenow = True
                csv_row = "'" + str(datetime.now()) + ",'long'"
                key_arr[0] = "long"
            elif cci < cci_prior and cci_prior > cci3:
                crossed = True
                tradenow = True
                csv_row = "'" + str(datetime.now()) + ",'short'"
                key_arr[0] = "short"
            else:
                csv_row = "'" + str(datetime.now()) + ",'flat'"
                crossed = False
                tradenow = False
            csv_row += ",'" + str(crossed) + "'," + str(cci) + "," + str(
                avg) + "," + str(cci_prior) + "," + str(averageh) + "," + str(
                    atr) + "," + str(bband_width) + "," + str(bband_b)
            print(key_arr)
            key_arr[1] = categories.categorize_atr15(atr)
            key_arr[4] = categories.categorize_cci_15(cci)
            key_arr[5] = categories.categorize_cci_15_avg(avg)
            key_arr[8] = categories.categorize_BBW15(bband_width)
            key_arr[9] = categories.categorize_BBb15(bband_b)
            stat = "check crossed status"

            #print("printing self app ********************************************")
            #print(Indicator.data)
            self.app.status1.update(stat)
            self.app.crossover.update(crossed)
            self.app.cci15.update(f"{cci:.02f}")
            self.app.cci15_av.update(f"{avg:.02f}")
            self.app.cci15p_av.update(f"{averageh:.02f}")
            self.app.cci15p.update(f"{cci_prior:.02f}")
            self.app.atr15.update(f"{atr:.02f}")
            self.app.bband15_width.update(f"{bband_width:.04f}")
            self.app.bband15_b.update(f"{bband_b:.04f}")
            self.app.qtrhour.update(qtrtime)

            #1 hour data
            log.info(
                "next datetime for 1 hour - should be 1 hour behind current hour {}"
                .format(datetime_1h))
            bars_1h = self.get_bars_data(dataContract, "5 D", "1 hour",
                                         datetime_1h)
            cci, avg, cci_prior, averageh, cci3 = calculate_cci(bars_1h)
            log.info("bars_1h {}".format(bars_1h[-1]))
            atr, atrprior = calculate_atr(bars_1h)
            bband_width, bband_b, bband_width_prior, bband_b_prior = calculate_bbands(
                bars_1h)
            csv_row += "," + str(cci) + "," + str(avg) + "," + str(
                atr) + "," + str(bband_width) + "," + str(bband_b)
            key_arr[2] = categories.categorize_atr1h(atr)
            key_arr[6] = categories.categorize_cci_1h(avg)
            key_arr[10] = categories.categorize_BBW1h(bband_width)
            key_arr[11] = categories.categorize_BBb1h(bband_b)
            log.info("starting 1H ")
            log.info("CCI       {} ".format(cci))
            log.info("CCIA:     {} ".format(avg))
            log.info("ATR:      {} ".format(atr))
            log.info("bband w:  {} ".format(bband_width))
            log.info("bband p:  {} ".format(bband_b))
            qtrtime = datetime.now()
            self.app.cci1h.update(f"{cci:.02f}")
            self.app.cci1h_av.update(f"{avg:.02f}")
            self.app.bband1h_b.update(f"{bband_b:.04f}")
            self.app.bband1h_width.update(f"{bband_width:.04f}")
            self.app.atr1h.update(f"{atr:.02f}")

            log.info(
                "requesting info for the following timeframe today: nextday: ".
                format(datetime_1d))
            bars_1d = self.get_bars_data(dataContract, "75 D", "1 day",
                                         datetime_1d)
            log.info("1d min bars {}".format(bars_1d[-1]))
            cci, avg, cci_prior, averageh, cci3 = calculate_cci(bars_1d)
            atr, atrprior = calculate_atr(bars_1d)
            bband_width, bband_b, bband_width_prior, bband_b_prior = calculate_bbands(
                bars_1d)
            csv_row += "," + str(cci) + "," + str(avg) + "," + str(
                atr) + "," + str(bband_width) + "," + str(bband_b)
            key_arr[3] = categories.categorize_atr1d(atr)
            key_arr[7] = categories.categorize_cci_1d(avg)
            key_arr[12] = categories.categorize_BBW1d(bband_width)
            key_arr[13] = categories.categorize_BBb1d(bband_b)
            log.info("starting 1H ")
            log.info("starting 1D ")
            log.info("CCIP      {} ".format(cci))
            log.info("CCIPA:    {} ".format(avg))
            log.info("ATR:      {} ".format(atr))
            log.info("bband w:  {} ".format(bband_width))
            log.info("bband p:  {} ".format(bband_b))
            qtrtime = datetime.now()
            qtrtime = datetime.now()
            self.app.cci1d.update(f"{cci:.02f}")
            self.app.cci1d_av.update(f"{avg:.02f}")
            self.app.bband1d_b.update(f"{bband_b:.04f}")
            self.app.bband1d_width.update(f"{bband_width:.04f}")
            self.app.atr1d.update(f"{atr:.02f}")
            if tradenow:
                csv_file = csv.reader(open('data/ccibb.csv', "rt"),
                                      delimiter="'")
                for row in csv_file:
                    if (''.join(key_arr)) == row[0]:
                        print("we have a match in ccibb.csv")
                        print("found a match in CCIBB ", row)
                        status_done = self.row_results(self, row)
                        ccibb_trade = True
                csv_file = csv.reader(open('data/cci.csv', "rt"),
                                      delimiter="'")
                for row in csv_file:
                    if (''.join(key_arr[0:8])) == row[0]:
                        print("we have a match in cci.csv")
                        print("found a math in CCI ", row)
                        status_done = self.row_results(self, row)
                        cci_trade = True
            csv_row += "," + (''.join(key_arr)) + "," + (''.join(
                key_arr[0:8])) + "," + str(ccibb_trade) + "," + str(
                    ccibb_trade)
            with open('data/hist15.csv', mode='a') as hist15:
                histwriter = csv.writer(hist15,
                                        delimiter=',',
                                        quotechar='"',
                                        quoting=csv.QUOTE_MINIMAL)
                histwriter.writerow([csv_row])
            tradenow = False
            cci_trade = False
            ccibb_trade = False
            print(
                "end of run self **********************************************************************************************"
            )