示例#1
0
def get_future_price_data(f):
    
    is_open = f.time_window_closes > util.get_utc_time_now()
    precision = "%0.2f"
    number_split_by_dp = str(f.target_price).split(".")
    if len(number_split_by_dp) == 2:
        precision = "%%0.%if" % max(2,len(number_split_by_dp[1].rstrip('0')))
    future_price = {
        'expires': f.time_to_match_price.strftime(DATETIME_FORMAT),
        'js_expires': int(util.datetime_to_unix_time(f.time_to_match_price) * 1e3),
        'is_open': is_open,
        'target_price_str': precision % float(f.target_price),
        'target_price': float(precision % float(f.target_price)),
        'currency_symbol': "$",
        'exchange': f.exchange,
        'currency_code': f.currency_code,
        'deposits': [
            {
                'received_address': d.prediction.receive_address,
                'return_address': d.prediction.return_address,
                'received_address_short': d.prediction.receive_address[:10],
                'return_address_short': d.prediction.return_address[:10],
                'amount': float(d.amount),
                'time_received': d.time.strftime("%Y-%m-%d %H:%M:%S"),
                'js_time_received': int(util.datetime_to_unix_time(d.time) * 1e3),
                'lt': d.prediction.price_will_be_less_than_target,
                'returns': [{
                    'return_address': r.to_prediction.return_address,
                    'return_address_short': r.to_prediction.return_address[:10],
                    'return_amount': float(r.amount),
                    'is_unpaid': Returned_Tx_To_Returned_Amount_Link.objects.filter(returned_amount=r).count() == 0,
                    } for r in Returned_Amount.objects.filter(from_received_amount=d)]
                } for d in Received_Amount.objects.filter(prediction__future_price=f).order_by('time', 'id')]
    }
    future_price["has_unpaid_returns"] = False
    for deposit in future_price['deposits']:
        for returned_amount in deposit['returns']:
            if returned_amount['is_unpaid']:
                future_price["has_unpaid_returns"] = True
                break
        if future_price["has_unpaid_returns"]:
            break
    future_price["total_more_than"] = sum([d["amount"] for d in future_price["deposits"] if not d["lt"]])
    future_price["total_less_than"] = sum([d["amount"] for d in future_price["deposits"] if d["lt"]])
    actual_price = Bitcoin_Price.objects.filter(time=f.time_to_match_price)
    if len(actual_price) == 1:
        future_price["actual_price"] = float(actual_price[0].price)
        future_price["actual_price_url"] = "https://mtgox.com/api/1/BTCUSD/trades?since=%i" % (actual_price[0].rollover_id_a-1)
    else:
        future_price["actual_price"] = None
    return future_price
    
示例#2
0
 def bitcoin_price(self, future_price, **k):
     t = k["time"] if "time" in k else future_price.time_to_match_price
     n_bitcoin_prices = Bitcoin_Price.objects.filter(time=t).count()
     if n_bitcoin_prices == 0:
         t_a = util.datetime_to_unix_time(t) * 1e6 - 5
         t_b = util.datetime_to_unix_time(t) * 1e6 + 5
         b = Bitcoin_Price.objects.create(
             time=t,
             price=k["price"] if "price" in k else 1,
             rollover_id_a=k["rollover_id_a"] if "rollover_id_a" in k else t_a,
             rollover_id_b=k["rollover_id_b"] if "rollover_id_b" in k else t_b,
         )
         return b
