• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python market.Market类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中market.Market的典型用法代码示例。如果您正苦于以下问题:Python Market类的具体用法?Python Market怎么用?Python Market使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Market类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test

def test():
  player = Player(1, Team("Na'Vi", Sides.CT), .5, .2)
  Market.loadout_player(player, True)
  print player.loadout
  player.money += 4400
  Market.loadout_player(player, False)
  print player.loadout
开发者ID:vmgarcia,项目名称:CSGOSim,代码行数:7,代码来源:team.py


示例2: MarketApplication

class MarketApplication(tornado.web.Application):

    def __init__(self, market_ip, market_port, market_id=1,
                    bm_user=None, bm_pass=None, bm_port=None, seed_mode=0, dev_mode=False):

        self.transport = CryptoTransportLayer(market_ip,
                                               market_port,
                                               market_id,
                                               bm_user,
                                               bm_pass,
                                               bm_port,
                                               seed_mode,
                                               dev_mode)

        if seed_mode == 0:
            self.transport.join_network(dev_mode=dev_mode)

        self.market = Market(self.transport)
        self.market.republish_contracts()

        handlers = [
            (r"/", MainHandler),
            (r"/main", MainHandler),
            (r"/html/(.*)", tornado.web.StaticFileHandler, {'path': './html'}),
            (r"/ws", WebSocketHandler,
                dict(transport=self.transport, market=self.market))
        ]

        # TODO: Move debug settings to configuration location
        settings = dict(debug=True)
        tornado.web.Application.__init__(self, handlers, **settings)

    def get_transport(self):
        return self.transport
开发者ID:benhc123,项目名称:OpenBazaar,代码行数:34,代码来源:tornadoloop.py


示例3: respawn_players

  def respawn_players(self, env, pistol):

    for player in self.players:
      if (pistol):
        player.reset_money()

      player.respawn(env, pistol)
      Market.loadout_player(player, pistol)
开发者ID:vmgarcia,项目名称:CSGOSim,代码行数:8,代码来源:team.py


示例4: deadw

def deadw(m):
    "Computes deadweight loss for market m."
    # == Create analogous market with no tax == #
    m_no_tax = Market(m.ad, m.bd, m.az, m.bz, 0)   
    # == Compare surplus, return difference == #
    surp1 = m_no_tax.consumer_surp() + m_no_tax.producer_surp()  
    surp2 = m.consumer_surp() + m.producer_surp() + m.taxrev()
    return surp1 - surp2
开发者ID:361793842,项目名称:QuantEcon.applications,代码行数:8,代码来源:market_deadweight.py


示例5: FxSystem

class FxSystem(object):
    def __init__(self, pair, period, data_file):
        self.market = Market(pair, period)
        self.market.load_data(data_file)
        self.account = Account(self.market)

    def __repr__(self):
        out = "Fx System Trading {0} {1}.".format(self.market, self.account)
        return out
开发者ID:nanojack,项目名称:fx,代码行数:9,代码来源:main.py


示例6: hist_test

def hist_test(rounds=1):
    agent_types = ['miner', 'farmer', 'refiner', 'woodcutter', 'blacksmith']
    agents = [Agent(random.choice(agent_types)) for i in range(100)] # 100 random angets
    agents = {agent.id: agent for agent in agents}

    market = Market()
    market.agents = agents

    for i in range(rounds): #10 rounds of market simulation   
        market.simulate()

    return market.history.export()
开发者ID:johny5w,项目名称:market_sim,代码行数:12,代码来源:test.py


示例7: build_market

def build_market(num_agents):
    """ This returns a market with the number of agents from the parameter
    right now, 100,000 agents is about the most it can handle.  I was able to create a market with 500,000
    but one round of market.simulate() took over a minute.  1,000,000 agents couldn't even be created."""
    agent_types = ['miner', 'farmer', 'refiner', 'woodcutter', 'blacksmith']
    agents = [Agent(random.choice(agent_types)) for i in range(num_agents)] # 100 random angets
    agents = {agent.id: agent for agent in agents}

    market = Market()
    market.agents = agents
    
    return market
