示例#1
0
  def set_user(self, user):
    if user is None:
      self.user = None
      self.is_broker = False
      self.profile = None
      self.should_end = False
      self.email_lang = 'en'
      return

    if self.user:
      raise UserAlreadyLogged
    self.user = user
    self.email_lang = user.email_lang

    self.is_broker = self.user.is_broker

    from models import Broker
    if self.is_broker:
      self.profile = Broker.get_broker( TradeApplication.instance().db_session,user.id)
      self.user_accounts = json.loads(self.profile.accounts)
    else:
      self.profile = user

    if user.broker_id is not None:
      self.broker           = Broker.get_broker( TradeApplication.instance().db_session,user.broker.id)
      self.broker_accounts  = json.loads(self.broker.accounts)
  def publish_executions(symbol, entry_type, executed_count, order = None):
    entry_list = []

    if executed_count:
      entry_list.append( {
        "MDUpdateAction":"3",  # Delete Thru
        "Symbol": symbol,
        "MDEntryType": entry_type,
        "MDEntryPositionNo": executed_count,
        })

    if order:
      entry_list.append( {
        "MDUpdateAction":"1",  # Update
        "Symbol": symbol,
        "MDEntryType": entry_type,
        "MDEntryPositionNo": 1,
        "MDEntryID": order.id,
        "MDEntryPx": order.price,
        "MDEntrySize": order.leaves_qty,
        "MDEntryDate": order.created.date(),
        "MDEntryTime": order.created.time(),
        "OrderID": order.id,
        "Username": order.account_username,
        "Broker": order.broker_username
      })
    if entry_list:
      md = {
        "MsgType":"X",
        "MDBkTyp": '3', # Order Depth
        "MDIncGrp": entry_list
      }
      TradeApplication.instance().publish( 'MD_INCREMENTAL_' + symbol + '.' + entry_type , md )
示例#3
0
  def publish_executions(symbol, entry_type, executed_count, order = None):
    entry_list = []

    if executed_count:
      entry_list.append( {
        "MDUpdateAction":"3",  # Delete Thru
        "Symbol": symbol,
        "MDEntryType": entry_type,
        "MDEntryPositionNo": executed_count,
        })

    if order:
      entry_list.append( {
        "MDUpdateAction":"1",  # Update
        "Symbol": symbol,
        "MDEntryType": entry_type,
        "MDEntryPositionNo": 1,
        "MDEntryID": order.id,
        "MDEntryPx": order.price,
        "MDEntrySize": order.leaves_qty,
        "MDEntryDate": order.created.date(),
        "MDEntryTime": order.created.time(),
        "OrderID": order.id,
        "UserID": order.account_id,
        "Username": order.account_username,
        "Broker": order.broker_username
      })
    if entry_list:
      md = {
        "MsgType":"X",
        "MDBkTyp": '3', # Order Depth
        "MDIncGrp": entry_list
      }
      TradeApplication.instance().publish( 'MD_INCREMENTAL_' + symbol + '.' + entry_type , md )
示例#4
0
    def testSignUpWelcomeEmail(self, get_now):
        get_now.return_value = datetime.datetime(2014, 1, 1, 10, 10, 10)
        from models import User, UserEmail, BrokerDoesNotExistsException

        self.failUnlessRaises(BrokerDoesNotExistsException, User.signup,
                              self.db_session, 'rodrigo', '*****@*****.**',
                              'abc12345', 'NY', 'US', 1115)

        User.signup(self.db_session, 'rodrigo', '*****@*****.**', 'abc12345',
                    'NY', 'US', 5)

        TradeApplication.instance().publish.assert_called_with(
            'EMAIL', {
                'Language': u'en',
                'EmailType': '0',
                'UserID': 90000002,
                'OrigTime': datetime.datetime(2014, 1, 1, 10, 10, 10),
                'To': u'*****@*****.**',
                'Params':
                '{"username": "******", "id": 90000002, "state": "NY", "broker_id": 5, "broker_username": "******", "country_code": "US", "email": "*****@*****.**"}',
                'RawData': '',
                'Template': 'welcome',
                'BrokerID': 5,
                'MsgType': 'C',
                'EmailThreadID': 1,
                'RawDataLength': 0,
                'Subject': 'W'
            })
示例#5
0
  def set_user(self, user, permission_list):
    if user is None:
      self.user = None
      self.is_broker = False
      self.profile = None
      self.should_end = False
      self.email_lang = TradeApplication.instance().options.global_email_language
      return

    if self.user:
      raise UserAlreadyLogged
    self.user = user
    self.email_lang = user.email_lang
    self.permission_list = permission_list
    self.is_broker = self.user.is_broker

    from models import Broker
    if self.is_broker:
      self.profile = Broker.get_broker( TradeApplication.instance().db_session,user.id)
      self.user_accounts = json.loads(self.profile.accounts)
    else:
      self.profile = user

    if user.broker_id is not None:
      self.broker           = Broker.get_broker( TradeApplication.instance().db_session,user.broker.id)
      self.broker_accounts  = json.loads(self.broker.accounts)
