def setUp(self):
        Base.metadata.create_all()

        instrument = Instrument()
        instrument.ticker = 'MyTicker'
        instrument.asset_class = 'MyAssetClass'
        instrument.name = 'MyName'
        instrument.currency = 'USD'
        instrument.type = 'MyType'
        instrument.transactions_fees = 0.
        instrument.point_value = 1
        instrument.exchange = 'MyExchange'
        instrument.rolling_month = 'H'
        
        market_data = MarketData()
        market_data.instrument = instrument
        market_data.type = DataType.CLOSE
        market_data.date = datetime(2000,1,3)
        market_data.value = 100.
        
        session = Session()
        
        instrument_dao = InstrumentDAO()
        instrument_dao.save(session, instrument)
        
        market_data_dao = MarketDataDAO()
        market_data_dao.save(session, market_data)
        
        
        self.instrument_service = InstrumentService() 
Esempio n. 2
0
def restore_backup():
    try:
        with open(USERS_BACKUP_FILE, 'r') as json_file:
            users = json.load(json_file)
            user_objs = {}
            for user_id in users:
                user_dict = json.loads(users[user_id])
                u = User(user_dict['first_name'], user_dict['last_name'],
                         user_dict['email'], user_dict['password'],
                         user_dict['instrument_ids'], user_dict['is_deleted'])
                user_objs[user_id] = u
            lock.acquire()
            data_store.set_users(user_objs)
            lock.release()

    except FileNotFoundError:
        print('no users file to load from backup')

    try:
        with open(INSTRUMENTS_BACKUP_FILE, 'r') as json_file:
            instruments = json.load(json_file)
            instruments_objs = {}
            for inst_id in instruments:
                inst_dict = json.loads(instruments[inst_id])
                i = Instrument(inst_dict['name'], inst_dict['type'],
                               inst_dict['links'], inst_dict['images'])
                instruments_objs[inst_id] = i
            data_store.set_instruments(instruments_objs)

    except FileNotFoundError:
        print('no instruments file to load from backup')
Esempio n. 3
0
def add_instrument():
    instrument_content = request.json
    try:
        instruments = data_store.get_all_instruments()
        validators.validate_instrument(instrument_content, instruments)
    except ValueError as err:
        response = app.response_class(response=json.dumps({"err": str(err)}),
                                      status=400,
                                      mimetype='application/json')
        return response

    instrument = Instrument(instrument_content['name'],
                            instrument_content['type'],
                            instrument_content['links'])
    data_store.set_instrument(instrument)
    response = app.response_class(response=json.dumps(
        {"instrument": instrument.to_json()}),
                                  status=200,
                                  mimetype='application/json')
    return response
Esempio n. 4
0
    def addModule(self, module):
        """
        Add module to workspace and create a
        new instrument which includes this module. Adds entry in
        self._modulesDict dictionary.

        @type  module: model.module.Module
        @param module: Module to be added.
        """
        instr = Instrument()
        self.instruments.append(instr)
        module.instrument = instr
        instr.modules.append(module)
        self._modulesDict[module.id] = module

        self.setChanged()
        arg = ['add', module]
        self.notifyObservers(arg)
Esempio n. 5
0
    def disconnect(self, connection):
        """
        Delete connection. Test if we need to create a new instrument
        for the disconnected modules.

        @type  connection: model.connection.Connection
        @param connection: Connection which should be deleted.
        """
        fromVar = connection.fromVar
        toVar = connection.toVar
        toVar.module.instrument.connections.remove(connection)
        toVar.connection = None

        # Start breadth first search from toVar.module
        connectedModules = self._getConnectedModules(toVar.module)

        # If fromVar.module is in queue we're done, else insert all
        # modules from connectedModules queue into new instrument
        if not fromVar.module in connectedModules:
            oldInstr = toVar.module.instrument
            newInstr = Instrument()
            self.instruments.append(newInstr)

            oldInstrModules = list(oldInstr.modules)

            for m in oldInstrModules:
                if m in connectedModules:
                    m.instrument = newInstr
                    newInstr.modules.append(m)
                    oldInstr.modules.remove(m)

            for c in list(oldInstr.connections):
                if c.fromVar.module in connectedModules:
                    newInstr.connections.append(c)
                    oldInstr.connections.remove(c)

        self.setChanged()
        arg = ['disconnect', connection]
        self.notifyObservers(arg)