开发者ID:johny5w,项目名称:market_sim,代码行数:12,代码来源:test.py


示例8: MarketApplication

class MarketApplication(tornado.web.Application):

    def __init__(self, market_ip, market_port, market_id=1,
                    bm_user=None, bm_pass=None, bm_port=None, seed_peers=[],
                    seed_mode=0, dev_mode=False, db_path='db/ob.db'):

        db = Obdb(db_path)

        self.transport = CryptoTransportLayer(market_ip,
                                               market_port,
                                               market_id,
                                               db,
                                               bm_user,
                                               bm_pass,
                                               bm_port,
                                               seed_mode,
                                               dev_mode)

        self.market = Market(self.transport, db)

        def post_joined():
            self.transport._dht._refreshNode()
            self.market.republish_contracts()

        if seed_mode == 0:
            self.transport.join_network(seed_peers, post_joined)
            ioloop.PeriodicCallback(self.transport.join_network, 60000)
        else:
            self.transport.join_network([], post_joined)
            ioloop.PeriodicCallback(self.transport.join_network, 60000)

        Thread(target=reactor.run, args=(False,)).start()

        handlers = [
            (r"/", MainHandler),
            (r"/main", MainHandler),
            (r"/html/(.*)", tornado.web.StaticFileHandler, {'path': './html'}),
            (r"/ws", WebSocketHandler,
                dict(transport=self.transport, market=self.market, db=db))
        ]

        # TODO: Move debug settings to configuration location
        settings = dict(debug=True)
        tornado.web.Application.__init__(self, handlers, **settings)




    def get_transport(self):
        return self.transport
开发者ID:incorpusyehtee,项目名称:OpenBazaar,代码行数:50,代码来源:tornadoloop.py


示例9: __init__

    def __init__(self, market_ip, market_port, market_id=1,
                    bm_user=None, bm_pass=None, bm_port=None, seed_peers=[],
                    seed_mode=0, dev_mode=False, db_path='db/ob.db'):

        db = Obdb(db_path)
        self.transport = CryptoTransportLayer(market_ip,
                                               market_port,
                                               market_id,
                                               db,
                                               bm_user,
                                               bm_pass,
                                               bm_port,
                                               seed_mode,
                                               dev_mode)

        if seed_mode == 0:
            self.transport.join_network(seed_peers)

        self.market = Market(self.transport, db)
        self.market.republish_contracts()

        handlers = [
            (r"/", MainHandler),
            (r"/main", MainHandler),
            (r"/html/(.*)", tornado.web.StaticFileHandler, {'path': './html'}),
            (r"/ws", WebSocketHandler,
                dict(transport=self.transport, market=self.market, db=db))
        ]

        # TODO: Move debug settings to configuration location
        settings = dict(debug=True)
        tornado.web.Application.__init__(self, handlers, **settings)
开发者ID:kawalgrover,项目名称:OpenBazaar,代码行数:32,代码来源:tornadoloop.py


示例10: __init__

 def __init__(self):
     # Gui.__init__(self)
     # gui
     self.root = Tk()
     # compositions
     self.travian = Travian(self.root)
     self.market = Market(self.root, self.travian)
     self.raiding = Raiding(self.root, self.travian)
     self.info = Info(self.root, self.travian)
     # self.mail = Mail()
     # frames
     self.exit_frame = Frame(self.root, bd=5, relief=GROOVE)
     # items
     self.intvars = self.create_intvars()
     self.msg_var = StringVar()
     self.msg_var.set('Messages')
     self.old_news = self.create_news()
     self.news = self.create_news()
     # widgets
     self.buttons = self.create_buttons()
     self.checkboxes = self.create_checkboxes()
     self.messages = self.create_messages()
     # configure gui
     self.config_root()
     self.make_market_frame()
     self.make_raid_frame()
     self.make_info_frame()
     self.make_exit_frame()
开发者ID:michareichmann,项目名称:Travian,代码行数:28,代码来源:travian-gui.py


示例11: main

