Ejemplo n.º 1
0
def on_message(ws, message):
    try:
        message = json.loads(message)
        stream = message['stream']
        data = message['data']

        if '@kline' in stream:
            symbol = data['s']
            kline = data['k']
            if bool(kline['x']):
                update_history(symbol, kline['i'], kline)

        if '@ticker' in stream:
            symbol = stream.split('@')[0].upper()
            DATABASE.set(symbol,
                         json.dumps({
                             'bid': data['b'],
                             'ask': data['a']
                         }))
            update_price_change_percent(symbol, data['P'])
            # if symbol == 'BNBBTC':
            #     print(symbol, json.dumps({'bid': data['b'], 'ask': data['a']}))

    except KeyboardInterrupt:
        pass
    except:
        print(traceback.format_exc())
Ejemplo n.º 2
0
def launch():
    while True:
        to_general_log('wsBinance1', 'start websocket Binance')
        DATABASE.set(RUN_MONITOR_FLAG1, 'False')
        time.sleep(1)

        try:
            subs = ''
            count = 0
            for symbol in SYMBOLS[:100]:
                subs += symbol.lower() + '@kline_1h/'
                subs += symbol.lower() + '@kline_5m/'
                subs += symbol.lower() + '@ticker/'
                count += 1
            if subs != '':
                to_general_log('wsBinance1', f'{count} pairs')
                ws = websocket.WebSocketApp(
                    "wss://stream.binance.com:9443/stream?streams={}".format(
                        subs.strip('/')),
                    on_open=on_open,
                    on_message=on_message,
                    on_error=on_error,
                    on_close=on_close)
                ws.run_forever()
        except:
            print('wsBinance1 Error: websocket failed')
            print(traceback.format_exc())
Ejemplo n.º 3
0
def push_bxin_tick(symbol):
    while True:
        try:
            r = requests.get(
                f"https://bx.in.th/api/orderbook/?pairing={convert_symbol(symbol)}"
            )
            if r is not None:
                r = json.loads(r.text)
                bid = round(float(r['bids'][0][0]), 2)
                ask = round(float(r['asks'][0][0]), 2)
                bid_amount = float(r['bids'][0][1])
                ask_amount = float(r['asks'][0][1])
                # print(symbol, '  ', bid, bid_amount, '    ', ask, ask_amount)
                DATABASE.set(
                    'bxin_' + symbol,
                    json.dumps({
                        'ask': ask,
                        'bid': bid,
                        'ask_amount': ask_amount,
                        'bid_amount': bid_amount
                    }))
                # print(DATABASE.get('bxin_' + symbol))
            time.sleep(TIMEOUT_PUSH)
        except ConnectionError:
            log('Too many requests', 'BXIN')
            err_log(traceback.format_exc())
            time.sleep(4)
Ejemplo n.º 4
0
def on_open(ws):
    print('### opened ###')
    mem_cache_init_pusher()
    for symbol in SYMBOLS[:100]:
        init_price_change_percent(symbol)
        mem_cache_init(symbol)
    DATABASE.set(RUN_MONITOR_FLAG1, 'True')
    print('### monitor is allowed ###')
Ejemplo n.º 5
0
def init():
    # 生成表
    # DATABASE.create_tables([Point_Info, Point_Setting, User_Point, User_PointBill, Product_Point, Product_Point_Detail])
    # DATABASE.create_tables([
    #     Express_Info, My_Express_Info,
    #     Product_Point, Product_Point_Detail, My_Exchange_Info, My_History_Address,
    #     Area, My_Address,
    # ])
    # DATABASE.create_tables([Area,My_Address])
    DATABASE.create_tables([Tao_Channel_Info])
Ejemplo n.º 6
0
    def mob_attack(self, other, bot):
        stats = DATABASE.get_attr_by_id(
            self.id, ('health', 'armor', 'user_level', 'current_exp'))
        health = stats['health']
        armor = stats['armor']
        level = stats['user_level']
        current_exp = stats['current_exp']
        # Цикл битвы до смерти
        while other.health > 0 and health > 0:
            health -= int(other.damage * (1 - calculate_armor(armor)))
            other.attack(self.damage)

        else:
            # Проверка на смерть кого-либо
            if health <= 0:
                health = 0
                is_death = True

                DATABASE.update_by_id(self.id, 'health', health)
                DATABASE.update_by_id(self.id, 'is_death', is_death)

                self.resurrect_timer(bot)
                return 'death', 0, 0

            elif other.health <= 0:
                DATABASE.update_by_id(self.id, 'health', health)
                add_exp = other.get_exp(level)
                current_exp += add_exp
                DATABASE.update_by_id(self.id, 'current_exp', current_exp)
                next_level = levels.next_level(self)
                return 'kill', add_exp, next_level
