Exemplo n.º 1
0
def buy_coin(symbol, length, file_number):

    # if (symbol['symbol'] == 'ETHBTC') and (time.localtime().tm_min%2 == 0 and time.localtime().tm_sec == 1 or time.localtime().tm_sec == 2):
    #     print('buy_coin() still alive', symbol['symbol'], get_time())

    # if time.localtime().tm_min == 2:
    #     print("started buy coin ", symbol['symbol'], get_time())
    #     order_book = pickle_read('/home/ec2-user/environment/botfarming/Development/recent_order_books/'+symbol['symbol'] +'.pklz')
    #     try:
    #         print("current price:", order_book['bids'][0][0], symbol['symbol'], get_time())
    #     except Exception as e:
    #         print('symbol does not have a price:', symbol['symbol'])
    #         print(e)

    api_key = '41EwcPBxLxrwAw4a4W2cMRpXiQwaJ9Vibxt31pOWmWq8Hm3ZX2CBnJ80sIRJtbsI'
    api_secret = 'pnHoASmoe36q54DZOKsUujQqo4n5Ju25t5G0kBaioZZgGDOQPEHqgDDPA6s5dUiB'
    client = Client(api_key, api_secret)

    current_state = load_current_state(symbol['symbol'], file_number, length)

    if isinstance(current_state, dict):
        print('loading state to sell coin..', current_state['symbol'])
        buy_coin_from_state(current_state)
        return

    try:

        minutes = 300

        largest_bitcoin_order = .1
        part_of_bitcoin_to_use = .5
        price_to_start_buy_factor = 1.003

        sell_price_drop_factor = .997
        buy_price_increase_factor = 1.002

        price_to_buy_factor_array = [
            0, .977, .969, .973, .965, .962, .96, .958, .95, .956, .95
        ]
        price_to_sell_factor_array = [
            0, .977, .969, .973, .965, .962, .96, .958, .95, .956, .95
        ]
        lower_band_buy_factor_array = [
            0, 1.01, 1.15, 1.09, 1.055, 1.09, 1.12, 1.15, 1.16, 1.19, 1.19
        ]
        price_increase_factor_array = [
            0, 1.021, 1.021, 1.021, 1.021, 1.021, 1.021, 1.021, 1.021, 1.021,
            1.021
        ]

        minutes_until_sale = 2 * 300

        minutes_until_sale_final = 4 * 300

        datapoints_trailing = 4

        look_back_schedule = [1, 2, 4]
        look_back_gains = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        look_back_wins = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        look_back_losses = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        max_look_back_gain = 0

        a_b = random.randint(0, 1)

        should_trade = False

        for look_back in look_back_schedule:

            look_back_optimized = pickle_read(
                '/home/ec2-user/environment/botfarming/Development/optimization_factors/VLong_optimal_for_'
                + symbol['symbol'] + '_' + str(look_back) + '.pklz')

            if look_back_optimized != False:
                price_to_buy_factor_array[look_back] = look_back_optimized[
                    'optimal_buy_factor']
                price_to_sell_factor_array[look_back] = look_back_optimized[
                    'optimal_sell_factor']
                lower_band_buy_factor_array[look_back] = look_back_optimized[
                    'optimal_band_factor']
                price_increase_factor_array[look_back] = look_back_optimized[
                    'optimal_increase_factor']
                price_increase_factor_array[look_back] = 1.01
                look_back_gains[look_back] = look_back_optimized['gain']
                look_back_wins[look_back] = look_back_optimized['wins']
                look_back_losses[look_back] = look_back_optimized['losses']
                if look_back_gains[look_back] > max_look_back_gain:
                    max_look_back_gain = look_back_gains[look_back]
            else:
                #print('No trading parameters for', symbol['symbol'], 'look_back', look_back)
                time.sleep(60 * 1)
                return

        if max_look_back_gain <= 0:
            #print('This symbol has bad or no results and we should not trade on it ', symbol['symbol'], 'max_look_back_gain', max_look_back_gain)
            time.sleep(1 * 60)
            return

        while time.localtime().tm_sec < 3:
            time.sleep(.1)

        data = []

        end_time = int(time.time()) * 1000
        start_time = (end_time - 60 * 1000 * minutes *
                      (datapoints_trailing + 1))
        url = 'https://api.binance.com/api/v1/klines?symbol=' + symbol[
            'symbol'] + '&interval=' + length + '&startTime=' + str(
                start_time) + '&endTime=' + str(end_time)
        #print(url)
        data = requests.get(url).json()

        if isinstance(data, basestring):
            print('API request failed, exiting', symbol['symbol'])
            return

        trailing_volumes = []
        trailing_movement = []
        trailing_lows = []
        trailing_highs = []
        trailing_candles = []
        for index, candle in enumerate(data):
            if len(trailing_movement) >= datapoints_trailing:
                break
            trailing_volumes.append(
                float(candle[7]
                      ))  # 5 is symbol volume, 7 is quote asset volume (BTC)
            trailing_movement.append(abs(float(candle[4]) - float(candle[1])))
            trailing_highs.append(float(candle[2]))
            trailing_lows.append(float(candle[3]))
            trailing_candles.append(candle)

        while time.localtime().tm_sec < 1 or time.localtime().tm_sec > 2:

            order_book = get_order_book_local(symbol['symbol'])

            # if (symbol['symbol'] == 'ETHBTC'):
            #     print(symbol['symbol'],'time since orderbook update', int(time.time()) - order_book['time'])

            if int(time.time()) - order_book['time'] > 30:
                time.sleep(1)
                continue

            time.sleep(.3)
            current_price = float(order_book['bids'][0][0])

            # if (symbol['symbol'] == 'ETHBTC'):
            #     print('about to check lookback', symbol['symbol'], 'current_price',  current_price, get_time())

            for look_back in look_back_schedule:

                if look_back_wins[look_back] + look_back_losses[
                        look_back] < 3 or look_back_gains[look_back] / (
                            look_back_wins[look_back] +
                            look_back_losses[look_back]) < .05:
                    continue

                price_to_start_buy = float(
                    data[index - look_back][4]) * price_to_buy_factor_array[
                        look_back] * price_to_start_buy_factor

                if current_price <= price_to_start_buy:

                    should_buy = False

                    if lower_band_buy_factor_array[look_back] < 100:
                        candles_for_look_back = fn.get_n_minute_candles(
                            look_back, data[index - 22 * look_back - 1:index])
                        candles_for_look_back, smart_trailing_candles = fn.add_bollinger_bands_to_candles(
                            candles_for_look_back)
                        lower_band_for_index = candles_for_look_back[-1][14]
                        band_ok_value = lower_band_for_index * lower_band_buy_factor_array[
                            look_back]
                        band_ok = current_price < band_ok_value

                    else:
                        band_ok = True

                    if band_ok:
                        should_buy = True

                    if should_buy:

                        lower_band_buy_factor = lower_band_buy_factor_array[
                            look_back]
                        price_to_buy_factor = price_to_buy_factor_array[
                            look_back]
                        price_to_sell_factor = price_to_sell_factor_array[
                            look_back]
                        price_increase_factor = price_increase_factor_array[
                            look_back]

                        if lower_band_buy_factor < 100:
                            price_to_buy = min(
                                lower_band_for_index * lower_band_buy_factor,
                                float(data[index - look_back][4]) *
                                price_to_buy_factor)
                        else:
                            price_to_buy = float(
                                data[index -
                                     look_back][4]) * price_to_buy_factor

                        print('-------------------buy!', symbol['symbol'],
                              'look_back', look_back, 'price', price_to_buy,
                              'price_to_buy_factor',
                              price_to_buy_factor_array[look_back],
                              'price_to_sell_factor',
                              price_to_sell_factor_array[look_back],
                              'price_increase_factor',
                              price_increase_factor_array[look_back],
                              minutes_until_sale, 'look_back_gain',
                              look_back_gains[look_back], 'look_back_wins',
                              look_back_wins[look_back], 'look_back_losses',
                              look_back_losses[look_back], get_time())

                        if lower_band_buy_factor < 100:
                            price_to_buy = min(
                                lower_band_for_index * lower_band_buy_factor,
                                float(data[index - look_back][4]) *
                                price_to_buy_factor)
                        else:
                            price_to_buy = float(
                                data[index -
                                     look_back][4]) * price_to_buy_factor

                        price_to_sell = float(
                            data[index - look_back][4]) * price_to_sell_factor

                        amount_to_buy = part_of_bitcoin_to_use / price_to_buy
                        largest_buy_segment = largest_bitcoin_order / price_to_buy

                        price_decimals = get_min_decimals(
                            symbol['filters'][0]['minPrice'])

                        quantity_decimals = get_min_decimals(
                            symbol['filters'][1]['minQty'])
                        # quantity_decimals = get_min_decimals_new(symbol['filters'][2]['minNotional'])

                        current_state = {}
                        current_state['state'] = 'buying'
                        current_state['look_back'] = look_back
                        current_state['a_b'] = a_b
                        current_state['look_back_gains'] = look_back_gains[
                            look_back]
                        current_state['look_back_wins'] = look_back_wins[
                            look_back]
                        current_state['look_back_losses'] = look_back_losses[
                            look_back]
                        current_state[
                            'price_to_buy_factor'] = price_to_buy_factor
                        current_state[
                            'price_to_sell_factor'] = price_to_sell_factor
                        current_state[
                            'sell_price_drop_factor'] = sell_price_drop_factor
                        current_state['original_amount_to_buy'] = amount_to_buy
                        current_state[
                            'largest_bitcoin_order'] = largest_bitcoin_order
                        current_state[
                            'part_of_bitcoin_to_use'] = part_of_bitcoin_to_use
                        current_state[
                            'largest_buy_segment'] = largest_buy_segment
                        current_state['original_buy_time'] = int(time.time())
                        current_state['original_buy_time_readable'] = get_time(
                        )
                        current_state['symbol'] = symbol['symbol']
                        current_state['orderId'] = False
                        current_state['executedQty'] = 0
                        current_state['total_revenue'] = 0
                        current_state[
                            'minutes_until_sale'] = minutes_until_sale
                        current_state[
                            'minutes_until_sale_final'] = minutes_until_sale_final
                        current_state['price_to_buy'] = price_to_buy
                        current_state['price_to_sell'] = price_to_sell
                        current_state['compare_price'] = price_to_buy
                        current_state[
                            'price_increase_factor'] = price_increase_factor
                        current_state['minimum_price_seen'] = price_to_buy
                        current_state['length'] = length
                        current_state['file_number'] = str(file_number)
                        current_state['client'] = client
                        current_state['error_cancel_order'] = False
                        current_state['price_decimals'] = price_decimals
                        current_state['quantity_decimals'] = quantity_decimals
                        current_state['min_price'] = float(
                            symbol['filters'][0]['minPrice'])
                        current_state['min_quantity'] = min(
                            float(symbol['filters'][1]['minQty']),
                            float(symbol['filters'][2]['minNotional']))

                        pickle_write(
                            '/home/ec2-user/environment/botfarming/Development/program_state_'
                            + length + '/program_state_' + length + '_' +
                            str(file_number) + '_' + symbol['symbol'] +
                            '_3.pklz', current_state,
                            '******could not write state******')

                        time_to_give_up = int(time.time()) + 60 * 10
                        price_to_buy_max = price_to_buy * buy_price_increase_factor
                        amount_to_stop_buying = part_of_bitcoin_to_use / price_to_buy_max
                        print('max price for', symbol['symbol'],
                              price_to_buy_max)
                        while True:
                            if current_state['orderId'] != False:
                                buy_order_info = current_state[
                                    'client'].get_order(
                                        symbol=current_state['symbol'],
                                        orderId=current_state['orderId'])
                                if buy_order_info['status'] == 'FILLED':
                                    current_state[
                                        'executedQty'] = current_state[
                                            'executedQty'] + float(
                                                buy_order_info['executedQty'])
                                    current_state['original_price'] = float(
                                        buy_order_info['price'])
                                    current_state['state'] = 'buying'
                                    current_state['orderId'] = False
                                    pickle_write(
                                        '/home/ec2-user/environment/botfarming/Development/program_state_'
                                        + current_state['length'] +
                                        '/program_state_' +
                                        current_state['length'] + '_' +
                                        current_state['file_number'] + '_' +
                                        current_state['symbol'] + '_3.pklz',
                                        current_state,
                                        '******could not write state 2nd sell******'
                                    )
                                    if current_state[
                                            'executedQty'] >= amount_to_stop_buying:
                                        break

                            if int(time.time()) >= time_to_give_up:
                                if current_state['orderId'] != False:
                                    current_state = cancel_buy_order(
                                        current_state)
                                break

                            first_in_line_price, first_bid, second_in_line_price, second_bid, second_price_to_check = get_first_in_line_price_buying(
                                current_state)
                            if float(first_in_line_price) > price_to_buy_max:
                                if current_state['orderId'] != False:
                                    current_state = cancel_buy_order(
                                        current_state)
                                    if current_state[
                                            'executedQty'] >= amount_to_stop_buying:
                                        break
                            else:
                                if current_state['orderId'] != False:
                                    buy_order_info = current_state[
                                        'client'].get_order(
                                            symbol=current_state['symbol'],
                                            orderId=current_state['orderId'])
                                    if first_bid != float(
                                            buy_order_info['price']):
                                        current_state = cancel_buy_order(
                                            current_state)
                                        if current_state[
                                                'executedQty'] >= amount_to_stop_buying:
                                            break
                                        current_state = create_buy_order(
                                            current_state, first_in_line_price)
                                    else:
                                        if second_price_to_check > second_bid:
                                            current_state = cancel_buy_order(
                                                current_state)
                                            if current_state[
                                                    'executedQty'] >= amount_to_stop_buying:
                                                break
                                            current_state = create_buy_order(
                                                current_state,
                                                second_in_line_price)

                                else:
                                    current_state = create_buy_order(
                                        current_state, first_in_line_price)

                            if current_state['orderId'] != False:
                                time.sleep(5)
                            else:
                                time.sleep(.03)

                        if current_state['executedQty'] < current_state[
                                'min_quantity']:
                            print(
                                '[last line reached] no one bought cancel order - freeing coin',
                                current_state['symbol'], get_time())
                            pickle_write(
                                '/home/ec2-user/environment/botfarming/Development/program_state_'
                                + length + '/program_state_' + length + '_' +
                                str(file_number) + '_' + symbol['symbol'] +
                                '_3.pklz', False,
                                '******could not write state inside buy coin - no one bought coin******'
                            )
                            return True

                        current_state['original_quantity'] = current_state[
                            'executedQty']
                        current_state['state'] = 'selling'
                        pickle_write(
                            '/home/ec2-user/environment/botfarming/Development/program_state_'
                            + current_state['length'] + '/program_state_' +
                            current_state['length'] + '_' +
                            current_state['file_number'] + '_' +
                            current_state['symbol'] + '_3.pklz', current_state,
                            '******could not update state to selling******')

                        coin_sold = sell_coin_with_order_book_use_min(
                            current_state)

                        if coin_sold:
                            print('finished order - freeing coin',
                                  current_state['symbol'])
                            print('#########################')

                            return True

                        return False

    except Exception as e:
        print('some error - freeing coin:', symbol['symbol'])
        print(e)
        print_exception()
        time.sleep(60 * 4)
        return False
                                current_look_back = 0
                                for look_back in look_back_schedule:

                                    compare_price = float(data[index -
                                                               look_back][4])
                                    buy_price = compare_price * price_to_buy_factor_array[
                                        look_back]

                                    if float(candle[3]) < buy_price:

                                        # print('symbol,', symbol['symbol'])

                                        if lower_band_buy_factor_array[
                                                look_back] < 100:
                                            candles_for_look_back = fn.get_n_minute_candles(
                                                look_back,
                                                data[index - 22 * look_back -
                                                     1:index])
                                            candles_for_look_back, smart_trailing_candles = fn.add_bollinger_bands_to_candles(
                                                candles_for_look_back)
                                            lower_band_for_index = candles_for_look_back[
                                                -1][14]
                                            #print('lower_band_for_index', lower_band_for_index)
                                            band_ok_value = lower_band_for_index * lower_band_buy_factor_array[
                                                look_back]
                                            band_ok = float(
                                                candle[3]) < band_ok_value
                                        else:
                                            band_ok = True

                                        if band_ok:
                                            #print(symbol['symbol'])
Exemplo n.º 3
0
            current_gain = 0

            current_movement_win = []
            current_movement_loss = []

            percentage_made_win = []
            percentage_made_loss = []

            for s in symbols_trimmed:
                symbol = symbols_trimmed[s]

                data = ut.pickle_read(
                    '/home/ec2-user/environment/botfarming/Development/binance_training_data/'
                    + day + '/' + symbol['symbol'] + '_data_' + str(1) +
                    'm_p' + str(step_back) + '.pklz')
                data = fn.get_n_minute_candles(minutes, data)

                if not data:
                    continue

                trailing_closes = []
                trailing_volumes = []
                trailing_movement = []
                trailing_lows = []
                trailing_highs = []

                first = True
                sale_time = 0
                for index, candle in enumerate(data):

                    #if float(candle[0]) < float(sale_time):