示例#6
0
 def publish_trades(symbol, trades):
   md_trades = []
   for trade in trades:
     md_trades.append({
       "MDUpdateAction":"0",
       "MDEntryType": "2",  # Trade
       "Symbol": trade.symbol,
       "MDEntryPx": trade.price,
       "MDEntrySize": trade.size,
       "MDEntryDate": trade.created.date(),
       "MDEntryTime": trade.created.time(),
       "OrderID": trade.order_id,
       "Side": trade.side,
       "SecondaryOrderID": trade.counter_order_id,
       "TradeID": trade.id,
       "MDEntryBuyerID": trade.buyer_id,
       "MDEntrySellerID": trade.seller_id,
       "MDEntryBuyer": trade.buyer_username,
       "MDEntrySeller": trade.seller_username,
     })
   md = {
     "MsgType":"X",
     "MDBkTyp": '3', # Order Depth
     "MDIncGrp": md_trades
   }
   TradeApplication.instance().publish( 'MD_TRADE_' + symbol , md )
示例#7
0
  def cancel(self, session, order):
    if not order:
      # Generate an Order Cancel Reject - Order not found
      return

    # let's find the  order position
    self_side = []
    if order.is_buy:
      self_side = self.buy_side
    elif order.is_sell:
      self_side = self.sell_side

    order_found = False
    order_pos = bisect.bisect_left(self_side, order)
    for x in xrange( order_pos, len(self_side)):
      tmp_order = self_side[x]

      if tmp_order.id == order.id:
        order_found = True
        break

      if tmp_order.price != order.price:
        break

      order_pos += 1


    if not order_found:
      # Generate an Order Cancel Reject - Order not found
      return

    # update the order
    order.cancel_qty( order.leaves_qty )
    session.commit()

    # remove the order from the book
    self_side.pop( order_pos )


    # Generate a cancel report
    cancel_rpt = ExecutionReport( order, '1' if order.is_buy else '2' )
    TradeApplication.instance().publish(order.user_id, cancel_rpt.toJson() )

    if order.user_id != order.account_id:
      TradeApplication.instance().publish(order.account_id, cancel_rpt.toJson() )


    # market data
    md_entry_type = '0' if order.is_buy else '1'
    MarketDataPublisher.publish_cancel_order( self.symbol, md_entry_type, order_pos+1 )

    return ""
示例#8
0
  def cancel(self, session, order):
    if not order:
      # Generate an Order Cancel Reject - Order not found
      return

    # let's find the  order position
    self_side = []
    if order.is_buy:
      self_side = self.buy_side
    elif order.is_sell:
      self_side = self.sell_side

    order_found = False
    order_pos = bisect.bisect_left(self_side, order)
    for x in xrange( order_pos, len(self_side)):
      tmp_order = self_side[x]

      if tmp_order.id == order.id:
        order_found = True
        break

      if tmp_order.price != order.price:
        break

      order_pos += 1


    if not order_found:
      # Generate an Order Cancel Reject - Order not found
      return

    # update the order
    order.cancel_qty( order.leaves_qty )
    session.commit()

    # remove the order from the book
    self_side.pop( order_pos )


    # Generate a cancel report
    cancel_rpt = ExecutionReport( order, '1' if order.is_buy else '2' )
    TradeApplication.instance().publish(order.user_id, cancel_rpt.toJson() )

    if order.user_id != order.account_id:
      TradeApplication.instance().publish(order.account_id, cancel_rpt.toJson() )


    # market data
    md_entry_type = '0' if order.is_buy else '1'
    MarketDataPublisher.publish_cancel_order( self.symbol, md_entry_type, order_pos+1 )

    return ""
  def publish_cancel_order(symbol, entry_type, order_position ):

    md = {
      "MsgType":"X",
      "MDBkTyp": '3', # Order Depth
      "MDIncGrp": [{
        "MDUpdateAction":"2",  # Delete
        "Symbol": symbol,
        "MDEntryType": entry_type,
        "MDEntryPositionNo": order_position,
        }]
    }
    TradeApplication.instance().publish( 'MD_INCREMENTAL_' + symbol + '.' + entry_type , md )
示例#10
0
  def publish_cancel_order(symbol, entry_type, order_position ):

    md = {
      "MsgType":"X",
      "MDBkTyp": '3', # Order Depth
      "MDIncGrp": [{
        "MDUpdateAction":"2",  # Delete
        "Symbol": symbol,
        "MDEntryType": entry_type,
        "MDEntryPositionNo": order_position,
        }]
    }
    TradeApplication.instance().publish( 'MD_INCREMENTAL_' + symbol + '.' + entry_type , md )
