예제 #1
0
    def initialize(self):
        self.publish_queue = []
        self.options = options

        from models import engine, db_bootstrap
        self.db_session = scoped_session(sessionmaker(bind=engine))
        db_bootstrap(self.db_session)

        from session_manager import SessionManager
        self.session_manager = SessionManager(
            timeout_limit=self.options.session_timeout_limit)

        self.context = zmq.Context()
        self.input_socket = self.context.socket(zmq.REP)
        self.input_socket.bind(self.options.trade_in)

        self.publisher_socket = self.context.socket(zmq.PUB)
        self.publisher_socket.bind(self.options.trade_pub)

        input_log_file_handler = logging.handlers.TimedRotatingFileHandler(
            self.options.trade_log, when='MIDNIGHT')
        formatter = logging.Formatter('%(asctime)s - %(message)s')
        input_log_file_handler.setFormatter(formatter)

        self.replay_logger = logging.getLogger("REPLAY")
        self.replay_logger.setLevel(logging.INFO)
        self.replay_logger.addHandler(input_log_file_handler)
        self.replay_logger.info('START')

        self.log_start_data()
예제 #2
0
  def initialize(self):
    self.publish_queue = []
    self.options = options

    from models import engine, db_bootstrap
    self.db_session = scoped_session(sessionmaker(bind=engine))
    db_bootstrap(self.db_session)

    from session_manager import SessionManager
    self.session_manager = SessionManager(timeout_limit=self.options.session_timeout_limit)

    self.context = zmq.Context()
    self.input_socket = self.context.socket(zmq.REP)
    self.input_socket.bind(self.options.trade_in)

    self.publisher_socket = self.context.socket(zmq.PUB)
    self.publisher_socket.bind(self.options.trade_pub)

    input_log_file_handler = logging.handlers.TimedRotatingFileHandler( self.options.trade_log, when='MIDNIGHT')
    formatter = logging.Formatter('%(asctime)s - %(message)s')
    input_log_file_handler.setFormatter(formatter)

    self.replay_logger = logging.getLogger("REPLAY")
    self.replay_logger.setLevel(logging.INFO)
    self.replay_logger.addHandler(input_log_file_handler)
    self.replay_logger.info('START')

    self.log_start_data()
예제 #3
0
    def __init__(self):
        handlers = [
            (r"/api/receive", ReceiveHandler),
            (r"/api/walletnotify/(?P<txid>[^\/]+)", WalletNotifyHandler),
            (r"/api/blocknotify/(?P<hash>[^\/]+)", BlockNotifyHandler),
        ]
        settings = dict(cookie_secret='cookie_secret')
        tornado.web.Application.__init__(self, handlers, **settings)

        input_log_file_handler = logging.handlers.TimedRotatingFileHandler(
            options.log, when='MIDNIGHT')
        formatter = logging.Formatter('%(asctime)s - %(message)s')
        input_log_file_handler.setFormatter(formatter)

        self.bitcoind = AuthServiceProxy(options.rpc_url, options.rpc_username,
                                         options.rpc_password)
        self.paytxfee = self.bitcoind.getinfo()['paytxfee']

        self.replay_logger = logging.getLogger("REPLAY")
        self.replay_logger.setLevel(logging.INFO)
        self.replay_logger.addHandler(input_log_file_handler)
        self.replay_logger.info('START')

        from models import engine, db_bootstrap
        self.db_session = scoped_session(sessionmaker(bind=engine))
        db_bootstrap(self.db_session)

        self.log_start_data()
  def __init__(self):
    handlers = [
      (r"/api/receive", ReceiveHandler),
      (r"/api/walletnotify/(?P<txid>[^\/]+)", WalletNotifyHandler),
      (r"/api/blocknotify/(?P<hash>[^\/]+)", BlockNotifyHandler),
      ]
    settings = dict(
      cookie_secret='cookie_secret'
    )
    tornado.web.Application.__init__(self, handlers, **settings)

    input_log_file_handler = logging.handlers.TimedRotatingFileHandler( options.log, when='MIDNIGHT')
    formatter = logging.Formatter('%(asctime)s - %(message)s')
    input_log_file_handler.setFormatter(formatter)

    self.bitcoind = AuthServiceProxy(options.rpc_url, options.rpc_username, options.rpc_password )
    self.paytxfee = self.bitcoind.getinfo()['paytxfee']


    self.replay_logger = logging.getLogger("REPLAY")
    self.replay_logger.setLevel(logging.INFO)
    self.replay_logger.addHandler(input_log_file_handler)
    self.replay_logger.info('START')

    from models import engine, db_bootstrap
    self.db_session = scoped_session(sessionmaker(bind=engine))
    db_bootstrap(self.db_session)

    self.log_start_data()
