예제 #1
0
    def setUp(self):
        build_user()
        build_positions()

        mike = User(**{
             "username": "******",
             "realname": "Mike Bloom",
             "balance": 10000.0
        })
        mike.hash_password("password")
        mike.save()

        appl = Position(**{
            "ticker" : "AAPL",
            "amount": 5,
            "user_info_pk": mike.pk
        })

        tsla = Position(**{
            "ticker" : "TSLA",
            "amount": 10,
            "user_info_pk": mike.pk
        })

        appl.save()
        tsla.save()
예제 #2
0
    def create_position(self, parent_division_oid):
        url = f'{appUrl}/idm/api/catalog/entry/'
        headers = {"Accept-Encoding": "gzip, deflate", "Accept-Language": "ru"}
        params = {'search': '', 'countType': 'all', "sort": ""}

        initial_position_object = Position()
        position_json = initial_position_object.return_position_data_as_json()
        clientId = self.make_position_path(parentId=parent_division_oid)
        position_json.update({
            'clientId': clientId,
            'parentId': parent_division_oid
        })
        print(position_json)

        response = self.rest.call_request(request_type="POST",
                                          url=url,
                                          json=position_json,
                                          headers=headers,
                                          params=params)
        json_response = response.json()
        print(json_response)
        created_position = Position()
        self.fill_position_data_from_response(created_position, json_response)
        setattr(initial_position_object, 'id', created_position.id)
        assert initial_position_object.__eq__(created_position)

        return created_position
예제 #3
0
def check_for_winner(plays: int, board, position: Position):
    if plays >= 3:
        if right_and_left_check(board, position) or up_and_down_check(board, position) \
                or plus_sing_check(board, position) or x_sing_check(board, position) \
                or vertical_check(board, position):
            return position
        else:
            Position(0, 0)

    elif plays >= (len(board) * len(board)):
        return Position(0, 0, None)

    return Position(0, 0)
예제 #4
0
    def _search_max_area_rectangle(self):
        max_area_rectangle = (0, None, None)
        for rectangle_color in list(Color):
            rectangle = self._search_completed_color_rectangle(rectangle_color)
            if rectangle[0] > max_area_rectangle[0]:
                max_area_rectangle = rectangle

        if max_area_rectangle[0] >= self.width - 1:
            max_area_rectangle = (max_area_rectangle[0],
                                  Position(max_area_rectangle[1][0],
                                           max_area_rectangle[1][1]),
                                  Position(max_area_rectangle[2][0],
                                           max_area_rectangle[2][1]))
        else:
            return None
        return max_area_rectangle
def save_account_cny(account_info, message_array):
    for tradingAccount in message_array:
        position_db = Position()
        real_account_id = getattr(tradingAccount, 'AccountID', 'NULL')
        if (real_account_id[12:14] == '70') and (account_info.accountsuffix
                                                 == '70'):
            pass
        elif (real_account_id[12:14] == '01') and (account_info.accountsuffix
                                                   == '01'):
            pass
        else:
            continue

        position_db.date = today_str
        position_db.id = account_info.accountid
        position_db.symbol = 'CNY'
        # 结算准备金
        position_db.long = getattr(tradingAccount, 'Balance', 'NULL')

        if account_info.accountsuffix == '70':
            # 保证金可用余额
            position_db.long_avail = getattr(tradingAccount, 'Credit', 'NULL')
        else:
            # 现金
            position_db.long_avail = getattr(tradingAccount, 'Available',
                                             'NULL')

        # 上次结算准备金
        position_db.prev_net = getattr(tradingAccount, 'PreBalance', '0')
        position_db.update_date = datetime.now()
        position_list.append(position_db)
예제 #6
0
def seed(dbpath=DBPATH):
    ORM.dbpath = dbpath

    default = Account(username='******',
                      balance=10000.00,
                      first='sami',
                      last='s',
                      api_key="12345678912345678902")
    default.set_password('1234')
    default.save()

    default_buy = Trade(buy_sell='Buy',
                        username='******',
                        ticker='tsla',
                        price='100',
                        shares='10',
                        time=time())
    default_buy.save()

    default_sale = Trade(buy_sell='Sell',
                         username='******',
                         ticker='tsla',
                         price='110',
                         shares='5',
                         time=time())
    default_sale.save()

    default_position = Position(username='******', ticker='tsla', shares='5')
    default_position.save()
예제 #7
0
def generate_board(size):
    board_matrix = []

    for line in range(size):
        line_array = []
        for col in range(size):
            line_array.append(Position(col + 1, line + 1))
        board_matrix.append(line_array)
    return board_matrix
예제 #8
0
def __build_account_position(account_id, investor_position_array):
    position_list = []
    position_dict = dict()
    ticker_position_dict = dict()
    for investorPosition in investor_position_array:
        symbol = getattr(investorPosition, 'stock_code', 'NULL')
        # 过滤掉SP j1609&j1701这种的持仓数据
        if '&' in symbol:
            continue

        # 转换hedgeFlag字典
        # hedge_flag = getattr(investorPosition, 'm_nHedgeFlag', '0')
        # hedge_flag = HEDGE_FLAG_MAP[hedge_flag]
        hedge_flag = 0

        key = '%s|%s' % (symbol, hedge_flag)
        if key in ticker_position_dict:
            ticker_position_dict.get(key).append(investorPosition)
        else:
            ticker_position_dict[key] = [investorPosition]

    for (key, ticker_position_list) in ticker_position_dict.items():
        (symbol, hedge_flag) = key.split('|')
        td_long = 0
        td_long_cost = 0.0
        td_long_avail = 0

        for temp_position in ticker_position_list:
            td_long += float(getattr(temp_position, 'current_amount', '0'))
            td_long_cost += float(getattr(temp_position, 'cost_price', '0'))
            td_long_avail += float(getattr(temp_position, 'enable_amount',
                                           '0'))

        position_db = Position()
        position_db.date = now_date_str
        position_db.id = account_id
        position_db.symbol = symbol
        position_db.hedgeflag = hedge_flag
        position_db.long = td_long
        position_db.long_cost = td_long_cost
        position_db.long_avail = td_long_avail
        position_db.short = 0
        position_db.short_cost = 0
        position_db.short_avail = 0

        position_db.ys_position_long = td_long
        position_db.yd_long_remain = td_long
        position_db.ys_position_short = 0
        position_db.yd_short_remain = 0
        position_db.prev_net = td_long
        position_db.frozen = 0
        position_db.update_date = datetime.now()
        position_dict[key] = position_db
        position_list.append(position_db)
    return position_dict, position_list
