Ejemplo n.º 1
0
def cancel_limit_order(symbol, side, order_id, marker):
    try:
        remove_orders_info('Binance', order_id)
        order = BINANCE.cancel_order(symbol=symbol, orderId=order_id)
        to_general_log(symbol, '{} Limit order canceled ({}) > {}'.format(side, marker, json.dumps(order)))
    except:
        pass
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 launch(symbol):
    try:
        precision = get_precision(symbol)
        pip = get_pip(symbol)
        price_precision = len(
            '{0:.10f}'.format(pip).split('.')[1].split('1')[0]) + 1

        to_general_log(symbol, 'Start monitoring')

        while is_allowed(symbol):
            ma8 = get_ma_value(symbol, '5M', 8)
            ma21 = get_ma_value(symbol, '5M', 21)

            current_candle_open = float(get_current_candle(symbol, '5M')[1])
            current_candle_close = float(get_current_candle(symbol, '5M')[4])

            # looking for BUY signal
            if ma21 < ma8 < min(current_candle_open,
                                current_candle_close) and check_anchor_chart(
                                    symbol, 'buy'):

                # waiting trigger bar for BUY
                while True:
                    current_candle = get_current_candle(symbol, '5M')
                    current_candle_close = float(current_candle[4])
                    ma8 = get_ma_value(symbol, '5M', 8)

                    if current_candle_close < ma8:
                        entrance_point = round(
                            last_bars_extremum(symbol, 5, 'buy') + (30 * pip),
                            price_precision)

                        place_pending_order(symbol, 'buy', entrance_point,
                                            precision, price_precision)
                        break

            # looking for SELL signal
            if ma21 > ma8 > max(current_candle_open,
                                current_candle_close) and check_anchor_chart(
                                    symbol, 'sell'):

                # waiting trigger bar for SELL
                while True:
                    current_candle = get_current_candle(symbol, '5M')
                    current_candle_open = float(current_candle[1])
                    ma8 = get_ma_value(symbol, '5M', 8)

                    if current_candle_open > ma8:
                        entrance_point = round(
                            last_bars_extremum(symbol, 5, 'sell') - (30 * pip),
                            price_precision)

                        place_pending_order(symbol, 'sell', entrance_point,
                                            precision, price_precision)
                        break

            time.sleep(1)
    except:
        to_err_log(symbol, traceback.format_exc())
Ejemplo n.º 4
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...')
Ejemplo n.º 5
0
def launch(symbol):
    try:
        precision = get_precision(symbol)
        pip = get_pip(symbol)
        price_precision = len(
            '{0:.10f}'.format(pip).split('.')[1].split('1')[0]) + 1

        to_general_log(symbol, 'Start monitoring')

        while is_allowed(symbol):

            # looking for BUY signal
            if get_price_change_percent_difference(symbol) > 2:
                place_pending_order(symbol, 'buy', precision, price_precision)
                break

            # looking for SELL signal
            if get_price_change_percent_difference(symbol) > 2:
                place_pending_order(symbol, 'sell', precision, price_precision)
                break

            time.sleep(1)
    except:
        to_err_log(symbol, traceback.format_exc())
Ejemplo n.º 6
0
def place_market_order(symbol, side, quantity, marker):
    if quantity is None:
        to_general_log(symbol, 'ERROR Qty is NONE')
        return
    if side == 'buy':
        order = BINANCE.order_market_buy(symbol=symbol, quantity=quantity, recvWindow=10000000)
        to_general_log(symbol, '{} Market order placed ({}) > {}'.format(side, marker, json.dumps(order)))
        return order
    else:
        order = BINANCE.order_market_sell(symbol=symbol, quantity=quantity, recvWindow=10000000)
        to_general_log(symbol, '{} Market order placed ({}) > {}'.format(side, marker, json.dumps(order)))
        return order