def main():
    
    clear()
    print('Initializing Test...')
    
    print('Creating Agents...')
    
    agent_types = ['miner', 'farmer', 'refiner', 'woodcutter', 'blacksmith']
    agents = [Agent(random.choice(agent_types)) for i in range(100)] # 100 random angets
    agents = {agent.id: agent for agent in agents}
    
    # Debug Printing
    #print('Sample Agents...')
    #for agent in agents[:10]:
    #    print(agent)
    
    input('Hit any key to continue...')
    print('Creating Market...')
    market = Market()
    market.agents = agents #This needs to be part of the api for Market class
   
    
    for i in range(50): #10 rounds of market simulation    
        clear()
        market.simulate()
        report = market.market_report()    
        print(report)
        report = market.agent_report()
        print(report)
        input('Hit any key to continue...')
开发者ID:johny5w,项目名称:market_sim,代码行数:30,代码来源:test.py


示例12: test_market

def test_market(n, m, t, partial, writer):
    market = Market(n, m, t, partial)
    serialDictatorship.serial_dictatorship(market)
    serial_happy = evaluation.happy(market)
    serial_percent_served = evaluation.percent_served(market)
    serial_avg_time = evaluation.average_time(market)

    market.reset()
    serialDictatorship.modified_serial_dictatorship(market)
    mod_happy = evaluation.happy(market)
    mod_percent_served = evaluation.percent_served(market)
    mod_avg_time = evaluation.average_time(market)

    market.reset()
    minLocations.minimize_locations(market)
    min_loc_happy = evaluation.happy(market)
    min_loc_percent_served = evaluation.percent_served(market)
    min_loc_avg_time = evaluation.average_time(market)

    row = [n, m, t, partial, serial_happy, serial_percent_served,
           serial_avg_time, mod_happy, mod_percent_served, mod_avg_time,
           min_loc_happy, min_loc_percent_served, min_loc_avg_time]
    writer.writerow(row)
开发者ID:R4chel,项目名称:CornellDiningMatchingMarkets,代码行数:23,代码来源:results.py


示例13: __init__

    def __init__(self, market_ip, market_port, market_id=1,
                 bm_user=None, bm_pass=None, bm_port=None, seed_peers=[],
                 seed_mode=0, dev_mode=False, db_path='db/ob.db'):

        db = Obdb(db_path)

        self.transport = CryptoTransportLayer(market_ip,
                                              market_port,
                                              market_id,
                                              db,
                                              bm_user,
                                              bm_pass,
                                              bm_port,
                                              seed_mode,
                                              dev_mode)

        self.market = Market(self.transport, db)

        def post_joined():
            self.transport.dht._refreshNode()
            self.market.republish_contracts()

        peers = seed_peers if seed_mode == 0 else []
        self.transport.join_network(peers)

        Thread(target=reactor.run, args=(False,)).start()

        handlers = [
            (r"/", MainHandler),
            (r"/main", MainHandler),
            (r"/html/(.*)", OpenBazaarStaticHandler, {'path': './html'}),
            (r"/ws", WebSocketHandler,
                dict(transport=self.transport, market_application=self, db=db))
        ]

        # TODO: Move debug settings to configuration location
        settings = dict(debug=True)
        tornado.web.Application.__init__(self, handlers, **settings)
开发者ID:meeh420,项目名称:OpenBazaar,代码行数:38,代码来源:openbazaar_daemon.py


示例14: MarketApplication

