示例#1
0
def check_fund_status(taskobj):
    config = global_obj.get_obj("config")
    fund_list = config.get("fund_list", [])
    if len(fund_list) == 0:
        log.Waring("fund_list is empty")
        return
    ls = []
    for code in fund_list:
        old = fund_api.load_fund(code)
        code = str(code)
        fund_api.spiker_fund_and_save(code)
        ret = fund_api.load_fund(code)
        log.Info("spiker fund done", code)
        if old and ret:
            result = compare_fund(old,ret)
            if result:
                ls.append(result)
        else:
            log.Waring("load fund false", taskobj, type(old), type(ret))

    log.Info("spiker fund all", len(ls))
    if len(ls) > 0:
        htmobj = html.CHtml("你的韭菜日报:")
        for v in ls:
            line = "基金:%s(%s) 变化"%(v["name"],v["code"])
            htmobj.AddLine(line)
            htmobj.AddTable(v["data"], v["head"])
        html_text = htmobj.GetHtml()
        mailobj = global_obj.get_obj("mail")
        message  = mailobj.HtmlMailMessage()
        if message.SendMessage("韭菜研报", html_text):
            log.Info("send jiucai mail done")
    else:
        log.Info("基金信息没有变化")
def take_big_bet(_player_number, _address, _amount):
    log.Info("Start Take Big Bet ----------------")
    bet_address = _address
    player_address = get_player_address(_player_number)
    api.send(player_address, bet_address, _amount)
    log.Info("Big Bet Player_{} -> Number {}  Amount: {}".format(
        _player_number, _address, _amount))
    log.Info("End Take Big Bet ----------------")
示例#3
0
def beike_task():
    init()  #需要重新获取session
    data_list = start_community()
    save_excel(data_list)
    log.Info("保存excel完成")

    diff_list = []
    for data in data_list:
        ret = beike_db.load_xiaoqu(data["id"])
        if ret:
            ret = check_diff(data, ret)
            if ret["is_diff"]:
                diff_list.append(ret)
        beike_db.save_xiaoqu(data["id"], data)
    log.Info("数据保存完毕")
    send_diff_mail(diff_list)
示例#4
0
def save_new_bet_list(_bet_list, _bet_level):
    if _bet_list is None or len(_bet_list) == 0:
        return

    with db.atomic():
        for bet in _bet_list:
            try:
                dbbet = DBBet.get(DBBet.join_txid == bet["join_txid"])
            except DoesNotExist:
                dbbet = None

            if dbbet is None:
                log.Info("New bet: {} {}".format(bet["join_txid"], bet["bet_amount"]))
                DBBet.create(
                    join_txid=bet["join_txid"],
                    join_block_height=bet["join_block_height"],
                    join_block_hash=bet["join_block_hash"],
                    join_block_timestamp=bet["join_block_timestamp"],
                    bet_number=bet["bet_number"],
                    bet_address=bet["bet_address"],
                    bet_amount=bet["bet_amount"],
                    payment_address=bet["payment_address"],
                    bet_level=bet["bet_level"],
                    game_round=bet["bet_round"],
                    created_at=bet["created_at"],
                )
示例#5
0
def start_community():
    '''
    使用多线程爬取小区
    '''
    beike_conf = global_obj.get("config")["beike"]
    task_list = []
    for data in beike_conf["spider_list"]:
        cityName = data["city"]
        if "all" in data:
            community_list = get_all_community(cityName)
        else:
            community_list = data["community"]
        filterWord = None
        if "filter" in data:
            filterWord = data["filter"]
        for cName in community_list:
            task_list.append((
                cityName,
                cName,
                filterWord,
            ))

    task2_list = []
    data_list = []

    def _get_community_info(threadobj, cityName, cName, filterWord):
        result_list = get_community_info(cityName, cName, filterWord)
        data_list.extend(result_list.values())
        for cid, data in result_list.items():
            for url in data["house_url_list"]:
                task2_list.append((url, data["house_data"]))
            del data["house_url_list"]

    thread_tool.start_thread(_get_community_info, task_list, 5)
    log.Info("爬取小区信息完毕", len(task_list), len(task2_list))
    global g_count
    g_count = 0

    def _get_house_info(tobj, url, house_data):
        get_house_info(url, house_data)

    log.Info("开始爬取所有信息", len(task2_list))
    thread_tool.start_thread(_get_house_info, task2_list, 10)
    log.Info("爬取所有信息完成")
    return data_list