Esempio n. 6
0
def add_mmf_fund(message_array):
    global max_instrument_id
    for messageInfo in message_array:
        # print "good"
        ticker = getattr(messageInfo, 'InstrumentID', '')
        exchange_name = getattr(messageInfo, 'ExchangeID', '')
        if exchange_name == 'SSE':
            exchange_id = 18
        elif exchange_name == 'SZE':
            exchange_id = 19

        dict_key = '%s|%s' % (ticker, exchange_id)
        if dict_key in instrument_db_dict:
            continue

        mmf_fund_db = Instrument()
        max_instrument_id += 1
        mmf_fund_db.id = max_instrument_id
        mmf_fund_db.ticker = ticker
        mmf_fund_db.exchange_id = exchange_id
        mmf_fund_db.name = ''

        mmf_fund_db.fut_val_pt = getattr(messageInfo, 'VolumeMultiple', '')
        mmf_fund_db.multiplier = mmf_fund_db.fut_val_pt
        mmf_fund_db.max_market_order_vol = getattr(messageInfo,
                                                   'MaxMarketOrderVolume', '')
        mmf_fund_db.min_market_order_vol = getattr(messageInfo,
                                                   'MinMarketOrderVolume', '')
        mmf_fund_db.max_limit_order_vol = getattr(messageInfo,
                                                  'MaxLimitOrderVolume', '')
        mmf_fund_db.min_limit_order_vol = getattr(messageInfo,
                                                  'MinLimitOrderVolume', '')

        mmf_fund_db.ticker_exch = ticker
        mmf_fund_db.ticker_exch_real = ticker
        mmf_fund_db.market_status_id = 2
        mmf_fund_db.type_id = 15
        mmf_fund_db.market_sector_id = 4
        mmf_fund_db.round_lot_size = 100
        # price_tick = getattr(messageInfo, 'PriceTick', '')
        mmf_fund_db.tick_size_table = '0:0.001'
        mmf_fund_db.crncy = 'CNY'
        mmf_fund_db.longmarginratio = 0
        mmf_fund_db.shortmarginratio = 999
        mmf_fund_db.longmarginratio_speculation = mmf_fund_db.longmarginratio
        mmf_fund_db.shortmarginratio_speculation = mmf_fund_db.shortmarginratio
        mmf_fund_db.longmarginratio_hedge = mmf_fund_db.longmarginratio
        mmf_fund_db.shortmarginratio_hedge = mmf_fund_db.shortmarginratio
        mmf_fund_db.longmarginratio_arbitrage = mmf_fund_db.longmarginratio
        mmf_fund_db.shortmarginratio_arbitrage = mmf_fund_db.shortmarginratio

        if exchange_name == 'SSE':
            mmf_fund_db.is_settle_instantly = 1
            mmf_fund_db.is_purchase_to_redemption_instantly = 0
            mmf_fund_db.is_buy_to_redpur_instantly = 0
            mmf_fund_db.is_redpur_to_sell_instantly = 0
        elif exchange_name == 'SZE':
            mmf_fund_db.is_settle_instantly = 1
            mmf_fund_db.is_purchase_to_redemption_instantly = 1
            mmf_fund_db.is_buy_to_redpur_instantly = 1
            mmf_fund_db.is_redpur_to_sell_instantly = 1

        instrument_insert_list.append(mmf_fund_db)
        # print instrument_insert_list
        print 'prepare insert etf:', ticker
