예제 #1
0
def import_data(currency):
    range_param = '24h'  # 10mi,1h,12h,24h,1w,1m,3m,1y,ytd,all
    url = 'https://api.ethereumdb.com/v1/timeseries?pair={}-USD&range={}&type=line'.format(
        currency, range_param)

    print('fetching data for {}'.format(currency))
    data = reverse(requests.get(url).json())
    print('fetched data for {}'.format(currency))

    for i in range(len(data)):
        curr = data[i]
        prev_price = None
        if i == 0:
            # get latest record from database to calculate prev_data
            last_ticker = Ticker.select().where(
                Ticker.currency == currency,
                Ticker.datetime < datetime(data[i]['timestamp'])).order_by(
                    Ticker.datetime.desc())
            if last_ticker.exists():
                prev_price = last_ticker[0].price
        else:
            prev_price = data[i - 1]['price']

        ticker = TickerCalculator(currency=currency,
                                  epoch=curr['timestamp'],
                                  price=curr['price'],
                                  volume24h=curr['quoteVolume24h'],
                                  prev_price=prev_price)

        if Ticker.select().where(Ticker.epoch == ticker.epoch, Ticker.currency
                                 == currency).exists() is False:
            ticker.save()
예제 #2
0
def start():
    # remove all previous test trades
    test_trades = Trade.select().where(Trade.test == True)
    for test_trade in test_trades:
        test_trade.delete_instance()

    for symbol in SYMBOLS:
        tickers = reverse(Ticker.select().where(
            Ticker.currency == symbol,
            Ticker.epoch > 1614766446).order_by(-Ticker.epoch))

        for i in range(len(tickers)):
            last_30_tickers = reverse(get_last_x_items(tickers, i, 30))

            if len(last_30_tickers) < 30:
                continue

            strategy = Strategy(last_30_tickers, test=True)

            if strategy.when_buy():
                test_buy(symbol, strategy.ticker)

            if strategy.when_sell():
                test_sell(symbol, strategy.ticker)

    wallet(test=True)
예제 #3
0
def trade(symbol, test=False):
    tickers = Ticker.select().where(
        Ticker.currency == symbol).order_by(-Ticker.epoch).limit(30)
    strategy = Strategy(tickers, test)

    if strategy.diff == 0.0:
        return

    print("{}:{} {} \t => %{} \t => {}{}".format(
        strategy.ticker.datetime.hour, strategy.ticker.datetime.minute, symbol,
        round(strategy.diff_pct, 2), strategy.ticker.price, CURRENCY))

    if TELEGRAM_TOKEN and TELEGRAM_PUBLIC_CHAT_ID:
        log(symbol, strategy.diff_pct, strategy.ticker.price)

    if test is True:
        if strategy.when_buy():
            test_buy(symbol, strategy.ticker)

        if strategy.when_sell():
            test_sell(symbol, strategy.ticker)

    elif test is False:
        if strategy.when_buy():
            buy(symbol)

        if strategy.when_sell():
            sell(symbol)

        # print out current profit percentage when available.
        if hasattr(strategy, 'profit_pct'):
            print('PROFIT_PCT: %{} PROFIT: {}'.format(
                round(strategy.profit_pct, 2), strategy.profit))
예제 #4
0
def task(arg1, arg2):
    r = api.ticker()
    t = datetime.datetime.fromtimestamp(int(r['timestamp']))
    print(r)
    if Ticker.select().where(Ticker.timestamp == t).count() == 0:
        Ticker.create(
            last=r['last'],
            bid=r['bid'],
            ask=r['ask'],
            high=r['high'],
            low=r['low'],
            volume=r['volume'],
            timestamp=t
        )
예제 #5
0
    def when_buy(self):
        if len(self.tickers) != 30:
            return False

        if (self.buys - self.sells) > 0:
            return False

        if get_balance(test=self.test) < ORDER_INPUT:
            return False

        if self.diff_pct >= -4:
            return False

        last_hour_tickers = Ticker.select().where(Ticker.currency == self.ticker.currency).order_by(-Ticker.epoch).limit(60)
        (last_hour_diff, last_hour_diff_pct) = calc_diff(last_hour_tickers[0].price, self.ticker.price)

        return last_hour_diff_pct <= 6
예제 #6
0
from models import Ticker
from src.Scanner import Scanner
from src.Wallet import Wallet

wallet = Wallet()
currencies = Ticker.select().group_by(Ticker.currency)

for currency in currencies:
    tickers = Ticker.select().where(Ticker.currency == currency.currency,
                                    Ticker.epoch > 1614022644)
    scanner = Scanner(tickers, wallet)
    scanner.start()

