如何打印defaultdict自定义对象?

时间:2014-02-17 20:09:49

标签: python defaultdict

我正在尝试打印存储在defaultdict变量中的值,但我得到的只是它们的内存位置。

from enum import Enum
import datetime
from collections import defaultdict
import types
import pprint
from operator import itemgetter , attrgetter

class Order(object):

    def __init__(self, traderId,sym, qty,orderId,order_type,price,AON,trans):
        self.orderId = orderId;
        self.traderId = traderId;
        self.symbol = sym;
        self.quantity = qty;
        self.price = price;
        self.orderId = orderId;
        self.AllOrNone = AON;
        self.trans = trans;
        self.orderFilled = False;
        self.type = order_type;
        self.timeStamp = datetime.datetime.now()
        self.cancel = False


class INSTRUMENTS(Enum):
    VOD = "VOD"
    GOOG = "GOOG"
    IBM = "IBM"
    AMZN = "AMZN"
    EBAY = "EBAY"
    YHOO = "YHOO"
    MSFT = "MSFT"

class TYPE(Enum):
    BID = "BID"
    ASK = "Ask"

class TRANS_TYPE(Enum):
    MARKET = "Market order"
    LIMIT = "Limited order"

class Exchange:

    def __init__(self):
        print 'Exchange opened'
        self.orderBook = OrderBook()
        self.orders = []

    # new order from the server
    def newOrder(self,orderIn):
        # first check if the order already exists
        # If order exists, check if a cancel order
        # If not a cancel order check if parameters are the same
        orderIn.time = datetime.datetime.now()

        # process order depending of type
        if(orderIn.type == TYPE.ASK or orderIn.type == TYPE.BID):
            # create new book entry
            add_status = self.orderBook.add_order(orderIn)
            # if successful, add to list of orders
            if(add_status):
                self.orders.append(orderIn)
                return True
            else:
                return False
        else:
            print 'Invalid order: order type required!'
            return False

    def cancel_order(self,orderIn):
        print 'removing ...'
        status = self.orderBook.delete_Order(orderIn)
        if(status):
            #self.orders.remove(orderIn)
            return True
        else:
            return False

    def floating_orders(self):
        self.orderBook.display_book(INSTRUMENTS.EBAY)


class Price_Qty:
    def __init__(self,orderIn):
        self.quantity = orderIn.quantity
        self.price = orderIn.price
        self.orderId = orderIn.orderId
        self.depth = 0
        self.spread = None
        self.best_ask = None
        self.best_bid = None
        self.traderId = orderIn.traderId
        self.type = orderIn.type
        self.symbol = orderIn.symbol