def __get_account_cny(account_id, message_array):
    if local_server_name == 'huabao' or local_server_name == 'zhongxin':
        account_money_dict = dict()
        fr = open('account_money.txt')
        for line in fr:
            l = line.strip()
            if (l == '') or (l[0] == '#'):
                continue
            else:
                [key, data] = l.split('=')
                account_money_dict[key] = data
        fr.close()


    position_db = Position()
    for trading_account in message_array:
        position_db.date = now_date_str
        position_db.id = account_id
        position_db.symbol = 'CNY'

        if local_server_name == 'huabao' and account_id == '1':
            account_money = int(account_money_dict[account_id])
            position_db.long = account_money
            position_db.long_avail = account_money
            position_db.prev_net = account_money
            position_db.update_date = datetime.now()
        elif local_server_name == 'huabao' and account_id == '2':
            account_money = int(account_money_dict[account_id])
            position_db.long = account_money
            position_db.long_avail = account_money
            position_db.prev_net = account_money
            position_db.update_date = datetime.now()
        elif local_server_name == 'zhongxin' and account_id == '1':
            other_account_money = int(account_money_dict[account_id])
            position_db.long = float(getattr(trading_account, 'Balance', '0')) - other_account_money
            position_db.long_avail = position_db.long
            position_db.prev_net = float(getattr(trading_account, 'PreBalance', '0')) - other_account_money
            position_db.update_date = datetime.now()
        elif local_server_name == 'zhongxin' and account_id == '2':
            other_account_money = int(account_money_dict[account_id])
            position_db.long = float(getattr(trading_account, 'Balance', '0')) - other_account_money
            position_db.long_avail = position_db.long
            position_db.prev_net = float(getattr(trading_account, 'PreBalance', '0')) - other_account_money
            position_db.update_date = datetime.now()
        else:
            position_db.long = getattr(trading_account, 'Balance', '0')
            position_db.long_avail = getattr(trading_account, 'Available', '0')
            position_db.prev_net = getattr(trading_account, 'PreBalance', '0')
            position_db.update_date = datetime.now()
        break
    return position_db
def __build_account_position(account_id, investor_position_array):
    position_list = []
    for investor_position in investor_position_array:
        position_db = Position()
        position_db.date = now_date_str
        position_db.id = account_id
        message_symbol = getattr(investor_position, 'SYMBOL',
                                 'NULL').split('.')[0]
        if message_symbol not in instrument_dict:
            continue
        instrumet_db = instrument_dict[message_symbol]
        position_db.symbol = instrumet_db.ticker

        position_db.hedgeflag = 0

        long_qty_message = int(getattr(investor_position, 'LONG_QUANTITY', 0))
        long_avail_qty_message = int(
            getattr(investor_position, 'AVAILABLE_QUANTITY', 0))
        short_qty_message = abs(
            int(getattr(investor_position, 'SHORT_QUANTITY', 0)))
        if long_qty_message < 0:
            long_qty = 0
            long_avail_qty = 0
            short_qty = abs(long_qty_message)
        else:
            long_qty = long_qty_message
            long_avail_qty = long_avail_qty_message
            short_qty = short_qty_message

        average_price = float(getattr(investor_position, 'AVERAGE_PRICE', 0))

        position_db.long = long_qty
        position_db.long_cost = long_qty * average_price * float(
            instrumet_db.fut_val_pt)
        position_db.long_avail = long_avail_qty
        position_db.yd_position_long = long_qty
        position_db.yd_long_remain = long_qty

        position_db.short = short_qty
        position_db.short_cost = short_qty * average_price * float(
            instrumet_db.fut_val_pt)
        position_db.short_avail = short_qty
        position_db.yd_position_short = short_qty
        position_db.yd_short_remain = short_qty

        position_db.prev_net = position_db.yd_position_long - position_db.yd_position_short
        position_db.frozen = 0
        position_db.update_date = datetime.now()
        position_list.append(position_db)
    return position_list
def save_account_cny(account_id, message_array):
    for trading_account in message_array:
        position_db = Position()
        position_db.date = today_str
        position_db.id = account_id
        position_db.symbol = 'CNY'

        available = getattr(trading_account, 'Available', '0')
        margin = getattr(trading_account, 'Margin', '0')
        position_db.long = float(available) + float(margin)
        position_db.long_avail = available
        position_db.prev_net = getattr(trading_account, 'PreBalance', '0')
        position_db.update_date = datetime.now()
        position_list.append(position_db)
