def getNormalizedEstimatedPrice(market_trend, time_x=datetime.utcnow()): timeX = (toCryptsyServerTime(time_x) - epoch).total_seconds() estimatedPrice = estimateValue(timeX, market_trend.m, market_trend.n, market_trend.minX, market_trend.scalingFactorX, market_trend.minY, market_trend.scalingFactorY) normalizedEstimatedPrice = float(estimatedPrice) / 100000000 return normalizedEstimatedPrice
def plot_diagram(market_name, market_id): interval = timedelta(days=1, hours=4) cryptsy_mongo = CryptsyMongo(host="192.168.1.33") timeStart = datetime.utcnow() - interval cryptoCurrencyDataSamples = cryptsy_mongo.markets_collection.find( {"name": market_name, "lasttradetime": {"$gt": timeStart.strftime("%Y-%m-%d %H:%M:%S")}}) tradeData = [(cryptoCurrencySample['lasttradetime'], cryptoCurrencySample['lasttradeprice']) for cryptoCurrencySample in cryptoCurrencyDataSamples] uniqueTradeData = list(set(tradeData)) uniqueTradeData = sorted(uniqueTradeData, key=(lambda x: x[0])) times = [(datetime.strptime(tradeDataSample[0], '%Y-%m-%d %H:%M:%S') - epoch).total_seconds() for tradeDataSample in uniqueTradeData] prices = [float(tradeDataSample[1]) for tradeDataSample in uniqueTradeData] trades = cryptsy_mongo.trades_collection.find( {"marketid": str(market_id), "datetime": {"$gt": timeStart.strftime("%Y-%m-%d %H:%M:%S")}}) trade_samples = [] for trade in trades: trade_samples.append(((datetime.strptime(trade['datetime'], '%Y-%m-%d %H:%M:%S') - epoch).total_seconds(), float(trade['tradeprice']), trade['tradetype'])) buy_trade_times = [trade_sample[0] for trade_sample in trade_samples if trade_sample[2] == 'Buy'] buy_trade_price = [trade_sample[1] for trade_sample in trade_samples if trade_sample[2] == 'Buy'] sell_trade_times = [trade_sample[0] for trade_sample in trade_samples if trade_sample[2] == 'Sell'] sell_trade_price = [trade_sample[1] for trade_sample in trade_samples if trade_sample[2] == 'Sell'] times_x = [] prices_y = [] market_trend = cryptsy_mongo.calculateMarketTrend(market_name, market_id) for hour in range(0, 24): time_x = datetime.utcnow() - timedelta(hours=hour) price_y = getNormalizedEstimatedPrice(market_trend, time_x) times_x.append((toCryptsyServerTime(time_x) - epoch).total_seconds()) prices_y.append(price_y) plt.plot(times, prices) plt.plot(buy_trade_times, buy_trade_price, 'ro') plt.plot(sell_trade_times, sell_trade_price, 'go') plt.plot(times_x, prices_y, 'ko') plt.savefig("{}.png".format("{}-{}".format(market_name.replace('/', '-'), market_id)), format='png') plt.close()
def test_toCryptsyServerTime(self): now = datetime.now() cryptsy_time = toCryptsyServerTime(now) self.assertEqual(cryptsy_time, now - timedelta(hours=CRYPTSY_HOURS_DIFFERENCE))
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
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))