示例#11
0
def main():
  parser = argparse.ArgumentParser(description="Blinktrade Trade application")
  parser.add_argument('-i', "--instance", action="store", dest="instance", help='Instance name', type=str)
  parser.add_argument('-c', "--config", action="store", dest="config", default=os.path.expanduser('~/.bitex/bitex.ini'), help='Configuration file', type=str)
  arguments = parser.parse_args()

  if not arguments.instance:
    parser.print_help()
    return


  candidates = [ os.path.join(ROOT_PATH, 'config/bitex.ini'),
                 os.path.join(site_config_dir('bitex'), 'bitex.ini'),
                 arguments.config]
  config = ConfigParser.SafeConfigParser()
  config.read( candidates )

  options = ProjectOptions(config, arguments.instance)

  if not options.trade_in or \
     not options.trade_pub or \
     not options.trade_log or \
     not options.global_email_language or \
     not options.db_engine:
    raise RuntimeError("Invalid configuration file")

  application = TradeApplication.instance()
  application.initialize(options, arguments.instance)
  application.run()
示例#12
0
  def generate_md_full_refresh( session, symbol, market_depth, om, entries, req_id, timestamp  ):
    entry_list = []

    for entry_type in entries:
      if entry_type == '0' or entry_type == '1':
        if entry_type == '0': # Bid
          orders = om.buy_side
        else: # Offer
          orders = om.sell_side

        entry_position = 0
        for order in orders:
          if order.type == '1': # Hide the market orders
            continue

          entry_position += 1

          entry_list.append({
            "MDEntryType": entry_type,
            "MDEntryPositionNo": entry_position,
            "MDEntryID": order.id,
            "MDEntryPx": order.price,
            "MDEntrySize": order.leaves_qty,
            "MDEntryDate": order.created.date(),
            "MDEntryTime": order.created.time(),
            "OrderID": order.id,
            "UserID": order.account_id,
            "Username": order.account_username,
            "Broker": order.broker_username
          })

          if entry_position >= market_depth > 0:
            break

    md = {
      "MsgType":"W",
      "MDReqID": req_id,
      "MarketDepth": market_depth,
      "Symbol": symbol,
      "MDFullGrp": entry_list
    }
    TradeApplication.instance().publish( 'MD_FULL_REFRESH_' + symbol , md )
    return md
  def generate_md_full_refresh( session, symbol, market_depth, om, entries, req_id, timestamp  ):
    entry_list = []

    for entry_type in entries:
      if entry_type == '0' or entry_type == '1':
        if entry_type == '0': # Bid
          orders = om.buy_side
        else: # Offer
          orders = om.sell_side

        entry_position = 0
        for order in orders:
          if order.type == '1': # Hide the market orders
            continue

          entry_position += 1

          entry_list.append( {
            "MDEntryType": entry_type,
            "MDEntryPositionNo": entry_position,
            "MDEntryID": order.id,
            "MDEntryPx": order.price,
            "MDEntrySize": order.leaves_qty,
            "MDEntryDate": order.created.date(),
            "MDEntryTime": order.created.time(),
            "OrderID": order.id,
            "Username": order.account_username,
            "Broker": order.broker_username
          })

          if entry_position >= market_depth > 0:
            break

    md = {
      "MsgType":"W",
      "MDReqID": req_id,
      "MarketDepth": market_depth,
      "Symbol": symbol,
      "MDFullGrp": entry_list
    }
    TradeApplication.instance().publish( 'MD_FULL_REFRESH_' + symbol , md )

    return md
  def publish_new_order(symbol, entry_type, order_position, order ):
    md = {
      "MsgType":"X",
      "MDBkTyp": '3', # Order Depth
      "MDIncGrp": [{
        "MDUpdateAction":"0",  # new
        "Symbol": symbol,
        "MDEntryType": entry_type,
        "MDEntryPositionNo": order_position + 1,
        "MDEntryID": order.id,
        "MDEntryPx": order.price,
        "MDEntrySize": order.leaves_qty,
        "MDEntryDate": order.created.date(),
        "MDEntryTime": order.created.time(),
        "OrderID": order.id,
        "Username": order.account_username,
        "Broker": order.broker_username

      }]
    }
    TradeApplication.instance().publish( 'MD_INCREMENTAL_' + symbol + '.' + entry_type , md )
