示例#1
0
def the_future(request):

    #Check for rate limiting if too many requests
    max_allowable_requests = 3600
    ip = util.get_client_ip(request)
    Rate_Limit.objects.create(ip=ip, function='the_future')
    limit = Rate_Limit.objects.filter(ip=ip, function='the_future').count()
    if limit > max_allowable_requests:
        error_text = _("Slow down <span class='notranslate'>Rainman</span> - you've made too many requests in the last hour")
        return HttpResponse(error_text, mimetype="text/plain", status=429) 

    after = True
    if "after" in request.GET:
        time = util.unix_time_to_datetime_utc(float(request.GET["after"]) / 1e3)
    elif "before" in request.GET:
        time = util.unix_time_to_datetime_utc(float(request.GET["before"]) / 1e3)
        after=False
    else:
        time = util.get_utc_time_now()
    predictions_per_page = 10
    if after:
        future_price_times = Future_Price.objects.filter(time_to_match_price__gt=time).distinct('time_to_match_price').order_by('time_to_match_price')[0:predictions_per_page]
        future_prices = Future_Price.objects.filter(time_to_match_price__in=[x.time_to_match_price for x in future_price_times]).order_by('time_to_match_price', 'target_price')
    else:
        future_price_times = Future_Price.objects.filter(time_to_match_price__lt=time).distinct('time_to_match_price').order_by('-time_to_match_price')[0:predictions_per_page]
        future_prices = Future_Price.objects.filter(time_to_match_price__in=[x.time_to_match_price for x in future_price_times]).order_by('time_to_match_price', 'target_price')
    response_data = []
    for f in future_prices:
        received_amounts = Received_Amount.objects.filter(prediction__future_price=f)
        if len(received_amounts) > 0:
            expires = f.time_to_match_price.isoformat()
            prediction = {
                'id': f.id,
                'target_price': float(f.target_price),
                'deposits': [{
                    'amount': float(r.amount),
                    'lt': r.prediction.price_will_be_less_than_target,
                    'time_received': r.time.isoformat(),
                    'js_time_received': int(util.datetime_to_unix_time(r.time) * 1e3)
                    } for r in received_amounts]
                }
            if len(response_data) == 0 or response_data[-1]["expires"] != expires:
                response_data.append({
                    'expires': expires,
                    'js_expires': int(util.datetime_to_unix_time(f.time_to_match_price) * 1e3),
                    'predictions': [prediction]})
            else:
                response_data[-1]['predictions'].append(prediction)
                
    return HttpResponse(json.dumps(response_data), mimetype="application/json")
示例#2
0
def find_clear_minute_prices(trades, last_tid, last_price):
    """
    given a series of trades, find any clear minutes in that series and the
    price for that clear_minute
    """
    prices = []
    for trade in trades:
        trade_tid = int(trade["tid"])
        prior_date = util.unix_time_to_datetime_utc(last_tid * 1e-6)
        trade_date = util.unix_time_to_datetime_utc(int(trade["tid"]) * 1e-6)
        clear_minutes = get_clear_minutes(prior_date, trade_date)
        for clear_minute in clear_minutes:
            new_price = {
                'time': clear_minute,
                'price': last_price,
                "rollover_id_a": last_tid,
                "rollover_id_b": trade_tid,
                }
            prices.append(new_price)
        last_tid = trade_tid
        last_price = trade["price"]
    return prices