Esempio n. 7
0
def add_stock(message_array):
    # print 'hello'
    # print message_array
    global max_instrument_id
    for messageInfo in message_array:
        ticker = getattr(messageInfo, 'InstrumentID', '')
        # print ticker
        exchange_name = getattr(messageInfo, 'ExchangeID', '')
        if exchange_name == 'SSE':
            exchange_id = 18
        elif exchange_name == 'SZE':
            exchange_id = 19
        elif exchange_name == 'HGE':
            exchange_id = 13
        dict_key = '%s|%s' % (ticker, exchange_id)
        # # print instrument_db_dict
        if dict_key in instrument_db_dict:
            continue
        # instrument_name = getattr(messageInfo, 'InstrumentName', '')

        # print "bye"
        stock_db = Instrument()
        max_instrument_id += 1
        stock_db.id = max_instrument_id
        stock_db.ticker = ticker
        stock_db.exchange_id = exchange_id
        stock_db.name = ''

        stock_db.ticker_exch = ticker
        stock_db.ticker_exch_real = ticker
        stock_db.market_status_id = 2
        stock_db.market_sector_id = 4
        stock_db.type_id = 4
        stock_db.crncy = 'CNY'
        stock_db.round_lot_size = 100
        stock_db.tick_size_table = '0:0.01'
        stock_db.fut_val_pt = 1
        stock_db.max_market_order_vol = 0
        stock_db.min_market_order_vol = 0
        stock_db.max_limit_order_vol = 1000000
        stock_db.min_limit_order_vol = 100
        stock_db.longmarginratio = 0
        stock_db.shortmarginratio = 999
        stock_db.longmarginratio_speculation = stock_db.longmarginratio
        stock_db.shortmarginratio_speculation = stock_db.shortmarginratio
        stock_db.longmarginratio_hedge = stock_db.longmarginratio
        stock_db.shortmarginratio_hedge = stock_db.shortmarginratio
        stock_db.longmarginratio_arbitrage = stock_db.longmarginratio
        stock_db.shortmarginratio_arbitrage = stock_db.shortmarginratio
        stock_db.multiplier = 1
        stock_db.strike = 0
        stock_db.is_settle_instantly = 0
        stock_db.is_purchase_to_redemption_instantly = 0
        stock_db.is_buy_to_redpur_instantly = 1
        stock_db.is_redpur_to_sell_instantly = 1
        # print 'hi'
        instrument_insert_list.append(stock_db)
        print 'prepare insert stock:', ticker