class MarketApplication(tornado.web.Application):
    def __init__(self, market_ip, market_port, market_id=1,
                 bm_user=None, bm_pass=None, bm_port=None, seed_peers=[],
                 seed_mode=0, dev_mode=False, db_path='db/ob.db'):

        db = Obdb(db_path)

        self.transport = CryptoTransportLayer(market_ip,
                                              market_port,
                                              market_id,
                                              db,
                                              bm_user,
                                              bm_pass,
                                              bm_port,
                                              seed_mode,
                                              dev_mode)

        self.market = Market(self.transport, db)

        def post_joined():
            self.transport.dht._refreshNode()
            self.market.republish_contracts()

        peers = seed_peers if seed_mode == 0 else []
        self.transport.join_network(peers)

        Thread(target=reactor.run, args=(False,)).start()

        handlers = [
            (r"/", MainHandler),
            (r"/main", MainHandler),
            (r"/html/(.*)", OpenBazaarStaticHandler, {'path': './html'}),
            (r"/ws", WebSocketHandler,
                dict(transport=self.transport, market_application=self, db=db))
        ]

        # TODO: Move debug settings to configuration location
        settings = dict(debug=True)
        tornado.web.Application.__init__(self, handlers, **settings)

    def get_transport(self):
        return self.transport

    def setup_upnp_port_mappings(self, http_port, p2p_port):
        upnp.PortMapper.DEBUG = False
        print "Setting up UPnP Port Map Entry..."
        # TODO: Add some setting whether or not to use UPnP
        # if Settings.get(Settings.USE_UPNP_PORT_MAPPINGS):
        self.upnp_mapper = upnp.PortMapper()
        # TODO: Add some setting whether or not to clean all previous port
        # mappings left behind by us
        # if Settings.get(Settings.CLEAN_UPNP_PORT_MAPPINGS_ON_START):
        #    upnp_mapper.cleanMyMappings()

        # for now let's always clean mappings every time.
        self.upnp_mapper.clean_my_mappings()
        # result_http_port_mapping = self.upnp_mapper.add_port_mapping(http_port,
        #                                                             http_port)
        # print ("UPnP HTTP Port Map configuration done (%s -> %s) => %s" %
        #        (str(http_port), str(http_port), str(result_http_port_mapping)))

        result_tcp_p2p_mapping = self.upnp_mapper.add_port_mapping(p2p_port,
                                                                   p2p_port)
        print ("UPnP TCP P2P Port Map configuration done (%s -> %s) => %s" %
               (str(p2p_port), str(p2p_port), str(result_tcp_p2p_mapping)))

        result_udp_p2p_mapping = self.upnp_mapper.add_port_mapping(p2p_port,
                                                                   p2p_port,
                                                                   'UDP')
        print ("UPnP UDP P2P Port Map configuration done (%s -> %s) => %s" %
               (str(p2p_port), str(p2p_port), str(result_udp_p2p_mapping)))

        result = result_tcp_p2p_mapping and result_udp_p2p_mapping
        if not result:
            print("Warning: UPnP was not setup correctly. Try doing a port forward on %s and start the node again with -j" % p2p_port)

        return result

    def cleanup_upnp_port_mapping(self):
        try:
            if self.upnp_mapper is not None:
                print "Cleaning UPnP Port Mapping -> ", \
                    self.upnp_mapper.clean_my_mappings()
        except AttributeError:
            print "[openbazaar] MarketApplication.clean_upnp_port_mapping() failed!"
            pass

    def shutdown(self, x=None, y=None):
        print "MarketApplication.shutdown!"
        locallogger = logging.getLogger('[%s] %s' % (self.market.market_id, 'root'))
        locallogger.info("Received TERMINATE, exiting...")

        # application.get_transport().broadcast_goodbye()
        self.cleanup_upnp_port_mapping()
        tornado.ioloop.IOLoop.instance().stop()

        self.transport.shutdown()
        os._exit(0)
开发者ID:meeh420,项目名称:OpenBazaar,代码行数:98,代码来源:openbazaar_daemon.py


示例15: __init__

 def __init__(self, pair, period, data_file):
     self.market = Market(pair, period)
     self.market.load_data(data_file)
     self.account = Account(self.market)
开发者ID:nanojack,项目名称:fx,代码行数:4,代码来源:main.py


示例16: Advisor

        # profit - buy base / sell quote
        if self.quote > 0.0:
            profit = self.quote / self.market.get_ask()
        else: # loss - sell base / buy quote
            profit = self.quote / self.market.get_bid()

        #print "Opened at {0}, closed at {1}".format(self.position['price'], price)
        #print "PROFIT: {0} = {1}%".format(profit, 100*profit/self.position['price'])
 
        return profit