Ejemplo n.º 7
0
    def resurrect(self, bot):
        stats = DATABASE.get_attr_by_id(self.id, ('max_health', ))
        max_health = stats['max_health']

        health = int(max_health * 0.1)
        is_death = False

        DATABASE.update_by_id(self.id, 'health', health)
        DATABASE.update_by_id(self.id, 'is_death', is_death)

        bot.send_message(self.id, 'Вы возродились')
Ejemplo n.º 8
0
def initialize_database() -> None:
    """
    Initialize sqlite database of not found any.
    :return: None
    """
    path = f"{APP_DIR}\\database.db"

    if not os.path.exists(path=path):
        DATABASE.create_all()
        url = 'https://www.googleapis.com/books/v1/volumes?q=Hobbit'

        save_books_to_db(import_books(url=url))
Ejemplo n.º 9
0
def mem_cache_init_pusher():
    exchange_info = BINANCE.get_exchange_info()
    if exchange_info is not None:
        DATABASE.set(EXCHANGE_INFO, json.dumps(exchange_info))
        print('exchange_info', len(exchange_info), exchange_info)

    tickers = BINANCE.get_ticker()
    if tickers is not None:
        DATABASE.set(TICKERS, json.dumps(tickers))
        print('tickers', len(tickers), tickers)

    time.sleep(1)
Ejemplo n.º 10
0
def to_general_log(symbol, text):
    log = DATABASE.get(GENERAL_LOG)
    if log is None:
        log = '[]'
    log = json.loads(log)
    if len(log) > LOG_LENGTH:
        log = log[-(len(log) - 1):]

    dt = datetime.now().replace(microsecond=0).isoformat().replace('T', ' ')
    log.append(dt + ' ' + symbol + ': ' + text)
    DATABASE.set(GENERAL_LOG, json.dumps(log))
    print(dt + ' ' + symbol + ': ' + text)
Ejemplo n.º 11
0
def mem_cache_init(symbol):
    time_now = datetime.datetime.utcfromtimestamp(time.time()).strftime('%H:%M:%S')
    history5m = BINANCE.get_klines(symbol=symbol, interval=BINANCE.KLINE_INTERVAL_5MINUTE)
    history1h = BINANCE.get_klines(symbol=symbol, interval=BINANCE.KLINE_INTERVAL_1HOUR)

    print(symbol, time_now, '5M')
    DATABASE.set(symbol + '5M', json.dumps(history5m))

    print(symbol, time_now, '1H')
    DATABASE.set(symbol + '1H', json.dumps(history1h))

    time.sleep(0.5)
Ejemplo n.º 12
0
def push_market_info():
    try:
        global t_mi
        if time.time() - t_mi > to_mi:
            exchange_info = BINANCE.get_exchange_info()
            if exchange_info is not None:
                DATABASE.set(EXCHANGE_INFO, json.dumps(exchange_info))
                # print('exchange_info', len(exchange_info), exchange_info)
            t_mi = time.time()
            time.sleep(0.5)
    except requests.exceptions.ConnectionError as e:
        print(type(e))
        print(traceback.format_exc())
Ejemplo n.º 13
0
def push_volume():
    try:
        global t_volume
        if time.time() - t_volume > VOLUME_UPDATE:
            tickers = BINANCE.get_ticker()
            if tickers is not None:
                DATABASE.set(TICKERS, json.dumps(tickers))
                # print('tickers', len(tickers), tickers)
            t_volume = time.time()
            time.sleep(0.5)
    except requests.exceptions.ConnectionError as e:
        print(type(e))
        print(traceback.format_exc())
Ejemplo n.º 14
0
    def heal(self):
        stats = DATABASE.get_attr_by_id(
            self.id, ('health', 'max_health', 'health_per_second'))
        health = stats['health']
        max_health = stats['max_health']
        health_per_second = stats['health_per_second']

        if health < max_health:
            health += health_per_second
            if health > max_health:
                health = max_health

        DATABASE.update_by_id(self.id, 'health', health)
Ejemplo n.º 15
0
def next_level(player):
    user_stats = DATABASE.get_attr_by_id(player.id,
                                         ('user_level', 'current_exp'))
    level = user_stats['user_level']
    current_exp = user_stats['current_exp']
    if level >= 100:
        return False
    if current_exp >= levels[level]:
        current_exp -= levels[level]
        DATABASE.update_by_id(player.id, 'current_exp', current_exp)
        stats = player.next_level()
        return stats
    else:
        return False