示例#3
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")
示例#4
0
 def bitcoin_price(self, future_price, **k):
     t = k["time"] if "time" in k else future_price.time_to_match_price
     n_bitcoin_prices = Bitcoin_Price.objects.filter(time=t).count()
     if n_bitcoin_prices == 0:
         t_a = util.datetime_to_unix_time(t) * 1e6 - 5
         t_b = util.datetime_to_unix_time(t) * 1e6 + 5
         b = Bitcoin_Price.objects.create(
             time=t,
             price=k["price"] if "price" in k else 1,
             rollover_id_a=k["rollover_id_a"]
             if "rollover_id_a" in k else t_a,
             rollover_id_b=k["rollover_id_b"]
             if "rollover_id_b" in k else t_b,
         )
         return b
    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))

        """
示例#6
0
 def trade(self, **k):
     d = k["date"] if "date" in k else util.datetime_to_unix_time(util.get_utc_time_now())
     t = {
         "date": d,
         "price": k["price"] if "price" in k else 1,
         "amount": k["amount"] if "amount" in k else 1,
         "price_int": k["price_int"] if "price_int" in k else 1e5,
         "amount_int": k["amount_int"] if "amount_int" in k else 1e8,
         "tid": k["tid"] if "tid" in k else d*1e6,
         "price_currency": k["price_currency"] if "price_currency" in k else "USD",
         "item": k["item"] if "item" in k else "BTC",
         "trade_type": k["trade_type"] if "trade_type" in k else "bid",
         "primary": k["primary"] if "primary" in k else "Y",
         "properties": k["properties"] if "properties" in k else "limit",
         }
     self.trades.append(t)
示例#7
0
 def trade(self, **k):
     d = k["date"] if "date" in k else util.datetime_to_unix_time(
         util.get_utc_time_now())
     t = {
         "date": d,
         "price": k["price"] if "price" in k else 1,
         "amount": k["amount"] if "amount" in k else 1,
         "price_int": k["price_int"] if "price_int" in k else 1e5,
         "amount_int": k["amount_int"] if "amount_int" in k else 1e8,
         "tid": k["tid"] if "tid" in k else d * 1e6,
         "price_currency":
         k["price_currency"] if "price_currency" in k else "USD",
         "item": k["item"] if "item" in k else "BTC",
         "trade_type": k["trade_type"] if "trade_type" in k else "bid",
         "primary": k["primary"] if "primary" in k else "Y",
         "properties": k["properties"] if "properties" in k else "limit",
     }
     self.trades.append(t)
示例#8
0
    def handle(self, *args, **options):
        if already_running():
            #self.stdout.write("Already running")
            return
        time_started = util.get_utc_time_now()
        has_expired = False
        now = util.get_utc_time_now()
        one_hour = datetime.timedelta(0, 3600, 0)
        try:
            last_bitcoin_price = Bitcoin_Price.objects.order_by('-time')[0]
            last_tid = last_bitcoin_price.rollover_id_b
        except IndexError:
            last_tid = int(util.datetime_to_unix_time(now - one_hour) * 1e6)
        trades = self.get_gox_trades(
            last_tid - 1)  # needs to include the last rollover trade
        if len(trades) > 0:
            try:
                last_tid = int(trades[0]["tid"])
            except:
                return
            last_price = trades[0]["price"]
        while (len(trades) > 0 and not has_expired):
            prices = find_clear_minute_prices(trades, last_tid, last_price)
            for price in prices:
                bitcoin_price = Bitcoin_Price(**price)
                bitcoin_price.save()
            last_tid = int(trades[-1]["tid"])
            last_price = trades[-1]["price"]

            time.sleep(1)  # Don't hammer the gox server too hard
            time_taken = util.get_utc_time_now() - time_started
            has_expired = time_taken.total_seconds() > 30
            # Check if there are more trades after the last trade in the
            # previous set of trades
            if (len(trades) == 500):
                trades = self.get_gox_trades(last_tid)
            else:
                trades = []
 def handle(self, *args, **options):
     if already_running():
         #self.stdout.write("Already running")
         return
     time_started = util.get_utc_time_now()
     has_expired = False
     now = util.get_utc_time_now()
     one_hour = datetime.timedelta(0, 3600, 0)
     try:
         last_bitcoin_price = Bitcoin_Price.objects.order_by('-time')[0]
         last_tid = last_bitcoin_price.rollover_id_b
     except IndexError:
         last_tid = int(util.datetime_to_unix_time(now-one_hour) * 1e6)
     trades = self.get_gox_trades(last_tid - 1) # needs to include the last rollover trade
     if len(trades) > 0:
         try:
             last_tid = int(trades[0]["tid"])
         except:
             return
         last_price = trades[0]["price"]
     while (len(trades) > 0 and not has_expired):
         prices = find_clear_minute_prices(trades, last_tid, last_price)
         for price in prices:
             bitcoin_price = Bitcoin_Price(**price)
             bitcoin_price.save()
         last_tid = int(trades[-1]["tid"])
         last_price = trades[-1]["price"]
         
         time.sleep(1) # Don't hammer the gox server too hard
         time_taken = util.get_utc_time_now() - time_started
         has_expired = time_taken.total_seconds() > 30
         # Check if there are more trades after the last trade in the
         # previous set of trades
         if (len(trades) == 500):
             trades = self.get_gox_trades(last_tid)
         else:
             trades = []
示例#10
0
 def setUp(self):
     self.d = util.datetime_to_unix_time(
         datetime.datetime(2012, 1, 1, 2, 2, 2, 123, utc))
     self.trade(date=self.d, price=1)
     self.trade(date=self.d + ONE_M.total_seconds(), price=2)
示例#11
0
def get_server_time(request):
    now = util.get_utc_time_now()
    response_data = {
        "server_time": util.datetime_to_unix_time(now) * 1e3,
    }
    return HttpResponse(json.dumps(response_data), mimetype="application/json")
示例#12
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")
示例#13
0
def get_server_time(request):
    now = util.get_utc_time_now()
    response_data = {
        "server_time": util.datetime_to_unix_time(now) * 1e3,
        }        
    return HttpResponse(json.dumps(response_data), mimetype="application/json")
示例#14
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")
示例#15
0
def get_future_price_data(f):

    is_open = f.time_window_closes > util.get_utc_time_now()
    precision = "%0.2f"
    number_split_by_dp = str(f.target_price).split(".")
    if len(number_split_by_dp) == 2:
        precision = "%%0.%if" % max(2, len(number_split_by_dp[1].rstrip('0')))
    future_price = {
        'expires':
        f.time_to_match_price.strftime(DATETIME_FORMAT),
        'js_expires':
        int(util.datetime_to_unix_time(f.time_to_match_price) * 1e3),
        'is_open':
        is_open,
        'target_price_str':
        precision % float(f.target_price),
        'target_price':
        float(precision % float(f.target_price)),
        'currency_symbol':
        "$",
        'exchange':
        f.exchange,
        'currency_code':
        f.currency_code,
        'deposits': [{
            'received_address':
            d.prediction.receive_address,
            'return_address':
            d.prediction.return_address,
            'received_address_short':
            d.prediction.receive_address[:10],
            'return_address_short':
            d.prediction.return_address[:10],
            'amount':
            float(d.amount),
            'time_received':
            d.time.strftime("%Y-%m-%d %H:%M:%S"),
            'js_time_received':
            int(util.datetime_to_unix_time(d.time) * 1e3),
            'lt':
            d.prediction.price_will_be_less_than_target,
            'returns': [{
                'return_address':
                r.to_prediction.return_address,
                'return_address_short':
                r.to_prediction.return_address[:10],
                'return_amount':
                float(r.amount),
                'is_unpaid':
                Returned_Tx_To_Returned_Amount_Link.objects.filter(
                    returned_amount=r).count() == 0,
            } for r in Returned_Amount.objects.filter(from_received_amount=d)]
        } for d in Received_Amount.objects.filter(
            prediction__future_price=f).order_by('time', 'id')]
    }
    future_price["has_unpaid_returns"] = False
    for deposit in future_price['deposits']:
        for returned_amount in deposit['returns']:
            if returned_amount['is_unpaid']:
                future_price["has_unpaid_returns"] = True
                break
        if future_price["has_unpaid_returns"]:
            break
    future_price["total_more_than"] = sum(
        [d["amount"] for d in future_price["deposits"] if not d["lt"]])
    future_price["total_less_than"] = sum(
        [d["amount"] for d in future_price["deposits"] if d["lt"]])
    actual_price = Bitcoin_Price.objects.filter(time=f.time_to_match_price)
    if len(actual_price) == 1:
        future_price["actual_price"] = float(actual_price[0].price)
        future_price[
            "actual_price_url"] = "https://mtgox.com/api/1/BTCUSD/trades?since=%i" % (
                actual_price[0].rollover_id_a - 1)
    else:
        future_price["actual_price"] = None
    return future_price
示例#16
0
 def setUp(self):
     self.d = util.datetime_to_unix_time(datetime.datetime(2012,1,1,2,2,2,123,utc))
     self.trade(date=self.d, price=1)
     self.trade(date=self.d+ONE_M.total_seconds(), price=2)
示例#17
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")