Ejemplo n.º 7
0
def place_pending_order(symbol, signal_side, entrance_point, precision, price_precision):
    try:
        global signal_number
        signal_id = '{}_{}'.format(symbol.lower(), signal_number)

        while True:
            if is_cancel(symbol, signal_side):
                break

            # entrance point monitoring
            if is_entrance(symbol, signal_side, entrance_point):
                # signal_side = get_opposite_side(signal_side)

                if signal_side == 'buy':
                    stop_loss = round(entrance_point * (1 - (PERCENT_SL / 100)), price_precision)
                    take_profit = round(entrance_point * (1 + (PERCENT_TP / 100)), price_precision)
                else:
                    stop_loss = round(entrance_point * (1 + (PERCENT_SL / 100)), price_precision)
                    take_profit = round(entrance_point * (1 - (PERCENT_TP / 100)), price_precision)

                new_signal_report(symbol, signal_side.upper(), entrance_point, stop_loss, take_profit)

                quantity = get_quantity(symbol, signal_side)
                if quantity is None:
                    return
                open_order = place_market_order(symbol, signal_side, quantity, 'Entry')
                signal_number += 1
                save_trade('{}_SIGNAL'.format(signal_side.upper()), signal_id, open_order, 'Entry')
                cumulative_quote_qty = float(open_order['cummulativeQuoteQty'])
                order_side = get_opposite_side(signal_side)

                current_sl_order = 0
                current_tp_order = 0

                while True:

                    # stop loss monitoring
                    if is_close_to_stop_loss(symbol, signal_side, entrance_point, stop_loss, 80):
                        if current_sl_order == 0:

                            # cancel existed TP order
                            if current_tp_order != 0:
                                cancel_limit_order(symbol, order_side, current_tp_order['orderId'], 'TakeProfit')

                            # place SL limit order
                            if execute_stop_loss(symbol, signal_side):
                                qty = get_qty(symbol, signal_side, quantity, cumulative_quote_qty, stop_loss, precision)
                                to_general_log(symbol, 'get_qty: qty {}'.format(qty))

                                current_sl_order = place_limit_order(symbol, order_side, qty, stop_loss, 'StopLoss')
                            # else:
                            #     to_general_log(symbol, 'Skip stop loss for buy signal')

                        elif is_order_filled('Binance', current_sl_order['orderId']):
                            remove_orders_info('Binance', current_sl_order['orderId'])
                            to_general_log(symbol, '{} Limit order filled (StopLoss)'.format(order_side))
                            save_trade('{}_SIGNAL'.format(signal_side.upper()), signal_id, current_sl_order, 'SL')
                            break

                            # take profit monitoring
                    if is_close_to_take_profit(symbol, signal_side, entrance_point, take_profit, 80):
                        if current_tp_order == 0:

                            # cancel existed SL order
                            if current_sl_order != 0:
                                cancel_limit_order(symbol, order_side, current_sl_order['orderId'], 'StopLoss')

                            # place TP limit order
                            qty = get_qty(symbol, signal_side, quantity, cumulative_quote_qty, take_profit, precision)
                            to_general_log(symbol, 'get_qty: qty {}'.format(qty))

                            current_tp_order = place_limit_order(symbol, order_side, qty, take_profit, 'TakeProfit')

                        elif is_order_filled('Binance', current_tp_order['orderId']):
                            remove_orders_info('Binance', current_tp_order['orderId'])
                            to_general_log(symbol, '{} Limit order filled (TakeProfit)'.format(order_side))
                            save_trade('{}_SIGNAL'.format(signal_side.upper()), signal_id, current_tp_order, 'TP')
                            break
                    time.sleep(0.3)
                break
            time.sleep(.1)
    except:
        to_general_log(symbol, traceback.format_exc())
Ejemplo n.º 8
0
def new_signal_report(symbol, side, entrance_point, stop_loss, take_profit):
    text = 'NEW SIGNAL > {} {} at {}, SL: {}, TP: {}'.format(side, symbol, entrance_point, stop_loss, take_profit)
    to_general_log(symbol, text)
Ejemplo n.º 9
0
def on_error(ws, error):
    to_general_log('wsBinance1', f'{error}')