class Advisor(object):
    '''
    Uses technical indicators to advise on trading decisions
    '''
    def  __init__(self):
        pass



if __name__ == "__main__":
    market = Market("GBPCAD", "10m")
    market.load_data(DATA_FILE)
    account = Account(market)
    '''
    add the indicators
    need to implement indicators.INDICATOR_INFO
    to matche number of columns and names against talib functions
    '''

开发者ID:nanojack,项目名称:fx,代码行数:29,代码来源:new_account.py


示例17: Market

from market import Market

YHOO = Market("YHOO")

print YHOO.price

YHOO.pull_prices()

开发者ID:larrtang,项目名称:Public-Projects,代码行数:7,代码来源:main.py


示例18: capitalise

    def capitalise(self, environment, time):
        # We will ration the remaining excess deposits
        # and loan as capital ownership transfers
        # to balance books, if books don't need to be
        # balanced the same would work strictly on deposits
        # and loans with no capital explicitly

        # First resolve capital shortfall for firms
        # ie when firm needs to sell existing  capital instead of getting new owners
        for firm in environment.firms:
            # We calculate how much capital the firm has
            capital = 0.0
            for tranx in firm.accounts:
                if tranx.type_ == "capital":
                    if tranx.from_ == firm:
                        capital = capital + tranx.amount
                    if tranx.to == firm:
                        capital = capital - tranx.amount
            # Then find the firm's supply of capital given current books
            supply = -capital - firm.get_account("deposits") + firm.get_account("loans")
            # If there is a shortfall of capital supply
            if supply < 0.0:
                # We go through the books
                for tranx in firm.accounts:
                    # And find capital transactions
                    if tranx.type_ == "capital" and tranx.from_ == firm:
                        # Then we sell the appropriate amount to cover the shortfall
                        # TODO: we may want the sellout to be proportional or at least
                        # going through books at random, though in the current model it shouldn't matter
                        to_remove = min(-supply, tranx.amount)
                        tranx.amount = tranx.amount - to_remove
                        supply = supply + to_remove

        # First, we create the list that will be used for rationing
        # method from Market class, containing agents and their
        # excess supply or demand
        for_rationing = []

        # First we find household's demand for buying capital of the firms
        for household in environment.households:
            # We calculate the demand as the amount of wealth (deposits-loans) minus previously owned capital
            # We calculate capital by hand in case there is some reverse ownership
            deposits = 0.0
            loans = 0.0
            capital = 0.0
            for tranx in household.accounts:
                if tranx.type_ == "deposits":
                    if tranx.from_ == household:
                        deposits = deposits + tranx.amount
                if tranx.type_ == "loans":
                    if tranx.to == household:
                        loans = loans + tranx.amount
                if tranx.type_ == "capital":
                    if tranx.to == household:
                        capital = capital + tranx.amount
                    if tranx.from_ == household:
                        capital = capital - tranx.amount
            # demand = household.get_account("deposits") - household.get_account("loans") - household.get_account("capital")
            demand = deposits - loans - capital
            # And we add the household together with its demand to the list
            for_rationing.append([household, -demand])

        for firm in environment.firms:
            # Supply of the firms is the opposite of the demand of the household
            # that is the loans minus issued capital claims minus deposits
            # We calculate capital by hand in case there is some reverse ownership
            capital = 0.0
            for tranx in firm.accounts:
                if tranx.type_ == "capital":
                    if tranx.from_ == firm:
                        capital = capital + tranx.amount
                    if tranx.to == firm:
                        capital = capital - tranx.amount
            supply = -capital - firm.get_account("deposits") + firm.get_account("loans")
            # supply = -firm.get_account("capital") - firm.get_account("deposits") + firm.get_account("loans")
            # And we add the firm together with its supply to the list
            for_rationing.append([firm, supply])

        # We initialise the market clearing class
        from market import Market

        market = Market("market")

        # We find the pairs of capital ownership transfers
        # We move the capital proportionately with respect to demand
        rationed = market.rationing_proportional(for_rationing)

        # We add these to the books
        for ration in rationed:
            environment.new_transaction("capital", "", ration[0].identifier, ration[1].identifier, ration[2], 0, 0, -1)
            # And print it to the screen for easy greping
            print("%s sold %f worth of capital to %s at time %d.") % (
                ration[0].identifier,
                ration[2],
                ration[1].identifier,
                time,
            )

        # And net the capital transactions, so we don't accumulate
        # them over the course of the transaction
