예제 #1
0
    def __init__(self, tradesource, period, record_candles=True, start=None, quiet=False):
        self.tradesource = tradesource
        self.p_value, self.p_unit = parse_period(period)
        self.period = period
        self.step = pdelta(self.p_value, self.p_unit)
        self.exchange, self.base, self.alt = tradesource.exchange, tradesource.base, tradesource.alt
        self.candlefile = CANDLES + '{}_{}_{}_{}{}'.format(self.exchange, self.base, self.alt, self.p_value, self.p_unit)
        self.record_candles = record_candles
        self.quiet = quiet

        # check for candle directory
        if not os.path.exists(CANDLES):
            build_data_directories()

        # check for candle file
        if os.path.exists(self.candlefile):
            with open(self.candlefile, 'rb') as readfile:
                reader = csv.reader(readfile, delimiter=',')
                if start:
                    self.closed_candles = [[int(candle[0])] + [Decimal(x) for x in candle[1:]] for candle in reader if ut_to_dt(candle[0]) < start]
                else:
                    self.closed_candles = [[int(candle[0])] + [Decimal(x) for x in candle[1:]] for candle in reader]
            self.active_candle = self.closed_candles.pop() 

        # if no candle file, check for trades in tradesource
        elif self.tradesource.trades:
            if not self.quiet: print 'No candlefile found; generating from tradesource...'
            if start:
                self.closed_candles = [[int(candle[0])] + [Decimal(x) for x in candle[1:]] 
                                        for candle in trades_to_candles(self.tradesource.trades, period)
                                        if ut_to_dt(candle[0]) < start]
            else:
                self.closed_candles = [[int(candle[0])] + [Decimal(x) for x in candle[1:]] 
                                        for candle in trades_to_candles(self.tradesource.trades, period)]
            # assume the last candle is still active
            self.active_candle = self.closed_candles.pop()
            
        # if no candles or trades
        else:
            if not self.quiet: print 'No candlefile found; no tradefile found; waiting for new trades...'
            self.closed_candles = []
            self.active_candle = []
            self.active_trades = []
            self.next_start = None
            
        if self.active_candle: # at least one candle was found
            self.next_start = ut_to_dt(self.active_candle[0]) + self.step       
        
            # assume last candle is not closed yet (check in update)
            self.last_closed_known = False
        
            # get trade data from most recent candle
            self.active_trades = [trade for trade in self.tradesource.trades 
                                    if trade['timestamp'] >= self.active_candle[0]]
예제 #2
0
파일: plotting.py 프로젝트: xh3/cryptrade
    def plot(self, candles, period, ncandles=100, indicators=[]):

        self.p_value, self.p_unit = parse_period(period)

        self.candles = candles
        starts, opens, closes, highs, lows, volumes = np.array(
            self.candles).transpose()
        dates = [mdates.date2num(ut_to_dt(start)) for start in starts]
        self.candles = np.array([dates, opens, closes, highs,
                                lows, volumes]).transpose()

        start = ut_to_dt(starts[-ncandles]) - pdelta(self.p_value, self.p_unit)
        end = ut_to_dt(starts[-1]) + pdelta(self.p_value, self.p_unit)

        self.ax1.cla()
        self.ax1.xaxis_date()

        candlestick(self.ax1, self.candles[-ncandles:],
                    width=self.candleWidth(), colorup='cyan', colordown='blue')

        self.ax1.set_xlim(mdates.date2num(start), mdates.date2num(end))

        self.ax2.cla()
        self.ax2.xaxis_date()
        self.ax2.yaxis.set_ticklabels([])  # hide volume numbers

        self.ax2.set_xlim(mdates.date2num(start), mdates.date2num(end))

        # indicators
        plot_volume = True  # default case
        for indicator in indicators:
            values = indicator.calculate(self.candles)[-ncandles:]
            if indicator.plot_type == 'primary':
                self.ax1.plot(dates[-ncandles:], values[-ncandles:],
                              label=indicator.label)
            if indicator.plot_type == 'secondary':
                self.ax2.plot(dates[-ncandles:], values[-ncandles:],
                              '#00ffe8', linewidth=0.8, label=indicator.label)
                self.ax2.fill_between(dates[-ncandles:], 0,
                                      [float(x) for x in values],
                                      facecolor='#00ffe8', alpha=0.5)
                self.ax2.set_ylabel(indicator.label)
                plot_volume = False

        if plot_volume:
            bar = False
            if bar:
                self.ax2.bar(dates[-ncandles:], volumes[-ncandles:],  # bar
                             width=self.candlewidth(), facecolor='#00ffe8')
            else:
                self.ax2.plot(dates[-ncandles:], volumes[-ncandles:],  # curve
                              '#00ffe8', linewidth=0.8)
                self.ax2.fill_between(dates[-ncandles:], 0,
                                      [float(x) for x in volumes[-ncandles:]],
                                      facecolor='#00ffe8', alpha=0.5)
            self.ax2.set_ylabel('Volume')

        # legend
        if indicators:
            self.ax1.legend(loc=2, fancybox=True, prop={'size': 9})

        self.formatting()

        self.canvas.draw()  # update