示例#6
0
def get_block_height_hash_timestamp_by_txid(_txid):
    raw_transaction = get_raw_transaction_info(_txid)
    log.Info("Raw Transacion: {}".format(raw_transaction))
    if "height" in raw_transaction:
        height = raw_transaction["height"]
        hash = raw_transaction["blockhash"]
        timestamp = raw_transaction["blocktime"]
        return height, hash, timestamp
    return -1, -1, -1
示例#7
0
def init_db():
    if not os.path.exists(db_root):
        log.Info("To Create database dir!")
        os.mkdir(db_root)
    db.connect()
    db.create_tables([DBBet])

    db_settled.connect()
    db_settled.create_tables([DBBetRound])
示例#8
0
def send_diff_mail(diff_list):
    if len(diff_list) == 0:
        log.Info("no beike diff")
        return
    htmobj = html.CHtml("房奴调研:")

    def set_dff_house(new, old):
        head_list = new.keys()
        tbl_list = []
        t2 = []
        for key in head_list:
            v1 = str(new.get(key, "NULL"))
            if v1 != str(old.get(key, "NULL")):
                t2.append(htmobj.Font(v1, "red"))
            else:
                t2.append(v1)
        tbl_list.append(t2)
        tbl_list.append([str(old.get(key, "NULL")) for key in head_list])
        htmobj.AddTable(tbl_list, head_list)

    for data in diff_list:
        htmobj.AddLine("=" * 30)
        htmobj.AddLine("小区<%s>信息发生变化" % (data["name"]))
        if len(data["new"]) > 0:
            htmobj.AddLine("新增房源:")
            htmobj.AddDict2Table(data["new"])
        if len(data["del"]) > 0:
            htmobj.AddLine("有房源被删除:")
            htmobj.AddDict2Table(data["del"])
        if len(data["diff"]) > 0:
            htmobj.AddLine("房源信息发生变化:")
            for v in data["diff"]:
                v1 = v[0]
                v2 = v[1]
                htmobj.AddLine("-" * 30)
                set_dff_house(v1, v2)
                htmobj.AddLine("+" * 30)
        htmobj.AddLine("*" * 30)
    html_text = htmobj.GetHtml()
    mailobj = global_obj.get("mail")
    message = mailobj.HtmlMailMessage()
    if message.SendMessage("房奴调研", html_text):
        log.Info("send beike mail done")
示例#9
0
def send_to_many_from_unspent_list(unspent_list, to_dict, change_address):
    if unspent_list is None or len(unspent_list) == 0:
        log.Info("No unspent list!")
        return -1

    if to_dict is None or len(to_dict) == 0:
        log.Info("No to dict!")
        return -1

    input_list = list()
    total_balance = 0.0
    for unspent in unspent_list:
        txid = unspent['txid']
        vout = unspent['vout']
        amount = unspent['amount']
        total_balance += util.get_precision(amount, 8)
        input_list.append({"txid": txid, "vout": vout})

    total_send = 0.0
    for key in to_dict:
        send_amount = to_dict[key]
        total_send += send_amount

    fee = ((len(unspent_list) * 180 +
            (len(to_dict) + 1) * 34 + 10 + 40) / 1024) * 0.000015
    fee = util.get_precision(fee, 8)
    change_amount = total_balance - total_send - fee
    change_amount = util.get_precision(change_amount, 8)
    if change_amount < 0:
        log.Info("No enough money to send, balance: {}, send: {}".format(
            total_balance, total_send))
        return -1

    to_dict[change_address] = change_amount

    transaction_hash = rpc.createrawtransaction(input_list, to_dict)
    signed_hex = rpc.signrawtransaction(transaction_hash)['hex']
    out_txid = rpc.sendrawtransaction(signed_hex)

    log.Info("Balance: {}, send: {}, fee: {}, change: {}, out_txid: {}".format(
        total_balance, total_send, fee, change_amount, out_txid))
    return out_txid