示例#3
0
def find_clear_minute_prices(trades, last_tid, last_price):
    """
    given a series of trades, find any clear minutes in that series and the
    price for that clear_minute
    """
    prices = []
    for trade in trades:
        trade_tid = int(trade["tid"])
        prior_date = util.unix_time_to_datetime_utc(last_tid * 1e-6)
        trade_date = util.unix_time_to_datetime_utc(int(trade["tid"]) * 1e-6)
        clear_minutes = get_clear_minutes(prior_date, trade_date)
        for clear_minute in clear_minutes:
            new_price = {
                'time': clear_minute,
                'price': last_price,
                "rollover_id_a": last_tid,
                "rollover_id_b": trade_tid,
            }
            prices.append(new_price)
        last_tid = trade_tid
        last_price = trade["price"]
    return prices
    def get_initial_price(self):
        one_hour = datetime.timedelta(0,3600,0)
        time_of_interest = util.get_utc_time_now() - one_hour
        unix_time_of_interest = util.datetime_to_unix_time(time_of_interest) * 1e6
        url = "https://mtgox.com/api/1/BTCUSD/trades?since=%i" % unix_time_of_interest
        f = urllib.urlopen(url)
        trades_json = f.read()
        trades = json.loads(trades_json)["return"]
        last_trade = trades[-1]
        self.price_float = float(last_trade["price"])
        self.price_int = float(last_trade["price_int"])
        self.last_time_gox = util.unix_time_to_datetime_utc(last_trade["date"])
        print("INITIAL PRICE: %f" % (self.price_float))

        """
 def handle_trade(self, trade, new_msg_time_server, source):
     new_msg_time_gox = util.unix_time_to_datetime_utc(trade["date"])
     if(self.last_time_gox is not None):
         tickovers = util.get_clear_minutes(self.last_time_gox, new_msg_time_gox)
         # Set those minutes to the last price
         for tickover in tickovers:
             print("%s %f SAVING" % (tickover.isoformat(), self.price_float))
             new_bitcoin_price = {
                 'time': tickover,
                 'price': self.price_float,
                 }
             bitcoin_price = BitcoinPrice(**new_bitcoin_price)
             bitcoin_price.save()
     if source == "socket":
         self.price_float = trade["price"]
         self.price_int = trade["price_int"]
         self.last_time_server = new_msg_time_server
         self.last_time_gox = new_msg_time_gox
     print("%s %f %s" % (new_msg_time_gox.isoformat(), self.price_float, source))
示例#6
0
 def handle(self, *args, **options):
     wait_period = 2 #seconds between checks of the deposits
     if already_running():
         #self.stdout.write(datetime.datetime.now().isoformat() + " check_deposits is already running\n")
         return
     try:
         last_received_amount = Received_Amount.objects.order_by('-time')[0]
         last_tx_id = last_received_amount.tx_id
     except: #IndexError:
         last_tx_id = None
     #self.stdout.write("started\n")
     time_now = util.get_utc_time_now()
     while (time_now.second < 55):
         new_transactions = util.get_bitcoin_transactions(last_tx_id)
         #self.stdout.write("New txs: %i\n" % len(new_transactions))
         for new_tx in new_transactions:
             try:
                 amount = new_tx["amount"]
             except TypeError:
                 print "TYPERROR!!!!: %s" % new_tx
                 print new_tx["amount"]
             if(new_tx["amount"] > 0):
                 tx = {
                     "tx_id": new_tx["txid"],
                 }
                 num_existing_transaction_entries = Received_Amount.objects.filter(**tx).count()
                 predictions = Prediction.objects.filter(receive_address=new_tx["address"])
                 if(num_existing_transaction_entries == 0 and predictions.count() == 1):
                     tx["prediction"] = predictions[0]
                     tx["amount"] = new_tx["amount"]
                     tx["time"] = util.unix_time_to_datetime_utc(new_tx["time"])
                     new_payment_obj = Received_Amount(**tx)
                     new_payment_obj.save()
                 elif last_tx_id is not None:
                     pass
                     #TODO raise some better notice, something has gone wrong, should never count the same tx twice.
         if(len(new_transactions) > 0):
             last_tx_id = new_transactions[-1]["txid"]
         #self.stdout.write(last_tx_id + "\n")
         time.sleep(wait_period)
         time_now = util.get_utc_time_now()
示例#7
0
def make_new_prediction(request):

    #Check for rate limiting if too many predictions
    max_allowable_predictions = 100
    ip = util.get_client_ip(request)
    Rate_Limit.objects.create(ip=ip, function='make_new_prediction')
    limit = Rate_Limit.objects.filter(ip=ip, function='make_new_prediction').count()
    if limit > max_allowable_predictions:
        error_text = _("Slow down <span class='notranslate'>Rainman</span> - you've made too many predictions in the last hour")
        return HttpResponse(error_text, mimetype="text/plain", status=429)    
    
    lt = request.POST["lt"] == "lt"
    
    price = util.price(request.POST["price"])
    if price is None:
        error_text = _("Invalid price")
        return HttpResponse(error_text, mimetype="text/plain", status=400)
        
    unix_date = float(request.POST["time_to_check"]) / 1e3
    utc_date = util.unix_time_to_datetime_utc(unix_date)
    if utc_date is None:
        error_text = _("Invalid date")
        return HttpResponse(error_text, mimetype="text/plain", status=400)
    if not utc_date.second == 0 and utc_date.microsecond == 0:
        error_text = _("Date must not include seconds")
        return HttpResponse(error_text, mimetype="text/plain", status=400)
    if not util.datetime_is_in_the_future(utc_date, FUTURE_WINDOW):
        error_text = _("Must be at least two hours into the future")
        return HttpResponse(error_text, mimetype="text/plain", status=400)

    return_address = request.POST["return_address"]
    if re.search("\W", return_address) is not None:
        error_text = _("Return address is invalid")
        return HttpResponse(error_text, mimetype="text/plain", status=400)
    return_address_is_valid = util.validate_bitcoin_address(return_address)
    if not return_address_is_valid:
        error_text = _("Return address is invalid")
        return HttpResponse(error_text, mimetype="text/plain", status=400)

    account_name = str(int(lt)) + "-" + str(price) + "-" + str(util.datetime_to_unix_time(utc_date)) + "-" + return_address
    receive_address = util.get_bitcoin_address(account_name)

    future_price = {
        "target_price": price,
        "time_to_match_price": utc_date,
        "time_window_closes": utc_date - datetime.timedelta(0, FUTURE_WINDOW)
        }
    existing_future_price_obj = Future_Price.objects.filter(**future_price)
    if existing_future_price_obj.count() > 0:
        future_price_obj = existing_future_price_obj[0]
    else:
        future_price_obj = Future_Price(**future_price)
        future_price_obj.save()

    new_prediction = {
        "future_price": future_price_obj,
        "receive_address": receive_address,
        "price_will_be_less_than_target": lt,
        "return_address": return_address,
        }
    prediction_obj = Prediction(**new_prediction)
    prediction_obj.save()
    
    response_data = {
        "address": receive_address
        }
    return HttpResponse(json.dumps(response_data), mimetype="application/json")
示例#8
0
def make_new_prediction(request):

    #Check for rate limiting if too many predictions
    max_allowable_predictions = 100
    ip = util.get_client_ip(request)
    Rate_Limit.objects.create(ip=ip, function='make_new_prediction')
    limit = Rate_Limit.objects.filter(ip=ip,
                                      function='make_new_prediction').count()
    if limit > max_allowable_predictions:
        error_text = _(
            "Slow down <span class='notranslate'>Rainman</span> - you've made too many predictions in the last hour"
        )
        return HttpResponse(error_text, mimetype="text/plain", status=429)

    lt = request.POST["lt"] == "lt"

    price = util.price(request.POST["price"])
    if price is None:
        error_text = _("Invalid price")
        return HttpResponse(error_text, mimetype="text/plain", status=400)

    unix_date = float(request.POST["time_to_check"]) / 1e3
    utc_date = util.unix_time_to_datetime_utc(unix_date)
    if utc_date is None:
        error_text = _("Invalid date")
        return HttpResponse(error_text, mimetype="text/plain", status=400)
    if not utc_date.second == 0 and utc_date.microsecond == 0:
        error_text = _("Date must not include seconds")
        return HttpResponse(error_text, mimetype="text/plain", status=400)
    if not util.datetime_is_in_the_future(utc_date, FUTURE_WINDOW):
        error_text = _("Must be at least two hours into the future")
        return HttpResponse(error_text, mimetype="text/plain", status=400)

    return_address = request.POST["return_address"]
    if re.search("\W", return_address) is not None:
        error_text = _("Return address is invalid")
        return HttpResponse(error_text, mimetype="text/plain", status=400)
    return_address_is_valid = util.validate_bitcoin_address(return_address)
    if not return_address_is_valid:
        error_text = _("Return address is invalid")
        return HttpResponse(error_text, mimetype="text/plain", status=400)

    account_name = str(int(lt)) + "-" + str(price) + "-" + str(
        util.datetime_to_unix_time(utc_date)) + "-" + return_address
    receive_address = util.get_bitcoin_address(account_name)

    future_price = {
        "target_price": price,
        "time_to_match_price": utc_date,
        "time_window_closes": utc_date - datetime.timedelta(0, FUTURE_WINDOW)
    }
    existing_future_price_obj = Future_Price.objects.filter(**future_price)
    if existing_future_price_obj.count() > 0:
        future_price_obj = existing_future_price_obj[0]
    else:
        future_price_obj = Future_Price(**future_price)
        future_price_obj.save()

    new_prediction = {
        "future_price": future_price_obj,
        "receive_address": receive_address,
        "price_will_be_less_than_target": lt,
        "return_address": return_address,
    }
    prediction_obj = Prediction(**new_prediction)
    prediction_obj.save()

    response_data = {"address": receive_address}
    return HttpResponse(json.dumps(response_data), mimetype="application/json")
示例#9
0
def the_future(request):

    #Check for rate limiting if too many requests
    max_allowable_requests = 3600
    ip = util.get_client_ip(request)
    Rate_Limit.objects.create(ip=ip, function='the_future')
    limit = Rate_Limit.objects.filter(ip=ip, function='the_future').count()
    if limit > max_allowable_requests:
        error_text = _(
            "Slow down <span class='notranslate'>Rainman</span> - you've made too many requests in the last hour"
        )
        return HttpResponse(error_text, mimetype="text/plain", status=429)

    after = True
    if "after" in request.GET:
        time = util.unix_time_to_datetime_utc(
            float(request.GET["after"]) / 1e3)
    elif "before" in request.GET:
        time = util.unix_time_to_datetime_utc(
            float(request.GET["before"]) / 1e3)
        after = False
    else:
        time = util.get_utc_time_now()
    predictions_per_page = 10
    if after:
        future_price_times = Future_Price.objects.filter(
            time_to_match_price__gt=time).distinct(
                'time_to_match_price').order_by(
                    'time_to_match_price')[0:predictions_per_page]
        future_prices = Future_Price.objects.filter(time_to_match_price__in=[
            x.time_to_match_price for x in future_price_times
        ]).order_by('time_to_match_price', 'target_price')
    else:
        future_price_times = Future_Price.objects.filter(
            time_to_match_price__lt=time).distinct(
                'time_to_match_price').order_by(
                    '-time_to_match_price')[0:predictions_per_page]
        future_prices = Future_Price.objects.filter(time_to_match_price__in=[
            x.time_to_match_price for x in future_price_times
        ]).order_by('time_to_match_price', 'target_price')
    response_data = []
    for f in future_prices:
        received_amounts = Received_Amount.objects.filter(
            prediction__future_price=f)
        if len(received_amounts) > 0:
            expires = f.time_to_match_price.isoformat()
            prediction = {
                'id':
                f.id,
                'target_price':
                float(f.target_price),
                'deposits': [{
                    'amount':
                    float(r.amount),
                    'lt':
                    r.prediction.price_will_be_less_than_target,
                    'time_received':
                    r.time.isoformat(),
                    'js_time_received':
                    int(util.datetime_to_unix_time(r.time) * 1e3)
                } for r in received_amounts]
            }
            if len(response_data
                   ) == 0 or response_data[-1]["expires"] != expires:
                response_data.append({
                    'expires':
                    expires,
                    'js_expires':
                    int(
                        util.datetime_to_unix_time(f.time_to_match_price) *
                        1e3),
                    'predictions': [prediction]
                })
            else:
                response_data[-1]['predictions'].append(prediction)

    return HttpResponse(json.dumps(response_data), mimetype="application/json")