Exemplo n.º 1
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()
Exemplo n.º 2
0
def img_upload(device_mac, device_pos,created_at, meta):
    if device_mac == "":
        return False

    if device_pos == "":
        return False
    dev = Device()
    pos = Position()
    #print "upload_img",device_mac,device_pos

    device_id = dev.get_device_by_mac(device_mac)
    position_id = pos.get_position_id(device_id, device_pos)
    print "upload",device_id,position_id
    upload_path = os.path.join(getPWDDir(), CAPTURED_DIR)
    filename = meta['filename']
    filename = os.path.basename(filename)
    print filename,'----',upload_path

    filepath = os.path.join(upload_path, filename)
    with open(filepath, 'wb') as up:
        up.write(meta['body'])

    img = Image()
    img.path = filename
    img.position_id = position_id
    img.created_at = created_at
    img_id = img.create()
    print img_id
    if not img_id:
        return False
    return True
Exemplo n.º 3
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
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)
Exemplo n.º 5
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)
Exemplo n.º 6
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()
Exemplo n.º 7
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
Exemplo n.º 8
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_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)
Exemplo n.º 10
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
Exemplo n.º 11
0
def up_and_down_check(board, position: Position):
    y = position.col - 1
    x = position.line - 1
    try:
        first_position: Position = board[(x - 1) - len(board)][y]
        second_position: Position = board[(x - 2) - len(board)][y]
        if position.check_player_eq(first_position, second_position):
            return True
    except IndexError:
        pass
    try:
        first_position: Position = board[x + 1][y]
        second_position: Position = board[x + 2][y]
        if position.check_player_eq(first_position, second_position):
            return True
    except IndexError:
        pass
    return False
Exemplo n.º 12
0
def plus_sing_check(board, position: Position):
    y = position.col - 1
    x = position.line - 1
    try:
        first_position: Position = board[x + 1][y]
        second_position: Position = board[(x - 1) - len(board)][y]
        if position.check_player_eq(first_position, second_position):
            return True
    except IndexError:
        pass
    try:
        first_position: Position = board[x][(y - 1) - len(board)]
        second_position: Position = board[x][y + 1]
        if position.check_player_eq(first_position, second_position):
            return True
    except IndexError:
        pass
    return False
Exemplo n.º 13
0
def vertical_check(board, position: Position):
    y = position.col - 1
    x = position.line - 1
    # vertical down right
    try:
        first_position: Position = board[x + 1][y + 1]
        second_position: Position = board[x + 2][y + 2]
        if position.check_player_eq(first_position, second_position):
            return True
    except IndexError:
        pass

    # vertical down left
    try:
        first_position: Position = board[x + 1][(y - 1) - len(board)]
        second_position: Position = board[x + 2][(y - 2) - len(board)]
        if position.check_player_eq(first_position, second_position):
            return True
    except IndexError:
        pass

    # vertical up left
    try:
        first_position: Position = board[(x - 1) - len(board)][(y - 1) -
                                                               len(board)]
        second_position: Position = board[(x - 2 - len(board))][(y - 2) -
                                                                len(board)]

        if position.check_player_eq(first_position, second_position):
            return True
    except IndexError:
        pass

    # Vertical up right
    try:
        first_position: Position = board[(x - 1) - len(board)][y + 1]
        second_position: Position = board[(x - 2) - len(board)][y + 2]

        if position.check_player_eq(first_position, second_position):
            return True
    except IndexError:
        pass

    return False
Exemplo n.º 14
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
Exemplo n.º 15
0
def right_and_left_check(board, position: Position):
    y = position.col - 1
    x = position.line - 1

    try:
        first_position: Position = board[x][y + 1]
        second_position: Position = board[x][y + 2]
        if position.check_player_eq(first_position, second_position):
            return True
    except IndexError:
        pass

    try:
        first_position: Position = board[x][(y - 1) - len(board)]
        second_position: Position = board[x][(y - 2) - len(board)]
        if position.check_player_eq(first_position, second_position):
            return True
    except IndexError:
        pass

    return False
