Example #1
0
def main():

    try:
        market = sys.argv[1]
    except IndexError:
        market = 'not a currency pair'

    if market not in constants.MARKETS:
        while True:
            market = str(
                input(
                    "Please specify which currency pair to use (btcusd, ltcusd, etc)."
                ))
            if market in constants.MARKETS:
                break

    running = True

    md = MarketDataInterface(market)
    ts = TradingStrategy(market)
    om = OrderManager(market)

    while running:
        action = ts.get_final_strategy()
        price = (md.get_ticker_data(False))['value']
        order_details = om.get_order_status(id)

        if action['action'] == "buy":
            result = om.buy(pair=market, risk=action['risk'], price=price)
            order_details = om.get_order_status(result)
            if result[0]:
                logging.info('Successfully bought {0}{1} at {2}{3}'.format(
                    order_details['actual_amount'], market[:3],
                    order_details['actual_end_price'], market[-3:]))
            else:
                logging.info('Buy failed')

        elif action['action'] == "sell":
            result = om.sell(pair=market, risk=action['risk'], price=price)
            order_details = om.get_order_status(result)
            if result:
                logging.info('Successfully sold {0}{1} at {2}{3}'.format(
                    order_details['amount'], market[:3],
                    order_details['price'], market[-3:]))
            else:
                logging.info('Sell failed')

        elif action['action'] == "wait":
            logging.info('Waited {}s, did not trade'.format(
                settings.MAIN_TIMER))

        else:
            running = False
            logging.error('Unsupported action')

        time.sleep(settings.MAIN_TIMER)
        if not running:
            print('order error')
Example #2
0
def main():

    parser = argparse.ArgumentParser()
    parser.add_argument('market',
                        type=str,
                        choices=constants.MARKETS,
                        help='currency pair - btcusd, ltcusd, etc')
    market = (parser.parse_args()).market

    logging.info('the market {} was chosen'.format(market))

    ts = TradingStrategy(market)
    om = OrderManager(market)
    md = MarketDataInterface(market)

    running = True

    while running:
        action = ts.get_final_strategy()
        price = Decimal(str((md.get_ticker_data(False))[3]))

        time = datetime.datetime.now()
        if abs((time - datetime.datetime.strptime(
                md.get_ticker_data(False)[2],
                '%Y-%m-%d %H:%M:%S')).seconds) > 600:
            logging.error('database is out of date, exiting')
            running = False

        balance = om.get_balance()
        if None in balance.values():
            logging.info('failed to get account balance')

        try:
            if action['action'] == 'buy':
                amount = (Decimal(str(action['risk'])) *
                          Decimal(balance['second_available']) / price)
            elif action['action'] == 'sell':
                amount = (Decimal(str(action['risk'])) *
                          Decimal(balance['available']))
            else:
                amount = Decimal('0')
        except TypeError:
            logging.exception('could not determine amount')
            amount = Decimal('0')

        if action['action'] in ['buy', 'sell']:
            if market[-3:] in ['usd', 'eur']:
                if (amount * price) < constants.EUR_USD_MIN_TRANSACTION_SIZE:
                    action['action'] = 'wait'
                    amount = Decimal('0')
                    logging.info(
                        'do not have minimum amount ({}) to trade'.format(
                            constants.EUR_USD_MIN_TRANSACTION_SIZE))
                price = price.quantize(Decimal('.01'))

                if market[:3] in ['xrp', 'usd', 'eur']:
                    amount = amount.quantize(Decimal('.00001'))
                else:
                    amount = amount.quantize(Decimal('.00000001'))

            elif market[-3:] == 'btc':
                if (amount * price) < constants.BTC_MIN_TRANSACTION_SIZE:
                    action['action'] = 'wait'
                    amount = Decimal('0')
                    logging.info(
                        'do not have minimum amount ({}) to trade'.format(
                            constants.BTC_MIN_TRANSACTION_SIZE))
                price = price.quantize(Decimal('.00000001'))

        if action['action'] == 'buy':
            sleep(1)
            order_id = om.buy(price=price, amount=amount)
            if order_id:
                logging.info(
                    'successfully bought {amount}{currency_one} at {price}{currency_two} each'
                    .format(amount=amount,
                            currency_one=market[:3],
                            price=price,
                            currency_two=market[-3:]))

        elif action['action'] == 'sell':
            sleep(1)
            order_id = om.sell(price=price, amount=amount)
            if order_id:
                logging.info(
                    'successfully sold {amount}{currency_one} at {price}{currency_two} each'
                    .format(amount=amount,
                            currency_one=market[:3],
                            price=price,
                            currency_two=market[-3:]))

        elif action['action'] == 'wait':
            logging.info('waiting {}s, did not trade'.format(
                settings.MAIN_TIMER))

        else:
            running = False
            logging.error(
                'exiting trader - unsupported action (supported actions: buy, sell, wait), {}'
                .format(action))

        sleep(1)
        open_orders = om.get_open_orders()
        if open_orders:
            for order in open_orders:
                time = datetime.datetime.now().timestamp()
                sleep(1)
                if datetime.datetime.strptime(
                        order['datetime'],
                        '%Y-%m-%d %H:%M:%S').timestamp() < time - 21600:
                    om.cancel_order(order['id'])

        sleep(settings.MAIN_TIMER)
        logging.info('waited {}s to trade again'.format(settings.MAIN_TIMER))
            order_history[stock] = order_manager.cover(
                diff_value + current_price, stock, date)
            print(
                'Covered some of %s because its value exceeds 5%% of portfolio'
                % stock)
            new_comp = 100.0 * my_account.get_position_value(
                stock, date) / account_value
            print('New % of portfolio for {}: {:.3}'.format(stock, new_comp))

    # Buy stock new to undervalued list
    long_positions = my_account.get_long_positions()
    for stock in new_undervalued.index:
        if stock not in long_positions.index:
            account_value = my_account.get_account_value(date)
            five_percent_account = .05 * account_value
            order_history[stock] = order_manager.buy(five_percent_account,
                                                     stock, date)
            print('Bought %s because it is now on the undervalued list' %
                  stock)

    # Buy more of stock on undervalue list that is below 5% of account value
    long_positions = my_account.get_long_positions()
    for stock in long_positions.index:
        account_value = my_account.get_account_value(date)
        five_percent_account = .05 * account_value
        current_price = quote_manager.get_quote(stock, date)
        value = abs(my_account.get_position_value(stock, date))
        diff_value = five_percent_account - value
        if diff_value > current_price:
            order_history[stock] = order_manager.buy(diff_value, stock, date)
            print(
                'Bought some more of %s because its value falls below 5%% of portfolio'