예제 #12
0
 def buy(self, ticker, amount):
     #TODO make a trade
     """ buy a stock. if there is no current position, create one, if there is
     increase its amount. no return value """
     if amount < 0:
         raise ValueError
     cost = get_price(ticker)* amount
     if self.balance < cost:
         raise InsufficientFundsError
     self.balance -= cost
     current_position = self.position_for_stock(ticker)
     if current_position is None:
         current_position = Position(ticker=ticker, amount=0, user_info_pk=self.pk)
     current_position.amount += amount
     current_position.save()
     self.save
예제 #13
0
def __get_account_cny(account_id, message_array):
    position_db = Position()
    for trading_account in message_array:
        money_type = getattr(trading_account, 'money_type', '0')
        if money_type != '0':
            continue

        position_db.date = now_date_str
        position_db.id = account_id
        position_db.symbol = 'CNY'

        position_db.long = getattr(trading_account, 'current_balance', '0')
        position_db.long_avail = getattr(trading_account, 'enable_balance',
                                         '0')
        position_db.prev_net = getattr(trading_account, 'fund_balance', '0')
        position_db.update_date = datetime.now()
    return position_db
예제 #14
0
 def get_positions(self, whereclause=None):
     if whereclause == None:
         whereclause = ""
     result = {}
     cnxn = pyodbc.connect(self.constr_lora)
     cursor = cnxn.cursor()
     cursor.execute("SELECT [opus_id], \
                             [uuid_userref], \
                             [los_id], \
                             [person_ref], \
                             [kmd_suppid], \
                             [title], \
                             [position_id], \
                             [title_short], \
                             [paygrade_title], \
                             [is_manager], \
                             [payment_method], \
                             [payment_method_text], \
                             [weekly_hours_numerator], \
                             [weekly_hours_denominator], \
                             [invoice_recipient], \
                             [pos_pnr], \
                             [dsuser], \
                             [start_date], \
                             [leave_date], \
                             [manager_opus_id], \
                             [manager_uuid_userref], \
                             [updated], \
                             [deleted], \
                             [ad_user_deleted] \
                     FROM [pyt].[positions] \
                     " + whereclause + ";")
     for row in cursor.fetchall():
         opus_id = row.opus_id
         pos = Position(
             opus_id, row.uuid_userref, row.los_id, row.person_ref,
             row.kmd_suppid, row.title, row.position_id, row.title_short,
             row.paygrade_title, row.is_manager, row.payment_method,
             row.payment_method_text, row.weekly_hours_numerator,
             row.weekly_hours_denominator, row.invoice_recipient,
             row.pos_pnr, row.dsuser, row.start_date, row.leave_date,
             row.manager_opus_id, row.manager_uuid_userref, row.updated,
             row.deleted, row.ad_user_deleted)
         result[int(opus_id)] = pos
     return result
def __get_account_cny(account_id, message_array):
    query_position = session_portfolio.query(Position)
    position_db = query_position.filter(Position.id == account_id,
                                        Position.date == now_date_str,
                                        Position.symbol == 'CNY').first()
    if position_db is None:
        position_db = Position()

    for trading_account in message_array:
        position_db.date = now_date_str
        position_db.id = account_id
        position_db.symbol = 'CNY'

        position_db.long = getattr(trading_account, 'm_dBalance', '0')
        position_db.long_avail = getattr(trading_account, 'm_dAvailable', '0')
        position_db.prev_net = getattr(trading_account, 'm_dPreBalance', '0')
        position_db.update_date = datetime.now()
    return position_db
def __get_account_cny(account_id, base_model, pre_position_info_list):
    account_cny_db = None
    for position_info in pre_position_info_list:
        if position_info.symbol == 'CNY':
            account_cny_db = position_info

    if account_cny_db is None:
        account_cny_db = Position()
    account_cny_db.date = now_date_str
    account_cny_db.id = account_id
    account_cny_db.symbol = 'CNY'

    # 获取实时账户净值的数值
    account_cny_db.long = getattr(base_model, 'RT_ACCOUNT_NET_WORTH', '0')
    # 获取实时现金余额的数值
    account_cny_db.long_avail = getattr(base_model, 'RT_CASH_BALANCE', '0')
    # 获取账户日初始净值的数值
    account_cny_db.prev_net = getattr(base_model, 'BD_ACCOUNT_NET_WORTH', '0')
    account_cny_db.update_date = datetime.now()
    return account_cny_db
예제 #17
0
def _random_figure_generate(field_width):
    figures_list = list(__FIGURES_POSITIONS.keys())

    global __PREVIOUS_FIGURE
    if __PREVIOUS_FIGURE:
        figures_list.remove(__PREVIOUS_FIGURE)

    random_figure = random.choice(figures_list)

    __PREVIOUS_FIGURE = random_figure

    figure_positions = copy.deepcopy(__FIGURES_POSITIONS[random_figure])
    figure_color = __FIGURES_COLORS[random_figure]

    shift_positions = []
    shift = field_width // 2 - 1
    for position in figure_positions:
        shift_positions.append(Position(position[0], position[1] + shift))

    return shift_positions, figure_color
예제 #18
0
def play(game, turn):
    board_size = len(game.board)
    board = game.board
    player = game.players[turn]
    valid_play = False
    position = Position(0, 0)

    while not valid_play:
        line = int(input('Número da linha: '))
        col = int(input('Número da coluna: '))
        if line <= board_size and col <= board_size:
            position = board[line - 1][col - 1]
            if position.empty():
                position.player = player.initials()
                board[line - 1][col - 1] = position
                valid_play = True
            else:
                print("Jogada Inválida, preenchido por: " + position.player)
        else:
            print("Jogada inválida, esolha um número de 1 até " +
                  board_size.__str__())
    return [board, position]