#.........这里部分代码省略.........
开发者ID:cogeorg,项目名称:black_rhino,代码行数:101,代码来源:updater.py


示例19: consume_rationed

    def consume_rationed(self, environment, time):
        # We want the consumption to be done in random pairs
        # We use rationing from market clearing class to do that
        # Price is static for this example, otherwise we can't use rationing
        # and need some other market clearing
        price = 10.0
        environment.variable_parameters["price_of_goods"] = price
        # We need a list of agents and their demand or supply
        # Supply is denoted with positive float, demand with negative float
        for_rationing = []
        # Firms give us their supply, we assume that since the goods are
        # perishable their supply is all they have in stock
        from src.helper import Helper

        helper = Helper()
        for firm in environment.firms:
            # Firms produce based on their capital, for generality
            # we use their net capital, as in their capital stock
            # minus the capital owned of other agents
            capital = 0.0
            for tranx in firm.accounts:
                # This is own capital stock
                if tranx.type_ == "capital" and tranx.from_ == firm:
                    capital = capital + tranx.amount
                # And here is the ownership of other agents' stock
                if tranx.type_ == "capital" and tranx.to == firm:
                    capital = capital - tranx.amount
            # We find the amount produced through the Cobb-Douglas function
            amount = (
                helper.cobb_douglas(
                    firm.get_account("labour"),
                    capital,
                    firm.total_factor_productivity,
                    firm.labour_elasticity,
                    firm.capital_elasticity,
                )
                * price
            )
            # And assume firm wants to sell whole production given the perishable nature of the goods
            for_rationing.append([firm, amount])
        # Households give use their demand, we assume that they want to
        # consume the part of their wealth (cash and deposits) that they
        # do not want to save (determined through propensity to save)
        # We denote demand in units of the goods, so we divide the cash
        # households want to spend by price to get the demand
        for household in environment.households:
            demand = 0.0
            wealth = 0.0
            # For generality we calculate net wealth for this, that is the
            # amount of deposits they carry minus the amount of loans
            for tranx in household.accounts:
                if tranx.type_ == "deposits" and tranx.from_ == household:
                    wealth = wealth + tranx.amount
                if tranx.type_ == "loans" and tranx.to == household:
                    wealth = wealth - tranx.amount
            # Then the demand is determined by the agent's propensity to save
            # and the wealth calculated above
            demand = -((wealth * (1 - household.propensity_to_save)) / price)
            for_rationing.append([household, demand])
        # We import the market clearing class
        from market import Market

        # Put the appropriate settings, i.e.
        # tolerance of error, resolution of search
        # and amplification for exponential search
        # This does not matter for rationing
        # But in principle we need to initialize
        # with these values
        market = Market("market")
        # And we find the rationing, ie the amounts
        # of goods sold between pairs of agents
        # We find the actual trades
        rationed = market.rationing_proportional(for_rationing)
        # Then we go through the rationing
        # and move the goods and cash appropriately
        for ration in rationed:
            #
            #             A (from)    L (to)
            # bank        loan        deposit
            # household   goods       loan
            # firm        deposit     goods
            #
            # TODO: in the new version this may be irrelevant
            environment.new_transaction("goods", "", ration[1].identifier, ration[0].identifier, ration[2], 0, 0, -1)
            # The below makes sure the allocations of loans are correct
            # That is the banks don't allow overdraft for buying
            # consumption goods by the households
            to_finance = ration[2] * price
            itrange = list(range(0, len(environment.banks)))
            # And randomise this list for the purposes of iterating randomly
            random.shuffle(itrange)
            # And we iterate over the agents randomly by proxy of iterating
            # through their places on the list [agents]
            for i in itrange:
                current_bank = self.environment.banks[i]
                # We find how much in deposits the household has
                deposits_available = 0.0
                for tranx in ration[1].accounts:
                    if tranx.type_ == "deposits" and tranx.to == current_bank:
                        deposits_available = deposits_available + tranx.amount