wallet.balance()
예제 #7
0
def create_candles(interval=30, type='ask'):
    tickers = Ticker.select().order_by(Ticker.timestamp.desc())
    print(len(tickers))
    print(tickers[0].timestamp.timestamp())
    print(tickers[-1].timestamp.timestamp())

    origin = tickers[0].timestamp.timestamp()

    times = []
    candles = []
    group = []

    for t in tickers:
        if origin >= t.timestamp.timestamp() > origin - interval:
            group.append(t.ask if type == 'ask' else t.bid)
        else:
            if 0 < len(group):
                times.append(origin)
                # candles.append((datetime.datetime.fromtimestamp(origin), group[-1], max(group), min(group),  group[0]))
                candles.append((origin, group[-1], max(group), min(group),  group[0]))

            group = []

            origin -= interval

    t = [x for x in reversed(times)]
    cdl = [x for x in reversed(candles)]

    [print(c) for c in candles]

    # 描画
    # d = [x[0] for x in candles]
    # o = [x[1] for x in candles]
    # h = [x[2] for x in candles]
    # l = [x[3] for x in candles]
    # c = [x[4] for x in candles]

    # x = d, o, h, l, c
    # ohlc = []
    # ohlc.append(x)


    fig, ax = plt.subplots()
    # candlestick_ohlc(ax, cdl, width=(1.0 / 24 / 60 * interval), colorup='b', colordown='r')
    candlestick_ohlc(ax, cdl)

    xdate = [datetime.datetime.fromtimestamp(i) for i in t]
    # ax.xaxis.set_major_locator(ticker.MaxNLocator(1))

    def mydate(x, pos):
        try:
            return xdate[int(x)]
        except IndexError:
            return ''

    ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate))

    fig.autofmt_xdate()
    plt.xlabel('Date')
    plt.ylabel('Price')
    plt.subplots_adjust(left=0.09, bottom=0.20, right=0.94, top=0.90, wspace=0.2, hspace=0)
    plt.show()
예제 #8
0
def figure(symbol):
    # https://plotly.com/python/line-charts/
    fig = go.Figure(
        layout={
            'yaxis': {
                'title': 'PRICE axis'
            },
            'yaxis2': {
                'title': 'DIFF axis',
                'overlaying': 'y',
                'side': 'right'
            }
        })
    tickers = Ticker.select().where(
        Ticker.currency == symbol,
        Ticker.epoch > 1614809646).order_by(-Ticker.epoch)

    timestamps = []
    prices = []
    diffs = []
    # for ticker in tickers:
    for i in range(len(tickers)):
        timestamps.append(tickers[i].datetime)
        prices.append(tickers[i].price)

        last_30_tickers = get_last_x_items(tickers, i, 30)
        if (len(last_30_tickers) == 30):
            (diff, diff_pct) = calc_diff(last_30_tickers[0].price,
                                         tickers[i].price)
            diffs.append(diff_pct)

    fig.add_trace(
        go.Scatter(x=timestamps,
                   y=prices,
                   name=symbol,
                   line=dict(color='dodgerblue', width=4)))

    # fig.add_bar(x=timestamps, y=diffs, name='diffs', yaxis='y2', offsetgroup=1)

    # fig.add_trace(go.Scatter(x=timestamps, y=diffs, name=symbol,
    #                          line=dict(color='green', width=4)))

    trades = Trade.select().where(Trade.currency == symbol)

    buy_timestamps = []
    buy_prices = []
    sell_timestamps = []
    sell_prices = []
    for trade in trades:
        if trade.type == 'buy':
            buy_timestamps.append(trade.date)
            buy_prices.append(trade.price)
        if trade.type == 'sell':
            sell_timestamps.append(trade.date)
            sell_prices.append(trade.price)

    fig.add_trace(
        go.Scatter(x=buy_timestamps,
                   y=buy_prices,
                   mode='markers',
                   line=dict(width=10, color='Green'),
                   name='BUY'))

    fig.add_trace(
        go.Scatter(x=sell_timestamps,
                   y=sell_prices,
                   mode='markers',
                   line=dict(width=10, color='Red'),
                   name='SELL'))

    # Edit the layout
    fig.update_layout(title='{} Backtest results'.format(symbol),
                      xaxis_title='Timestamp',
                      yaxis_title='Price')

    fig.show()

    app = dash.Dash()
    app.layout = html.Div([dcc.Graph(figure=fig)])

    # Turn off reloader if inside Jupyter
    app.run_server(debug=False, use_reloader=False)