Ejemplo n.º 16
0
def update_orders_info(exchange, order_id, symbol, side, status, price, amount,
                       date, timestamp):
    orders = get_orders_info(exchange)

    orders.update({
        order_id: {
            'symbol': symbol,
            'side': side,
            'status': status,
            'price': price,
            'amount': amount,
            'date': date,
            'timestamp': timestamp
        }
    })
    DATABASE.set(exchange + ':' + ORDERS_INFO, json.dumps(orders))
Ejemplo n.º 17
0
def push_bank_rate():
    while True:
        try:
            r = requests.get(
                'https://www.krungsri.com/bank/en/Other/ExchangeRate/Todayrates.html'
            )
            if r is not None:
                bank_rate = \
                    r.text.split("</td></tr><tr style='background-color:transparent !important'>")[0].split('>')[-1]
                DATABASE.set(BANK_RATE, bank_rate)
                # print(bank_rate)
            time.sleep(TIMEOUT_PUSH)
        except ConnectionError:
            log('Too many requests', 'BankRate')
            err_log(traceback.format_exc())
            time.sleep(4)
Ejemplo n.º 18
0
def get_rsi_value(symbol, time_frame):
    try:
        k_lines = json.loads(DATABASE.get(symbol + time_frame.upper()))
        res = rsi(list(float(x[4]) for x in k_lines), RSI_PERIOD)
        return round(float(res[-1]), 2)
    except (TypeError, KeyError):
        to_err_log(symbol, f'{time_frame}', traceback.format_exc())
Ejemplo n.º 19
0
def get_ma_value(symbol, time_frame, period):
    try:
        k_lines = json.loads(DATABASE.get(symbol + time_frame.upper()))
        res = list(sma(list(float(x[4]) for x in k_lines), period))
        return round(float(res[-1]), 8)
    except (TypeError, KeyError):
        to_err_log(symbol, f'{time_frame} {period}', traceback.format_exc())
Ejemplo n.º 20
0
def get_balance2(asset):
    balances = DATABASE.get(BALANCE)
    if balances is not None:
        balances = json.loads(balances)
        # print(balances)
        for balance in balances:
            if balance['asset'] == asset:
                return float(balance['free'])
Ejemplo n.º 21
0
    def resurrect_timer(self, bot):
        stats = DATABASE.get_attr_by_id(self.id, ('time_for_resurrect', ))
        time_for_resurrect = stats['time_for_resurrect']

        time_to_start_resurrect = time.time()
        timer = Timer(time_for_resurrect, self.resurrect, [bot])

        DATABASE.update_by_id(self.id, 'time_to_start_resurrect',
                              time_to_start_resurrect)

        try:
            timer.start()

        except Exception as e:
            timer.cancel()
            self.resurrect(bot)
            print(e)
Ejemplo n.º 22
0
def get_test_data():
    bid1 = random.randrange(9600, 9700)
    ask1 = random.randrange(9700, 9800)
    bid2 = random.randrange(12000, 12400)
    ask2 = random.randrange(12450, 12800)
    bid3 = random.randrange(309000, 310000)
    ask3 = random.randrange(310000, 311000)
    bid4 = random.randrange(12000, 12400)
    ask4 = random.randrange(12450, 12800)
    bid_amount1 = round(random.uniform(0, 1), 2)
    ask_amount1 = round(random.uniform(0, 1), 2)
    bid_amount2 = round(random.uniform(0, 1), 2)
    ask_amount2 = round(random.uniform(0, 1), 2)
    bid_amount3 = round(random.uniform(0, 1), 2)
    ask_amount3 = round(random.uniform(0, 1), 2)
    bid_amount4 = round(random.uniform(0, 1), 2)
    ask_amount4 = round(random.uniform(0, 1), 2)

    bank_rate = float(str(DATABASE.get(BANK_RATE)))

    return [{
        "exchange": "ITBIT",
        "symbol": "XBT_USD",
        "bid": str(bid1),
        "bid_amount": str(bid_amount1),
        "ask": str(ask1),
        "ask_amount": str(ask_amount1),
        "bank_rate": str(bank_rate),
        "diff": str(round(bid3 / bank_rate / ask1 * 100 - 100, 2))
    }, {
        "exchange": "ITBIT",
        "symbol": "ETH_USD",
        "bid": str(bid2),
        "bid_amount": str(bid_amount2),
        "ask": str(ask2),
        "ask_amount": str(ask_amount2),
        "bank_rate": str(bank_rate),
        "diff": str(round(bid4 / bank_rate / ask2 * 100 - 100, 2))
    }, {
        "exchange": "BXIN",
        "symbol": "THB_BTC",
        "bid": str(bid3),
        "bid_amount": str(bid_amount3),
        "ask": str(ask3),
        "ask_amount": str(ask_amount3),
        "bank_rate": str(bank_rate),
        "diff": str(round(bid1 / bank_rate / ask3 * 100 - 100, 2))
    }, {
        "exchange": "BXIN",
        "symbol": "THB_ETH",
        "bid": str(bid4),
        "bid_amount": str(bid_amount4),
        "ask": str(ask4),
        "ask_amount": str(ask_amount4),
        "bank_rate": str(bank_rate),
        "diff": str(round(bid2 / bank_rate / ask4 * 100 - 100, 2))
    }]