Esempio n. 8
0
def add_option(message_array):
    global max_instrument_id
    for messageInfo in message_array:
        ticker = getattr(messageInfo, 'InstrumentID', '')
        exchange_name = getattr(messageInfo, 'ExchangeID', '')
        if exchange_name == 'SSE':
            exchange_id = 18
        elif exchange_name == 'SZE':
            exchange_id = 19

        dict_key = '%s|%s' % (ticker, exchange_id)
        if dict_key in instrument_db_dict:
            continue

        option_db = Instrument()
        max_instrument_id += 1
        option_db.id = max_instrument_id
        option_db.ticker = ticker
        option_db.exchange_id = exchange_id
        option_db.fut_val_pt = getattr(messageInfo, 'VolumeMultiple', '')
        option_db.max_market_order_vol = getattr(messageInfo,
                                                 'MaxMarketOrderVolume', '')
        option_db.min_market_order_vol = getattr(messageInfo,
                                                 'MinMarketOrderVolume', '')
        option_db.max_limit_order_vol = getattr(messageInfo,
                                                'MaxLimitOrderVolume', '')
        option_db.min_limit_order_vol = getattr(messageInfo,
                                                'MinLimitOrderVolume', '')
        option_db.strike = getattr(messageInfo, 'ExecPrice', '')

        exchange_inst_id = getattr(messageInfo, 'ExchangeInstID', '')
        undl_tickers = exchange_inst_id[0:6]
        option_db.undl_tickers = undl_tickers
        option_db.track_undl_tickers = undl_tickers
        if 'M' in exchange_inst_id:
            option_db.contract_adjustment = 0
        elif 'A' in exchange_inst_id:
            option_db.contract_adjustment = 1
        elif 'B' in exchange_inst_id:
            option_db.contract_adjustment = 2
        elif 'C' in exchange_inst_id:
            option_db.contract_adjustment = 3

        option_db.create_date = getattr(messageInfo, 'CreateDate', '')
        option_db.expire_date = getattr(messageInfo, 'ExpireDate', '')

        instrument_name = getattr(messageInfo, 'InstrumentName', '').strip()
        instrument_name = instrument_name.replace('购', 'Call').replace('沽', 'Put').replace('月', 'month') \
            .replace('中国平安', undl_tickers).replace('上汽集团', undl_tickers)
        if 'Call' in instrument_name:
            put_call = 1
        else:
            put_call = 0
        option_db.name = instrument_name
        option_db.put_call = put_call

        price_tick = getattr(messageInfo, 'PriceTick', '')
        option_db.tick_size_table = '0:%s' % (float(price_tick), )

        option_db.ticker_exch = ticker
        option_db.ticker_exch_real = ticker
        option_db.market_status_id = 2
        option_db.type_id = 10  # option
        option_db.market_sector_id = 4
        option_db.round_lot_size = 1
        option_db.longmarginratio = 0
        option_db.shortmarginratio = 0.15
        option_db.longmarginratio_speculation = option_db.longmarginratio
        option_db.shortmarginratio_speculation = option_db.shortmarginratio
        option_db.longmarginratio_hedge = option_db.longmarginratio
        option_db.shortmarginratio_hedge = option_db.shortmarginratio
        option_db.longmarginratio_arbitrage = option_db.longmarginratio
        option_db.shortmarginratio_arbitrage = option_db.shortmarginratio
        option_db.multiplier = 10000
        option_db.crncy = 'CNY'
        option_db.effective_since = filter_date_str
        option_db.is_settle_instantly = 1
        option_db.is_purchase_to_redemption_instantly = 0
        option_db.is_buy_to_redpur_instantly = 0
        option_db.is_redpur_to_sell_instantly = 0
        option_db.option_margin_factor1 = 0.15
        option_db.option_margin_factor2 = 0.07
        instrument_insert_list.append(option_db)
        # print instrument_insert_list
        print 'prepare insert option:', ticker
Esempio n. 9
0
def add_structured_fund(message_array):
    global max_instrument_id
    for messageInfo in message_array:
        ticker = getattr(messageInfo, 'InstrumentID', '')

        if ticker not in structured_fund_dict:
            continue
        # print ticker
        exchange_name = getattr(messageInfo, 'ExchangeID', '')

        if exchange_name == 'SSE':
            exchange_id = 18
        elif exchange_name == 'SZE':
            exchange_id = 19
        else:
            print '-------------------', exchange_id
        dict_key = '%s|%s' % (ticker, exchange_id)
        if dict_key in instrument_db_dict:
            continue

        structured_fund_db = Instrument()
        max_instrument_id += 1
        structured_fund_db.id = max_instrument_id
        structured_fund_db.ticker = ticker
        structured_fund_db.exchange_id = exchange_id
        structured_fund_db.name = ''

        undl_ticker_str = ''
        if ticker in undl_ticker_dict:
            undl_ticker_list = undl_ticker_dict[ticker]
            undl_ticker_str = ';'.join(undl_ticker_list)
        structured_fund_db.undl_tickers = undl_ticker_str

        if exchange_id == 18:
            structured_fund_db.is_settle_instantly = 0
            structured_fund_db.is_purchase_to_redemption_instantly = 0
            structured_fund_db.is_buy_to_redpur_instantly = 1
            structured_fund_db.is_redpur_to_sell_instantly = 1
        elif exchange_id == 19:
            structured_fund_db.is_settle_instantly = 0
            structured_fund_db.is_purchase_to_redemption_instantly = 0
            structured_fund_db.is_buy_to_redpur_instantly = 0
            structured_fund_db.is_redpur_to_sell_instantly = 0

        structured_fund_db.ticker_exch = ticker
        structured_fund_db.ticker_exch_real = ticker
        structured_fund_db.market_sector_id = 4
        structured_fund_db.type_id = 16
        structured_fund_db.crncy = 'CNY'
        structured_fund_db.round_lot_size = 100
        structured_fund_db.tick_size_table = '0:0.001'
        structured_fund_db.market_status_id = 2
        structured_fund_db.fut_val_pt = 1
        structured_fund_db.max_limit_order_vol = 1000000
        structured_fund_db.min_limit_order_vol = 100
        structured_fund_db.max_market_order_vol = 0
        structured_fund_db.min_market_order_vol = 0
        structured_fund_db.longmarginratio = 0
        structured_fund_db.shortmarginratio = 999
        structured_fund_db.longmarginratio_speculation = structured_fund_db.longmarginratio
        structured_fund_db.shortmarginratio_speculation = structured_fund_db.shortmarginratio
        structured_fund_db.longmarginratio_hedge = structured_fund_db.longmarginratio
        structured_fund_db.shortmarginratio_hedge = structured_fund_db.shortmarginratio
        structured_fund_db.longmarginratio_arbitrage = structured_fund_db.longmarginratio
        structured_fund_db.shortmarginratio_arbitrage = structured_fund_db.shortmarginratio
        structured_fund_db.multiplier = 1
        instrument_insert_list.append(structured_fund_db)
        # print instrument_insert_list
        print 'prepare insert structured fund:', ticker