示例#10
0
def Work(targets, action, callback=None, exclusive_callback=None):
    def Done(request, result):
        comp = request.args[0]
        queue.Complete(comp)
        if callback:
            if not isinstance(result, list):
                result = [result]
            for r in result:
                if r and callback(comp, r) == False:
                    queue.Stop()
        Push()

    def Except(request, except_info):
        traceback.print_exception(*except_info)
        raise CommandError('Error running worker task')

    if flags.parallel:
        # TODO: Might want even more processors if we are using distcc...
        processor_count = util.GetProcessorCount()
        log.Info("Found %d processors" % processor_count)
        workers = processor_count * constants.WORKERS_PER_PROCESSOR
        log.Info('[Parallel Mode - %d workers]' % workers)
    else:
        workers = 1
        print '[Serial Mode]'
    pool = threadpool.ThreadPool(workers)

    def Push():
        next = queue.Next(exclusive_callback)
        for req in threadpool.makeRequests(action, next, Done, Except):
            pool.putRequest(req)

    queue = Queue()
    for comp in targets:
        queue.Populate(comp)
    Push()
    # Need 'while' loop in case 'wait()' exits due to empty queue, but we are in the process of adding more requests.
    while not queue.Finished():
        pool.wait()
        time.sleep(0.1)
示例#11
0
def get_community_info(cityName, keyword, filter_word=None):
    '''
    cityName: 城市
    keyword: 小区名
    filter_word 过滤关键字, 对region进行匹配
    @return
        返回小区列表
    '''
    global g_session

    data = {
        "cityName": cityName,
        "channel": "xiaoqu",
        "keyword": keyword,
        "query": keyword,
    }

    url = url_encode("https://ajax.api.ke.com/sug/headerSearch", data)
    result, _ = get_url(url, session=g_session)
    result_list = {}
    if is_not_ok(result):
        log.Error("get_community_info url false", cityName, keyword,
                  result.status_code)
        return
    result_data = js2py_val(result.content)
    if result_data["errno"] != 0:
        log.Error("get_community_info not ok", cityName, keyword, keyword)
        return result_list

    if len(result_data["data"]) == 0:
        log.Waring("get_community_info data is nil", cityName, result)
        return result_list
    for data in result_data["data"]["result"]:
        if filter_word and not filter_word in data["region"]:
            log.Info("get_community_info ingore by filter_word", cityName,
                     keyword, data)
            continue
        new_data = {
            "city": cityName,
            "name": data["text"],
            "id": data["id"],
            "region": data["region"],
            "house_url_list": [],
            "house_data": {},
        }
        new_data["house_url_list"] = get_house_list(data["id"])
        result_list[new_data["id"]] = new_data

    return result_list
示例#12
0
def send_to_address_from_unspent_list(unspent_list, to_address):
    if unspent_list is None or len(unspent_list) == 0:
        log.Info("No unspent list!")
        return -1

    if to_address is None:
        log.Info("No to address!")
        return -1

    input_list = []
    total_balance = 0.0
    for unspent in unspent_list:
        txid = unspent['txid']
        vout = unspent['vout']
        amount = unspent['amount']
        total_balance += util.get_precision(amount, 8)
        input_list.append({"txid": txid, "vout": vout})

    fee = ((len(unspent_list) * 180 + 1 * 34 + 10 + 40) / 1024) * 0.000015
    fee = util.get_precision(fee, 8)
    total_send = total_balance - fee
    total_send = util.get_precision(total_send, 8)
    send_dict = dict()
    send_dict[to_address] = total_send

    if total_send <= 0.0:
        log.Info("No enough money, send faild!")
        return -1

    transaction_hash = rpc.createrawtransaction(input_list, send_dict)
    signed_hex = rpc.signrawtransaction(transaction_hash)['hex']
    out_txid = rpc.sendrawtransaction(signed_hex)

    log.Info("Balance: {}, send: {}, fee: {}, out_txid: {}".format(
        total_balance, total_send, fee, out_txid))
    return out_txid
示例#13
0
def on_block_height_changed(_curr_block_height):
    log.Info("On Block Height Changed: {}".format(_curr_block_height))
    step1_try_save_bet_list(_curr_block_height, 1)
    small_settled_game_round_list = step2_try_settle_bets(
        _curr_block_height, 1)

    step1_try_save_bet_list(_curr_block_height, 2)
    big_settled_game_round_list = step2_try_settle_bets(_curr_block_height, 2)

    step1_try_save_bet_list(_curr_block_height, 3)
    large_settled_game_round_list = step2_try_settle_bets(
        _curr_block_height, 3)

    viewupdator.update_view(small_settled_game_round_list,
                            big_settled_game_round_list,
                            large_settled_game_round_list, _curr_block_height)
