Ejemplo n.º 1
0
def trading_history(market_name, market_id):
    interval = timedelta(days=1, hours=4)

    cryptsy_mongo = CryptsyMongo(host="192.168.1.33")

    timeStart = datetime.utcnow() - interval
    trades = cryptsy_mongo.trades_collection.find(
        {"marketid": str(market_id), "datetime": {"$gt": timeStart.strftime("%Y-%m-%d %H:%M:%S")}}).sort('datetime', -1)

    for trade in trades:
        print "{} - {}({}) - {} {} at {} - total: {}".format(datetime.strptime(trade['datetime'], '%Y-%m-%d %H:%M:%S'),
                                                             market_name, market_id, trade['tradetype'],
                                                             toEightDigit(float(trade['quantity'])),
                                                             toEightDigit(float(trade['tradeprice'])),
                                                             toEightDigit(float(trade['total'])))
def getSellPrice(market_trend):
    actual_estimated_price = cryptsy_mongo.getNormalizedEstimatedPrice(market_trend)

    if market_trend.m > 0.5:
        last_buy_trade = next(cryptsy_mongo.getLastTradeFor(market_id=market_trend.marketId, trade_type="Buy"))
        trade_price = float(last_buy_trade['tradeprice'])
        sell_price = trade_price + priceVariation(price=trade_price, fee_multiplier=2, percent_value=1)
        logger.info("Sell - getSellPrice - {}({}) - GROWING_TREND - sell_price: {}".format(market_trend.marketName,
                                                                                           market_trend.marketId,
                                                                                           toEightDigit(sell_price)))
    elif market_trend > 0.0:
        last_buy_trade = next(cryptsy_mongo.getLastTradeFor(market_id=market_trend.marketId, trade_type="Buy"))
        trade_price = float(last_buy_trade['tradeprice'])
        sell_price = trade_price + priceVariation(price=trade_price, fee_multiplier=4, percent_value=0.25)
        logger.info("Sell - getSellPrice - {}({}) - CONSTANT_TREND - sell_price: {}".format(market_trend.marketName,
                                                                                           market_trend.marketId,
                                                                                           toEightDigit(sell_price)))
    else:
        sell_price = actual_estimated_price
        logger.info("Sell - getSellPrice - {}({}) - DECREASING_TREND - sell_price: {}".format(market_trend.marketName,
                                                                                              market_trend.marketId,
                                                                                              toEightDigit(sell_price)))

    return sell_price
def getBuyPrice(market_trend):
    actual_estimated_price = cryptsy_mongo.getNormalizedEstimatedPrice(market_trend)
    std_buy_price = actual_estimated_price - market_trend.std

    if market_trend.m > 0.5:
        buy_price = actual_estimated_price - priceVariation(actual_estimated_price)
        logger.info("Buy - getBuyPrice - {}({}) - GROWING_TREND - buy_price: {}".format(market_trend.marketName,
                                                                                        market_trend.marketId,
                                                                                        toEightDigit(buy_price)))
    elif market_trend > -0.1:
        variation_buy_price = actual_estimated_price - priceVariation(actual_estimated_price, fee_multiplier=2,
                                                                      percent_value=0.5)
        buy_price = min(std_buy_price, variation_buy_price)
        logger.info("Buy - getBuyPrice - {}({}) - CONSTANT_TREND - buy_price: {}".format(market_trend.marketName,
                                                                                         market_trend.marketId,
                                                                                         toEightDigit(buy_price)))
    else:
        variation_buy_price = actual_estimated_price - priceVariation(actual_estimated_price, fee_multiplier=2,
                                                                      percent_value=max(1.5, abs(market_trend.m)))
        buy_price = min(std_buy_price, variation_buy_price)
        logger.info("Buy - getBuyPrice - {}({}) - DECREASING_TREND - buy_price: {}".format(market_trend.marketName,
                                                                                           market_trend.marketId,
                                                                                           toEightDigit(buy_price)))

    return buy_price