Exemplo n.º 16
0
    def post(self):
        jdatas = json.loads(self.request.body)
        #device_mac = self.get_argument('mac', '')
        device_mac = jdatas['mac']

        dev = Device()
        device_id = dev.get_device_by_mac(device_mac)
        #position_infos = self.get_argument('positions', [])
        position_infos = jdatas['positions']

        for pos_info in position_infos:
            position = pos_info['position']
            object_name = pos_info['object_name']
            duration = pos_info['duration']
            pos = Position()
            pos.device_id = device_id
            pos.position = position
            pos.object_name = object_name
            pos.duration = duration
            pos_id = pos.create()
            print pos_id
            if not pos_id:
                self.write('fail')
                return
        self.write('ok')
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
Exemplo n.º 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]
Exemplo n.º 19
0
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)
Exemplo n.º 20
0
def get_summery_info(user):
    dev_observed = Device_Observed()
    res = {'user_name': user.name, 'device_counts': dev_observed.count_user_devices(user.id), 'device_info': []}
    devices = dev_observed.observed_devices(user.id)
    print devices
    pos = Position()
    for dev in devices:
        contents_dev = {}
        print dev
        contents_dev['location'] = dev.location
        contents_dev['position_contents'] = []
        positions = pos.get_position_by_device_id(dev.id)
        if positions:
            for pos in positions:
                img = Image()
                image_count = img.count_by('where position_id = ?', pos.id)
                contents_dev['position_contents'].append({'position': pos.position,
                                                          'duration': pos.duration,
                                                          'image_count': image_count,
                                                          'object_name': pos.object_name})
        res['device_info'].append(contents_dev)

    return res
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
Exemplo n.º 22
0
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
    })
Exemplo n.º 23
0
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
    })
Exemplo n.º 24
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
Exemplo n.º 25
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
Exemplo n.º 26
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
Exemplo n.º 27
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)
Exemplo n.º 28
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
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)
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 __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 get(self):

        usr = self.get_current_user()

        device_observed = Device_Observed()
        position = Position()
        image = Image()
        devices = device_observed.observed_devices(usr.id)
        if not devices or len(devices) < 1:
            return self.render('no_devices.html', user_name=usr.name, page_name="browser")

        positions = []
        for dev in devices:
            positions.extend(position.get_position_by_device_id(dev.id))
            current_position_id = self.get_argument('position_id', '')
        current_page = self.get_argument('page', '')
        if current_page:
            current_page = int(current_page)
        else:
            current_page = 1
            
        if current_position_id:
            current_position_id = current_position_id
        else:
            # positions = position.get_position_by_device_id(devices[0].id)
            if positions:
                current_position_id = positions[0].id
            else:
                current_position_id = 0
        total_image_num = image.count_by_position_id(current_position_id)
        total_page_num = total_image_num/IMAGE_NUMBER_FOR_PAGE+1
        start_image_num = (current_page - 1)*IMAGE_NUMBER_FOR_PAGE + 1

        if total_page_num < current_page:
            current_page = total_page_num

        images = image.find_by('order by id desc limit ? offset ?',
                               IMAGE_NUMBER_FOR_PAGE,
                               (current_page - 1)*IMAGE_NUMBER_FOR_PAGE)
        for img in images:
            img.created_at = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(img.created_at))
        # get the start and end page num
        if current_page > 3:
            start_page_num = current_page-3
        else:
            start_page_num = 1

        end_page_num = start_page_num+6
        if end_page_num>total_page_num:
            end_page_num = total_page_num
            start_page_num = end_page_num-6
            if start_page_num<1:
                start_page_num = 1

        end_image_num  = start_image_num+len(images)-1

        return self.render('browser.html',
                           page_name='browser',
                           positions=positions,
                           current_position_id=current_position_id,
                           current_page=current_page,
                           total_page_num=total_page_num,
                           total_image_num=total_image_num,
                           start_image_num=start_image_num,
                           end_image_num=end_image_num,
                           start_page_num=start_page_num,
                           end_page_num=end_page_num,
                           user_name=usr.name,
                           images=images
                           )
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
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
Exemplo n.º 35
0
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)
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