예제 #19
0
파일: pms.py 프로젝트: zhangkaiqiang128/PMS
def position_submit():

    position = Position()

    position.lng = float(request.args.get("lng"))
    position.lat = float(request.args.get("lat"))
    position.device_id = request.args.get("id")
    position.device_type = request.args.get("type")
    position.coords_type = request.args.get("coords_type")

    position.post_time = time.strftime(
        "%Y-%m-%d %H:%M:%S",
        time.localtime(int(request.args.get("time")) / 1000))
    position.receive_time = time.strftime("%Y-%m-%d %H:%M:%S",
                                          time.localtime())

    Cache.write(position)
    position.save()

    res = {"status": 200, "message": "success", "content": {}}

    return json.dumps(res)
예제 #20
0
    def get_children_by_parent_node_oid(self, parent_oid=None, child_oid=None):
        url = f'{appUrl}/idm/api/catalog/entry/{parent_oid}'
        headers = {
            'WWW-Operation-Context': 'orgStruct',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'ru'
        }
        params = {
            'search': None,
            'countType': 'all',
            'sort': None,
            'node': f'root/{parent_oid}'
        }
        json = None

        response = self.rest.call_request(request_type="GET",
                                          url=url,
                                          json=json,
                                          headers=headers,
                                          params=params)
        json_response = response.json()
        print(json_response)

        children_object = None
        for children in json_response['children']:
            if children['id'] == child_oid:
                children_object = children

                break
        if children_object == None:
            print(
                f'[ERROR] Cant get children with oid {child_oid} in node with oid {parent_oid}'
            )

        children_got_by_oid = Position()
        self.fill_position_data_from_response(
            position_object=children_got_by_oid, json_response=children_object)
        print(children_got_by_oid)
        return children_got_by_oid
예제 #21
0
    def initUI(self):
        self.central_widget = QWidget()

        self.v_layout = QVBoxLayout(self.central_widget)
        self.v_layout.setContentsMargins(11, 11, 11, 11)
        self.v_layout.setSpacing(6)

        hlayout = QHBoxLayout()
        hlayout.setContentsMargins(11, 11, 11, 11)
        hlayout.setSpacing(0)
        self.v_layout.addLayout(hlayout)

        self.new_game_btn = QPushButton("New Game")
        self.new_game_btn.setFixedSize(self.new_game_btn.sizeHint())
        hlayout.addWidget(self.new_game_btn)

        hlayout.addStretch(1)

        player_lbl = QLabel("Player Turn: ")
        player_lbl.setFixedSize(player_lbl.sizeHint())
        self.active_player_lbl = QLabel(PLAYERS[1])
        self.active_player_lbl.setFixedSize(self.active_player_lbl.sizeHint())
        hlayout.addWidget(player_lbl)
        hlayout.addWidget(self.active_player_lbl)

        self.board_layout = QGridLayout()
        self.board_layout.setContentsMargins(11, 11, 11, 11)
        self.board_layout.setSpacing(0)

        self.v_layout.addLayout(self.board_layout)

        self.setCentralWidget(self.central_widget)

        for i in range(15):
            for j in range(15):
                sq = Square(Position(i, j))
                self.squares[i][j] = sq
                self.board_layout.addWidget(sq, i, j)
예제 #22
0
    def _check_rotate_left(self):
        min_row = self.field.height
        min_column = self.field.width
        for position in self.positions_list:
            if position.row < min_row:
                min_row = position.row
            if position.column < min_column:
                min_column = position.column

        new_min_row = self.field.height
        new_min_column = self.field.width
        new_positions = []
        for position in self.positions_list:
            new_row = min_row - (position.column - min_column)
            new_column = position.row - min_row + min_column

            new_positions.append(Position(new_row, new_column))

            if new_row < new_min_row:
                new_min_row = new_row
            if new_column < new_min_column:
                new_min_column = new_column

        if new_min_row < min_row:
            for new_position in new_positions:
                new_position.row += min_row - new_min_row
        if new_min_column < min_column:
            for new_position in new_positions:
                new_position.column += min_column - new_min_column

        for new_position in new_positions:
            if not self._is_valid_position(new_position.row,
                                           new_position.column):
                return

        return new_positions
예제 #23
0
파일: pms.py 프로젝트: zhangkaiqiang128/PMS
def position_query_all():
    position = Position()
    res = position.query_all()

    content = []

    for p in res:
        print(p)
        content.append({
            "id": p[0],
            "lat": p[1],
            "lng": p[2],
            "postTime": int(time.mktime(p[3].timetuple()) * 1000),
            "receiveTime": int(time.mktime(p[4].timetuple()) * 1000),
            "deviceId": p[5],
            "deviceType": p[6],
            "coords_type": p[7]
        })

    return json.dumps({
        "status": 200,
        "message": "success",
        "content": content
    })