Esempio n. 10
0
 def __init__(self, f):
     self.d = self.meta_data_get(f)
     self._instruments = [Instrument(i) for i in self.d]
def pre_add_future(message_array):
    global max_instrument_id
    for message_info in message_array:
        ticker = getattr(message_info, 'InstrumentID', '')
        exchange_name = getattr(message_info, 'ExchangeID', '')
        if 'CFFEX' == exchange_name:
            exchange_id = 25
        elif 'SHFE' == exchange_name:
            exchange_id = 20
        elif 'DCE' == exchange_name:
            exchange_id = 21
        elif 'CZCE' == exchange_name:
            exchange_id = 22
        else:
            continue
        dict_key = '%s|%s' % (ticker, exchange_id)
        if dict_key in future_db_dict:
            continue

        future_db = Instrument()
        max_instrument_id += 1
        future_db.id = max_instrument_id
        future_db.ticker = ticker
        future_db.exchange_id = exchange_id
        future_db.fut_val_pt = getattr(message_info, 'VolumeMultiple', '')
        future_db.max_market_order_vol = getattr(message_info,
                                                 'MaxMarketOrderVolume', '')
        future_db.min_market_order_vol = getattr(message_info,
                                                 'MinMarketOrderVolume', '')
        future_db.max_limit_order_vol = getattr(message_info,
                                                'MaxLimitOrderVolume', '')
        future_db.min_limit_order_vol = getattr(message_info,
                                                'MinLimitOrderVolume', '')
        future_db.longmarginratio = getattr(message_info, 'LongMarginRatio',
                                            '')
        future_db.shortmarginratio = getattr(message_info, 'ShortMarginRatio',
                                             '')
        future_db.longmarginratio_speculation = future_db.longmarginratio
        future_db.shortmarginratio_speculation = future_db.shortmarginratio
        future_db.longmarginratio_hedge = future_db.longmarginratio
        future_db.shortmarginratio_hedge = future_db.shortmarginratio
        future_db.longmarginratio_arbitrage = future_db.longmarginratio
        future_db.shortmarginratio_arbitrage = future_db.shortmarginratio

        future_db.create_date = getattr(message_info, 'CreateDate', '')
        future_db.expire_date = getattr(message_info, 'ExpireDate', '')

        future_db.ticker_exch = ticker
        future_db.ticker_exch_real = ticker
        future_db.type_id = 1  # future
        future_db.market_status_id = 2
        future_db.multiplier = 1
        future_db.crncy = 'CNY'
        future_db.effective_since = getattr(message_info, 'OpenDate', '')

        product_id = getattr(message_info, 'ProductID', '')
        name_message = getattr(message_info, 'InstrumentName', '')
        price_tick = getattr(message_info, 'PriceTick', '')

        if (product_id == 'TF') or (product_id == 'T'):
            future_db.market_sector_id = 5
            future_db.round_lot_size = 1
            future_db.tick_size_table = '0:%f' % (float(price_tick), )
            future_db.undl_tickers = product_id
            future_db.name = ticker
        elif (product_id == 'IC') or (product_id == 'IF') or (product_id
                                                              == 'IH'):
            future_db.market_sector_id = 6
            future_db.round_lot_size = 1
            future_db.tick_size_table = '0:%f' % (float(price_tick), )

            future_db.longmarginratio_hedge = 0.2
            future_db.shortmarginratio_hedge = 0.2

            undl_ticker = ''
            if product_id == 'IF':
                undl_ticker = 'SHSZ300'
            elif product_id == 'IC':
                undl_ticker = 'SH000905'
            elif product_id == 'IH':
                undl_ticker = 'SSE50'
            future_db.undl_tickers = undl_ticker

            future_db.name = name_message.replace('中证', 'cs').replace('上证', 'SSE').replace('股指', 'IDX') \
                .replace('期货', 'Future').replace('国债', 'TF').replace('指数', 'Index').strip()
        else:
            future_db.market_sector_id = 1
            future_db.round_lot_size = 1
            future_db.tick_size_table = '0:%f' % (float(price_tick), )
            if product_id == 'cu':
                expire_date = getattr(message_info, 'ExpireDate', '')
                if now.strftime('%Y-%m') == expire_date[:7]:
                    future_db.round_lot_size = 5
            future_db.undl_tickers = product_id
            future_db.name = ticker

        future_db.is_settle_instantly = 1
        future_db.is_purchase_to_redemption_instantly = 0
        future_db.is_buy_to_redpur_instantly = 0
        future_db.is_redpur_to_sell_instantly = 0

        ticker_type = filter(lambda x: not x.isdigit(), ticker)
        future_db.session = __get_trading_info_list(ticker_type)[-1]
        future_insert_list.append(future_db)
        # platform_logger.info('prepare insert future:', ticker)
        print('prepare insert future: %s') % ticker