def investBTC(btcBalance, active_markets, markets):
    market_names = [market for market in markets]

    btcMarketNames = filter(lambda x: 'BTC' in x and 'Points' not in x, market_names)

    logger.debug("activeMarkets: {}".format(active_markets))

    inactive_btc_markets = filter(lambda x: int(markets[x]) not in active_markets, btcMarketNames)

    logger.debug("inactive_btc_markets: {}".format(
        [int(markets[inactive_btc_market]) for inactive_btc_market in inactive_btc_markets]))

    market_trends, marketIds = getMarketTrends(inactive_btc_markets, markets)

    sorted_market_trends = sorted(market_trends, key=lambda x: abs(0.0 - x.m))

    sorted_market_trend_ids = [x.marketId for x in sorted_market_trends]

    logger.info("sorted_market_trend_ids: {}".format(sorted_market_trend_ids))

    avg_filtered_market_trends = filter(lambda x: x.m != 0.0 and x.m >= -0.1 and x.avg >= 0.000001,
                                        sorted_market_trends)

    avg_filtered_market_trends_ids = [x.marketId for x in avg_filtered_market_trends]

    logger.debug("avg_filtered_market_trends_ids: {}".format(avg_filtered_market_trends_ids))

    # sorted_market_trends_to_bet_on = filter(lambda x: x.std > (x.avg * FEE + x.avg * DESIRED_EARNING),
    # avg_filtered_market_trends)

    # sorted_market_trends_to_bet_on = filter(lambda x: x.std > 2 * (x.avg * FEE), avg_filtered_market_trends)
    sorted_market_trends_to_bet_on = avg_filtered_market_trends

    sorted_market_trends_to_bet_on_ids = [x.marketId for x in sorted_market_trends_to_bet_on]

    logger.info("sorted_market_trends_to_bet_on_ids: {}".format(sorted_market_trends_to_bet_on_ids))

    best_markets_last_3h = cryptsy_mongo.getBestPerformingMarketsFrom(
        toCryptsyServerTime(datetime.utcnow() - timedelta(hours=3)))

    logger.debug("best_markets_last_3h: {}".format(best_markets_last_3h))

    worst_markets_last_30m = cryptsy_mongo.getWorstPerformingMarketsFrom(
        toCryptsyServerTime(datetime.utcnow() - timedelta(minutes=30)))

    logger.debug("worst_markets_last_30m: {}".format(worst_markets_last_30m))

    worst_performing_markets = [int(market_id) for market_id in set(worst_markets_last_30m)]

    logger.info("worst_performing_markets: {}".format(worst_performing_markets))

    best_performing_markets = [int(market) for market in best_markets_last_3h if
                               int(market) not in worst_performing_markets]

    logger.info("best_performing_markets: {}".format(best_performing_markets))

    logger.info("marketIds: {}".format(marketIds))

    logger.info("userMarketIds: {}".format(userMarketIds))

    suggested_market_ids = filter(lambda x: x in marketIds, userMarketIds) + filter(lambda x: x in marketIds,
                                                                                    best_performing_markets)

    suggested_market_trends = []

    for market_id in suggested_market_ids:
        for market_trend in market_trends:
            if int(market_trend.marketId) == market_id:
                suggested_market_trends.append(market_trend)

    other_sorted_market_trends = filter(
        lambda x: int(x.marketId) not in suggested_market_ids and int(x.marketId) not in worst_performing_markets,
        sorted_market_trends_to_bet_on)

    marketTrendsToInvestOn = suggested_market_trends + other_sorted_market_trends

    market_multipliers = cryptsy_mongo.getMarketsMultipliers()

    logger.info("Buy - Markets Multiplier: {}".format(market_multipliers))

    for market_trend in marketTrendsToInvestOn:

        if btcBalance < MINIMUM_AMOUNT_TO_INVEST:
            break

        market_multiplier = market_multipliers[
            market_trend.marketId] if market_trend.marketId in market_multipliers else 0

        # logger.info(
        # "Buy - {}({}) multiplier: {}".format(market_trend.marketName, market_trend.marketId, market_multiplier))

        if int(market_trend.marketId) in userMarketIds:
            desiredAmountToInvest = TEST_STAKE
        elif market_multiplier > 0:
            desiredAmountToInvest = BASE_STAKE * market_multiplier
        elif market_multiplier == 0:
            desiredAmountToInvest = TEST_STAKE
        elif market_multiplier < 0:
            desiredAmountToInvest = TEST_STAKE
        else:
            desiredAmountToInvest = TEST_STAKE

        amountToInvest = min(desiredAmountToInvest, btcBalance)

        one_hour_trend = getMarketTrendFor(market_trend.marketName, market_trend.marketId, 1)

        two_hours_trend = getMarketTrendFor(market_trend.marketName, market_trend.marketId, 2)

        three_hours_trend = getMarketTrendFor(market_trend.marketName, market_trend.marketId, 3)

        if three_hours_trend.m == 0.0 or three_hours_trend.m < 0.0 or three_hours_trend.num_samples < 25:
            logger.info(
                "Buy - REJECTED - {}({}) has m: {} and number samples: {}".format(three_hours_trend.marketName,
                                                                                  three_hours_trend.marketId,
                                                                                  three_hours_trend.m,
                                                                                  three_hours_trend.num_samples))
            continue
        elif two_hours_trend.m > one_hour_trend.m < 0.3:
            logger.info(
                "Buy - REJECTED - {}({}) has 3h-2h-1h: {}, {}, {} ".format(three_hours_trend.marketName,
                                                                           three_hours_trend.marketId,
                                                                           three_hours_trend.m,
                                                                           two_hours_trend.m,
                                                                           one_hour_trend.m))
            continue

        buyPrice = getBuyPrice(three_hours_trend)

        quantity = calculateQuantity(amountToInvest, FEE, buyPrice)

        if buyPrice <= 0.0 or quantity <= 0.0:
            logger.info(
                "Buy - REJECTED - {}({}) quantity: {} price: {}.".format(market_trend.marketName, market_trend.marketId,
                                                                         quantity,
                                                                         toEightDigit(buyPrice)))
            continue

        logger.info(
            "Buy - PLACING - {}({}) quantity: {}, price: {}".format(three_hours_trend.marketName,
                                                                    three_hours_trend.marketId,
                                                                    quantity,
                                                                    toEightDigit(buyPrice)))

        responseBody, apiCallSucceded = cryptsyClient.placeBuyOrder(market_trend.marketId, quantity, buyPrice)
        if apiCallSucceded:
            btcBalance -= amountToInvest