示例#14
0
def get_input_addresses(_txid):
    raw_transaction = get_raw_transaction_info(_txid)
    input_address_list = []
    for vin in raw_transaction["vin"]:
        in_txid = vin["txid"]
        index = vin["vout"]
        info = get_raw_transaction_info(in_txid)
        input_address = None
        for vout_info in info["vout"]:
            if vout_info["n"] == index:
                input_address = vout_info["scriptPubKey"]["addresses"][0]
                break
        if input_address is None:
            log.Info("Error, get input address faild!")
        input_address_list.append(input_address)
    return input_address_list
示例#15
0
def game_loop():
    try:
        global prev_block_height
        while True:
            # try:
            curr_block_height = api.get_current_block_height()
            #log.Info("Current Block Height: {} {}".format(curr_block_height, int(time.time())))
            if curr_block_height != prev_block_height:
                prev_block_height = curr_block_height
                on_block_height_changed(curr_block_height)
            time.sleep(1)
    except Exception as e:
        _ex_str = traceback.print_exc()
        # print(_ex_str)
        if _ex_str is not None:
            log.Info("Exception: " + _ex_str)
def WriteIfContentDifferent(filename, content):
  """Write file only if content is different or if filename does not exist.

  Args:
    filename: filename of file.
    content: string containing contents of file.
  """
  if os.path.exists(filename):
    f = open(filename, 'r');
    old_content = f.read()
    f.close()
    if old_content == content:
      return
  f = open(filename, 'w')
  f.write(content)
  f.close()
  log.Info('Writing %s' % filename)
示例#17
0
def send_to_many_from_input_txid_list(_input_txid_list, _to_dict,
                                      _change_address):
    all_unspent_list = rpc.listunspent()
    unspent_dict = {}
    for unspent in all_unspent_list:
        unspent_dict[unspent["txid"]] = unspent

    input_unspent_list = []
    for txid in _input_txid_list:
        unspent = unspent_dict.get(txid, None)
        if unspent is None:
            log.Info("Fatal Error, can not found unspent in unspent list: {}".
                     format(txid))
            return None
        input_unspent_list.append(unspent)

    return send_to_many_from_unspent_list(input_unspent_list, _to_dict,
                                          _change_address)
示例#18
0
def send(_from_address, _to_address, _amount):
    balance = get_address_balance(_from_address)
    if balance < _amount + 0.5:
        log.Info("No enough money to send {} from {} to {}".format(
            _amount, _from_address, _to_address))
        return -1

    selected_unspent = []
    unspent_list = get_unspent_list_by_address(_from_address, True)
    selected_input_amount = 0
    for unspent in unspent_list:
        selected_unspent.append(unspent)
        selected_input_amount += unspent["amount"]
        if selected_input_amount > _amount + 0.5:
            break

    return send_to_many_from_unspent_list(selected_unspent,
                                          {_to_address: _amount},
                                          _from_address)
示例#19
0
def thread_spike_fund(threadobj, *fund_list):
    ok = 0
    err = 0
    i=0
    l = len(fund_list)
    fund_yeild = {}
    stock_total = {}
    for code in fund_list:
        i+=1
        if i%50 == 0:
            log.Info("thread_spike_fund",threadobj.getName(),i,l-i)
        try:
            data = fund_api.spiker_fund_and_save(code)
            base_data = data["base"]
            if not base_data["type"] in __filter_stop_type:
                continue
            if not tools.is_float(base_data["new_worth_ratio"]):
                continue
            for k,v in base_data["stock"].items():
                if not k in stock_total:
                    stock_total[k] = 0
                stock_total[k]+=1
            fund_yeild[code] = {
                "now": base_data["new_worth_ratio"],
                "history":data["data"]["yield"],
                "name": data["name"]
            }
            ok+=1
        except BaseException as error:
            log.Error("spiker fund false", threadobj.getName(), code, error)
            err+=1
            continue

    return {
        "ok":ok,
        "error":err,
        "data":{
            "stock":stock_total,
            "yeild":fund_yeild,
        },
    }