示例#15
0
  def publish_new_order(symbol, entry_type, order_position, order ):
    md = {
      "MsgType":"X",
      "MDBkTyp": '3', # Order Depth
      "MDIncGrp": [{
        "MDUpdateAction":"0",  # new
        "Symbol": symbol,
        "MDEntryType": entry_type,
        "MDEntryPositionNo": order_position + 1,
        "MDEntryID": order.id,
        "MDEntryPx": order.price,
        "MDEntrySize": order.leaves_qty,
        "MDEntryDate": order.created.date(),
        "MDEntryTime": order.created.time(),
        "OrderID": order.id,
        "UserID": order.account_id,
        "Username": order.account_username,
        "Broker": order.broker_username

      }]
    }
    TradeApplication.instance().publish( 'MD_INCREMENTAL_' + symbol + '.' + entry_type , md )
  def __init__(self, session_id, remote_ip=None, client_version=None):
    self.session_id     = session_id
    self.remote_ip      = remote_ip
    self.client_version = client_version

    self.user             = None
    self.is_broker        = False
    self.profile          = None
    self.broker           = None
    self.should_end       = False
    self.user_accounts    = None
    self.broker_accounts  = None
    self.email_lang       = TradeApplication.instance().options.global_email_language
    self.permission_list  = {'*':[]}
示例#17
0
  def __init__(self, session_id, remote_ip=None, client_version=None):
    self.session_id     = session_id
    self.remote_ip      = remote_ip
    self.client_version = client_version

    self.user             = None
    self.is_broker        = False
    self.profile          = None
    self.broker           = None
    self.should_end       = False
    self.user_accounts    = None
    self.broker_accounts  = None
    self.email_lang       = TradeApplication.instance().options.global_email_language
    self.permission_list  = {'*':[]}
 def publish_trades(symbol, trades):
   md_trades = []
   for trade in trades:
     md_trades.append({
       "MDUpdateAction":"0",
       "MDEntryType": "2",  # Trade
       "Symbol": trade.symbol,
       "MDEntryPx": trade.price,
       "MDEntrySize": trade.size,
       "MDEntryDate": trade.created.date(),
       "MDEntryTime": trade.created.time(),
       "OrderID": trade.order_id,
       "Side": trade.side,
       "SecondaryOrderID": trade.counter_order_id,
       "TradeID": trade.id,
       "MDEntryBuyer": trade.buyer_username,
       "MDEntrySeller": trade.seller_username,
     })
   md = {
     "MsgType":"X",
     "MDBkTyp": '3', # Order Depth
     "MDIncGrp": md_trades
   }
   TradeApplication.instance().publish( 'MD_TRADE_' + symbol , md )
示例#19
0
  def testSignUpWelcomeEmail(self, get_now):
    get_now.return_value  = datetime.datetime(2014, 1, 1, 10, 10, 10)
    from models import User, UserEmail, BrokerDoesNotExistsException

    self.failUnlessRaises(BrokerDoesNotExistsException,
      User.signup, self.db_session, 'rodrigo', '*****@*****.**', 'abc12345', 'NY', 'US', 1115 )

    User.signup(self.db_session, 'rodrigo', '*****@*****.**', 'abc12345', 'NY', 'US', 5)

    TradeApplication.instance().publish.assert_called_with('EMAIL', {
      'Language': u'en',
      'EmailType': '0',
      'UserID': 9000000,
      'OrigTime': datetime.datetime(2014, 1, 1, 10, 10, 10),
      'To': u'*****@*****.**',
      'Params': '{"username": "******", "id": 9000000, "state": "NY", "broker_id": 5, "broker_username": "******", "country_code": "US", "email": "*****@*****.**"}',
      'RawData': '',
      'Template': 'welcome',
      'BrokerID': 5,
      'MsgType': 'C',
      'EmailThreadID': 1,
      'RawDataLength': 0,
      'Subject': 'W'}
    )
示例#20
0
def main():
    parser = argparse.ArgumentParser(
        description="Blinktrade Trade application")
    parser.add_argument('-i',
                        "--instance",
                        action="store",
                        dest="instance",
                        help='Instance name',
                        type=str)
    parser.add_argument('-c',
                        "--config",
                        action="store",
                        dest="config",
                        default=os.path.expanduser('~/.blinktrade/bitex.ini'),
                        help='Configuration file',
                        type=str)
    arguments = parser.parse_args()

    if not arguments.instance:
        parser.print_help()
        return

    candidates = [
        os.path.join(site_config_dir('blinktrade'), 'bitex.ini'),
        os.path.expanduser('~/.blinktrade/bitex.ini'), arguments.config
    ]
    config = ConfigParser.SafeConfigParser()
    config.read(candidates)

    options = ProjectOptions(config, arguments.instance)

    if not options.trade_in or \
       not options.trade_pub or \
       not options.trade_log or \
       not options.global_email_language or \
       not options.sqlalchemy_connection_string or \
       not options.sqlalchemy_engine:
        raise RuntimeError("Invalid configuration file")

    application = TradeApplication.instance()
    application.initialize(options, arguments.instance)
    application.run()