def save_account_position(account_info, investor_position_array):
    tick_position_dict = dict()
    for investor_position in investor_position_array:
        symbol = getattr(investor_position, 'InstrumentID', 'NULL')

        # 投机:'1'|套保:'3'
        # hedge_flag = getattr(investor_position, 'HedgeFlag', '0')
        # hedge_flag = const.HEDGE_FLAG_MAP[hedge_flag]
        hedge_flag = 0

        key = '%s|%s' % (symbol, hedge_flag)
        if key in tick_position_dict:
            tick_position_dict.get(key).append(investor_position)
        else:
            tick_position_dict[key] = [investor_position]

    for (key, tickPositionList) in tick_position_dict.items():
        (symbol, hedge_flag) = key.split('|')

        td_long = 0
        td_long_cost = 0.0
        td_long_avail = 0

        td_short = 0
        td_short_cost = 0.0
        td_short_avail = 0

        yd_long = 0
        yd_long_remain = 0

        yd_short = 0
        yd_short_remain = 0

        prev_net = 0
        purchase_avail = 0

        long_frozen = 0
        short_frozen = 0

        save_flag = False
        for position_message in tickPositionList:
            real_account_id = getattr(position_message, 'AccountID', 'NULL')
            if (real_account_id[12:14] == '70') and (account_info.accountsuffix
                                                     == '70'):
                save_flag = True
            elif (real_account_id[12:14]
                  == '01') and (account_info.accountsuffix == '01'):
                save_flag = True
            else:
                continue

            position = float(getattr(position_message, 'Position', '0'))
            positionCost = float(getattr(position_message, 'PositionCost',
                                         '0'))
            ydPosition = float(getattr(position_message, 'YdPosition', '0'))

            # todayPurRedVolume = getattr(position_message, 'TodayPurRedVolume', '0')
            # todayPosition = getattr(position_message, 'TodayPosition', '0')
            openVolume = float(getattr(position_message, 'OpenVolume', '0'))
            closeVolume = float(getattr(position_message, 'CloseVolume', '0'))
            long_frozen = getattr(position_message, 'LongFrozen', '0')
            short_frozen = getattr(position_message, 'ShortFrozen', '0')

            long_flag = True
            # 净:'1'|多头:'2'|空头:'3'|备兑:'4'
            posi_direction = getattr(position_message, 'PosiDirection', '0')
            if posi_direction == '2':
                long_flag = True
            elif posi_direction == '3':
                long_flag = False
            elif (posi_direction == '1') and (ydPosition < 0):
                long_flag = False
            elif (posi_direction == '1') and (ydPosition >= 0):
                long_flag = True
            else:
                print 'Error in OnRspQryInvestorPosition'

            if long_flag:
                td_long = position
                td_long_cost = positionCost
                yd_long = ydPosition
                if (ydPosition - closeVolume) > 0:
                    yd_long_remain = ydPosition - closeVolume
                else:
                    yd_long_remain = 0
            else:
                td_short = abs(position)
                td_short_cost = abs(positionCost)
                yd_short = abs(ydPosition)
                if (abs(ydPosition) - openVolume) > 0:
                    yd_short_remain = abs(ydPosition) - openVolume
                else:
                    yd_short_remain = 0

        if save_flag:
            td_long_avail = yd_long
            td_short_avail = yd_short

            purchase_avail = yd_long
            prev_net = int(yd_long) - int(yd_short)

            position_db = Position()
            position_db.date = today_str
            position_db.id = account_info.accountid
            position_db.symbol = symbol
            position_db.hedgeflag = hedge_flag
            position_db.long = td_long
            position_db.long_cost = td_long_cost
            position_db.long_avail = td_long_avail
            position_db.short = td_short
            position_db.short_cost = td_short_cost
            position_db.short_avail = td_short_avail
            position_db.yd_position_long = yd_long
            position_db.yd_position_short = yd_short
            position_db.yd_long_remain = yd_long_remain
            position_db.yd_short_remain = yd_short_remain
            position_db.prev_net = prev_net
            position_db.purchase_avail = purchase_avail
            position_db.frozen = long_frozen
            position_db.update_date = datetime.now()
            position_list.append(position_db)
예제 #25
0
    def build_people_and_positions_from_opusxml(self):
        '''
        OPUS XML filen fra KMD indeholder to tags employee og orgunit.
        Denne funktion splitter "employee" tagget op i to dictionaries,
        som indeholder henholdsvis Person og Position objekter, der bliver
        kædet sammen med CPR.
        Der er også en reference til den orgunit som en position tilhører.

        I Person dictionary er CPR nøgle.
        I Position dictionary er OPUS ID (medarbejdernr) nøgle.
        Begge er unikke og ændre sig ikke.

        OBS: Et CPR nr kan i teorien godt ændre sig, hvis en person f.eks.
        skifter køn, men OPUS kan ikke håndtere den slags forandringer, derfor
        er det heller ikke et problem i dette script. Hvis OPUS engang bliver 
        woke, skal scriptet her rettes til.
        '''
        pos_repo = Position_repo(self.constr_lora)
        disabled_orgs = pos_repo.get_disabled_orgunits()
        for emp in self.root.findall('employee'):
            if emp.get('action') == None:
                cpr = emp.find('cpr').text
                opus_id = emp.get('id')
                los_id = int(emp.find('orgUnit').text)
                if los_id in disabled_orgs:
                    # vi har nogle orgunits som indeholder ikke-medarbejdere, dem ønsker vi ikke i SOFD'en og de bliver sorteret fra her.
                    continue

                userId = None
                if emp.find('userId') != None:
                    userId = emp.find('userId').text

                # sætter en start dato fra de forskellige datapunkter vi har at gøre godt med. Det er lidt rodet fordi det er en manuel indtastning fra løn
                # Entry date er aldrig none, men tom når der ikke er en dato
                startdate = None
                if emp.find('entryDate').text != None:
                    startdate = emp.find('entryDate').text
                elif emp.find('initialEntry') != None:
                    startdate = emp.find('initialEntry').text
                elif emp.find('entryIntoGroup') != None:
                    startdate = emp.find('entryIntoGroup').text

                if startdate == None:
                    # Hvis der ikke er en start dato for en stilling, er den oprettet forkert i løn og kan ikke meldes til vores andre systemer, derfor ignorer vi den.
                    print(opus_id)
                    continue
                else:
                    startdate = datetime.strptime(startdate, '%Y-%m-%d').date()

                leavedate = None
                if emp.find('leaveDate') != None:
                    leavedate = emp.find('leaveDate').text

                per = Person(cpr,
                             emp.find('firstName').text,
                             emp.find('lastName').text,
                             emp.find('address').text,
                             emp.find('postalCode').text,
                             emp.find('city').text,
                             emp.find('country').text,
                             True)

                pos = Position(opus_id,
                               None,
                               los_id,
                               cpr,
                               emp.find('cpr').get('suppId'),
                               emp.find('position').text,
                               emp.find('positionId').text,
                               emp.find('positionShort').text,
                               emp.find('payGradeText').text,
                               emp.find('isManager').text,
                               emp.find('workContract').text,
                               emp.find('workContractText').text,
                               emp.find('numerator').text,
                               emp.find('denominator').text,
                               emp.find('invoiceRecipient').text,
                               emp.find('productionNumber').text,
                               userId,
                               startdate,
                               leavedate,
                               None,
                               None,
                               True,
                               False,
                               False)

                self.persons[cpr] = per
                self.positions[int(opus_id)] = pos
            elif emp.get('action') == 'leave':
                # OPUS filen indeholder alle stillinger der har eksisteret, vi sorterer de nedlagte fra her.
                continue