def pre_add_option(message_array):
    global max_instrument_id
    for messageInfo in message_array:
        ticker = getattr(messageInfo, 'InstrumentID', '')
        exchange_name = getattr(messageInfo, 'ExchangeID', '')
        if 'CFFEX' == exchange_name:
            exchange_id = 25
        elif 'SHFE' == exchange_name:
            exchange_id = 20
        elif 'DCE' == exchange_name:
            exchange_id = 21
        elif 'CZCE' == exchange_name:
            exchange_id = 22
        else:
            continue

        if ticker in option_db_dict:
            continue

        option_db = Instrument()
        max_instrument_id += 1
        option_db.id = max_instrument_id
        option_db.ticker = ticker
        option_db.exchange_id = exchange_id
        option_db.fut_val_pt = getattr(messageInfo, 'VolumeMultiple', '')
        option_db.max_market_order_vol = getattr(messageInfo,
                                                 'MaxMarketOrderVolume', '')
        option_db.min_market_order_vol = getattr(messageInfo,
                                                 'MinMarketOrderVolume', '')
        option_db.max_limit_order_vol = getattr(messageInfo,
                                                'MaxLimitOrderVolume', '')
        option_db.min_limit_order_vol = getattr(messageInfo,
                                                'MinLimitOrderVolume', '')

        undl_tickers = getattr(messageInfo, 'UnderlyingInstrID', '')
        option_db.undl_tickers = undl_tickers

        option_db.create_date = getattr(messageInfo, 'CreateDate', '')
        option_db.expire_date = getattr(messageInfo, 'ExpireDate', '')

        instrument_name = getattr(messageInfo, 'InstrumentName', '').strip()
        instrument_name = instrument_name.replace('买权', 'Call').replace(
            '卖权', 'Put').replace('白糖', 'SR')

        option_db.name = ticker

        put_call = __get_put_call(instrument_name)
        option_db.put_call = put_call

        if put_call == 0:
            option_db.strike = ticker.replace('-', '').split('P')[-1]
        else:
            option_db.strike = ticker.replace('-', '').split('C')[-1]

        price_tick = getattr(messageInfo, 'PriceTick', '')
        option_db.tick_size_table = '0:%s' % (float(price_tick), )

        option_db.ticker_exch = ticker
        option_db.ticker_exch_real = ticker
        option_db.market_status_id = 2
        option_db.type_id = 10  # option
        option_db.market_sector_id = 1
        option_db.round_lot_size = 1
        option_db.longmarginratio = 0
        option_db.shortmarginratio = 0.15
        option_db.longmarginratio_speculation = option_db.longmarginratio
        option_db.shortmarginratio_speculation = option_db.shortmarginratio
        option_db.longmarginratio_hedge = option_db.longmarginratio
        option_db.shortmarginratio_hedge = option_db.shortmarginratio
        option_db.longmarginratio_arbitrage = option_db.longmarginratio
        option_db.shortmarginratio_arbitrage = option_db.shortmarginratio
        option_db.multiplier = 10
        option_db.crncy = 'CNY'

        option_db.effective_since = filter_date_str
        option_db.is_settle_instantly = 1
        option_db.is_purchase_to_redemption_instantly = 0
        option_db.is_buy_to_redpur_instantly = 0
        option_db.is_redpur_to_sell_instantly = 0
        option_db.option_margin_factor1 = 0.5
        option_db.option_margin_factor2 = 0.5

        ticker_type = filter(lambda x: not x.isdigit(), undl_tickers)
        option_db.session = __get_trading_info_list(ticker_type)[-1]
        option_db.track_undl_tickers = __get_track_undl_tickers(ticker_type)
        option_insert_list.append(option_db)
        print 'prepare insert option:', ticker