示例#21
0
ROOT_PATH = os.path.abspath( os.path.join(os.path.dirname(__file__), "../"))
sys.path.insert( 0, ROOT_PATH)

import unittest
import json

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

import  datetime

import mock

from trade_application import  TradeApplication

TradeApplication.instance().publish = mock.MagicMock()

class BaseTest(unittest.TestCase):
  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)" ],
示例#22
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)
示例#23
0
  def match(self, session, order, order_matcher_disabled=False):
    other_side = []
    self_side = []
    if order.is_buy:
      self_side = self.buy_side
      other_side = self.sell_side
    elif order.is_sell:
      other_side = self.buy_side
      self_side = self.sell_side


    execution_reports = []
    trades_to_publish = []

    execution_side = '1' if order.is_buy else '2'

    rpt_order  = ExecutionReport( order, execution_side )
    execution_reports.append( ( order.user_id, rpt_order.toJson() )  )
    if order.user_id != order.account_id:
      execution_reports.append( ( order.account_id, rpt_order.toJson() )  )

    is_last_match_a_partial_execution_on_counter_order = False
    execution_counter = 0
    number_of_filled_counter_market_orders = 0

    if not order_matcher_disabled:
      for execution_counter in xrange(0, len(other_side) + 1):
        if execution_counter == len(other_side):
          break # workaround to make the execution_counter be counted until the last order.

        if not order.leaves_qty > 0:
          break

        counter_order = other_side[execution_counter]

        if not order.has_match(counter_order):
          break

        # check for self execution
        if order.account_id == counter_order.account_id:
          # self execution.... let's cancel the counter order
          counter_order.cancel_qty( counter_order.leaves_qty )

          # generate a cancel report
          cancel_rpt_counter_order  = ExecutionReport( counter_order, execution_side )
          execution_reports.append( ( counter_order.user_id, cancel_rpt_counter_order.toJson() )  )
          if counter_order.user_id != counter_order.account_id:
            execution_reports.append( ( counter_order.account_id, cancel_rpt_counter_order.toJson() )  )

          # go to the next order
          is_last_match_a_partial_execution_on_counter_order = False
          continue

        # Get the desired executed price and qty, by matching against the counter_order
        executed_qty = order.match( counter_order, order.leaves_qty)

        if counter_order.type == '1': # Market Order
          executed_price = order.price
          number_of_filled_counter_market_orders += 1
        else:
          executed_price = counter_order.price

        # let's get the available qty to execute on the order side
        available_qty_on_order_side = order.get_available_qty_to_execute(session,
                                                                         '1' if order.is_buy else '2',
                                                                         executed_qty,
                                                                         executed_price )

        qty_to_cancel_from_order = 0
        if available_qty_on_order_side <  executed_qty:
          # ops ... looks like the order.user didn't have enough to execute the order
          executed_qty = available_qty_on_order_side

          # cancel the remaining  qty
          qty_to_cancel_from_order = order.leaves_qty - executed_qty


        # check if the order got fully cancelled
        if not executed_qty:
          order.cancel_qty( qty_to_cancel_from_order )
          cancel_rpt_order  = ExecutionReport( order, execution_side )
          execution_reports.append( ( order.user_id, cancel_rpt_order.toJson() )  )
          if order.user_id != order.account_id:
            execution_reports.append( ( order.account_id, cancel_rpt_order.toJson() )  )
          break


        # let's get the available qty to execute on the counter side
        available_qty_on_counter_side = counter_order.get_available_qty_to_execute(session,
                                                                                   '1' if counter_order.is_buy else '2',
                                                                                   executed_qty,
                                                                                   executed_price )

        qty_to_cancel_from_counter_order = 0
        if available_qty_on_counter_side <  executed_qty:
          if qty_to_cancel_from_order:
            qty_to_cancel_from_order -= executed_qty - available_qty_on_order_side

            # ops ... looks like the counter_order.user didn't have enough to execute the order
          executed_qty = available_qty_on_counter_side

          # cancel the remaining  qty
          qty_to_cancel_from_counter_order = counter_order.leaves_qty - executed_qty


        # check if the counter order was fully cancelled due the lack
        if not executed_qty:
          # just cancel the counter order, and go to the next order.
          counter_order.cancel_qty( qty_to_cancel_from_counter_order )

          # generate a cancel report
          cancel_rpt_counter_order  = ExecutionReport( counter_order, execution_side )
          execution_reports.append( ( counter_order.user_id, cancel_rpt_counter_order.toJson() )  )
          if counter_order.user_id != counter_order.account_id:
            execution_reports.append( ( counter_order.account_id, cancel_rpt_counter_order.toJson() )  )

          # go to the next order
          is_last_match_a_partial_execution_on_counter_order = False
          continue

        # lets perform the execution
        if executed_qty:
          order.execute( executed_qty, executed_price )
          counter_order.execute(executed_qty, executed_price )

          trade = Trade.create(session, order, counter_order, self.symbol, executed_qty, executed_price )
          trades_to_publish.append(trade)

          rpt_order         = ExecutionReport( order, execution_side )
          execution_reports.append( ( order.user_id, rpt_order.toJson() )  )
          if order.user_id != order.account_id:
            execution_reports.append( ( order.account_id, rpt_order.toJson() )  )

          rpt_counter_order = ExecutionReport( counter_order, execution_side )
          execution_reports.append( ( counter_order.user_id, rpt_counter_order.toJson() )  )
          if counter_order.user_id != counter_order.account_id:
            execution_reports.append( ( counter_order.account_id, rpt_counter_order.toJson() )  )

          def generate_email_subject_and_body( session, order, trade ):
            from json import  dumps
            from pyblinktrade.json_encoder import  JsonEncoder
            from models import Currency

            qty_currency = order.symbol[:3]
            formatted_qty = Currency.format_number( session, qty_currency, trade.size / 1.e8 )


            price_currency = order.symbol[3:]
            formatted_price = Currency.format_number( session, price_currency, trade.price / 1.e8 )

            formatted_total_price = Currency.format_number( session, price_currency, trade.size/1.e8 * trade.price/1.e8 )

            email_subject =  'E'
            email_template = "order-execution"
            email_params = {
              'username': order.user.username,
              'order_id': order.id,
              'trade_id': trade.id,
              'side': order.side,
              'executed_when': trade.created,
              'qty': formatted_qty,
              'price': formatted_price,
              'total': formatted_total_price
            }
            return  email_subject, email_template, dumps(email_params, cls=JsonEncoder)

          email_data = generate_email_subject_and_body(session, order, trade)
          UserEmail.create( session = session,
                            user_id = order.account_id,
                            broker_id = order.broker_id,
                            subject = email_data[0],
                            template= email_data[1],
                            language= order.email_lang,
                            params  = email_data[2])

          email_data = generate_email_subject_and_body(session, counter_order, trade)
          UserEmail.create( session = session,
                            user_id = counter_order.account_id,
                            broker_id = counter_order.broker_id,
                            subject = email_data[0],
                            template= email_data[1],
                            language= counter_order.email_lang,
                            params  = email_data[2])


        #
        # let's do the partial cancels
        #

        # Cancel the qty from the current order
        if qty_to_cancel_from_order:
          order.cancel_qty(qty_to_cancel_from_order)

          # generate a cancel report
          cancel_rpt_order  = ExecutionReport( order, execution_side )
          execution_reports.append( ( order.user_id, cancel_rpt_order.toJson() )  )

          if order.user_id != order.account_id:
            execution_reports.append( ( order.account_id, cancel_rpt_order.toJson() )  )


        if qty_to_cancel_from_counter_order:
          counter_order.cancel_qty(qty_to_cancel_from_counter_order)

          # generate a cancel report
          cancel_rpt_counter_order  = ExecutionReport( counter_order, execution_side )
          execution_reports.append( ( counter_order.user_id, cancel_rpt_counter_order.toJson() )  )
          if counter_order.user_id != counter_order.account_id:
            execution_reports.append( ( counter_order.account_id, cancel_rpt_counter_order.toJson() )  )

        if counter_order.leaves_qty > 0:
          is_last_match_a_partial_execution_on_counter_order = True


    md_entry_type = '0' if order.is_buy else '1'
    counter_md_entry_type = '1' if order.is_buy else '0'

    # let's include the order in the book if the order is not fully executed.
    if order.leaves_qty > 0:
      insert_pos = bisect.bisect_right(self_side, order)
      self_side.insert( insert_pos, order )

      if order.type == '2': # Limited orders go to the book.
        MarketDataPublisher.publish_new_order( self.symbol, md_entry_type , insert_pos, order)

    # don't send the first execution report (NEW) if the order was fully cancelled
    if order.is_cancelled and order.cum_qty == 0:
      execution_reports.pop(0)

    # Publish all execution reports
    for user_id, execution_report in execution_reports:
      TradeApplication.instance().publish( user_id, execution_report )

    # Publish Market Data for the counter order
    if execution_counter:
      if is_last_match_a_partial_execution_on_counter_order:
        del other_side[0: execution_counter-1]
        MarketDataPublisher.publish_executions( self.symbol,
                                                 counter_md_entry_type,
                                                 execution_counter - 1 - number_of_filled_counter_market_orders,
                                                 other_side[0] )
      else:
        del other_side[0: execution_counter]
        MarketDataPublisher.publish_executions( self.symbol,
                                                 counter_md_entry_type,
                                                 execution_counter - number_of_filled_counter_market_orders )

    if trades_to_publish:
      MarketDataPublisher.publish_trades(self.symbol, trades_to_publish)
    return ""