def __build_account_position(account_id, investor_position_array):
    last_position_dict = dict()
    query_position = session_portfolio.query(Position)
    for position_db in query_position.filter(Position.id == account_id,
                                             Position.date == now_date_str):
        if position_db.symbol == 'CNY':
            continue
        last_position_dict[position_db.symbol] = position_db

    position_list = []
    position_dict = dict()
    ticker_position_dict = dict()
    for investorPosition in investor_position_array:
        symbol = getattr(investorPosition, 'm_strInstrumentID', 'NULL')
        # 过滤掉SP j1609&j1701这种的持仓数据
        if '&' in symbol:
            continue

        # 转换hedgeFlag字典
        hedge_flag = getattr(investorPosition, 'm_nHedgeFlag', '0')
        hedge_flag = HEDGE_FLAG_MAP[hedge_flag]

        key = '%s|%s' % (symbol, hedge_flag)
        if key in ticker_position_dict:
            ticker_position_dict.get(key).append(investorPosition)
        else:
            ticker_position_dict[key] = [investorPosition]

    for (key, ticker_position_list) in ticker_position_dict.items():
        (symbol, hedge_flag) = key.split('|')
        td_long = 0
        td_long_cost = 0.0
        yd_long_remain = 0

        td_short = 0
        td_short_cost = 0.0
        yd_short_remain = 0
        long_frozen = 0

        for temp_position in ticker_position_list:
            qty_value = int(getattr(temp_position, 'm_nPosition', '0'))
            qty_cost_value = float(
                getattr(temp_position, 'm_dPositionCost', '0'))

            #  1:净,2:多头,3:空头
            posiDirection_str = getattr(temp_position, 'm_nDirection', '0')
            posiDirection = Direction_Map[posiDirection_str]

            #  1:今日持仓,0:历史持仓
            is_today = getattr(temp_position, 'm_bIsToday', '0')
            if is_today == '0' and posiDirection == '2':
                yd_long_remain = qty_value
                td_long_cost += qty_cost_value
            elif is_today == '0' and posiDirection == '3':
                yd_short_remain = qty_value
                td_short_cost += qty_cost_value
            elif is_today == '1' and posiDirection == '2':
                td_long = qty_value
                td_long_cost += qty_cost_value
            elif is_today == '1' and posiDirection == '3':
                td_short = qty_value
                td_short_cost += qty_cost_value
            else:
                print 'error m_bIsToday:%s, posiDirection:%s' % (is_today,
                                                                 posiDirection)
                continue

        prev_net = yd_long_remain - yd_short_remain

        if symbol in last_position_dict:
            position_db = last_position_dict[symbol]
        else:
            position_db = Position()
            position_db.yd_position_long = yd_long_remain
            position_db.yd_position_short = yd_short_remain

        position_db.date = now_date_str
        position_db.id = account_id
        position_db.symbol = symbol
        position_db.hedgeflag = hedge_flag
        position_db.long = td_long + yd_long_remain
        position_db.long_cost = td_long_cost
        position_db.long_avail = td_long + yd_long_remain
        position_db.short = td_short + yd_short_remain
        position_db.short_cost = td_short_cost
        position_db.short_avail = td_short + yd_short_remain

        position_db.yd_long_remain = yd_long_remain
        position_db.yd_short_remain = yd_short_remain
        position_db.prev_net = prev_net
        position_db.frozen = long_frozen
        position_db.update_date = datetime.now()
        position_dict[key] = position_db
        position_list.append(position_db)
    return position_dict, position_list