示例#20
0
def send_to_many(_from_address, _to_dict):
    total_send = 0
    for address in _to_dict:
        total_send += _to_dict[address]

    balance = get_address_balance(_from_address)
    if balance < total_send + 0.5:
        log.Info("No enough money to send! {} -> {}", balance, total_send)
        return -1

    selected_unspent = []
    unspent_list = get_unspent_list_by_address(_from_address, True)
    selected_input_amount = 0
    for unspent in unspent_list:
        selected_unspent.append(unspent)
        selected_input_amount += unspent["amount"]
        if selected_input_amount > total_send + 0.5:
            break

    return send_to_many_from_unspent_list(selected_unspent, _to_dict,
                                          _from_address)
示例#21
0
def http_post_request(url, params, add_to_headers=None):
    headers = {
        "Accept":
        "application/json",
        'Content-Type':
        'application/json;charset=UTF-8',
        "origin":
        "https://explorer.geekcash.org",
        "referer":
        "https://explorer.geekcash.org/address/GaZVcUBuuMPbdqhf6uoR85vkVXYPfcpiLK",
        'user-agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
    }
    if add_to_headers:
        headers.update(add_to_headers)

    postdata = json.dumps(params)

    response = requests.post(url, postdata, headers=headers, timeout=10)
    log.Info(response.text)
    json_obj = json.loads(response.text)
    return json_obj
示例#22
0
    def _Shell(self):
        start = time.time()

        # Provide programs with some common root paths.
        # TODO: Should I just have a master set of vars?
        # TODO: If this is only used by 'Tests', should I move this?
        env = os.environ.copy()
        env['ATLAS_ROOT_DIR'] = util.GetRootDirectory()
        env['ATLAS_BUILD_DIR'] = os.path.join(util.GetRootDirectory(),
                                              util.GetBuildDirectory())

        # The 'exec' command prevents shell from forking, so that killing process on timeout kills off the shell AND the actual command child process
        # TODO: If sub-command spawns off child procs, are we kiling those too?
        command = 'exec ' + self._RawCommand()
        process = LockedProcess(
            args=command,
            cwd=self.work_dir,
            buffered=self.buffered,
            env=env,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,  # Pipe everyting through stdout
            shell=True)  # Need shell to run 'make', 'gcc' etc.
        while process.Poll() is None:
            now = time.time()
            if self.timeout is not None and (now - start) > self.timeout:
                log.Info("Timeout Triggered! (%s sec)" % self.timeout)
                process.Kill()
                time.sleep(1)
                return TIMEOUT, process.Output()
            time.sleep(1)
        assert process.ReturnCode() is not None

        if process.ReturnCode():
            return FAILURE, process.Output()
        else:
            return SUCCESS, process.Output()
示例#23
0
def Main(args):

  metrics.total_timer.Start()
  print "Atlas v%s" % constants.VERSION

  flags.__init__()
  filecache.Init()
  registry.__init__()


  opts, args = getopt.getopt(
      args,
      'v',
      ['test_timeout=', 'help', 'metrics', 'no-color', 'opt', 'serial', 'verbose',
       'version'])

  for o, a in opts:
    if o in ['--help']:
      usage()
      return True
    elif o in ['--metrics']:
      flags.metrics = True
    elif o in ['--no-color']:
      flags.color = False
    elif o in ['--opt']:
      flags.debug = False
    elif o in ['--serial']:
      flags.parallel = False
    elif o in ['--test_timeout']:
      constants.TEST_TIMEOUT = int(a)  # TODO: Modifying 'constants' is messy
      log.Info("Test timeout set to %d secs" % constants.TEST_TIMEOUT)
    elif o in ['-v', '--verbose']:
      print "[Verbose Mode]"
      flags.verbose = True
    elif o in ['--version']:
      return True  # Version printed above

  if not args:
    usage()
    return False

  command_name = args[0].lower()
  targets = args[1:]

  command_map = {
                 'depend': Graph.DependList,
                 'clean': Graph.Clean,
                 'build': Graph.Build,
                 'rebuild': Graph.Rebuild,
                 'run': Graph.Run,
                 'test': Graph.Test
                }

  command = SelectCommand(command_name, command_map)

  if not command:
    usage('Unknown command: ' + command_name)
    return False

  deps = Graph()
  globals.master_graph = deps  # Need a better way to set module-wide global
  success = None
  try:
    metrics.load_timer.Start()
    deps = Graph()
    parser = loader.Loader(deps)
    globals.master_loader = parser  # Need a better way to set module-wide global
    parser.Load(os.getcwd())
    metrics.load_timer.Stop()

    metrics.action_timer.Start()
    success = command(deps, targets)
    metrics.action_timer.Stop()

    metrics.total_timer.Stop()
    metrics.Report(command_name, targets)
    return success

  except util.ConfigError, e:
    print 'Config Error: %s' % e
    return False
