Esempio n. 1
0
def get_bid5_price(market_data):
    price = round(market_data['bid5_px'], 2)
    if price > 0:
        return price
    log_helper.warn('the price might meet DownLimit')
    price = round(market_data['bid1_px'], 2)
    if price > 0:
        return price

    return round(market_data['ask1_px'], 2)
Esempio n. 2
0
    def cache_tile(tile, file_name):
        if not tile.decoded_data:
            warn("Trying to cache a tile without data: {}", tile)

        file_path = os.path.join(FileHelper.get_cache_directory(), file_name)
        try:
            with open(file_path, 'wb') as f:
                pickle.dump(tile, f, pickle.HIGHEST_PROTOCOL)
        except:
            debug("Error while writing tile '{}' to cache", str(tile))
 def close_connection(self):
     """
      * Closes the current db connection
     :return: 
     """
     if self.conn:
         try:
             self.conn.close()
             debug("Connection closed")
         except:
             warn("Closing connection failed: {}".format(sys.exc_info()))
     self.conn = None
Esempio n. 4
0
def sell_work(context,
              data_cache_manager,
              pool_item_cache,
              pool_name,
              trigger_condition_check,
              mdHelper=None):
    for tempUser in pool_item_cache:
        poolItemList = list(pool_item_cache[tempUser].values())
        for poolItem in itertools.chain.from_iterable(poolItemList):
            if poolItem.is_sent_order:
                continue
            vol = int(poolItem.vol)
            marketData = context.market_depths_df.ix[poolItem.stock]
            last_px = marketData['last_px']
            if last_px <= 0:
                continue

            need_trigger = False
            pre_close = marketData['pre_close']
            if not trigger_condition_check(
                    poolItem, marketData, mdHelper=mdHelper):
                continue

            positions = data_cache_manager.accounts[tempUser][
                'position'].set_index('StockCode')
            if poolItem.stock not in positions.index:
                log_helper.warn('no position on {0} when stop loss'.format(
                    poolItem.stock))
                continue

            available_sell_vol = positions['CoverableSize'][poolItem.stock]
            if available_sell_vol == 0:
                log_helper.warn('0 position on {0}  when stop loss'.format(
                    poolItem.stock))
                continue
            if vol > available_sell_vol > 0:
                vol = available_sell_vol

            if poolItem.waySell == u'追五挂单':
                order_price = common.get_bid5_price(marketData)
                poolItem.is_sent_order = True
                state = data_cache_manager.accounts[tempUser]['tradeApi'].sell(
                    poolItem.stock, order_price, vol)
                log_helper.info(
                    '[user:{0}][{1} sell stock({2}) at price:{3}]@{4}. state:{5}'
                    .format(tempUser, pool_name, poolItem.stock, order_price,
                            vol, state))
                state = state.splitlines()
                state = [i.split('\t') for i in state]
                if len(state) > 1:
                    poolItem.state = str(
                        pd.DataFrame(state[1:], columns=state[0]).iloc[0, 0])
Esempio n. 5
0
 def clear_cache():
     """
      * Removes all files from the cache
     """
     cache = os.path.join(FileHelper.get_cache_directory())
     if not os.path.exists(cache):
         return
     files = glob.glob(os.path.join(cache, "*"))
     for f in files:
         try:
             os.remove(f)
         except:
             warn("File could not be deleted: {}", f)
Esempio n. 6
0
    def load_url(url):
        reply = FileHelper.load_url_async(url)
        while not reply.isFinished():
            QApplication.processEvents()

        http_status_code = reply.attribute(
            QNetworkRequest.HttpStatusCodeAttribute)
        if http_status_code == 200:
            content = reply.readAll().data()
        else:
            if http_status_code is None:
                content = "Request failed: {}".format(reply.errorString())
            else:
                content = "Request failed: HTTP status {}".format(
                    http_status_code)
            warn(content)
        return http_status_code, content
