Exemplo n.º 1
0
def update_market(cid, crypto, pair, market, market_name, platform):
    account = get_settings(cid)
    account.current_crypto = crypto
    account.current_pair = pair
    account.current_market = market
    account.current_market_name = market_name
    account.current_platform = platform
    system('sql').session.commit()
Exemplo n.º 2
0
def get_settings(cid):
    try:
        system('sql').session.expire_all()
        return system('sql').session.query(Account).filter(
            Account.id == cid).one()
    except Exception as e:
        system('sql').session.rollback()
        print("Error al consultar datos de la cuenta")
        print(e)
    return None
Exemplo n.º 3
0
def get_groups():
    try:
        system('sql').session.expire_all()
        return system('sql').session.query(Account).filter(
            Account.is_group == 1, Account.is_verified == 1).all()
    except Exception as e:
        system('sql').session.rollback()
        print("Error al consultar grupos activos")
        print(e)
    return None
Exemplo n.º 4
0
def get_binance_symbol_data(symbol,
                            kline_size,
                            save=False,
                            sma=None,
                            auto_increment=True):
    if sma is None:
        form = 'all'
        data_df = get_data_frame(symbol, kline_size, form='all')
        klines = get_klines_times(symbol, kline_size, data_df)
    else:
        form = 'sma-%s' % sma
        data_df = get_data_frame(symbol, kline_size, form=form)
        if data_df.shape[0] < sma or auto_increment is False:
            oldest_point = (datetime.now() -
                            timedelta(days=sma)).strftime("%d %b %Y %H:%M:%S")
            newest_point = pd.to_datetime(
                system('algorithms').client.get_klines(
                    symbol=symbol, interval=kline_size)[-1][0],
                unit='ms').strftime("%d %b %Y %H:%M:%S")
            # print(oldest_point, newest_point)
            klines = system('algorithms').client.get_historical_klines(
                symbol=symbol,
                interval=kline_size,
                start_str=oldest_point,
                end_str=newest_point)
        else:
            klines = get_klines_times(symbol, kline_size, data_df)

    data = pd.DataFrame(klines,
                        columns=[
                            'timestamp', 'open', 'high', 'low', 'close',
                            'volume', 'close_time', 'quote_av', 'trades',
                            'tb_base_av', 'tb_quote_av', 'ignore'
                        ])
    # print(len(data.index))

    data.drop(
        ['close_time', 'ignore', 'tb_base_av', 'quote_av', 'tb_quote_av'],
        axis='columns',
        inplace=True)

    data['timestamp'] = pd.to_datetime(data['timestamp'], unit='ms')

    data['time'] = data['timestamp']
    data.set_index('timestamp', inplace=True, drop=False)

    convert_columns_to_float(
        data, ['open', 'high', 'low', 'close', 'volume', 'trades'])

    data_df = merge_df(data_df, data, auto_increment)

    if save:
        save_extracted_data(symbol, kline_size, data_df, form=form)
    # print(data_df.shape)
    return data_df
Exemplo n.º 5
0
def symbol_info(crypto, ref, exchange='BINANCE'):
    data = {}
    if exchange == 'BINANCE':
        info = system('algorithms').client.get_symbol_info(crypto + ref)
        data['min_quantity'] = float(info['filters'][2]['minQty'])
        data['max_quantity'] = float(info['filters'][2]['maxQty'])
        data['min_notional'] = float(info['filters'][3]['minNotional'])
        data['crypto_quantity'] = system(
            'algorithms').client.get_asset_balance(asset=crypto).get('free')
        data['ref_quantity'] = system('algorithms').client.get_asset_balance(
            asset=ref).get('free')
    return data
Exemplo n.º 6
0
def get_klines(symbol, kline_size, data_df):
    oldest_point, newest_point = minutes_of_new_data(symbol,
                                                     kline_size,
                                                     data_df,
                                                     source="algorithms")
    delta_min = (newest_point - oldest_point).total_seconds() / 60
    available_data = math.ceil(delta_min /
                               system('algorithms').sizes[kline_size])
    print(oldest_point, newest_point, available_data)
    return system('algorithms').client.get_historical_klines(
        symbol=symbol,
        interval=kline_size,
        start_str=oldest_point.strftime("%d %b %Y %H:%M:%S"),
        end_str=newest_point.strftime("%d %b %Y %H:%M:%S"))
Exemplo n.º 7
0
def minutes_of_new_data(symbol, kline_size, data, source):
    global old, new
    if len(data) > 0:
        old = parser.parse(data["timestamp"].iloc[-1])
    elif source == "algorithms":
        old = datetime.strptime('1 Jan 2021', '%d %b %Y')
    if source == "algorithms":
        new = pd.to_datetime(system('algorithms').client.get_klines(
            symbol=symbol, interval=kline_size)[-1][0],
                             unit='ms')
    return old, new
Exemplo n.º 8
0
def get_binance_klines_times(symbol,
                             kline_size,
                             data,
                             old_date=None,
                             new_date=None):
    try:
        if old_date is None or new_date is None:
            old_date = (pd.to_datetime(data.iloc[-1:].timestamp.item()) +
                        timedelta(minutes=1)).strftime("%d %b %Y %H:%M:%S")
            new_date = pd.to_datetime(system('algorithms').client.get_klines(
                symbol=symbol, interval=kline_size)[-1][0],
                                      unit='ms').strftime("%d %b %Y %H:%M:%S")

        # print(old_date, new_date)

        return system('algorithms').client.get_historical_klines(
            symbol=symbol,
            interval=kline_size,
            start_str=old_date,
            end_str=new_date)
    except:
        print('Error de extracción, reintentando')
        return None
Exemplo n.º 9
0
def update_settings(cid, name, verified, group):
    try:
        account = Account(cid, name)
        account.is_verified = verified
        account.is_group = group
        system('sql').session.merge(account)
        system('sql').session.commit()
    except Exception as e:
        system('sql').session.rollback()
        print("Error al guardar datos del usuario")
        print(e)
Exemplo n.º 10
0
def create_order(symbol, quantity, price, operation='BUY'):
    order = None
    side = None
    if operation == 'BUY':
        side = SIDE_BUY
    if operation == 'SELL':
        side = SIDE_SELL
    try:
        order = system('binance').client.create_order(
            symbol=symbol,
            side=side,
            type=ORDER_TYPE_LIMIT,
            timeInForce=TIME_IN_FORCE_GTC,
            quantity=quantity,
            price=price)
    except BinanceAPIException as e:
        print(e)
    return order, order.get('orderId')
Exemplo n.º 11
0
    def __init__(self,
                 crypto,
                 ref,
                 configuration,
                 temporalities,
                 indicators,
                 trade,
                 effectivity,
                 result_indicators,
                 exchange='BINANCE'):
        self.client = system('algorithms').client
        self.symbol = crypto + ref
        self.crypto = crypto
        self.ref = ref
        self.exchange = exchange

        # Default Values
        self.max_min = None
        self.order_status = None
        self.order = None
        self.process_is_started = False
        self.first_iteration = False
        self.trade_type = 'micro'
        self.operative = False

        # Settings
        self.strategy = strategy_selector[os.environ["strategy"]]
        self.configuration = configuration
        self.indicators = indicators
        self.result_indicators = result_indicators
        self.trade = trade
        self.effectivity = effectivity
        self.temporalities = temporalities

        self.testing = []
        self.chat_ids = []
Exemplo n.º 12
0
def cancel_order(symbol, order):
    order_id = order.get('orderId')
    cancel = system('binance').client.cancel_order(symbol=symbol,
                                                   orderId=order_id)
    return cancel