示例#24
0
def step2_try_settle_bets(_curr_block_height, _bet_level):
    unsettle_bet_list = db.get_unsettle_bet_list(_bet_level)
    settled_game_round_list = []
    if unsettle_bet_list is None or len(unsettle_bet_list) == 0:
        return settled_game_round_list

    min_bet_amount = model.get_min_bet_amount(_bet_level)

    min_block_height = -1
    max_block_height = -1
    bet_dict = {}

    for bet in unsettle_bet_list:
        log.Info("###############: {} {} {}".format(bet.join_txid,
                                                    bet.join_block_hash,
                                                    bet.bet_number))
        if min_block_height < 0 or bet.join_block_height < min_block_height:
            min_block_height = bet.join_block_height

        if max_block_height < 0 or bet.join_block_height > max_block_height:
            max_block_height = bet.join_block_height

        bet_dict[bet.join_txid] = bet

    if _curr_block_height == min_block_height:
        return settled_game_round_list

    for block in range(min_block_height, _curr_block_height + 1):
        check_block = block + 1
        if check_block > _curr_block_height:
            break
        block_hash, block_nonce, block_timestamp = api.get_block_hash_nonce_timestamp_by_height(
            check_block)
        nonce_last_number = int(str(block_nonce)[-1])
        selected_bet_list = []
        has_loser = False
        has_winer = False
        log.Info("Check Block: {} {} {}".format(block, "Nonce: ", block_nonce))
        for txid in bet_dict:
            dbbet = bet_dict[txid]
            if dbbet.join_block_height < check_block:
                selected_bet_list.append(dbbet)
                if dbbet.bet_amount < min_bet_amount:
                    has_loser = True
                else:
                    if dbbet.bet_number == nonce_last_number:
                        has_winer = True
                    else:
                        has_loser = True

        log.Info("Has winer: {} {} {}".format(has_winer, "Has Loaser: ",
                                              has_loser))

        if has_winer and has_loser:
            winer_list = []
            loser_list = []
            total_loser_amount = 0.0
            total_winer_amount = 0.0
            for dbbet in selected_bet_list:
                if dbbet.bet_amount < min_bet_amount:
                    loser_list.append(dbbet)
                    total_loser_amount += dbbet.bet_amount
                    dbbet.bet_state = 0
                else:
                    if dbbet.bet_number == nonce_last_number:
                        winer_list.append(dbbet)
                        total_winer_amount += dbbet.bet_amount
                        dbbet.bet_state = 1
                    else:
                        loser_list.append(dbbet)
                        total_loser_amount += dbbet.bet_amount
                        dbbet.bet_state = 0

                dbbet.settlement_block_height = check_block
                dbbet.settlement_block_hash = block_hash
                dbbet.settlement_block_nonce = block_nonce

                del bet_dict[dbbet.join_txid]

            log.Info("Winer Count: {} {} {}".format(len(winer_list),
                                                    "Loser Count: ",
                                                    len(loser_list)))
            log.Info("Total winer amount: {} {} {}".format(
                total_winer_amount, "Total loser amount: ",
                total_loser_amount))
            total_reward = total_loser_amount * (1 - dev_reward_percentage)
            total_reward = util.get_precision(total_reward, 8)
            dev_reward = total_loser_amount - total_reward
            log.Info("Total winer reward: {} {} {}".format(
                total_reward, "dev reward: ", dev_reward))

            pay_input_txid_list = []
            to_dict = {}
            # pay to winers
            for dbbet in winer_list:
                reward_percentage = dbbet.bet_amount / total_winer_amount
                reward_percentage = util.get_precision(reward_percentage, 3)
                reward_amount = total_reward * reward_percentage
                reward_amount = util.get_precision(reward_amount, 8)
                dbbet.reward_amount = reward_amount
                pay_amount = reward_amount + dbbet.bet_amount
                pay_amount = util.get_precision(pay_amount, 8)
                to_dict[dbbet.payment_address] = pay_amount
                pay_input_txid_list.append(dbbet.join_txid)
                log.Info(
                    "Txid {} bet_amount: {} reward%: {}  reward:{}  payment:{}"
                    .format(dbbet.join_txid, dbbet.bet_amount,
                            reward_percentage, reward_amount, pay_amount))

            for dbbet in loser_list:
                pay_input_txid_list.append(dbbet.join_txid)

            pay_reward_txid = api.send_to_many_from_input_txid_list(
                pay_input_txid_list, to_dict, model.dev_reward_address)

            if pay_reward_txid == -1:
                log.Info("Error! Payment Faild!")

            settled_bet_list = []
            for dbbet in winer_list:
                dbbet.payment_state = 1
                dbbet.reward_txid = pay_reward_txid
                dbbet.update_at = datetime.datetime.now()
                settled_bet_list.append(dbbet)
                log.Info(
                    "Winner: {}  join_height: {}  address:{}  bet_number: {}".
                    format(dbbet.join_txid, dbbet.join_block_height,
                           dbbet.payment_address, dbbet.bet_number))

            for dbbet in loser_list:
                dbbet.update_at = datetime.datetime.now()
                settled_bet_list.append(dbbet)
                log.Info(
                    "Loser: {}  Join_height: {}  address: {}  bet_number: {}  bet_amount: {}"
                    .format(dbbet.join_txid, dbbet.join_block_height,
                            dbbet.payment_address, dbbet.bet_number,
                            dbbet.bet_amount))

            # last_game_round = db.get_last_game_round_number(_bet_level)
            curr_game_round = db.get_curr_unsettle_game_round(_bet_level)
            settled_game_round_list.append(curr_game_round)

            min_join_block = -1
            max_join_block = -1
            for dbbet in settled_bet_list:
                dbbet.game_round = curr_game_round
                if min_join_block < 0 or dbbet.join_block_height < min_join_block:
                    min_join_block = dbbet.join_block_height
                if max_join_block < 0 or dbbet.join_block_height > max_join_block:
                    max_join_block = dbbet.join_block_height

            db.save_settlement_bet_list(settled_bet_list)
            db.save_settled_header_data(
                curr_game_round,
                nonce_last_number,
                _bet_level,
                len(settled_bet_list),
                len(winer_list),
                len(loser_list),
                total_winer_amount + total_loser_amount,
                total_loser_amount,
                dev_reward,
                min_join_block,
                check_block,
                block_nonce,
            )
    return settled_game_round_list