예제 #5
0
    def initialize(self, options, instance_name):
        self.publish_queue = []
        self.options = options
        self.instance_name = instance_name

        self.order_matcher_disabled = False
        if options.has_option('order_matcher_disabled'):
            self.order_matcher_disabled = True

        from models import Base, db_bootstrap
        db_engine = options.sqlalchemy_engine + ':///' + \
                    os.path.expanduser(options.sqlalchemy_connection_string)
        engine = create_engine(db_engine, echo=options.db_echo)
        Base.metadata.create_all(engine)

        self.db_session = scoped_session(sessionmaker(bind=engine))
        db_bootstrap(self.db_session)

        from session_manager import SessionManager
        self.session_manager = SessionManager(
            timeout_limit=self.options.session_timeout_limit)

        self.context = zmq.Context()
        self.input_socket = self.context.socket(zmq.REP)
        self.input_socket.bind(self.options.trade_in)

        self.publisher_socket = self.context.socket(zmq.PUB)
        self.publisher_socket.bind(self.options.trade_pub)

        input_log_file_handler = logging.handlers.TimedRotatingFileHandler(
            os.path.expanduser(self.options.trade_log), when='MIDNIGHT')
        input_log_file_handler.setFormatter(
            logging.Formatter('%(asctime)s - %(message)s'))

        self.replay_logger = logging.getLogger(self.instance_name)
        self.replay_logger.setLevel(logging.INFO)
        self.replay_logger.addHandler(input_log_file_handler)

        ch = logging.StreamHandler(sys.stdout)
        ch.setLevel(logging.DEBUG)
        ch.setFormatter(
            logging.Formatter(
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
        self.replay_logger.addHandler(ch)

        self.replay_logger.info('START')

        self.log_start_data()
예제 #6
0
    def initialize(self, options, instance_name):
        self.publish_queue = []
        self.options = options
        self.instance_name = instance_name

        self.order_matcher_disabled = False
        if options.has_option("order_matcher_disabled"):
            self.order_matcher_disabled = True

        from models import Base, db_bootstrap

        db_engine = options.sqlalchemy_engine + ":///" + os.path.expanduser(options.sqlalchemy_connection_string)
        engine = create_engine(db_engine, echo=options.db_echo)
        Base.metadata.create_all(engine)

        self.db_session = scoped_session(sessionmaker(bind=engine))
        db_bootstrap(self.db_session)

        from session_manager import SessionManager

        self.session_manager = SessionManager(timeout_limit=self.options.session_timeout_limit)

        self.context = zmq.Context()
        self.input_socket = self.context.socket(zmq.REP)
        self.input_socket.bind(self.options.trade_in)

        self.publisher_socket = self.context.socket(zmq.PUB)
        self.publisher_socket.bind(self.options.trade_pub)

        input_log_file_handler = logging.handlers.TimedRotatingFileHandler(
            os.path.expanduser(self.options.trade_log), when="MIDNIGHT"
        )
        input_log_file_handler.setFormatter(logging.Formatter("%(asctime)s - %(message)s"))

        self.replay_logger = logging.getLogger(self.instance_name)
        self.replay_logger.setLevel(logging.INFO)
        self.replay_logger.addHandler(input_log_file_handler)

        ch = logging.StreamHandler(sys.stdout)
        ch.setLevel(logging.DEBUG)
        ch.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
        self.replay_logger.addHandler(ch)

        self.replay_logger.info("START")

        self.log_start_data()
예제 #7
0
    def __init__(self, options, instance_name):
        self.options = options
        self.instance_name = instance_name
        handlers = [
            (r"/api/receive", ReceiveHandler),
            (r"/api/walletnotify/(?P<txid>[^\/]+)", WalletNotifyHandler),
            (r"/api/blocknotify/(?P<hash>[^\/]+)", BlockNotifyHandler),
        ]
        settings = dict(cookie_secret='cookie_secret')
        tornado.web.Application.__init__(self, handlers, **settings)

        input_log_file_handler = logging.handlers.TimedRotatingFileHandler(
            self.options.log, when='MIDNIGHT')
        formatter = logging.Formatter('%(asctime)s - %(message)s')
        input_log_file_handler.setFormatter(formatter)

        self.bitcoind = AuthServiceProxy(self.options.rpc_url)
        self.paytxfee = self.bitcoind.getinfo()['paytxfee']

        self.replay_logger = logging.getLogger(self.instance_name)
        self.replay_logger.setLevel(logging.DEBUG)
        self.replay_logger.addHandler(input_log_file_handler)
        self.replay_logger.info('START')

        ch = logging.StreamHandler(sys.stdout)
        ch.setLevel(logging.DEBUG)
        ch.setFormatter(
            logging.Formatter(
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
        self.replay_logger.addHandler(ch)

        from models import Base, db_bootstrap
        engine = create_engine(self.options.db_engine,
                               echo=self.options.db_echo)
        Base.metadata.create_all(engine)
        self.db_session = scoped_session(sessionmaker(bind=engine))
        db_bootstrap(self.db_session)

        self.log_start_data()
  def __init__(self, options, instance_name):
    self.options = options
    self.instance_name = instance_name
    handlers = [
      (r"/api/receive", ReceiveHandler),
      (r"/api/walletnotify/(?P<txid>[^\/]+)", WalletNotifyHandler),
      (r"/api/blocknotify/(?P<hash>[^\/]+)", BlockNotifyHandler),
      ]
    settings = dict(
      cookie_secret='cookie_secret'
    )
    tornado.web.Application.__init__(self, handlers, **settings)

    input_log_file_handler = logging.handlers.TimedRotatingFileHandler( self.options.log, when='MIDNIGHT')
    formatter = logging.Formatter('%(asctime)s - %(message)s')
    input_log_file_handler.setFormatter(formatter)

    self.bitcoind = AuthServiceProxy(self.options.rpc_url )
    self.paytxfee = self.bitcoind.getinfo()['paytxfee']


    self.replay_logger = logging.getLogger(self.instance_name)
    self.replay_logger.setLevel(logging.INFO)
    self.replay_logger.addHandler(input_log_file_handler)
    self.replay_logger.info('START')

    ch = logging.StreamHandler(sys.stdout)
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
    self.replay_logger.addHandler(ch)


    from models import Base, db_bootstrap
    engine = create_engine( self.options.db_engine, echo=self.options.db_echo)
    Base.metadata.create_all(engine)
    self.db_session = scoped_session(sessionmaker(bind=engine))
    db_bootstrap(self.db_session)

    self.log_start_data()
예제 #9
0
  def initialize(self, options, instance_name):
    self.publish_queue = []
    self.options = options
    self.instance_name = instance_name

    from models import Base, db_bootstrap
    engine = create_engine( options.db_engine, echo=options.db_echo)
    Base.metadata.create_all(engine)


    self.db_session = scoped_session(sessionmaker(bind=engine))
    db_bootstrap(self.db_session)

    from session_manager import SessionManager
    self.session_manager = SessionManager(timeout_limit=self.options.session_timeout_limit)

    self.context = zmq.Context()
    self.input_socket = self.context.socket(zmq.REP)
    self.input_socket.bind(self.options.trade_in)

    self.publisher_socket = self.context.socket(zmq.PUB)
    self.publisher_socket.bind(self.options.trade_pub)

    input_log_file_handler = logging.handlers.TimedRotatingFileHandler( self.options.trade_log, when='MIDNIGHT')
    input_log_file_handler.setFormatter(logging.Formatter('%(asctime)s - %(message)s'))

    self.replay_logger = logging.getLogger(self.instance_name)
    self.replay_logger.setLevel(logging.INFO)
    self.replay_logger.addHandler(input_log_file_handler)

    ch = logging.StreamHandler(sys.stdout)
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
    self.replay_logger.addHandler(ch)

    self.replay_logger.info('START')

    self.log_start_data()
예제 #10
0
파일: main.py 프로젝트: bitcoinland/bitex
    def __init__(self, opt, instance_name):
        self.options = opt
        self.instance_name = instance_name

        handlers = [
            (r'/', WebSocketHandler),
            (r'/get_deposit(.*)', DepositHandler),
            (r'/_webhook/verification_form', VerificationWebHookHandler),
            (r'/_webhook/deposit_receipt', DepositReceiptWebHookHandler),
            (r'/process_deposit(.*)', ProcessDepositHandler),
            (r'/api/(?P<version>[^\/]+)/(?P<symbol>[^\/]+)/(?P<resource>[^\/]+)', RestApiHandler)
        ]
        settings = dict(
            cookie_secret='cookie_secret'
        )
        tornado.web.Application.__init__(self, handlers, **settings)


        self.allowed_origins = json.loads(self.options.allowed_origins)
        self.allow_all_origins = self.allowed_origins[0] == '*'

        input_log_file_handler = logging.handlers.TimedRotatingFileHandler(
          os.path.expanduser(self.options.gateway_log), when='MIDNIGHT')
        formatter = logging.Formatter('%(asctime)s - %(message)s')
        input_log_file_handler.setFormatter(formatter)

        self.replay_logger = logging.getLogger(self.instance_name)
        self.replay_logger.setLevel(logging.INFO)
        self.replay_logger.addHandler(input_log_file_handler)

        ch = logging.StreamHandler(sys.stdout)
        ch.setLevel(logging.DEBUG)
        ch.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
        self.replay_logger.addHandler(ch)

        self.replay_logger.info('START')
        self.log_start_data()

        from models import Base, db_bootstrap
        db_engine = self.options.sqlalchemy_engine + ':///' +\
                    os.path.expanduser(self.options.sqlalchemy_connection_string)
        engine = create_engine( db_engine, echo=self.options.db_echo)
        Base.metadata.create_all(engine)
        self.db_session = scoped_session(sessionmaker(bind=engine))
        db_bootstrap(self.db_session)


        self.zmq_context = zmq.Context()

        self.trade_in_socket = self.zmq_context.socket(zmq.REQ)
        self.trade_in_socket.connect(self.options.trade_in)

        self.application_trade_client = TradeClient(
            self.zmq_context,
            self.trade_in_socket)
        self.application_trade_client.connect()

        self.security_list = self.application_trade_client.getSecurityList()
        self.md_subscriber = {}

        for instrument in self.security_list.get('Instruments'):
            symbol = instrument['Symbol']
            self.md_subscriber[symbol] = MarketDataSubscriber.get(symbol, self)
            self.md_subscriber[symbol].subscribe(
                self.zmq_context,
                self.options.trade_pub,
                self.application_trade_client)

        last_trade_id = Trade.get_last_trade_id(self.db_session)
        trade_list = self.application_trade_client.getLastTrades(last_trade_id)

        for trade in trade_list:
            msg = dict()
            msg['id']               = trade[0]
            msg['symbol']           = trade[1]
            msg['side']             = trade[2]
            msg['price']            = trade[3]
            msg['size']             = trade[4]
            msg['buyer_id']         = trade[5]
            msg['seller_id']        = trade[6]
            msg['buyer_username']   = trade[7]
            msg['seller_username']  = trade[8]
            msg['created']          = trade[9]
            msg['trade_date']       = trade[9][:10]
            msg['trade_time']       = trade[9][11:]
            msg['order_id']         = trade[10]
            msg['counter_order_id'] = trade[11]
            Trade.create( self.db_session, msg)

        all_trades = Trade.get_all_trades(self.db_session)
        for t in all_trades:
          trade_info = dict()
          trade_info['price'] = t.price
          trade_info['size'] = t.size
          trade_info['trade_date'] = t.created.strftime('%Y-%m-%d')
          trade_info['trade_time'] = t.created.strftime('%H:%M:%S')
          self.md_subscriber[ t.symbol ].inst_status.push_trade(trade_info)

        for symbol, subscriber in self.md_subscriber.iteritems():
            subscriber.ready()

        self.connections = {}

        self.heart_beat_timer = tornado.ioloop.PeriodicCallback(
            self.send_heartbeat_to_trade,
            30000)
        self.heart_beat_timer.start()
예제 #11
0
    def __init__(self, opt, instance_name):
        self.options = opt
        self.instance_name = instance_name

        handlers = [
            (r'/', WebSocketHandler), (r'/get_deposit(.*)', DepositHandler),
            (r'/_webhook/verification_form', VerificationWebHookHandler),
            (r'/_webhook/deposit_receipt', DepositReceiptWebHookHandler),
            (r'/process_deposit(.*)', ProcessDepositHandler),
            (r'/api/(?P<version>[^\/]+)/(?P<symbol>[^\/]+)/(?P<resource>[^\/]+)',
             RestApiHandler)
        ]
        settings = dict(cookie_secret='cookie_secret')
        tornado.web.Application.__init__(self, handlers, **settings)

        self.allowed_origins = json.loads(self.options.allowed_origins)
        self.allow_all_origins = self.allowed_origins[0] == '*'

        input_log_file_handler = logging.handlers.TimedRotatingFileHandler(
            os.path.expanduser(self.options.gateway_log), when='MIDNIGHT')
        formatter = logging.Formatter('%(asctime)s - %(message)s')
        input_log_file_handler.setFormatter(formatter)

        self.replay_logger = logging.getLogger(self.instance_name)
        self.replay_logger.setLevel(logging.INFO)
        self.replay_logger.addHandler(input_log_file_handler)

        ch = logging.StreamHandler(sys.stdout)
        ch.setLevel(logging.DEBUG)
        ch.setFormatter(
            logging.Formatter(
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
        self.replay_logger.addHandler(ch)

        self.replay_logger.info('START')
        self.log_start_data()

        self.update_tor_nodes()

        from models import Base, db_bootstrap
        db_engine = self.options.sqlalchemy_engine + ':///' +\
                    os.path.expanduser(self.options.sqlalchemy_connection_string)
        engine = create_engine(db_engine, echo=self.options.db_echo)
        Base.metadata.create_all(engine)
        self.db_session = scoped_session(sessionmaker(bind=engine))
        db_bootstrap(self.db_session)

        self.zmq_context = zmq.Context()

        self.trade_in_socket = self.zmq_context.socket(zmq.REQ)
        self.trade_in_socket.connect(self.options.trade_in)

        self.application_trade_client = TradeClient(self.zmq_context,
                                                    self.trade_in_socket)
        self.application_trade_client.connect()

        self.security_list = self.application_trade_client.getSecurityList()
        self.md_subscriber = {}

        for instrument in self.security_list.get('Instruments'):
            symbol = instrument['Symbol']
            self.md_subscriber[symbol] = MarketDataSubscriber.get(symbol, self)
            self.md_subscriber[symbol].subscribe(self.zmq_context,
                                                 self.options.trade_pub,
                                                 self.application_trade_client)

        last_trade_id = Trade.get_last_trade_id(self.db_session)
        trade_list = self.application_trade_client.getLastTrades(last_trade_id)

        for trade in trade_list:
            msg = dict()
            msg['id'] = trade[0]
            msg['symbol'] = trade[1]
            msg['side'] = trade[2]
            msg['price'] = trade[3]
            msg['size'] = trade[4]
            msg['buyer_id'] = trade[5]
            msg['seller_id'] = trade[6]
            msg['buyer_username'] = trade[7]
            msg['seller_username'] = trade[8]
            msg['created'] = trade[9]
            msg['trade_date'] = trade[9][:10]
            msg['trade_time'] = trade[9][11:]
            msg['order_id'] = trade[10]
            msg['counter_order_id'] = trade[11]
            Trade.create(self.db_session, msg)

        all_trades = Trade.get_all_trades(self.db_session)
        for t in all_trades:
            trade_info = dict()
            trade_info['price'] = t.price
            trade_info['size'] = t.size
            trade_info['trade_date'] = t.created.strftime('%Y-%m-%d')
            trade_info['trade_time'] = t.created.strftime('%H:%M:%S')
            self.md_subscriber[t.symbol].inst_status.push_trade(trade_info)

        for symbol, subscriber in self.md_subscriber.iteritems():
            subscriber.ready()

        self.connections = {}

        self.heart_beat_timer = tornado.ioloop.PeriodicCallback(
            self.send_heartbeat_to_trade, 30000)
        self.heart_beat_timer.start()

        self.update_tor_nodes_timer = tornado.ioloop.PeriodicCallback(
            self.update_tor_nodes, 3600000)
        self.update_tor_nodes_timer.start()
예제 #12
0
    def __init__(self, opt):
        handlers = [
            (r'/', WebSocketHandler),
            (r'/get_deposit(.*)', DepositHandler),
            (r'/_webhook/verification_form', VerificationWebHookHandler),
            (r'/_webhook/deposit_receipt', DepositReceiptWebHookHandler),
            (r'/process_deposit(.*)', ProcessDepositHandler),
            (r'/api/(?P<version>[^\/]+)/(?P<symbol>[^\/]+)/(?P<resource>[^\/]+)', RestApiHandler)
        ]
        settings = dict(
            cookie_secret='cookie_secret'
        )
        tornado.web.Application.__init__(self, handlers, **settings)

        self.replay_logger = logging.getLogger("REPLAY")
        self.replay_logger.setLevel(logging.INFO)
        self.replay_logger.addHandler(input_log_file_handler)
        self.replay_logger.info('START')
        self.log_start_data()


        from models import ENGINE, db_bootstrap
        self.db_session = scoped_session(sessionmaker(bind=ENGINE))
        db_bootstrap(self.db_session)


        self.zmq_context = zmq.Context()

        self.trade_in_socket = self.zmq_context.socket(zmq.REQ)
        self.trade_in_socket.connect(opt.trade_in)

        self.application_trade_client = TradeClient(
            self.zmq_context,
            self.trade_in_socket)
        self.application_trade_client.connect()

        instruments = self.application_trade_client.getSecurityList()
        self.md_subscriber = {}

        for instrument in instruments:
            symbol = instrument['Symbol']
            self.md_subscriber[symbol] = MarketDataSubscriber.get(symbol, self)
            self.md_subscriber[symbol].subscribe(
                self.zmq_context,
                options.trade_pub,
                self.application_trade_client)

        last_trade_id = Trade.get_last_trade_id()
        trade_list = self.application_trade_client.getLastTrades(last_trade_id)

        for trade in trade_list:
            msg = dict()
            msg['id']               = trade[0]
            msg['symbol']           = trade[1]
            msg['side']             = trade[2]
            msg['price']            = trade[3]
            msg['size']             = trade[4]
            msg['buyer_username']   = trade[5]
            msg['seller_username']  = trade[6]
            msg['created']          = trade[7]
            msg['trade_date']       = trade[7][:10]
            msg['trade_time']       = trade[7][11:]
            msg['order_id']         = trade[8]
            msg['counter_order_id'] = trade[9]
            Trade.create( self.db_session, msg)

        all_trades = Trade.get_all_trades(self.db_session)
        for t in all_trades:
          trade_info = dict()
          trade_info['price'] = t.price
          trade_info['size'] = t.size
          trade_info['trade_date'] = t.created.strftime('%Y-%m-%d')
          trade_info['trade_time'] = t.created.strftime('%H:%M:%S')
          self.md_subscriber[ t.symbol ].inst_status.push_trade(trade_info)

        for symbol, subscriber in self.md_subscriber.iteritems():
            subscriber.ready()

        self.connections = {}

        self.heart_beat_timer = tornado.ioloop.PeriodicCallback(
            self.send_heartbeat_to_trade,
            30000)
        self.heart_beat_timer.start()
예제 #13
0
  def setUp(self):
    from models import Base, db_bootstrap

    self.engine = create_engine('sqlite://', echo=False)
    Base.metadata.create_all(self.engine)

    self.db_session = scoped_session(sessionmaker(bind=self.engine))
    TradeApplication.instance().db_session = self.db_session

    db_bootstrap(self.db_session)
    
    currencies = [
      [ "BTC" , u"฿"       , "Bitcoin"  ,  True,  10000, "{:,.8f}", u"฿ #,##0.00000000;(฿ #,##0.00000000)"  , "{:,.8f}", u"฿ #,##0.00000000;(฿ #,##0.0000000)" ],
      [ "USD" , u"$"       , "Dollar"   ,  False, 100  , "{:,.2f}", u"¤ #,##0.00;(¤ #,##0.00)"              , "{:,.2f}", u"¤ #,##0.00;(¤ #,##0.00)"            ]
    ]

    from models import Currency, Instrument, Broker, User
    for c in currencies:
      e = Currency(code                 = c[0],
                   sign                 = c[1],
                   description          = c[2],
                   is_crypto            = c[3],
                   pip                  = c[4],
                   format_python        = c[5],
                   format_js            = c[6],
                   human_format_python  = c[7],
                   human_format_js      = c[8] )
      self.db_session.add(e)
      self.db_session.commit()


    instruments = [
      ["BTCUSD", "USD", "BTC / USD"]
    ]
    for currency_description in instruments:
      e = Instrument(symbol=currency_description[0],
                     currency=currency_description[1],
                     description=currency_description[2])
      self.db_session.add(e)
      self.db_session.commit()

    # user root
    e = User(id                   = -1,
             username             = '******',
             email                = '*****@*****.**',
             password             = '******',
             country_code         = 'US',
             state                = 'NY',
             transaction_fee_buy  = 0,
             transaction_fee_sell = 0,
             verified             = 3,
             is_staff             = True,
             is_system            = True,
             is_broker            = True,
             email_lang           = 'en')
    self.db_session.add(e)

    # user blinktrade
    e = User(id                   = 8999999,
             username             = '******',
             email                = '*****@*****.**',
             password             = '******',
             country_code         = 'US',
             state                = 'NY',
             transaction_fee_buy  = 0,
             transaction_fee_sell = 0,
             verified             = 3,
             is_staff             = True,
             is_broker            = True,
             email_lang           = 'en')
    self.db_session.add(e)


    # user exchange
    e = User(id                   = 5,
             username             = '******',
             email                = '*****@*****.**',
             broker_id            = 8999999,
             broker_username      = '******',
             password             = '******',
             country_code         = 'US',
             state                = 'NY',
             transaction_fee_buy  = 0,
             transaction_fee_sell = 0,
             verified             = 5,
             is_broker            = True,
             email_lang           = 'en')
    self.db_session.add(e)
    self.db_session.commit()



    # broker exchange
    e = Broker(id                       = 5,
               short_name               = 'exchange',
               business_name            = 'BlinkTrade Demo Exchange',
               address                  = '21 Bitcoin Ave',
               signup_label             = 'BlinkTrade Demo Exchange',
               city                     = 'New York',
               state                    = 'NY',
               zip_code                 = '10000',
               country_code             = 'US',
               lang                     = 'en',
               country                  = 'United States',
               mandrill_api_key         = None,
               mailer_from_name         = 'BlinkTrade',
               mailer_from_email        = '*****@*****.**',
               mailer_signature         = 'BlinkTrade Demo Exchange',
               mailchimp_list_id        = '5c7b7818d8',
               phone_number_1           = None,
               phone_number_2           = None,
               skype                    = 'blinktrade',
               email                    = '*****@*****.**',
               verification_jotform     = 'https://secure.jotform.co/form/42336230941852?user_id={{UserID}}&username={{Username}}&broker_id={{BrokerID}}&broker_username={{BrokerUsername}}&email={{Email}}&phoneNumber[country]=1&address[state]={{State}}&address[country]=United+States',
               upload_jotform           = 'https://secure.jotform.co/form/42344880060854?user_id={{UserID}}&username={{Username}}&broker_id={{BrokerID}}&broker_username={{BrokerUsername}}&deposit_method={{DepositMethod}}&control_number={{ControlNumber}}&deposit_id={{DepositID}}',
               currencies               = 'USD',
               withdraw_structure       = json.dumps(
                   {
                   "BTC": [
                       {
                       "method":"bitcoin",
                       "description":"Bitcoin withdrawal",
                       "disclaimer": "",
                       "percent_fee":0,
                       "fixed_fee":0,
                       "limits": {
                         "0": {"enabled": True, "min": 500000, "max": 100000000},
                         "1": {"enabled": True, "min": 500000, "max": 100000000},
                         "2": {"enabled": True, "min": 500000, "max": 100000000},
                         "3": {"enabled": True, "min": 500000},
                         "4": {"enabled": True, "min": 500000},
                         "5": {"enabled": True, "min": 500000}
                       },
                       "fields": [
                           {"side":"client", "name": "Wallet"        , "validator":"validateAddress",  "type":"text"  , "value":""       , "label":"Wallet",        "placeholder":"" },
                           {"side":"broker", "name": "TransactionID" , "validator":"validateAlphaNum", "type":"text"  , "value":""       , "label":"TransactionID", "placeholder":"" }
                       ]
                     }
                   ],
                   "USD": [
                       {
                       "method":"swift",
                       "description":"Swift International Transfer",
                       "disclaimer":"84 hours, 1%  fee + $25",
                       "percent_fee": 1,
                       "fixed_fee": 2500000000,
                       "limits": {
                         "0": {"enabled": False},
                         "1": {"enabled": False},
                         "2": {"enabled": False},
                         "3": {"enabled": True, "min": 3500000000,  "max":  280000000000},
                         "4": {"enabled": True, "min": 3500000000,  "max": 5000000000000},
                         "5": {"enabled": True, "min": 3500000000}
                       },
                       "fields": [
                           {"side":"client", "name": "BankName"     , "validator":"validateAlphaNum", "type":"text"  , "value":""  , "label":"Banco name", "placeholder": "ex. JPMORGAN CHASE BANK, N.A" },
                           {"side":"client", "name": "BankSwift"    , "validator":"validateAlphaNum", "type":"text"  , "value":""  , "label":"Swift code", "placeholder": "ex. CHASUS33" },
                           {"side":"client", "name": "RoutingNumber", "validator":"validateAlphaNum", "type":"text"  , "value":""  , "label":"Routing Number", "placeholder":"ex. 021000021" },
                           {"side":"client", "name": "AccountNumber", "validator":"validateAlphaNum", "type":"text"  , "value":""  , "label":"Account Number", "placeholder":"ex. 88888-8" },
                           {"side":"broker", "name": "TransactionID", "validator":"validateAlphaNum", "type":"text"  , "value":""  , "label":"TransactionID", "placeholder":"" }
                       ]
                     }
                   ]
                 }
               ).decode('utf-8'),
               crypto_currencies        = json.dumps([
                   {
                   "Wallets": [
                       {
                       "managed_by": "BlinkTrade, Exchange Operator, Mediator ",
                       "signatures": [],
                       "type": "cold",
                       "multisig": False,
                       "address": "n3yyGwzyfTxbKB8hkkv2AsQ9nBQgEozsV4"
                     },
                       {
                       "managed_by": "Exchange Operator ",
                       "signatures": [],
                       "type": "hot",
                       "multisig": False,
                       "address": "msQRdMPcwLr3rWsLzG56ABhHtfavHH2yVW"
                     }
                   ],
                   "CurrencyCode": "BTC",
                   "Confirmations": [
                     [          0,        200000000, 1],
                     [  200000000,      20000000000, 3],
                     [20000000000, 2100000000000000, 6]
                   ],
                   "CurrencyDescription": "Bitcoin"
                 }
               ]).decode('utf-8'),
               accept_customers_from    = json.dumps([["*"],[ "CU", "SO", "SD",  "NG", "IR", "KP" ]]).decode('utf-8'),
               is_broker_hub            = False,
               support_url              = 'mailto:[email protected]',
               tos_url                  = 'https://docs.google.com/a/blinktrade.com/document/d/1HyFRs_2Seh4LGZYjPk8bmbxueUjF7RMz-koAM3rG2Pc/pub?embedded=true',
               fee_structure            = json.dumps([
                   { "Operation" : "Wire transfer",      "Fee":"1%"            , "Terms":"Exchange operator decides its fees" }
               ] ).decode('utf-8'),
               transaction_fee_buy      = 60,
               transaction_fee_sell     = 60,
               accounts                 = json.dumps({
                 "bonus":[ 90000000, "exchange_bonus", [ "USD", 100000000 ] ] ,
                 "fees":[  90000001, "exchange_fees" ]
               }).decode('utf-8'),
               status                   = '1',
               ranking                  = 5 )
    self.db_session.add(e)
    self.db_session.commit()
예제 #14
0
    def __init__(self, opt):
        handlers = [
            (r'/', WebSocketHandler), (r'/get_deposit(.*)', DepositHandler),
            (r'/_webhook/verification_form', VerificationWebHookHandler),
            (r'/_webhook/deposit_receipt', DepositReceiptWebHookHandler),
            (r'/process_deposit(.*)', ProcessDepositHandler),
            (r'/api/(?P<version>[^\/]+)/(?P<symbol>[^\/]+)/(?P<resource>[^\/]+)',
             RestApiHandler)
        ]
        settings = dict(cookie_secret='cookie_secret')
        tornado.web.Application.__init__(self, handlers, **settings)

        self.replay_logger = logging.getLogger("REPLAY")
        self.replay_logger.setLevel(logging.INFO)
        self.replay_logger.addHandler(input_log_file_handler)
        self.replay_logger.info('START')
        self.log_start_data()

        from models import ENGINE, db_bootstrap
        self.db_session = scoped_session(sessionmaker(bind=ENGINE))
        db_bootstrap(self.db_session)

        self.zmq_context = zmq.Context()

        self.trade_in_socket = self.zmq_context.socket(zmq.REQ)
        self.trade_in_socket.connect(opt.trade_in)

        self.application_trade_client = TradeClient(self.zmq_context,
                                                    self.trade_in_socket)
        self.application_trade_client.connect()

        instruments = self.application_trade_client.getSecurityList()
        self.md_subscriber = {}

        for instrument in instruments:
            symbol = instrument['Symbol']
            self.md_subscriber[symbol] = MarketDataSubscriber.get(symbol, self)
            self.md_subscriber[symbol].subscribe(self.zmq_context,
                                                 options.trade_pub,
                                                 self.application_trade_client)

        last_trade_id = Trade.get_last_trade_id()
        trade_list = self.application_trade_client.getLastTrades(last_trade_id)

        for trade in trade_list:
            msg = dict()
            msg['id'] = trade[0]
            msg['symbol'] = trade[1]
            msg['side'] = trade[2]
            msg['price'] = trade[3]
            msg['size'] = trade[4]
            msg['buyer_username'] = trade[5]
            msg['seller_username'] = trade[6]
            msg['created'] = trade[7]
            msg['trade_date'] = trade[7][:10]
            msg['trade_time'] = trade[7][11:]
            msg['order_id'] = trade[8]
            msg['counter_order_id'] = trade[9]
            Trade.create(self.db_session, msg)

        all_trades = Trade.get_all_trades(self.db_session)
        for t in all_trades:
            trade_info = dict()
            trade_info['price'] = t.price
            trade_info['size'] = t.size
            trade_info['trade_date'] = t.created.strftime('%Y-%m-%d')
            trade_info['trade_time'] = t.created.strftime('%H:%M:%S')
            self.md_subscriber[t.symbol].inst_status.push_trade(trade_info)

        for symbol, subscriber in self.md_subscriber.iteritems():
            subscriber.ready()

        self.connections = {}

        self.heart_beat_timer = tornado.ioloop.PeriodicCallback(
            self.send_heartbeat_to_trade, 30000)
        self.heart_beat_timer.start()
예제 #15
0
  def setUp(self):
    from models import Base, db_bootstrap

    self.engine = create_engine('sqlite://', echo=True)
    Base.metadata.create_all(self.engine)

    self.db_session = scoped_session(sessionmaker(bind=self.engine))
    TradeApplication.instance().db_session = self.db_session

    db_bootstrap(self.db_session)
    
    currencies = [
      [ "BTC" , u"฿"       , "Bitcoin"  ,  True,  10000, "{:,.8f}", u"฿ #,##0.00000000;(฿ #,##0.00000000)"  , "{:,.8f}", u"฿ #,##0.00000000;(฿ #,##0.0000000)" ],
      [ "USD" , u"$"       , "Dollar"   ,  False, 100  , "{:,.2f}", u"¤ #,##0.00;(¤ #,##0.00)"              , "{:,.2f}", u"¤ #,##0.00;(¤ #,##0.00)"            ]
    ]

    from models import Currency, Instrument, Broker, User, DepositMethods
    for c in currencies:
      e = Currency(code                 = c[0],
                   sign                 = c[1],
                   description          = c[2],
                   is_crypto            = c[3],
                   pip                  = c[4],
                   format_python        = c[5],
                   format_js            = c[6],
                   human_format_python  = c[7],
                   human_format_js      = c[8] )
      self.db_session.add(e)
      self.db_session.commit()


    instruments = [
      ["BTCUSD", "USD", "BTC / USD"]
    ]
    for currency_description in instruments:
      e = Instrument(symbol=currency_description[0],
                     currency=currency_description[1],
                     description=currency_description[2])
      self.db_session.add(e)
      self.db_session.commit()

    # user root
    e = User(id                   = -1,
             username             = '******',
             email                = '*****@*****.**',
             password             = '******',
             country_code         = 'US',
             state                = 'NY',
             transaction_fee_buy  = 0,
             transaction_fee_sell = 0,
             verified             = 3,
             is_staff             = True,
             is_system            = True,
             is_broker            = True,
             email_lang           = 'en')
    self.db_session.add(e)

    # user blinktrade
    e = User(id                   = 8999999,
             username             = '******',
             email                = '*****@*****.**',
             password             = '******',
             country_code         = 'US',
             state                = 'NY',
             transaction_fee_buy  = 0,
             transaction_fee_sell = 0,
             verified             = 3,
             is_staff             = True,
             is_broker            = True,
             email_lang           = 'en')
    self.db_session.add(e)


    # user exchange
    e = User(id                   = 5,
             username             = '******',
             email                = '*****@*****.**',
             broker_id            = 8999999,
             broker_username      = '******',
             password             = '******',
             country_code         = 'US',
             state                = 'NY',
             transaction_fee_buy  = 0,
             transaction_fee_sell = 0,
             verified             = 5,
             is_broker            = True,
             email_lang           = 'en')
    self.db_session.add(e)
    self.db_session.commit()

    # user exchange bonus
    e = User(id                   = 90000000,
             username             = '******',
             email                = '*****@*****.**',
             broker_id            = 5,
             broker_username      = '******',
             password             = '******',
             country_code         = 'US',
             state                = 'NY',
             transaction_fee_buy  = 0,
             transaction_fee_sell = 0,
             verified             = 5,
             is_broker            = True,
             email_lang           = 'en')
    self.db_session.add(e)
    self.db_session.commit()
    self.user_exchange_bonus = e

    # user exchange fees
    e = User(id                   = 90000001,
             username             = '******',
             email                = '*****@*****.**',
             broker_id            = 5,
             broker_username      = '******',
             password             = '******',
             country_code         = 'US',
             state                = 'NY',
             transaction_fee_buy  = 0,
             transaction_fee_sell = 0,
             verified             = 5,
             is_broker            = True,
             email_lang           = 'en')
    self.db_session.add(e)
    self.db_session.commit()
    self.user_exchange_fees = e

    # broker exchange
    e = Broker(id                       = 5,
               short_name               = 'exchange',
               business_name            = 'BlinkTrade Demo Exchange',
               address                  = '21 Bitcoin Ave',
               signup_label             = 'BlinkTrade Demo Exchange',
               city                     = 'New York',
               state                    = 'NY',
               zip_code                 = '10000',
               country_code             = 'US',
               lang                     = 'en',
               country                  = 'United States',
               mandrill_api_key         = None,
               mailer_from_name         = 'BlinkTrade',
               mailer_from_email        = '*****@*****.**',
               mailer_signature         = 'BlinkTrade Demo Exchange',
               mailchimp_list_id        = '5c7b7818d8',
               phone_number_1           = None,
               phone_number_2           = None,
               skype                    = 'blinktrade',
               email                    = '*****@*****.**',
               verification_jotform     = 'https://secure.jotform.co/form/42336230941852?user_id={{UserID}}&username={{Username}}&broker_id={{BrokerID}}&broker_username={{BrokerUsername}}&email={{Email}}&phoneNumber[country]=1&address[state]={{State}}&address[country]=United+States',
               upload_jotform           = 'https://secure.jotform.co/form/42344880060854?user_id={{UserID}}&username={{Username}}&broker_id={{BrokerID}}&broker_username={{BrokerUsername}}&deposit_method={{DepositMethod}}&control_number={{ControlNumber}}&deposit_id={{DepositID}}',
               currencies               = 'USD',
               withdraw_structure       = json.dumps(
                   {
                   "BTC": [
                       {
                       "method":"bitcoin",
                       "description":"Bitcoin withdrawal",
                       "disclaimer": "",
                       "percent_fee":0,
                       "fixed_fee":0,
                       "limits": {
                         "0": {"enabled": True, "min": 500000, "max": 100000000},
                         "1": {"enabled": True, "min": 500000, "max": 100000000},
                         "2": {"enabled": True, "min": 500000, "max": 100000000},
                         "3": {"enabled": True, "min": 500000},
                         "4": {"enabled": True, "min": 500000},
                         "5": {"enabled": True, "min": 500000}
                       },
                       "fields": [
                           {"side":"client", "name": "Wallet"        , "validator":"validateAddress",  "type":"text"  , "value":""       , "label":"Wallet",        "placeholder":"" },
                           {"side":"broker", "name": "TransactionID" , "validator":"validateAlphaNum", "type":"text"  , "value":""       , "label":"TransactionID", "placeholder":"" }
                       ]
                     }
                   ],
                   "USD": [
                       {
                       "method":"swift",
                       "description":"Swift International Transfer",
                       "disclaimer":"84 hours, 1%  fee + $25",
                       "percent_fee": 1,
                       "fixed_fee": 2500000000,
                       "limits": {
                         "0": {"enabled": False},
                         "1": {"enabled": False},
                         "2": {"enabled": False},
                         "3": {"enabled": True, "min": 3500000000,  "max":  280000000000},
                         "4": {"enabled": True, "min": 3500000000,  "max": 5000000000000},
                         "5": {"enabled": True, "min": 3500000000}
                       },
                       "fields": [
                           {"side":"client", "name": "BankName"     , "validator":"validateAlphaNum", "type":"text"  , "value":""  , "label":"Banco name", "placeholder": "ex. JPMORGAN CHASE BANK, N.A" },
                           {"side":"client", "name": "BankSwift"    , "validator":"validateAlphaNum", "type":"text"  , "value":""  , "label":"Swift code", "placeholder": "ex. CHASUS33" },
                           {"side":"client", "name": "RoutingNumber", "validator":"validateAlphaNum", "type":"text"  , "value":""  , "label":"Routing Number", "placeholder":"ex. 021000021" },
                           {"side":"client", "name": "AccountNumber", "validator":"validateAlphaNum", "type":"text"  , "value":""  , "label":"Account Number", "placeholder":"ex. 88888-8" },
                           {"side":"broker", "name": "TransactionID", "validator":"validateAlphaNum", "type":"text"  , "value":""  , "label":"TransactionID", "placeholder":"" }
                       ]
                     }
                   ]
                 }
               ).decode('utf-8'),
               crypto_currencies        = json.dumps([
                   {
                   "Wallets": [
                       {
                       "managed_by": "BlinkTrade, Exchange Operator, Mediator ",
                       "signatures": [],
                       "type": "cold",
                       "multisig": False,
                       "address": "n3yyGwzyfTxbKB8hkkv2AsQ9nBQgEozsV4"
                     },
                       {
                       "managed_by": "Exchange Operator ",
                       "signatures": [],
                       "type": "hot",
                       "multisig": False,
                       "address": "msQRdMPcwLr3rWsLzG56ABhHtfavHH2yVW"
                     }
                   ],
                   "CurrencyCode": "BTC",
                   "Confirmations": [
                     [          0,        200000000, 1],
                     [  200000000,      20000000000, 3],
                     [20000000000, 2100000000000000, 6]
                   ],
                   "CurrencyDescription": "Bitcoin"
                 }
               ]).decode('utf-8'),
               accept_customers_from    = json.dumps([["*"],[ "CU", "SO", "SD",  "NG", "IR", "KP" ]]).decode('utf-8'),
               is_broker_hub            = False,
               support_url              = 'mailto:[email protected]',
               tos_url                  = 'https://docs.google.com/a/blinktrade.com/document/d/1HyFRs_2Seh4LGZYjPk8bmbxueUjF7RMz-koAM3rG2Pc/pub?embedded=true',
               fee_structure            = json.dumps([
                   { "Operation" : "Wire transfer",      "Fee":"1%"            , "Terms":"Exchange operator decides its fees" }
               ] ).decode('utf-8'),
               transaction_fee_buy      = 60,
               transaction_fee_sell     = 60,
               accounts                 = json.dumps({
                 "bonus":[ 90000000, "exchange_bonus", [ "USD", 100000000 ] ] ,
                 "fees":[  90000001, "exchange_fees" ]
               }).decode('utf-8'),
               status                   = '1',
               ranking                  = 5 )
    self.db_session.add(e)
    self.db_session.commit()

    
    e = DepositMethods(id                         = 501,
                        broker_id                 = 5,
                        name                      = 'usps',
                        description               = 'USPS Money order',
                        disclaimer                = '1 business day',
                        type                      = 'DTP',
                        percent_fee               = 0,
                        fixed_fee                 = 500000000,
                        broker_deposit_ctrl_num   = 501000001,
                        currency                  = 'USD',
                        deposit_limits            = json.dumps({
                          "0": {"enabled": False},
                          "1": {"enabled": False},
                          "2": {"enabled": False},
                          "3": {"enabled": True, "min" : 1000000000, "max":  280000000000 },
                          "4": {"enabled": True, "min" : 1000000000, "max": 5000000000000 },
                          "5": {"enabled": True, "min" : 1000000000 }
                        }).decode('utf-8'),
                        html_template             = """
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/2.3.0/css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body style="background-color: #ffffff">
    <div class="container">
      <div class="content-fluid">
        <table class="table table-condensed">
          <tr>
            <td>Order ID:</td>
            <td>*|control_number|*</td>
          </tr>
          <tr>
            <td>Created:</td>
            <td>*|created|*</td>
          </tr>
          <tr>
            <td>Deposit Method:</td>
            <td>Money Order</td>
          </tr>
          <tr>
            <td>Instructions:</td>
            <td>
              1. Head to your local United States Postal Service and purchase a money order slip for the correct amount. Learn more about USPS money orders <a href="https://www.usps.com/shop/money-orders.htm">here</a><br/>
              2. Fill out the money order form. <b>Important: Make sure to write your confirmation code directly on it!</b><br/>
              3. Take a picture of the filled out money order<br/>
              4. Upload the photo of the money order in the system<br/>
              5. Send the money order to :
              <strong>Satoshi Nakamoto<strong><br/>
              <strong>21 Bitcoin Street<strong><br/>
              <strong>New York - NY - 10001<strong><br/>
            </td>
          </tr>
          <tr>
            <td>Total Deposit:</td>
            <td>$ *|value|*</td>
          </tr>
          <tr>
            <td>Notes:</td>
            <td> <small>
              Please complete your deposit according to your preferred method. Be sure to send a copy of the Order ID with the receipt of completed payment to us.
            </small> </td>
          </tr>
        </table>
      </div>
    </div>
  </body>
</html>
                        """,
                        parameters                = '{}')
    self.db_session.add(e)
    self.db_session.commit()
    self.deposit_method_501 = e

    self.deposit_method_501.generate_deposit(self.db_session, 
                                             self.user_exchange_bonus,
                                             100000000000,
                                             None)
예제 #16
0
    def setUp(self):
        from models import Base, db_bootstrap

        self.engine = create_engine('sqlite://', echo=False)
        Base.metadata.create_all(self.engine)

        self.db_session = scoped_session(sessionmaker(bind=self.engine))
        TradeApplication.instance().db_session = self.db_session

        db_bootstrap(self.db_session)

        currencies = [[
            "BTC", u"฿", "Bitcoin", True, 10000, "{:,.8f}",
            u"฿ #,##0.00000000;(฿ #,##0.00000000)", "{:,.8f}",
            u"฿ #,##0.00000000;(฿ #,##0.0000000)"
        ],
                      [
                          "USD", u"$", "Dollar", False, 100, "{:,.2f}",
                          u"¤ #,##0.00;(¤ #,##0.00)", "{:,.2f}",
                          u"¤ #,##0.00;(¤ #,##0.00)"
                      ]]

        for c in currencies:
            e = Currency(code=c[0],
                         sign=c[1],
                         description=c[2],
                         is_crypto=c[3],
                         pip=c[4],
                         format_python=c[5],
                         format_js=c[6],
                         human_format_python=c[7],
                         human_format_js=c[8])
            self.db_session.add(e)
            self.db_session.commit()

        instruments = [["BTCUSD", "USD", "BTC / USD"]]
        for currency_description in instruments:
            e = Instrument(symbol=currency_description[0],
                           currency=currency_description[1],
                           description=currency_description[2])
            self.db_session.add(e)
            self.db_session.commit()

        # user root
        e = User(id=-1,
                 username='******',
                 email='*****@*****.**',
                 password='******',
                 country_code='US',
                 state='NY',
                 transaction_fee_buy=0,
                 transaction_fee_sell=0,
                 verified=3,
                 is_staff=True,
                 is_system=True,
                 is_broker=True,
                 email_lang='en')
        self.db_session.add(e)

        # user blinktrade
        e = User(id=8999999,
                 username='******',
                 email='*****@*****.**',
                 password='******',
                 country_code='US',
                 state='NY',
                 transaction_fee_buy=0,
                 transaction_fee_sell=0,
                 verified=3,
                 is_staff=True,
                 is_broker=True,
                 email_lang='en')
        self.db_session.add(e)

        # user exchange
        e = User(id=5,
                 username='******',
                 email='*****@*****.**',
                 broker_id=8999999,
                 broker_username='******',
                 password='******',
                 country_code='US',
                 state='NY',
                 transaction_fee_buy=0,
                 transaction_fee_sell=0,
                 verified=5,
                 is_broker=True,
                 email_lang='en')
        self.db_session.add(e)
        self.db_session.commit()

        # user exchange bonus
        e = User(id=90000000,
                 username='******',
                 email='*****@*****.**',
                 broker_id=5,
                 broker_username='******',
                 password='******',
                 country_code='US',
                 state='NY',
                 transaction_fee_buy=0,
                 transaction_fee_sell=0,
                 verified=5,
                 is_broker=True,
                 email_lang='en')
        self.db_session.add(e)
        self.db_session.commit()
        self.user_exchange_bonus = e

        # user exchange fees
        e = User(id=90000001,
                 username='******',
                 email='*****@*****.**',
                 broker_id=5,
                 broker_username='******',
                 password='******',
                 country_code='US',
                 state='NY',
                 transaction_fee_buy=0,
                 transaction_fee_sell=0,
                 verified=5,
                 is_broker=True,
                 email_lang='en')
        self.db_session.add(e)
        self.db_session.commit()
        self.user_exchange_fees = e

        # broker exchange
        e = Broker(
            id=5,
            short_name='exchange',
            business_name='BlinkTrade Demo Exchange',
            address='21 Bitcoin Ave',
            signup_label='BlinkTrade Demo Exchange',
            city='New York',
            state='NY',
            zip_code='10000',
            country_code='US',
            lang='en',
            country='United States',
            mandrill_api_key=None,
            mailer_from_name='BlinkTrade',
            mailer_from_email='*****@*****.**',
            mailer_signature='BlinkTrade Demo Exchange',
            mailchimp_list_id='5c7b7818d8',
            phone_number_1=None,
            phone_number_2=None,
            skype='blinktrade',
            email='*****@*****.**',
            verification_jotform=
            'https://secure.jotform.co/form/42336230941852?user_id={{UserID}}&username={{Username}}&broker_id={{BrokerID}}&broker_username={{BrokerUsername}}&email={{Email}}&phoneNumber[country]=1&address[state]={{State}}&address[country]=United+States',
            upload_jotform=
            'https://secure.jotform.co/form/42344880060854?user_id={{UserID}}&username={{Username}}&broker_id={{BrokerID}}&broker_username={{BrokerUsername}}&deposit_method={{DepositMethod}}&control_number={{ControlNumber}}&deposit_id={{DepositID}}',
            currencies='USD',
            withdraw_structure=json.dumps({
                "BTC": [{
                    "method":
                    "bitcoin",
                    "description":
                    "Bitcoin withdrawal",
                    "disclaimer":
                    "",
                    "percent_fee":
                    0,
                    "fixed_fee":
                    0,
                    "limits": {
                        "0": {
                            "enabled": True,
                            "min": 500000,
                            "max": 100000000
                        },
                        "1": {
                            "enabled": True,
                            "min": 500000,
                            "max": 100000000
                        },
                        "2": {
                            "enabled": True,
                            "min": 500000,
                            "max": 100000000
                        },
                        "3": {
                            "enabled": True,
                            "min": 500000
                        },
                        "4": {
                            "enabled": True,
                            "min": 500000
                        },
                        "5": {
                            "enabled": True,
                            "min": 500000
                        }
                    },
                    "fields": [{
                        "side": "client",
                        "name": "Wallet",
                        "validator": "validateAddress",
                        "type": "text",
                        "value": "",
                        "label": "Wallet",
                        "placeholder": ""
                    }, {
                        "side": "broker",
                        "name": "TransactionID",
                        "validator": "validateAlphaNum",
                        "type": "text",
                        "value": "",
                        "label": "TransactionID",
                        "placeholder": ""
                    }]
                }],
                "USD": [{
                    "method":
                    "swift",
                    "description":
                    "Swift International Transfer",
                    "disclaimer":
                    "84 hours, 1%  fee + $25",
                    "percent_fee":
                    1,
                    "fixed_fee":
                    2500000000,
                    "limits": {
                        "0": {
                            "enabled": False
                        },
                        "1": {
                            "enabled": False
                        },
                        "2": {
                            "enabled": False
                        },
                        "3": {
                            "enabled": True,
                            "min": 3500000000,
                            "max": 280000000000
                        },
                        "4": {
                            "enabled": True,
                            "min": 3500000000,
                            "max": 5000000000000
                        },
                        "5": {
                            "enabled": True,
                            "min": 3500000000
                        }
                    },
                    "fields": [{
                        "side": "client",
                        "name": "BankName",
                        "validator": "validateAlphaNum",
                        "type": "text",
                        "value": "",
                        "label": "Banco name",
                        "placeholder": "ex. JPMORGAN CHASE BANK, N.A"
                    }, {
                        "side": "client",
                        "name": "BankSwift",
                        "validator": "validateAlphaNum",
                        "type": "text",
                        "value": "",
                        "label": "Swift code",
                        "placeholder": "ex. CHASUS33"
                    }, {
                        "side": "client",
                        "name": "RoutingNumber",
                        "validator": "validateAlphaNum",
                        "type": "text",
                        "value": "",
                        "label": "Routing Number",
                        "placeholder": "ex. 021000021"
                    }, {
                        "side": "client",
                        "name": "AccountNumber",
                        "validator": "validateAlphaNum",
                        "type": "text",
                        "value": "",
                        "label": "Account Number",
                        "placeholder": "ex. 88888-8"
                    }, {
                        "side": "broker",
                        "name": "TransactionID",
                        "validator": "validateAlphaNum",
                        "type": "text",
                        "value": "",
                        "label": "TransactionID",
                        "placeholder": ""
                    }]
                }]
            }).decode('utf-8'),
            crypto_currencies=json.dumps([{
                "Wallets": [{
                    "managed_by": "BlinkTrade, Exchange Operator, Mediator ",
                    "signatures": [],
                    "type": "cold",
                    "multisig": False,
                    "address": "n3yyGwzyfTxbKB8hkkv2AsQ9nBQgEozsV4"
                }, {
                    "managed_by": "Exchange Operator ",
                    "signatures": [],
                    "type": "hot",
                    "multisig": False,
                    "address": "msQRdMPcwLr3rWsLzG56ABhHtfavHH2yVW"
                }],
                "CurrencyCode":
                "BTC",
                "Confirmations": [[0, 200000000, 1],
                                  [200000000, 20000000000, 3],
                                  [20000000000, 2100000000000000, 6]],
                "CurrencyDescription":
                "Bitcoin"
            }]).decode('utf-8'),
            accept_customers_from=json.dumps(
                [["*"], ["CU", "SO", "SD", "NG", "IR", "KP"]]).decode('utf-8'),
            is_broker_hub=False,
            support_url='mailto:[email protected]',
            tos_url=
            'https://docs.google.com/a/blinktrade.com/document/d/1HyFRs_2Seh4LGZYjPk8bmbxueUjF7RMz-koAM3rG2Pc/pub?embedded=true',
            fee_structure=json.dumps([{
                "Operation":
                "Wire transfer",
                "Fee":
                "1%",
                "Terms":
                "Exchange operator decides its fees"
            }]).decode('utf-8'),
            transaction_fee_buy=60,
            transaction_fee_sell=60,
            accounts=json.dumps({
                "bonus": [90000000, "exchange_bonus", ["USD", 100000000]],
                "fees": [90000001, "exchange_fees"]
            }).decode('utf-8'),
            status='1',
            ranking=5)
        self.db_session.add(e)
        self.db_session.commit()

        e = DepositMethods(id=501,
                           broker_id=5,
                           name='usps',
                           description='USPS Money order',
                           disclaimer='1 business day',
                           type='DTP',
                           percent_fee=0,
                           fixed_fee=500000000,
                           broker_deposit_ctrl_num=501000001,
                           currency='USD',
                           deposit_limits=json.dumps({
                               "0": {
                                   "enabled": False
                               },
                               "1": {
                                   "enabled": False
                               },
                               "2": {
                                   "enabled": False
                               },
                               "3": {
                                   "enabled": True,
                                   "min": 1000000000,
                                   "max": 280000000000
                               },
                               "4": {
                                   "enabled": True,
                                   "min": 1000000000,
                                   "max": 5000000000000
                               },
                               "5": {
                                   "enabled": True,
                                   "min": 1000000000
                               }
                           }).decode('utf-8'),
                           html_template="""
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/2.3.0/css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body style="background-color: #ffffff">
    <div class="container">
      <div class="content-fluid">
        <table class="table table-condensed">
          <tr>
            <td>Order ID:</td>
            <td>*|control_number|*</td>
          </tr>
          <tr>
            <td>Created:</td>
            <td>*|created|*</td>
          </tr>
          <tr>
            <td>Deposit Method:</td>
            <td>Money Order</td>
          </tr>
          <tr>
            <td>Instructions:</td>
            <td>
              1. Head to your local United States Postal Service and purchase a money order slip for the correct amount. Learn more about USPS money orders <a href="https://www.usps.com/shop/money-orders.htm">here</a><br/>
              2. Fill out the money order form. <b>Important: Make sure to write your confirmation code directly on it!</b><br/>
              3. Take a picture of the filled out money order<br/>
              4. Upload the photo of the money order in the system<br/>
              5. Send the money order to :
              <strong>Satoshi Nakamoto<strong><br/>
              <strong>21 Bitcoin Street<strong><br/>
              <strong>New York - NY - 10001<strong><br/>
            </td>
          </tr>
          <tr>
            <td>Total Deposit:</td>
            <td>$ *|value|*</td>
          </tr>
          <tr>
            <td>Notes:</td>
            <td> <small>
              Please complete your deposit according to your preferred method. Be sure to send a copy of the Order ID with the receipt of completed payment to us.
            </small> </td>
          </tr>
        </table>
      </div>
    </div>
  </body>
</html>
                        """,
                           parameters='{}')
        self.db_session.add(e)
        self.db_session.commit()
        self.deposit_method_501 = e

        self.deposit_method_501.generate_deposit(self.db_session,
                                                 self.user_exchange_bonus,
                                                 100000000000, None)