def save_account_position(account_id, investor_position_array):
    tick_position_dict = dict()
    for investor_position in investor_position_array:
        symbol = getattr(investor_position, 'InstrumentID', 'NULL')
        hedge_flag = getattr(investor_position, 'HedgeFlag', '0')
        if hedge_flag == '1':
            hedge_flag = '0'
        elif hedge_flag == '2':
            hedge_flag = '1'
        elif hedge_flag == '3':
            hedge_flag = '2'
        key = '%s|%s' % (symbol, hedge_flag)
        if key in tick_position_dict:
            tick_position_dict.get(key).append(investor_position)
        else:
            tick_position_dict[key] = [investor_position]

    for (key, tickPositionList) in tick_position_dict.items():
        (symbol, hedge_flag) = key.split('|')

        td_long = 0
        td_long_cost = 0.0
        td_long_avail = 0

        yd_long = 0
        yd_long_remain = 0

        td_short = 0
        td_short_cost = 0.0
        td_short_avail = 0

        yd_short = 0
        yd_short_remain = 0

        long_frozen = 0
        short_frozen = 0
        prev_net = 0

        for temp_position in tickPositionList:
            # 转换hedgeFlag字典
            direction = getattr(temp_position, 'Direction', 'NULL')
            position = int(getattr(temp_position, 'Position', 'NULL'))
            position_cost = getattr(temp_position, 'PositionCost', 'NULL')
            yd_position = int(getattr(temp_position, 'YdPosition', 'NULL'))
            if direction == '0':
                td_long = position
                td_long_avail = position
                td_long_cost = position_cost
                yd_long = yd_position
            else:
                td_short = position
                td_short_avail = position
                td_short_cost = position_cost
                yd_short = yd_position

        prev_net = yd_long - yd_short
        (yd_long_remain, yd_short_remain) = calculation_by_trade(symbol, yd_long, yd_short)

        position_db = Position()
        position_db.date = today_str
        position_db.id = account_id
        position_db.symbol = symbol
        position_db.hedgeflag = hedge_flag
        position_db.long = td_long
        position_db.long_cost = td_long_cost
        position_db.long_avail = td_long_avail
        position_db.short = td_short
        position_db.short_cost = td_short_cost
        position_db.short_avail = td_short_avail
        position_db.yd_position_long = yd_long
        position_db.yd_position_short = yd_short
        position_db.yd_long_remain = yd_long_remain
        position_db.yd_short_remain = yd_short_remain
        position_db.prev_net = prev_net
        # position_db.purchase_avail = purchase_avail
        position_db.frozen = long_frozen
        position_db.update_date = datetime.now()
        position_list.append(position_db)
def __build_account_position(account_id, investor_position_array):
    position_list = []
    position_dict = dict()
    ticker_position_dict = dict()
    for investorPosition in investor_position_array:
        symbol = getattr(investorPosition, 'InstrumentID', 'NULL')
        # 过滤掉SP j1609&j1701这种的持仓数据
        if '&' in symbol:
            continue
        if local_server_name == 'huabao':
            if not ('IH' in symbol or 'IC' in symbol or 'IF' in symbol):
                continue
        if local_server_name == 'zhongxin':
            if 'IH' in symbol or 'IC' in symbol or 'IF' in symbol:
                continue

        # 转换hedgeFlag字典
        hedge_flag = getattr(investorPosition, 'HedgeFlag', '0')
        hedge_flag = const.HEDGE_FLAG_MAP[hedge_flag]

        key = '%s|%s' % (symbol, hedge_flag)
        if key in ticker_position_dict:
            ticker_position_dict.get(key).append(investorPosition)
        else:
            ticker_position_dict[key] = [investorPosition]

    for (key, ticker_position_list) in ticker_position_dict.items():
        (symbol, hedge_flag) = key.split('|')
        td_long = 0
        td_long_avail = 0
        td_long_cost = 0.0
        yd_long = 0
        yd_long_remain = 0

        td_short = 0
        td_short_avail = 0
        td_short_cost = 0.0
        yd_short = 0
        yd_short_remain = 0

        long_Frozen = 0
        short_Frozen = 0
        prev_net = 0

        posiDirection_dict = dict()
        for temp_position in ticker_position_list:
            #  1:净,2:多头,3:空头
            posiDirection = getattr(temp_position, 'PosiDirection', '0')
            if posiDirection in posiDirection_dict:
                posiDirection_dict[posiDirection].append(temp_position)
            else:
                posiDirection_dict[posiDirection] = [temp_position]

        for (posiDirection, direction_position_list) in posiDirection_dict.items():
            position = 0
            ydPosition = 0
            position_cost = 0.0
            for temp_position in direction_position_list:
                #  1:今日持仓,2:历史持仓
                positionDate = getattr(temp_position, 'PositionDate', '1')
                if positionDate == '1':
                    position = int(getattr(temp_position, 'Position', '0'))
                    position_cost = float(getattr(temp_position, 'PositionCost', '0'))
                    ydPosition = int(getattr(temp_position, 'YdPosition', '0'))
                elif positionDate == '2':
                    position += int(getattr(temp_position, 'Position', '0'))
                    position_cost = float(getattr(temp_position, 'PositionCost', '0'))
                    ydPosition += int(getattr(temp_position, 'YdPosition', '0'))
                else:
                    print 'error positionDate:', positionDate
                    continue

            if posiDirection == '1':
                td_long = position
                td_long_avail = position

                yd_long = ydPosition
                yd_long_remain = ydPosition

                td_long_cost = position_cost
            elif posiDirection == '2':
                td_long = position
                td_long_avail = position

                yd_long = ydPosition
                yd_long_remain = ydPosition

                td_long_cost = position_cost
            elif posiDirection == '3':
                td_short = position
                td_short_avail = position

                yd_short = ydPosition
                yd_short_remain = ydPosition

                td_short_cost = position_cost
            else:
                print 'error posiDirection:', posiDirection

        prev_net = yd_long - yd_short
        position_db = Position()
        position_db.date = now_date_str
        position_db.id = account_id
        position_db.symbol = symbol
        position_db.hedgeflag = hedge_flag
        position_db.long = td_long
        if symbol == '510050':
            pre_settlement_price = float(getattr(temp_position, 'PreSettlementPrice', '0'))
            position_db.long_cost = td_long * pre_settlement_price
            position_db.long_avail = yd_long_remain
        else:
            position_db.long_cost = td_long_cost
            position_db.long_avail = td_long_avail
        position_db.short = td_short
        position_db.short_cost = td_short_cost
        position_db.short_avail = td_short_avail
        position_db.yd_position_long = yd_long
        position_db.yd_position_short = yd_short
        position_db.yd_long_remain = yd_long_remain
        position_db.yd_short_remain = yd_short_remain
        position_db.prev_net = prev_net
        position_db.frozen = long_Frozen
        position_db.update_date = datetime.now()
        position_dict[key] = position_db
        position_list.append(position_db)
    return position_dict, position_list
def __calculation_position(account_id, position_info_list, trade_list):
    position_info_dict = dict()
    # 根据yd值还原早上持仓
    for position_db in position_info_list:
        position_db.td_buy_long = 0
        position_db.long_avail = position_db.yd_position_long
        position_db.yd_long_remain = position_db.yd_position_long

        position_db.td_sell_short = 0
        position_db.short_avail = position_db.yd_position_short
        position_db.yd_short_remain = position_db.yd_position_short
        position_info_dict[position_db.symbol] = position_db

    for trade_db in trade_list:
        if trade_db.symbol.upper() not in instrument_dict:
            print 'error trade ticker:%s' % trade_db.symbol
            continue
        instrument_db = instrument_dict[trade_db.symbol.upper()]

        if trade_db.symbol not in position_info_dict:
            position_db = Position()
            position_db.date = now_date_str
            position_db.id = account_id
            position_db.symbol = trade_db.symbol
            position_db.hedgeflag = 0

            qty = trade_db.qty
            total_cost = trade_db.qty * trade_db.price * instrument_db.fut_val_pt
            if qty >= 0:
                position_db.long = qty
                position_db.long_cost = total_cost
                position_db.long_avail = qty
                position_db.yd_position_long = 0
                position_db.yd_long_remain = 0

                position_db.short = 0
                position_db.short_cost = 0
                position_db.short_avail = 0
                position_db.yd_position_short = 0
                position_db.yd_short_remain = 0

                position_db.day_long = trade_db.qty
                position_db.day_long_cost = trade_db.qty * trade_db.price * instrument_db.fut_val_pt
            else:
                position_db.short = qty
                position_db.short_cost = total_cost
                position_db.short_avail = qty
                position_db.yd_position_short = 0
                position_db.yd_short_remain = 0

                position_db.long = 0
                position_db.long_cost = 0
                position_db.long_avail = 0
                position_db.yd_position_long = 0
                position_db.yd_long_remain = 0

                position_db.day_short = trade_db.qty
                position_db.day_short_cost = trade_db.qty * trade_db.price * instrument_db.fut_val_pt

            position_db.prev_net = 0
            position_db.frozen = 0
            position_db.update_date = datetime.now()
            position_info_dict[position_db.symbol] = position_db
        else:
            position_db = position_info_dict[trade_db.symbol]
            # 期货
            if instrument_db.type_id == 1:
                if trade_db.direction == 0:
                    # 买开
                    if trade_db.offsetflag == 0:
                        position_db.td_buy_long += trade_db.qty
                        position_db.long_cost += trade_db.qty * trade_db.price * instrument_db.fut_val_pt
                    # 买平
                    elif trade_db.offsetflag == 1:
                        a = min(trade_db.qty, position_db.short)
                        position_db.yd_short_remain -= max(
                            trade_db.qty - position_db.short, 0)
                        position_db.td_sell_short -= a
                        position_db.short_cost -= trade_db.qty * trade_db.price * instrument_db.fut_val_pt
                    # 买平昨
                    elif trade_db.offsetflag == 4:
                        position_db.yd_short_remain -= trade_db.qty

                    position_db.day_long += trade_db.qty
                    position_db.day_long_cost += trade_db.qty * trade_db.price * instrument_db.fut_val_pt
                elif trade_db.direction == 1:
                    # 卖开
                    if trade_db.offsetflag == 0:
                        position_db.td_sell_short += trade_db.qty
                        position_db.short_cost += trade_db.qty * trade_db.price * instrument_db.fut_val_pt
                    # 卖平
                    elif trade_db.offsetflag == 1:
                        a = min(trade_db.qty, position_db.long)
                        position_db.yd_long_remain -= max(
                            trade_db.qty - position_db.long, 0)
                        position_db.td_buy_long -= a
                        position_db.long_cost -= trade_db.qty * trade_db.price * instrument_db.fut_val_pt
                    # 卖平昨
                    elif trade_db.offsetflag == 4:
                        position_db.yd_long_remain -= trade_db.qty

                    position_db.day_short += trade_db.qty
                    position_db.day_short_cost += trade_db.qty * trade_db.price * instrument_db.fut_val_pt
                position_db.long_avail = position_db.td_buy_long + position_db.yd_long_remain
                position_db.short_avail = position_db.td_sell_short + position_db.yd_short_remain

                position_db.long = position_db.long_avail
                position_db.short = position_db.short_avail
            # 股票
            elif instrument_db.type_id == 4:
                if trade_db.direction == 0:
                    position_db.long += trade_db.qty
                    position_db.long_cost += trade_db.qty * trade_db.price * instrument_db.fut_val_pt
                elif trade_db.direction == 1:
                    position_db.long -= trade_db.qty
                    position_db.long_cost -= trade_db.qty * trade_db.price * instrument_db.fut_val_pt
                    position_db.short_avail -= trade_db.qty
            position_info_dict[position_db.symbol] = position_db

    result_list = []
    for key in position_info_dict.keys():
        result_list.append(position_info_dict[key])
    return result_list