def update(self): """ Checks for new trades and updates the candle data. """ new_trades = self.tradesource.new_trades if new_trades: self.active_trades += [{'timestamp': int(trade['timestamp']), 'price': Decimal(trade['price']), 'amount': Decimal(trade['amount'])} for trade in new_trades] if not self.next_start: first = ut_to_dt(self.active_trades[0]['timestamp']) start = datetime( year=first.year, month=first.month, day=first.day) while start + self.step < first: start += self.step self.next_start = start + self.step self.active_candle = get_candle( dt_to_ut(start), self.active_trades) self.last_closed_known = False # dump older trades if active candle has closed, # accounting for possible gaps while ut_to_dt( self.active_trades[-1]['timestamp']) > self.next_start: self.dump() # update active candle new_candle = get_candle(self.active_candle[0], new_trades) self.active_candle = self.update_candle( self.active_candle, new_candle)
def update(self): """ Checks for new trades and updates the candle data. """ new_trades = self.tradesource.new_trades if new_trades: self.active_trades += [{ 'timestamp': int(trade['timestamp']), 'price': Decimal(trade['price']), 'amount': Decimal(trade['amount']) } for trade in new_trades] if not self.next_start: first = ut_to_dt(self.active_trades[0]['timestamp']) start = datetime(year=first.year, month=first.month, day=first.day) while start + self.step < first: start += self.step self.next_start = start + self.step self.active_candle = get_candle(dt_to_ut(start), self.active_trades) self.last_closed_known = False # dump older trades if active candle has closed, # accounting for possible gaps while ut_to_dt( self.active_trades[-1]['timestamp']) > self.next_start: self.dump() # update active candle new_candle = get_candle(self.active_candle[0], new_trades) self.active_candle = self.update_candle(self.active_candle, new_candle)
def dump(self): """ Run once the candle is completed, to close the candle and record it to the candle data file. """ to_dump = [t for t in self.active_trades if ut_to_dt(t['timestamp']) < self.next_start] to_keep = [t for t in self.active_trades if ut_to_dt(t['timestamp']) >= self.next_start] if len(to_dump): if not self.quiet: print '{} {}{} candle closed at {} with {} trades'.format(self.exchange, self.p_value, self.p_unit, to_dump[-1]['price'], len(to_dump)) dump_candle = get_candle(self.active_candle[0], to_dump) self.closed_candles.append(dump_candle) if self.record_candles: # if last entry not closed, pop out the last entry before rewriting with update if not self.last_closed_known: save_candlefile(self.closed_candles, self.period, self.candlefile, replace=True) else: save_candlefile([dump_candle], self.period, self.candlefile, replace=False) self.active_trades = to_keep self.active_candle = get_candle(dt_to_ut(self.next_start), [to_keep[0]]) self.next_start += self.step # only closed candles are saved, so last will always be closed on further updates self.last_closed_known = True
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]]
def update(self): self.new_trades = [] response = self.api.trades({}, self.symbol) if response: trades = sorted(response, key=lambda x: int(x['timestamp'])) new_trades = [{ 'timestamp': int(t['timestamp']), 'price': Decimal(t['price']), 'amount': Decimal(t['amount']) } for t in trades if t['timestamp'] > self.last_trade()['timestamp'] and t['exchange'] == self.exchange] if new_trades: self.new_trades = new_trades # print each new trade, and add it to the # trade file if record_trades==True for trade in new_trades: if not self.quiet: print "{} {} {} {} {} {}".format( ut_to_dt(trade['timestamp']), self.exchange, trade['price'], self.alt, trade['amount'], self.base) self.trades.append({ 'timestamp': int(trade['timestamp']), 'price': Decimal(trade['price']), 'amount': Decimal(trade['amount']) }) self.price = self.trades[-1]['price'] # write new trades to tradefile if self.record_trades: tradefile = TRADES + '{}_{}_{}'.format( self.exchange, self.base, self.alt) if not os.path.exists(TRADES): build_data_directories() with open(tradefile, 'a') as writefile: writer = csv.writer(writefile, delimiter=',') writer.writerow([ trade['timestamp'], trade['price'], trade['amount'] ]) return self.new_trades
def update(self): self.new_trades = [] response = self.api.trades({}, self.symbol) if response: trades = sorted(response, key=lambda x: int(x['timestamp'])) new_trades = [{'timestamp': int(t['timestamp']), 'price': Decimal(t['price']), 'amount': Decimal(t['amount'])} for t in trades if t['timestamp'] > self.last_trade()['timestamp'] and t['exchange'] == self.exchange] if new_trades: self.new_trades = new_trades # print each new trade, and add it to the # trade file if record_trades==True for trade in new_trades: if not self.quiet: print "{} {} {} {} {} {}".format( ut_to_dt(trade['timestamp']), self.exchange, trade['price'], self.alt, trade['amount'], self.base) self.trades.append({'timestamp': int(trade['timestamp']), 'price': Decimal(trade['price']), 'amount': Decimal(trade['amount'])}) self.price = self.trades[-1]['price'] # write new trades to tradefile if self.record_trades: tradefile = TRADES+'{}_{}_{}'.format( self.exchange, self.base, self.alt) if not os.path.exists(TRADES): build_data_directories() with open(tradefile, 'a') as writefile: writer = csv.writer(writefile, delimiter=',') writer.writerow([trade['timestamp'], trade['price'], trade['amount']]) return self.new_trades
def get_candles_from(self, timestamp): timestamp = dt_to_ut(ut_to_dt(timestamp) - self.step) g = itertools.dropwhile( lambda c: c[0] < timestamp, self.closed_candles) return list(g)
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
def get_candles_from(self, timestamp): timestamp = dt_to_ut(ut_to_dt(timestamp) - self.step) g = itertools.dropwhile(lambda c: c[0] < timestamp, self.closed_candles) return list(g)
def get_candles_from(self, timestamp): # candles containing timestamp and beginning after timestamp timestamp = dt_to_ut(ut_to_dt(timestamp) - self.step) g = itertools.dropwhile(lambda c: c[0] < timestamp, self.closed_candles) return list(g)