Esempio n. 7
0
    def add_pool_item(self, line_edit_account, stock, combo_pos, dict_cache, targetTableWidget, price_way, apply_all = False):
        userName = qs2ps(line_edit_account.text())
        if len(userName) > 0:
            pos = qs2ps(combo_pos.currentText())        

            if apply_all:
                for userName in dict_cache.keys():
                    poolItem = BasePoolItem(stock, pos, price_way)
                    if poolItem.stock not in dict_cache[userName].keys():
                        dict_cache[userName][poolItem.stock] = poolItem
                        log_helper.info('[info] [apply all] add {0} for user:{1}'.format(poolItem.log_str(), userName))
            else:
                poolItem = BasePoolItem(stock, pos, price_way)
                if poolItem.stock not in dict_cache[userName].keys():
                    dict_cache[userName][poolItem.stock] = poolItem
                    log_helper.info('[info]add {0} for user:{1}'.format(poolItem.log_str(), userName))

            self.update_table_widget(targetTableWidget, line_edit_account, dict_cache)
        else:
            log_helper.warn(u"[warn]请先选中账户")
        return None
Esempio n. 8
0
    def update_table_widget(self, targetTableWidget, line_edit_account, dict_cache):
        curAcc = qs2ps(line_edit_account.text())
        if len(curAcc) == 0:
            log_helper.warn(u"[warn]请先选中账户")
            return

        targetTableWidget.clearContents()
        if curAcc not in dict_cache.keys():
            log_helper.warn('[warn] {0} not in cache'.format(curAcc))
            dict_cache[curAcc] = OrderedDict()
            return

        current_account_cache = dict_cache[curAcc]
        entrust = self.accounts[curAcc]['entrustAll']
        i = 0
        for item in current_account_cache.values():
            k = 0
            targetTableWidget.setItem(i, k, QtGui.QTableWidgetItem(item.stock))
            k += 1
            targetTableWidget.setItem(i, k, QtGui.QTableWidgetItem(get_stock_name(item.stock)))
            k += 1
            targetTableWidget.setItem(i, k, QtGui.QTableWidgetItem(item.pos))
            table_name = str(qs2ps(targetTableWidget.objectName()))
            #print('targetTableWidget.objectName:', table_name)
            
            # 把所有委托编号对应的成交信息返回到界面
            state = item.state
            #print('account:', curAcc, ' table:', targetTableWidget.objectName, ' state:', state)
            if state is None:
                i += 1
                continue

            targetTableWidget.setItem(i, k, QtGui.QTableWidgetItem(state))
            if state in entrust['EntruId'].values:
                info = entrust[entrust['EntruId'] == state]
                #log_helper.info('info:{0}, state:{1}, {2}'.format(info, state, info['OrderState'].iloc[0]))
                targetTableWidget.setItem(i, k, QtGui.QTableWidgetItem(info['OrderState'].iloc[0]))

            i += 1
Esempio n. 9
0
 def is_mapbox_vector_tile(self):
     """
      * A .mbtiles file is a Mapbox Vector Tile if the binary tile data is gzipped.
     :return:
     """
     debug("Checking if file corresponds to Mapbox format (i.e. gzipped)")
     is_mapbox_pbf = False
     try:
         tile_data_tuples = self.load_tiles(max_tiles=1, zoom_level=None)
         if len(tile_data_tuples) == 1:
             undecoded_data = tile_data_tuples[0][1]
             if undecoded_data:
                 is_mapbox_pbf = FileHelper.is_gzipped(undecoded_data)
                 if is_mapbox_pbf:
                     debug("File is valid mbtiles")
                 else:
                     debug("pbf is not gzipped")
     except:
         warn(
             "Something went wrong. This file doesn't seem to be a Mapbox Vector Tile. {}",
             sys.exc_info())
     return is_mapbox_pbf
def get_tile_bounds(zoom, bounds, scheme="xyz"):
    """
     * Returns the tile boundaries in XYZ scheme in the form [(x_min, y_min), (x_max, y_max)] where both values are tuples
    :param scheme: 
    :param zoom: 
    :param bounds: 
    :return: 
    """
    if scheme not in ["xyz", "tms"]:
        raise RuntimeError("Scheme not supported: {}".format(scheme))
    if not bounds:
        warn("Bounds is not available")
    tile_bounds = None
    if bounds:
        lng_min = bounds[0]
        lat_min = bounds[1]
        lng_max = bounds[2]
        lat_max = bounds[3]

        xy_min = latlon_to_tile(zoom, lat_max, lng_min, scheme)
        xy_max = latlon_to_tile(zoom, lat_min, lng_max, scheme)

        x_min = int(min(xy_min[0], xy_max[0]))
        x_max = int(max(xy_min[0], xy_max[0]))
        y_min = int(min(xy_min[1], xy_max[1]))
        y_max = int(max(xy_min[1], xy_max[1]))

        tile_bounds = {
            "zoom": int(zoom),
            "x_min": int(x_min),
            "x_max": int(x_max),
            "y_min": int(y_min),
            "y_max": int(y_max),
            "width": int(x_max-x_min+1),
            "height": int(y_max-y_min+1)
        }
    return tile_bounds
Esempio n. 11
0
def buy_up_limit_work(context, data_cache_manager, pool_item_cache, pool_name):
    for tempUser in pool_item_cache:
        try:
            if tempUser not in data_cache_manager.accounts.keys():
                #log_helper.warn('account {0} not exist for pool {1}'.format(tempUser, pool_name))
                continue

            if data_cache_manager.exceed_max_trade_count(tempUser, pool_name):
                log_helper.warn(
                    '{0} exceed max trade times at pool {1}'.format(
                        tempUser, pool_name))
                time.sleep(15)
                continue

            posLimit = common.get_total_max_position_percent(
                data_cache_manager.accounts[tempUser]['posLimit'])
            usable = data_cache_manager.accounts[tempUser]['usable']
            asset = data_cache_manager.accounts[tempUser]['asset']
            poolItemList = list(pool_item_cache[tempUser].values())
            total_pos = 0.0
            for poolItem in poolItemList:
                if poolItem.is_sent_order:
                    continue

                pos = common.percent2float(poolItem.pos)
                total_pos += pos
                if not common.check_position_limit(data_cache_manager.accounts,
                                                   tempUser,
                                                   to_buy_percent=total_pos,
                                                   max_limit=posLimit):
                    poolItem.state = u'仓位超{0}'.format(posLimit)
                    continue

                if poolItem.stock not in context.market_depths_df.index:
                    log_helper.warn(
                        'failed to get market data for stock:{0}'.format(
                            poolItem.stock))
                    continue

                market_data = context.market_depths_df.ix[poolItem.stock]
                pre_close = market_data['pre_close']
                if pre_close <= 0:
                    continue

                high_limit = round(pre_close * 1.1, 2)
                if common.is_open_high_limit(market_data):
                    continue

                last_px = market_data['last_px']
                if last_px < (high_limit - 0.01):
                    continue

                price = high_limit
                vol = common.get_order_vol(asset, pos, price)
                poolItem.is_sent_order = True
                state = data_cache_manager.accounts[tempUser]['tradeApi'].buy(
                    poolItem.stock, price, vol)
                log_helper.info(
                    '[{0}]{1} buy {2} at {3} @ {4} state:{5}'.format(
                        tempUser, pool_name, poolItem.stock, price, vol,
                        state))
                state = state.splitlines()
                state = [i.split('\t') for i in state]
                if len(state) > 1:
                    poolItem.state = str(
                        pd.DataFrame(state[1:], columns=state[0]).iloc[0, 0])
                    data_cache_manager.orderid2pooldict[common.get_order_key(
                        tempUser, poolItem.state)] = pool_name
                    data_cache_manager.add_orderid_to_dict(
                        pool_name, poolItem.stock, poolItem.state, tempUser)

        except Exception, e:
            log_helper.error(u'[error]请检查{0}买入条件单是否正确:{1}'.format(
                pool_name, e))