Ejemplo n.º 23
0
def get_pip(symbol):
    exchange_info = DATABASE.get(EXCHANGE_INFO)
    if exchange_info is None:
        return
    exchange_info = json.loads(exchange_info)
    symbols = exchange_info['symbols']
    for symbol_info in symbols:
        if symbol_info['symbol'] == symbol:
            return float(symbol_info['filters'][0]['tickSize'])
Ejemplo n.º 24
0
def split_symbol(symbol):
    exchange_info = DATABASE.get(EXCHANGE_INFO)
    if exchange_info is not None:
        symbols_info = json.loads(exchange_info)['symbols']
        for symbol_info in symbols_info:
            if symbol_info['symbol'] == symbol:
                return {
                    'base': symbol_info['baseAsset'],
                    'quote': symbol_info['quoteAsset']
                }
Ejemplo n.º 25
0
def normalize_symbol(asset1, asset2):
    exchange_info = DATABASE.get(EXCHANGE_INFO)
    if exchange_info is None:
        return
    exchange_info = json.loads(exchange_info)
    symbols = list(x['symbol'] for x in exchange_info['symbols'])
    if asset1 + asset2 in symbols:
        return asset1 + asset2
    if asset2 + asset1 in symbols:
        return asset2 + asset1
Ejemplo n.º 26
0
def update_history(symbol, time_frame, kline):
    try:
        time_now = datetime.datetime.utcfromtimestamp(time.time()).strftime('%H:%M:%S')
        history = DATABASE.get(symbol + time_frame.upper())
        if history is not None:
            history = json.loads(history)
            history.pop(0)

            kline = [kline['t'], kline['o'], kline['h'],
                     kline['l'], kline['c'], kline['v'],
                     kline['T'], kline['q'], kline['n'],
                     kline['V'], kline['Q'], kline['B']]

            history.append(kline)

            print(symbol, time_now, time_frame.upper())
            DATABASE.set(symbol + time_frame.upper(), json.dumps(history))
    except:
        to_general_log(symbol, 'Connect timeout. Reconnection...')
def on_message(ws, message):
    # print(type(message), message)
    message = json.loads(message)
    if 'e' in message:
        if message['e'] == 'outboundAccountInfo':
            balances = message['B']
            xd = []
            for balance in balances:
                xd.append({'asset': balance['a'], 'free': balance['f']})
                DATABASE.set(BALANCE, json.dumps(xd))
            print('WS: balances updated', len(xd))
            print(xd)
        if message['e'] == 'executionReport':
            update_orders_info('Binance', message['i'],
                               message['s'], message['S'],
                               format_status(message['X']), message['p'],
                               message['q'], message['O'],
                               int(time.time() * 1000))
            print('Update orders', format_status(message['X']), message)
Ejemplo n.º 28
0
def get_24_volume(symbol):
    tickers = DATABASE.get(TICKERS)
    if tickers is None:
        return
    tickers = json.loads(tickers)
    for ticker in tickers:
        if ticker['symbol'] == symbol:
            if split_symbol(symbol)['base'] == PREF_WALL:
                return float(ticker['volume'])
            return float(ticker['quoteVolume'])
Ejemplo n.º 29
0
def get_min_notional(symbol):
    exchange_info = DATABASE.get(EXCHANGE_INFO)
    if exchange_info is None:
        return
    exchange_info = json.loads(exchange_info)
    symbols = exchange_info['symbols']
    for s in symbols:
        if s['symbol'] == symbol:
            for f in s['filters']:
                if f['filterType'] == 'MIN_NOTIONAL':
                    return float(f['minNotional'])
def generate():
    log = DATABASE.get(GENERAL_LOG)
    if log is not None:
        log = json.loads(log)
        f = open(LOG_PATH + 'general.log', "w")
        for text in log:
            f.write(text + '\n')
            print(text)
        f.close()
        print('Done\nCheck {}'.format(LOG_PATH + 'general.log'))
    else:
        print('Log is empty')