if __name__ == "__main__":
    
    
    logger.info('Starting instrument creation ...')
    
    session = Session()
    
    Base.metadata.create_all()
    
    instrument_dao = InstrumentDAO()
    
    try:
        
        ad = instrument_dao.get_by_ticker(session, 'AD')
        if not ad:
            ad = Instrument()
        ad.ticker = 'AD'
        ad.name = 'Australian Dollar'
        ad.asset_class = 'Currencies'
        ad.transactions_fees = .00005
        instrument_dao.save(session, ad)
    
        bo = instrument_dao.get_by_ticker(session, 'BO')
        if not bo:
            bo = Instrument()
        bo.ticker = 'BO'
        bo.name = 'Soybean Oil'
        bo.asset_class = 'Grains'
        bo.transactions_fees = .015
        instrument_dao.save(session, bo)
def add_future(message_array):
    global max_instrument_id
    for message_info in message_array:
        ticker = getattr(message_info, 'InstrumentID', '')
        exchange_name = getattr(message_info, 'ExchangeID', '')
        if exchange_name == 'CFFEX':
            exchange_id = 25
        dict_key = '%s|%s' % (ticker, exchange_id)
        if dict_key in shf_db_dict:
            continue

        future_db = Instrument()
        max_instrument_id += 1
        future_db.id = max_instrument_id
        future_db.ticker = ticker
        future_db.exchange_id = exchange_id

        instrument_name = getattr(message_info, 'InstrumentName', '')
        future_db.name = instrument_name.replace('中证', 'cs').replace('上证', 'SSE') \
            .replace('股指', 'IDX').replace('期货', 'Future').replace('国债', 'TF').strip()

        future_db.fut_val_pt = getattr(message_info, 'VolumeMultiple', '')
        future_db.max_market_order_vol = getattr(message_info,
                                                 'MaxMarketOrderVolume', '')
        future_db.min_market_order_vol = getattr(message_info,
                                                 'MinMarketOrderVolume', '')
        future_db.max_limit_order_vol = getattr(message_info,
                                                'MaxLimitOrderVolume', '')
        future_db.min_limit_order_vol = getattr(message_info,
                                                'MinLimitOrderVolume', '')

        product_id = getattr(message_info, 'ProductID', '')
        undl_ticker = ''
        if product_id == 'IF':
            undl_ticker = 'SHSZ300'
        elif product_id == 'IC':
            undl_ticker = 'SH000905'
        elif product_id == 'IH':
            undl_ticker = 'SSE50'
        elif product_id == 'TF':
            undl_ticker = 'TF'
        elif product_id == 'T':
            undl_ticker = 'T'
        future_db.undl_tickers = undl_ticker

        future_db.create_date = getattr(message_info, 'CreateDate', '')
        future_db.expire_date = getattr(message_info, 'ExpireDate', '')

        price_tick = getattr(message_info, 'PriceTick', '')
        future_db.tick_size_table = '0:%s' % (float(price_tick), )

        future_db.market_status = 2
        future_db.type_Id = 1  # future
        future_db.round_lot_size = 1
        future_db.multiplier = 1

        if (product_id == 'T') or (product_id == 'TF'):
            future_db.longmarginratio = 0.015
            future_db.shortmarginratio = 0.015
            future_db.market_sector_id = 5
        else:
            future_db.longmarginratio = 0.1
            future_db.shortmarginratio = 0.1
            future_db.market_sector_id = 6
        instrument_insert_list.append(future_db)
        print 'prepare insert future:', ticker
def add_option(message_array):
    global max_instrument_id
    for message_info in message_array:
        ticker = getattr(message_info, 'InstrumentID', '')
        exchange_name = getattr(message_info, 'ExchangeID', '')
        if exchange_name == 'CFFEX':
            exchange_id = 25
        dict_key = '%s|%s' % (ticker, exchange_id)
        if dict_key in shf_db_dict:
            continue

        option_db = Instrument()
        max_instrument_id += 1
        option_db.id = max_instrument_id
        option_db.ticker = ticker
        option_db.exchange_id = exchange_id

        option_db.fut_val_pt = getattr(message_info, 'VolumeMultiple', '')
        option_db.max_market_order_vol = getattr(message_info,
                                                 'MaxMarketOrderVolume', '')
        option_db.min_market_order_vol = getattr(message_info,
                                                 'MinMarketOrderVolume', '')
        option_db.max_limit_order_vol = getattr(message_info,
                                                'MaxLimitOrderVolume', '')
        option_db.min_limit_order_vol = getattr(message_info,
                                                'MinLimitOrderVolume', '')

        option_db.strike = getattr(message_info, 'StrikePrice', '')
        option_db.create_date = getattr(message_info, 'CreateDate', '')
        option_db.expire_date = getattr(message_info, 'ExpireDate', '')

        underlying_instr_id = getattr(message_info, 'UnderlyingInstrID', '')
        undl_ticker = underlying_instr_id.replace('HO',
                                                  'IH').replace('IO', 'IF')
        undl_ticker = rebuild_undl_ticker(undl_ticker)
        option_db.undl_tickers = undl_ticker

        instrument_name = getattr(message_info, 'InstrumentName', '')
        instrument_name = instrument_name.replace(u'期权', 'OPTION').replace(
            u'股指', 'IDX').strip()
        option_db.name = instrument_name

        if '-C-' in ticker:
            put_call = 1
        else:
            put_call = 0
        option_db.put_call = put_call

        option_db.market_status_id = 2
        option_db.type_id = 10  # option
        option_db.market_sector_id = 6
        option_db.round_lot_size = 1
        option_db.tick_size_table = '0:0.2'
        option_db.longmarginratio = 1
        option_db.shortmarginratio = 0.15
        option_db.multiplier = 1
        instrument_insert_list.append(option_db)
        print 'prepare insert option:', ticker