示例#25
0
def step1_try_save_bet_list(_curr_block_height, _bet_level):
    bet_list = []

    if _bet_level == 1:
        bet_address_dict = model.small_bet_address_dict
        bet_address_number_dict = model.small_address_number_dict
    elif _bet_level == 2:
        bet_address_dict = model.big_bet_address_dict
        bet_address_number_dict = model.big_address_number_dict
    elif _bet_level == 3:
        bet_address_dict = model.large_bet_address_dict
        bet_address_number_dict = model.large_address_number_dict
    else:
        log.Info("Error!, Wrong Diff Level: {}".format(_bet_level))
        return

    curr_game_round = db.get_curr_unsettle_game_round(_bet_level)

    for account_name in bet_address_dict:
        bet_address = bet_address_dict[account_name]
        unspent_list = api.get_unspent_list_by_address(bet_address)
        if len(unspent_list) > 0:
            for unspent in unspent_list:
                bet_data = {}

                bet_number = bet_address_number_dict.get(bet_address, None)
                if bet_number is None:
                    log.Info("Fatal Error, get bet number error! {}".format(
                        bet_address))
                    return

                unspent_txid = unspent["txid"]
                join_block_height, join_block_hash, join_block_timestamp = \
                    api.get_block_height_hash_timestamp_by_txid(unspent["txid"])

                # 这里确保当前的unspent确认了后,再保存
                if join_block_height == -1 or join_block_hash == -1 or join_block_timestamp == -1:
                    continue

                input_address_list = api.get_input_addresses(unspent_txid)
                if len(input_address_list) == 0:
                    log.Info("Fatal Error, get input address faild! {}".format(
                        unspent_txid))
                    return

                bet_data["join_txid"] = unspent_txid
                bet_data["join_block_height"] = join_block_height
                bet_data["join_block_hash"] = join_block_hash
                bet_data["join_block_timestamp"] = join_block_timestamp
                bet_data["bet_number"] = bet_number
                bet_data["bet_address"] = unspent["address"]
                bet_data["bet_amount"] = util.get_precision(
                    float(unspent["amount"]), 8)
                bet_data["payment_address"] = input_address_list[0]
                bet_data["bet_level"] = _bet_level
                bet_data["bet_round"] = curr_game_round
                bet_data["created_at"] = util.timestamp2utctime(
                    join_block_timestamp)

                bet_list.append(bet_data)
    db.save_new_bet_list(bet_list, _bet_level)
示例#26
0
def log(log_str):
    sys_time = get_current_strtime()
    slog = '[{0}] {1}'.format(sys_time, log_str)
    log.Info(slog)
示例#27
0
    selected_unspent = []
    unspent_list = get_unspent_list_by_address(_from_address, True)
    selected_input_amount = 0
    for unspent in unspent_list:
        selected_unspent.append(unspent)
        selected_input_amount += unspent["amount"]
        if selected_input_amount > total_send + 0.5:
            break

    return send_to_many_from_unspent_list(selected_unspent, _to_dict,
                                          _from_address)


#result = send_all_unspent_list_to_address("Gcx6ce8xpSjpNJPd9SrPYdhZ2Nim2eEhyQ")
#log.Info(result)
"""
min_conf = 0
max_conf = 999999999

address_list = []

for x in range(500, 1001):
    account_name = "sub_{}".format(x)
    addresses = rpc.getaddressesbyaccount(account_name)
    log.Info("account_name: ", account_name, "address: ", addresses)
    address_list += addresses

log.Info(address_list)
unspent_list = rpc.listunspent(min_conf, max_conf, address_list)
log.Info(unspent_list)
log.Info("Count: ", len(unspent_list))
示例#28
0
def update_all_fund(taskobj):
    fund_list = fund_api.fund_all()
    l = len(fund_list)
    log.Info("update_all_fund", taskobj, l)
    thread_num = 5
    args_list = split_args(thread_num,fund_list)
    result = thread_api.start_args(thread_spike_fund, args_list)
    all_ok = 0
    all_error = 0
    stock_total = {}
    top_fund = []
    for data in result:
        all_ok+=data["ok"]
        all_error+=data["error"]
        tools.combine_dict(stock_total, data["data"]["stock"])
        for code, v in data["data"]["yeild"].items():
            top_fund.append((code, v))
    
    top_stock = [ (k, v) for k,v in stock_total.items() ]
    top_stock = sorted(top_stock, key = lambda k:tofloat(k[1]), reverse = True)
    top_fund = sorted(top_fund, key = lambda d:tofloat(d[1]["now"]), reverse = True)

    def write_stock_list():
        with open("stock_list.txt", "w") as fp:
            for v in top_stock:
                fp.write("%s    %s\n"%(v[0],v[1]))


    #write_stock_list()

    top20stock = top_stock[:40]
    top20fund = top_fund[:20]
    tail20fund = list(reversed(top_fund[len(top_fund) - 20:]))

    def make_fund(fund_list):
        ls = []
        for v in fund_list:
            code = v[0]
            data = v[1]
            d = data["history"]
            l = [data["name"], code, data["now"], 
                d.get("month1",0), d.get("month3", 0), d.get("month6", 0) ,d.get("year1", 0)
                ]
            ls.append(l)
        return ls


    htmobj = html.CHtml("韭菜排行:")
    if len(top20stock) > 0:
        htmobj.AddLine("基金持仓top20股票")
        htmobj.AddTable(top20stock, head = ["股票名","基金持有数"])

    head = ["基金名","代码","今日收益", "近1月收益", "近3月收益", "近6月收益", "近1年收益"]
    if len(top20fund) > 0:
        htmobj.AddLine("收益top20")
        htmobj.AddTable(make_fund(top20fund), head = head)
    if len(tail20fund) > 0:
        htmobj.AddLine("亏损top20")
        htmobj.AddTable(make_fund(tail20fund), head = head)

    html_text = htmobj.GetHtml()
    mailobj = global_obj.get_obj("mail")
    message  = mailobj.HtmlMailMessage()
    if message.SendMessage("韭菜排行榜", html_text):
        log.Info("send jiucai mail done")