示例#24
0
  def match(self, session, order, order_matcher_disabled=False):
    other_side = []
    self_side = []
    if order.is_buy:
      self_side = self.buy_side
      other_side = self.sell_side
    elif order.is_sell:
      other_side = self.buy_side
      self_side = self.sell_side


    execution_reports = []
    trades_to_publish = []

    execution_side = '1' if order.is_buy else '2'

    rpt_order  = ExecutionReport( order, execution_side )
    execution_reports.append( ( order.user_id, rpt_order.toJson() )  )
    if order.user_id != order.account_id:
      execution_reports.append( ( order.account_id, rpt_order.toJson() )  )

    is_last_match_a_partial_execution_on_counter_order = False
    execution_counter = 0
    number_of_filled_counter_market_orders = 0

    if not order_matcher_disabled:
      for execution_counter in xrange(0, len(other_side) + 1):
        if execution_counter == len(other_side):
          break # workaround to make the execution_counter be counted until the last order.

        if not order.leaves_qty > 0:
          break

        counter_order = other_side[execution_counter]

        if not order.has_match(counter_order):
          break

        # check for self execution
        if order.account_id == counter_order.account_id:
          # self execution.... let's cancel the counter order
          counter_order.cancel_qty( counter_order.leaves_qty )

          # generate a cancel report
          cancel_rpt_counter_order  = ExecutionReport( counter_order, execution_side )
          execution_reports.append( ( counter_order.user_id, cancel_rpt_counter_order.toJson() )  )
          if counter_order.user_id != counter_order.account_id:
            execution_reports.append( ( counter_order.account_id, cancel_rpt_counter_order.toJson() )  )

          # go to the next order
          is_last_match_a_partial_execution_on_counter_order = False
          continue

        # Get the desired executed price and qty, by matching against the counter_order
        executed_qty = order.match( counter_order, order.leaves_qty)

        if counter_order.type == '1': # Market Order
          executed_price = order.price
          number_of_filled_counter_market_orders += 1
        else:
          executed_price = counter_order.price

        # let's get the available qty to execute on the order side
        available_qty_on_order_side = order.get_available_qty_to_execute(session,
                                                                         '1' if order.is_buy else '2',
                                                                         executed_qty,
                                                                         executed_price )

        qty_to_cancel_from_order = 0
        if available_qty_on_order_side <  executed_qty:
          # ops ... looks like the order.user didn't have enough to execute the order
          executed_qty = available_qty_on_order_side

          # cancel the remaining  qty
          qty_to_cancel_from_order = order.leaves_qty - executed_qty


        # check if the order got fully cancelled
        if not executed_qty:
          order.cancel_qty( qty_to_cancel_from_order )
          cancel_rpt_order  = ExecutionReport( order, execution_side )
          execution_reports.append( ( order.user_id, cancel_rpt_order.toJson() )  )
          if order.user_id != order.account_id:
            execution_reports.append( ( order.account_id, cancel_rpt_order.toJson() )  )
          break


        # let's get the available qty to execute on the counter side
        available_qty_on_counter_side = counter_order.get_available_qty_to_execute(session,
                                                                                   '1' if counter_order.is_buy else '2',
                                                                                   executed_qty,
                                                                                   executed_price )

        qty_to_cancel_from_counter_order = 0
        if available_qty_on_counter_side <  executed_qty:
          if qty_to_cancel_from_order:
            qty_to_cancel_from_order -= executed_qty - available_qty_on_order_side

            # ops ... looks like the counter_order.user didn't have enough to execute the order
          executed_qty = available_qty_on_counter_side

          # cancel the remaining  qty
          qty_to_cancel_from_counter_order = counter_order.leaves_qty - executed_qty


        # check if the counter order was fully cancelled due the lack
        if not executed_qty:
          # just cancel the counter order, and go to the next order.
          counter_order.cancel_qty( qty_to_cancel_from_counter_order )

          # generate a cancel report
          cancel_rpt_counter_order  = ExecutionReport( counter_order, execution_side )
          execution_reports.append( ( counter_order.user_id, cancel_rpt_counter_order.toJson() )  )
          if counter_order.user_id != counter_order.account_id:
            execution_reports.append( ( counter_order.account_id, cancel_rpt_counter_order.toJson() )  )

          # go to the next order
          is_last_match_a_partial_execution_on_counter_order = False
          continue

        # lets perform the execution
        if executed_qty:
          order.execute( executed_qty, executed_price )
          counter_order.execute(executed_qty, executed_price )

          trade = Trade.create(session, order, counter_order, self.symbol, executed_qty, executed_price )
          trades_to_publish.append(trade)

          rpt_order         = ExecutionReport( order, execution_side )
          execution_reports.append( ( order.user_id, rpt_order.toJson() )  )
          if order.user_id != order.account_id:
            execution_reports.append( ( order.account_id, rpt_order.toJson() )  )

          rpt_counter_order = ExecutionReport( counter_order, execution_side )
          execution_reports.append( ( counter_order.user_id, rpt_counter_order.toJson() )  )
          if counter_order.user_id != counter_order.account_id:
            execution_reports.append( ( counter_order.account_id, rpt_counter_order.toJson() )  )

          def generate_email_subject_and_body( session, order, trade ):
            from json import  dumps
            from pyblinktrade.json_encoder import  JsonEncoder
            from models import Currency

            qty_currency = order.symbol[:3]
            formatted_qty = Currency.format_number( session, qty_currency, trade.size / 1.e8 )


            price_currency = order.symbol[3:]
            formatted_price = Currency.format_number( session, price_currency, trade.price / 1.e8 )

            formatted_total_price = Currency.format_number( session, price_currency, trade.size/1.e8 * trade.price/1.e8 )

            email_subject =  'E'
            email_template = "order-execution"
            email_params = {
              'username': order.user.username,
              'order_id': order.id,
              'trade_id': trade.id,
              'side': order.side,
              'executed_when': trade.created,
              'qty': formatted_qty,
              'price': formatted_price,
              'total': formatted_total_price
            }
            return  email_subject, email_template, dumps(email_params, cls=JsonEncoder)

          email_data = generate_email_subject_and_body(session, counter_order, trade)
          UserEmail.create( session = session,
                            user_id = counter_order.account_id,
                            broker_id = counter_order.broker_id,
                            subject = email_data[0],
                            template= email_data[1],
                            language= counter_order.email_lang,
                            params  = email_data[2])


        #
        # let's do the partial cancels
        #

        # Cancel the qty from the current order
        if qty_to_cancel_from_order:
          order.cancel_qty(qty_to_cancel_from_order)

          # generate a cancel report
          cancel_rpt_order  = ExecutionReport( order, execution_side )
          execution_reports.append( ( order.user_id, cancel_rpt_order.toJson() )  )

          if order.user_id != order.account_id:
            execution_reports.append( ( order.account_id, cancel_rpt_order.toJson() )  )


        if qty_to_cancel_from_counter_order:
          counter_order.cancel_qty(qty_to_cancel_from_counter_order)

          # generate a cancel report
          cancel_rpt_counter_order  = ExecutionReport( counter_order, execution_side )
          execution_reports.append( ( counter_order.user_id, cancel_rpt_counter_order.toJson() )  )
          if counter_order.user_id != counter_order.account_id:
            execution_reports.append( ( counter_order.account_id, cancel_rpt_counter_order.toJson() )  )

        if counter_order.leaves_qty > 0:
          is_last_match_a_partial_execution_on_counter_order = True


    md_entry_type = '0' if order.is_buy else '1'
    counter_md_entry_type = '1' if order.is_buy else '0'

    # let's include the order in the book if the order is not fully executed.
    if order.leaves_qty > 0:
      insert_pos = bisect.bisect_right(self_side, order)
      self_side.insert( insert_pos, order )

      if order.type == '2': # Limited orders go to the book.
        MarketDataPublisher.publish_new_order( self.symbol, md_entry_type , insert_pos, order)

    # don't send the first execution report (NEW) if the order was fully cancelled
    if order.is_cancelled and order.cum_qty == 0:
      execution_reports.pop(0)

    # Publish all execution reports
    for user_id, execution_report in execution_reports:
      TradeApplication.instance().publish( user_id, execution_report )

    # Publish Market Data for the counter order
    if execution_counter:
      if is_last_match_a_partial_execution_on_counter_order:
        del other_side[0: execution_counter-1]
        MarketDataPublisher.publish_executions( self.symbol,
                                                 counter_md_entry_type,
                                                 execution_counter - 1 - number_of_filled_counter_market_orders,
                                                 other_side[0] )
      else:
        del other_side[0: execution_counter]
        MarketDataPublisher.publish_executions( self.symbol,
                                                 counter_md_entry_type,
                                                 execution_counter - number_of_filled_counter_market_orders )

    if trades_to_publish:
      MarketDataPublisher.publish_trades(self.symbol, trades_to_publish)
    return ""
示例#25
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)
示例#26
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()
示例#27
0
sys.path.insert(0, ROOT_PATH)

import unittest
import json

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

import datetime

import mock

from trade_application import TradeApplication
from models import Instrument, Currency, Broker, User, DepositMethods

TradeApplication.instance().publish = mock.MagicMock()


class BaseTest(unittest.TestCase):
    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 = [[