class OrderBook:
    def __init__(self):
        self.asks = defaultdict(list)
        self.bids = defaultdict(list)
        self.tape = []


    def display_book(self,symbol):
        """ given a symbol, display the orders """
        asks = self.asks[symbol]
        bids = self.asks[symbol]
        if asks is not None:
            for item in asks:
                print(item.pop())
                #print str(item.symbol) + ' ' + str(item.quantity) + ' ' + str(item.symbol) + ' at ' + str(item.price)
        if bids is not None:
            for item in bids:
                print(item.pop())
                #print str(item.type) + ' ' + str(item.quantity) + ' ' + str(item.symbol) + ' at ' + str(item.price)

    def sort_book(self,orderIn):
        if orderIn.type == TYPE.ASK:
            # reverse sort in descending order
            print str(self.asks[orderIn.symbol])
            self.asks[orderIn.symbol].sort(key = lambda x: x.price)
        else:
            #sort in ascending order
            self.bids[orderIn.symbol].sort(key = lambda x: x.price)

    def add_order(self,orderIn):
        if orderIn is None:
            print 'Add operation failed: order object is null'
            return False
        if(orderIn.type == TYPE.BID):
            temp = self.bids
        elif(orderIn.type == TYPE.ASK):
            temp = self.asks
        else:
            print 'Add operation failed: order has no type provided'
            return False
        # If book for this symbol empty, create one
        if len(temp) == 0:
            print str(orderIn.symbol) + ' book empty.\n ' + ' Creating book...'
            # create new defaultdict entry for this symbol
            # 'symbol' is the unique key and value return for this key is a list of Price_Qty objects
            temp[orderIn.symbol] = [Price_Qty(orderIn)]
            return True
        elif (temp.has_key(orderIn.symbol)):
            # if the symbol already exists in the list,
            # first retrieve the list and append the new pair
            temp[orderIn.symbol].append(Price_Qty(orderIn))
            self.sort_book(orderIn)
            #self.display_book(INSTRUMENTS.AMZN)
            print 'order successfully added to the book'
            return True
        else: 
            #print 'This should not happen : Add_order failed!: fail to add ' + str(orderIn.symbol) + ' ask/bid: ' + orderIn.type
            print str(orderIn.symbol) + ' order placed '
            temp[orderIn.symbol] = [Price_Qty(orderIn)]
            return True

        # bid side of the book is empty
    def delete_Order(self,orderIn):
        if orderIn is None:
            print 'Cancelling delete operation... Object passed is null'
            return False
        if(orderIn.type == TYPE.BID):
            bookIn = self.bids
        elif(orderIn.type == TYPE.ASK):
            print 'deleting ask order...'
            bookIn = self.asks
        else:
            print 'Delete operation failed!'
            return False
        if len(bookIn) == 0:
            print str(orderIn.type) + ' book empty'
            return False
        elif(bookIn.has_key(orderIn.symbol)):
            print 'deleting ' + str(orderIn.type) +' of ' + str(orderIn.quantity) +' '+ str(orderIn.symbol) + ' from book'
            # identify the correct book 
            key = orderIn.symbol
            # extract the list of orders for this symbol
            _list = bookIn[key]
            if(_list is None):
                print 'book for ' + str(orderIn.symbol) + ' is empty'
                return False
            else:
                for item in _list:
                    if(item.orderId == orderIn.orderId and item.traderId == orderIn.traderId):
                        _list.remove((item))
                        print 'order deleted'
                        return True
        else:
            print 'Fail to remove buy order! order id = ' +str(orderIn.orderId) 
            return False



newOrder1 = Order(1,INSTRUMENTS.AMZN,7,1,TYPE.BID,45,True,TRANS_TYPE.MARKET)
newOrder2 = Order(2,INSTRUMENTS.EBAY,26,3,TYPE.BID,8,True,TRANS_TYPE.MARKET)
newOrder3 = Order(3,INSTRUMENTS.AMZN,15,4,TYPE.ASK,5,True,TRANS_TYPE.MARKET)
newOrder4 = Order(4,INSTRUMENTS.GOOG,44,5,TYPE.BID,4,True,TRANS_TYPE.MARKET)
newOrder5 = Order(5,INSTRUMENTS.IBM,7,1,TYPE.ASK,55,True,TRANS_TYPE.MARKET)
newOrder6 = Order(6,INSTRUMENTS.AMZN,6,3,TYPE.ASK,8,True,TRANS_TYPE.MARKET)
newOrder7 = Order(7,INSTRUMENTS.EBAY,5,4,TYPE.BID,5,True,TRANS_TYPE.MARKET)
newOrder8 = Order(8,INSTRUMENTS.AMZN,4,5,TYPE.ASK,4,True,TRANS_TYPE.MARKET)

newExchange = Exchange()

newExchange.newOrder(newOrder1)
newExchange.newOrder(newOrder2)
newExchange.newOrder(newOrder3)
newExchange.newOrder(newOrder4)
newExchange.newOrder(newOrder5)
newExchange.newOrder(newOrder6)
newExchange.newOrder(newOrder7)
newExchange.newOrder(newOrder8)
newExchange.cancel_order(newOrder4)
newExchange.floating_orders()

此代码打印方法输出:

[< main .Price_Qty实例位于0x00000000024BD608>,< main .Price_Qty实例位于0x00000000024BD6C8>,< main .Price_Qty实例位于0x00000000024BD748>]

有任何帮助

0 个答案:

没有答案