Ejemplo n.º 5
0
def main(argv):
    global public
    global private

    getEnv(argv)

    global cryptsy_client
    cryptsy_client = CryptsyPy(public, private)
    # cryptsy_mongo = CryptsyMongo(host="192.168.1.33")
    cryptsy_mongo = CryptsyMongo()

    recent_market_trends = cryptsy_mongo.getRecentMarketTrends()

    recent_trades = cryptsy_client.getRecentTrades()
    if recent_trades is not None:
        cryptsy_mongo.persistTrades(recent_trades)

    if hours is not None:
        start_time = toCryptsyServerTime(datetime.utcnow() - timedelta(hours=int(hours)))
    else:
        now = datetime.utcnow()
        start_time = toCryptsyServerTime(datetime(now.year, now.month, now.day))

    total_buy_best = 0.0
    total_sell_best = 0.0
    total_fee_best = 0.0
    print "Best markets:"
    mongotradeStats = cryptsy_mongo.getAllTradesFrom(start_time)
    filteredTradeStats = filter(
        lambda x: mongotradeStats[x]['Sell'] >= mongotradeStats[x]['Fee'] + mongotradeStats[x]['Buy'],
        mongotradeStats)
    sortedTradeStats = sorted(filteredTradeStats,
                              key=lambda x: mongotradeStats[x]['Sell'] - mongotradeStats[x]['Buy'] - mongotradeStats[x][
                                  'Fee'],
                              reverse=True)

    for tradeStat in sortedTradeStats:
        sell = float(mongotradeStats[tradeStat]['Sell'])
        buy = float(mongotradeStats[tradeStat]['Buy'])
        fee = float(mongotradeStats[tradeStat]['Fee'])

        total_buy_best += buy
        total_sell_best += sell
        total_fee_best += fee

        std = next((toEightDigit(market_trend.std) for market_trend in recent_market_trends if
                    int(market_trend.marketId) == int(tradeStat)), None)
        print "MarketId: {}, Std:{}, Sell: {}, Buy: {}, Earn: {}".format(tradeStat, std,
                                                                         toEightDigit(sell), toEightDigit(buy),
                                                                         toEightDigit(sell - buy - fee))

    print "Best markets total: buy: {}, sell: {}, fee:{} - earnings: {}".format(total_buy_best, total_sell_best,
                                                                                total_fee_best,
                                                                                total_sell_best - total_buy_best - total_fee_best)

    total_buy_worst = 0.0
    total_sell_worst = 0.0
    total_fee_worst = 0.0
    print "Worst markets:"
    mongotradeStats = cryptsy_mongo.getAllTradesFrom(start_time)
    filteredTradeStats = filter(
        lambda x: 0 < mongotradeStats[x]['Sell'] < mongotradeStats[x]['Fee'] + mongotradeStats[x]['Buy'],
        mongotradeStats)
    sortedTradeStats = sorted(filteredTradeStats,
                              key=lambda x: mongotradeStats[x]['Sell'] - mongotradeStats[x]['Buy'] - mongotradeStats[x][
                                  'Fee'])

    for tradeStat in sortedTradeStats:
        sell = float(mongotradeStats[tradeStat]['Sell'])
        buy = float(mongotradeStats[tradeStat]['Buy'])
        fee = float(mongotradeStats[tradeStat]['Fee'])

        total_buy_worst += buy
        total_sell_worst += sell
        total_fee_worst += fee

        std = next((toEightDigit(market_trend.std) for market_trend in recent_market_trends if
                    int(market_trend.marketId) == int(tradeStat)), None)
        print "MarketId: {}, Std:{}, Sell: {}, Buy: {}, Earn: {}".format(tradeStat, std,
                                                                         toEightDigit(sell), toEightDigit(buy),
                                                                         toEightDigit(sell - buy - fee))

    print "Worst markets total: buy: {}, sell: {}, fee:{} - earnings: {}".format(total_buy_worst, total_sell_worst,
                                                                                 total_fee_worst,
                                                                                 total_sell_worst - total_buy_worst - total_fee_worst)

    print "Total stats: total earning: {}".format(
        (total_sell_best + total_sell_worst) - (total_buy_best + total_buy_worst + total_fee_best + total_fee_worst))