#.........这里部分代码省略.........
开发者ID:cogeorg,项目名称:black_rhino,代码行数:101,代码来源:updater.py


示例20: MarketApplication

class MarketApplication(tornado.web.Application):
    def __init__(self, market_ip, market_port, market_id=1,
                 bm_user=None, bm_pass=None, bm_port=None, seed_peers=[],
                 seed_mode=0, dev_mode=False, db_path='db/ob.db'):

        db = Obdb(db_path)

        self.transport = CryptoTransportLayer(market_ip,
                                              market_port,
                                              market_id,
                                              db,
                                              bm_user,
                                              bm_pass,
                                              bm_port,
                                              seed_mode,
                                              dev_mode)

        self.market = Market(self.transport, db)

        def post_joined():
            self.transport.dht._refreshNode()
            self.market.republish_contracts()

        peers = seed_peers if seed_mode == 0 else []
        self.transport.join_network(peers)

        Thread(target=reactor.run, args=(False,)).start()

        handlers = [
            (r"/", MainHandler),
            (r"/main", MainHandler),
            (r"/html/(.*)", OpenBazaarStaticHandler, {'path': './html'}),
            (r"/ws", WebSocketHandler,
                dict(transport=self.transport, market=self.market, db=db))
        ]

        # TODO: Move debug settings to configuration location
        settings = dict(debug=True)
        tornado.web.Application.__init__(self, handlers, **settings)

    def get_transport(self):
        return self.transport

    def setup_upnp_port_mappings(self, http_port, p2p_port):
        upnp.PortMapper.DEBUG = False
        print "Setting up UPnP Port Map Entry..."
        # TODO: Add some setting whether or not to use UPnP
        # if Settings.get(Settings.USE_UPNP_PORT_MAPPINGS):
        self.upnp_mapper = upnp.PortMapper()
        # TODO: Add some setting whether or not to clean all previous port
        # mappings left behind by us
        # if Settings.get(Settings.CLEAN_UPNP_PORT_MAPPINGS_ON_START):
        #    upnp_mapper.cleanMyMappings()

        # for now let's always clean mappings every time.
        self.upnp_mapper.clean_my_mappings()
        # result_http_port_mapping = self.upnp_mapper.add_port_mapping(http_port,
        #                                                             http_port)
        # print ("UPnP HTTP Port Map configuration done (%s -> %s) => %s" %
        #        (str(http_port), str(http_port), str(result_http_port_mapping)))

        result_tcp_p2p_mapping = self.upnp_mapper.add_port_mapping(p2p_port,
                                                                   p2p_port)
        print ("UPnP TCP P2P Port Map configuration done (%s -> %s) => %s" %
               (str(p2p_port), str(p2p_port), str(result_tcp_p2p_mapping)))

        result_udp_p2p_mapping = self.upnp_mapper.add_port_mapping(p2p_port,
                                                                   p2p_port,
                                                                   'UDP')
        print ("UPnP UDP P2P Port Map configuration done (%s -> %s) => %s" %
               (str(p2p_port), str(p2p_port), str(result_udp_p2p_mapping)))

        # return result_http_port_mapping and \
        return result_tcp_p2p_mapping and \
               result_udp_p2p_mapping

    def cleanup_upnp_port_mapping(self):
        try:
            if self.upnp_mapper is not None:
                print "Cleaning UPnP Port Mapping -> ", \
                    self.upnp_mapper.clean_my_mappings()
        except AttributeError:
            print "[openbazaar] MarketApplication.clean_upnp_port_mapping() failed!"
            pass
开发者ID:Macarse,项目名称:OpenBazaar,代码行数:84,代码来源:tornadoloop.py



注:本文中的market.Market类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python contracts.Contract类代码示例发布时间:2022-05-27
下一篇:
Python markdown_deux.markdown函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap