コード例 #1
0
ファイル: genus.py プロジェクト: edword01/vnpy
    def start(self):
        """"""
        self.register_event()

        # For child app
        child_settings = fix.SessionSettings()
        child_dict = fix.Dictionary()

        child_dict.setString("ConnectionType", "acceptor")
        child_dict.setString("ResetOnLogon", "Y")
        child_dict.setString("FileLogPath", "./genus_log/child")
        child_dict.setString("LogonTimeout", "30")
        child_dict.setString("StartTime", "00:00:00")
        child_dict.setString("EndTime", "00:00:00")
        child_dict.setString("HeartBtInt", "30")
        child_dict.setString("CheckLatency", "N")
        child_dict.setString("UseDataDictionary", "N")
        child_dict.setString("FileStorePath", "./genus_store/child")
        child_dict.setString("ScreenLogShowIncoming", "N")
        child_dict.setString("ScreenLogShowOutgoing", "N")
        child_dict.setString("ScreenLogShowEvents", "N")

        child_dict.setString("SocketAcceptHost", SETTINGS["genus.child_host"])
        child_dict.setString("SocketAcceptPort", SETTINGS["genus.child_port"])

        child_session = fix.SessionID("FIX.4.2",
                                      SETTINGS["genus.child_sender"],
                                      SETTINGS["genus.child_target"])
        child_settings.set(child_session, child_dict)

        child_store_factory = fix.FileStoreFactory(child_settings)
        child_log_factory = fix.ScreenLogFactory(child_settings)

        self.child_app: GenusChildApp = GenusChildApp(self)
        self.child_socket = fix.SocketAcceptor(self.child_app,
                                               child_store_factory,
                                               child_settings,
                                               child_log_factory)
        self.child_socket.start()

        # For parent app
        parent_settings = fix.SessionSettings()
        parent_dict = fix.Dictionary()

        parent_dict.setString("ConnectionType", "initiator")
        parent_dict.setString("ResetOnLogon", "Y")
        parent_dict.setString("FileLogPath", "./genus_log/parent")
        parent_dict.setString("LogonTimeout", "30")
        parent_dict.setString("StartTime", "00:00:00")
        parent_dict.setString("EndTime", "00:00:00")
        parent_dict.setString("HeartBtInt", "30")
        parent_dict.setString("CheckLatency", "N")
        parent_dict.setString("UseDataDictionary", "N")
        parent_dict.setString("FileStorePath", "./genus_store/parent")
        parent_dict.setString("ScreenLogShowIncoming", "N")
        parent_dict.setString("ScreenLogShowOutgoing", "N")
        parent_dict.setString("ScreenLogShowEvents", "N")

        parent_dict.setString("SocketConnectHost",
                              SETTINGS["genus.parent_host"])
        parent_dict.setString("SocketConnectPort",
                              SETTINGS["genus.parent_port"])

        parent_session = fix.SessionID("FIX.4.2",
                                       SETTINGS["genus.parent_sender"],
                                       SETTINGS["genus.parent_target"])
        parent_settings.set(parent_session, parent_dict)

        parent_store_factory = fix.FileStoreFactory(parent_settings)
        parent_log_factory = fix.ScreenLogFactory(parent_settings)

        self.parent_app: GenusParentApp = GenusParentApp(self)
        self.parent_socket = fix.SocketInitiator(self.parent_app,
                                                 parent_store_factory,
                                                 parent_settings,
                                                 parent_log_factory)
        self.parent_socket.start()
コード例 #2
0
        message.getField(side)
        message.getField(ordtype)
        message.getField(text)
        print
        print 'Message received! It reads:'
        print ' = '.join(self.parse(msgtype))
        print self.getFieldName(symbol), '=', symbol.getString()
        print ' = '.join(self.parse(side))
        print ' = '.join(self.parse(ordtype))
        print self.getFieldName(text), '=', text.getString()

    def run(self, acceptor):
        self.acceptor = acceptor
        sleep(60)


fileName = 'exchange_settings.ini'
settings = fix.SessionSettings(fileName)

app = MyApplication()

storeFactory = fix.FileStoreFactory(settings)
logFactory = fix.FileLogFactory(settings)

acceptor = fix.SocketAcceptor(app, storeFactory, settings, logFactory)
acceptor.start()

app.run(acceptor)

acceptor.stop()
コード例 #3
0
ファイル: client.py プロジェクト: minikiller/pytradesimulator
def main(client_config="configs/client1.cfg", debug=None):
    """FIX client

    Sends new order over a FIX session.

    """
    if debug:
        logger.setLevel(logging.DEBUG)
        logger.info(f"Logging set to debug.")
    else:
        logger.setLevel(logging.INFO)
        logger.info(f"Logging set to info.")

    config = configparser.ConfigParser()

    config.read(client_config)

    sender_compid = config["SESSION"]["SenderCompID"]
    target_compid = config["SESSION"]["TargetCompID"]

    settings = fix.SessionSettings(client_config)
    store = fix.FileStoreFactory(settings)
    app = UserClient()

    app.set_logging(logger)

    initiator = fix.SocketInitiator(app, store, settings)

    initiator.start()

    sleep(1)

    while True:
        try:
            sleep(1)
            choice = int(
                input(
                    "Enter choice :- "
                    "\n1. New order"
                    "\n2. Replace order"
                    "\n3. Delete order"
                    "\n4. Test order"
                    "\n5. Test batch order"
                    "\n> "
                )
            )
            if choice == 1:
                print("Enter order :- ")
                symbol = input("Symbol: ")
                price = input("Price: ")
                quantity = input("Quantity: ")
                side = input("Side: ")
                order_type = input("Type: ")

                message = new_order(
                    sender_compid,
                    target_compid,
                    symbol,
                    quantity,
                    price,
                    side,
                    order_type,
                    0
                )

                print("Sending new order...")
                send(message)
            elif choice == 2:
                order_id = input("Enter OrderID: ")
                price = input("Price: ")
                quantity = input("Quantity: ")

                message = replace_order(
                    sender_compid, target_compid, quantity, price, order_id
                )

                print("Sending replace order...")
                send(message)
            elif choice == 3:
                order_id = input("Enter OrderID: ")

                message = delete_order(sender_compid, target_compid, order_id)

                print("Sending delete order...")
                send(message)
            elif choice == 4:
                message = test_order()
                sendMsg(message)
            elif choice == 5:
                send_bat_order()

        except KeyboardInterrupt:
            initiator.stop()
            print("Goodbye... !\n")
コード例 #4
0
from __future__ import print_function
import sys
import time
import quickfix as fix
import at_application

if len(sys.argv) == 0:
    print("usage: at.py -f FILE")
    exit

file = sys.argv[1]

settings = fix.SessionSettings(file)
application = at_application.Application()
factory = fix.FileStoreFactory("store")

acceptor = fix.SocketAcceptor(application, factory, settings)

acceptor.start()
while 1:
    time.sleep(1)
acceptor.stop()
コード例 #5
0
ファイル: initiator.py プロジェクト: kazamage/quickfix
    def toAdmin(self, message, sessionID):
        logger.info(
            f'toAdmin sessionID: [{sessionID.toString()}], message: [{message.toString()}], main: [{threading.main_thread().ident}], current[{threading.current_thread().ident}]'
        )

    def fromAdmin(self, message, sessionID):
        logger.info(
            f'fromAdmin sessionID: [{sessionID.toString()}], message: [{message.toString()}], main: [{threading.main_thread().ident}], current[{threading.current_thread().ident}]'
        )

    def toApp(self, message, sessionID):
        logger.info(
            f'toApp sessionID: [{sessionID.toString()}], message: [{message.toString()}], main: [{threading.main_thread().ident}], current[{threading.current_thread().ident}]'
        )

    def fromApp(self, message, sessionID):
        logger.info(
            f'fromApp sessionID: [{sessionID.toString()}], message: [{message.toString()}], main: [{threading.main_thread().ident}], current[{threading.current_thread().ident}]'
        )


if __name__ == '__main__':
    settings = fix.SessionSettings('./initiator.cfg')
    application = Application()
    storeFactory = fix.FileStoreFactory('./initiator/store')
    logFactory = fix.FileLogFactory('./initiator/log')
    initiator = fix.SocketInitiator(application, storeFactory, settings,
                                    logFactory)
    initiator.start()
    ioloop.IOLoop.current().start()
コード例 #6
0
ファイル: acceptor.py プロジェクト: kazamage/quickfix
        quote.setField(fix.QuoteID(str(uuid4())))
        self.io_loop.add_callback(self.send_to_target, quote)

    def send_to_target(self, message):
        logger.info(
            f'send_to_target  main: [{threading.main_thread().ident}], current[{threading.current_thread().ident}]'
        )
        try:
            logger.info(fix.Session.sendToTarget(message, self.sessionID))
        except:
            logger.exception('unknown error')


def connect():
    pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
    return redis.StrictRedis(connection_pool=pool)


if __name__ == '__main__':
    settings = fix.SessionSettings('./acceptor.cfg')
    application = Application()
    storeFactory = fix.FileStoreFactory('./acceptor/store')
    logFactory = fix.FileLogFactory('./acceptor/log')
    acceptor = fix.SocketAcceptor(application, storeFactory, settings,
                                  logFactory)
    acceptor.start()
    ioloop.IOLoop.current().start()
    # conn = connect()
    # conn.set('f**k', 'moge')
    # print(conn.get('f**k'))
コード例 #7
0
    def getOrderDetails(self, orderID):
        table = texttable.Texttable()
        table.set_cols_width([16, 32])
        for key in self.orders[orderID]:
            table.add_row([key, self.orders[orderID][key]])
        print table.draw()


if len(sys.argv) > 1:
    configFile = sys.argv[1]
else:
    configFile = 'mfs-quickfix.cfg'
settings     = quickfix.SessionSettings(configFile)
application  = FIXServer()
logFactory   = quickfix.ScreenLogFactory(settings)
storeFactory = quickfix.FileStoreFactory(settings)
acceptor     = quickfix.SocketAcceptor(application, storeFactory, settings)
fixServer    = threading.Thread(target=acceptor.start())
fixServer.start()

def help():
    print "Commands are: "
    print "\tbook                       ## Shows current order book"
    print "\tack [orderID]              ## Sends acknowledgement on orderID"
    print "\tcancel [orderID]           ## Sends cancel ack on orderID"
    print "\tfill [orderID] [quantity]  ## Sends a fill on orderID with quantity"
    print "\torder [orderID]            ## Provides details about the order"
    print "\tremove [orderID]           ## Removes the order from the book"
    print "\treplace [orderID]          ## Sends a ReplaceAck on orderID"
    print "\treplacepend [orderID]      ## Sends a ReplacePending message for orderID"
    print "\texit                       ## Shuts down this server"
コード例 #8
0
    print('q:quit')
    print("{}".format("-" * ch_count))
    print('')

#print "getcwd:" + os.getcwd()

logging.config.fileConfig(os.path.join(os.getcwd(), baseconfdir, loggingconf))
logger = logging.getLogger()
cf = ConfigParser.ConfigParser()
cf_path = os.path.join(os.getcwd(), baseconfdir, globalConf)
cf.read(cf_path)
settings = fix.SessionSettings(os.path.join(os.getcwd(), baseconfdir, cf.get("main", "fix_cfg_file")))

application = application.Application()
application.setUserIDPasswd(cf.get("main", "userID"), cf.get("main", "password"))
factory = fix.FileStoreFactory("log")
log = fix.FileLogFactory("log")
# acpt = fix.SocketAcceptorBase(application, factory, settings, log)
# acpt.start()
init = fix.SocketInitiatorBase(application, factory, settings, log)
init.start()
test = Test(cf, cf_path)



ch = 0
while 1:
    tips()
    try:
        ch = raw_input(u"your choice:\n\n")
        if ch == '1':
コード例 #9
0
def main():


    config_file = './client.cfg'
    try:
        sleep_seconds = 3
        #start session
        settings = fix.SessionSettings(config_file)
        application = Application()
        storeFactory = fix.FileStoreFactory(settings)
        logFactory = fix.FileLogFactory(settings)
        initiator = fix.SocketInitiator(application, storeFactory, settings, logFactory)
        initiator.start()
        print(f'INITIATOR STARTED...\nSLEEPING {sleep_seconds} SECONDS...')
        time.sleep(sleep_seconds)
        timeframe = 5
        previous_bar = datetime.datetime.now().minute

        run = True
        auto = False

        if not auto:
            while True:
                if run:
                    application.timeframe = timeframe

                    # print(f'')
                    print(f'RUNNING TIME : {datetime.datetime.now()}')
                    previous_bar = datetime.datetime.now().minute

                    input_ = input('enter 1 for order, 2 for exit, 3 for order status update, 4 for order cancel request test for test request :\n ')
                    print('\n')

                    if input_ == '1':
                        print ("Putin Order")
                        limit_price = np.float(input('Limit Price From Strategy =')) #from strategy output, last_close +- limit
                        application.limit_price = limit_price
                        order_type = str(input('Order Type = ')) #from strategy output
                        if order_type != '1':
                            price = np.float(input('Limit Price='))
                        else:
                            price=None
                        symbol = str(input('Symbol='))
                        currency = str(input('Currency='))
                        side = str(input('Side='))
                        # time_id = str(input('time_id='))
                        quantity = int(input('quantity='))
                        application.quote_request(symbol=symbol, currency=currency, quantity=quantity, side=side, order_type=order_type,
                                      price=price)
        #             #     # initiator.stop()
        #             time.sleep(10)
                    if input_ == '2':
                        sys.exit(0)
        else:
            while True:
                symbol = str(input('Symbol = ' ))
                currency = str(input('Currency = '))
                lot = int(input('Lot = '))
                limit_pips = int(input('Limit Pips = '))


                gc.collect()
                time.sleep(10)
                now = datetime.datetime.now()
                print(now)
                hdf_path = f'd:/Data/minute_data{symbol}.h5'
                # hdf_path = 'minute_data' + symbol + currency + '.h5'
                lock = filelock.FileLock(hdf_path + ".lock")

                executed_period = None
                last_period = None
                decimals = np.where("JPY" in currency, 100, 10000)

                position = 0

                with lock.acquire(poll_intervall=0.005):
                    store = pd.HDFStore(hdf_path,
                                        mode='r')
                    df = store[symbol]
                    # df = store[symbol + currency]

                    store.close()

                ask = df.copy()
                ask.index = ask.index + pd.Timedelta(hours=7)
                del df

                print('Last Period : ' + str(last_period) + " while mext period : " + str(
                    (ask.index[-1] + pd.to_timedelta('1min')).ceil(
                        str(timeframe) + 'T')) + " - ASK INDEX" + str(
                    ask.index[-1]) + '- ASK INDDEX PREVIOUS : ' + str(ask.index[-2]))

                new_period = (ask.index[-1] + pd.to_timedelta('1min')).ceil(str(timeframe) + 'T')
                if (last_period != new_period) & (new_period != executed_period):
                    executed_period = new_period

                    ask = ask.resample(str(timeframe) + 'T', label='right', closed='right', base=0).agg(
                        {'open': 'first', 'low': 'min', 'high': 'max', 'close': 'last'})

                    ask = ask.dropna()
                    print('Strategy run')
                    print("Close Price : " + str(ask.iloc[-1].close))
                    ask_price = ask.iloc[-1].close

                    if np.logical_or(position == 0, position < 0):
                        limit_price = ask_price - limit_pips/decimals
                        position = 1
                    elif position > 0:
                        limit_price = ask_price + limit_pips/decimals
                        position = -1
                    application.limit_price = limit_price
                    application.quote_request(symbol=symbol, currency=currency, quantity=lot, side=position,
                                              order_type=1,
                                              price=None)




    except (fix.ConfigError or fix.RuntimeError) as error:
        print(f'ERROR\n{error}')
コード例 #10
0
def main():

    print('Running on IP :' + str(host))

    #connect with clients
    context = zmq.Context()
    socket = context.socket(zmq.REP)
    socket.bind('tcp://*:%s' % port)
    print('Collecting Orders from clients')

    #set path of config file for FIX connection
    config_file = './client.cfg'
    try:
        sleep_seconds = 3

        #start session
        settings = fix.SessionSettings(config_file)
        application = Application_Order_Handler()
        storeFactory = fix.FileStoreFactory(settings)
        logFactory = fix.FileLogFactory(settings)
        initiator = fix.SocketInitiator(application, storeFactory, settings, logFactory)
        initiator.start()
        print(f'INITIATOR STARTED...\nSLEEPING {sleep_seconds} SECONDS...')
        time.sleep(sleep_seconds)
        timeframe = 5

        run = True
        auto = False

        if not auto:
            while True:
                if run:
                    # application.timeframe = timeframe

                    print(f'RUNNING TIME : {datetime.datetime.now()}')

                    #get order from the client
                    message = socket.recv_json()
                    print(f'RECEIVED ORDER\n{message}')
                    print('###########')
                    socket.send_string("great")
                    message = json.loads(message)
                    action = message['action']
                    symbol = message['symbol']
                    bloomberg_symbol = f'{symbol[:3]}/{symbol[3:]}'
                    if action == 'cancel_quotes':
                        # stop if any current quotes request
                        application.no_trade[bloomberg_symbol] = 1
                        # application.no_trade = 1
                        print(f'{bloomberg_symbol} - ANY PREVIOUS RFQ PASSED!')
                        # time.sleep(5)  # 1 - sleep to catch passing previous quotes
                        continue
                    currency = message['currency']
                    quantity = message['lot']
                    limit_price = message['price']

                    #get last position
                    last_position = application.symbol_positions[bloomberg_symbol]['position']
                    if action == 'buy':
                        if last_position == 0:
                            no_trade = 0
                            # application.symbol_positions[bloomberg_symbol]['position'] = quantity
                            # quantity = quantity
                        elif last_position > 0:
                            no_trade = 1
                            # quantity = quantity
                        else:
                            no_trade = 0
                            # quantity = quantity + abs(last_quantity)
                            # application.symbol_positions[bloomberg_symbol]['position'] = quantity
                            # quantity = 2 * quantity
                    elif action == 'sell':
                        if last_position == 0:
                            no_trade = 0
                            # application.symbol_positions[bloomberg_symbol]['position'] = -quantity
                            # quantity = quantity
                        elif last_position < 0:
                            no_trade = 1
                            # quantity = quantity
                        else:
                            # quantity = quantity + abs(last_quantity)
                            no_trade = 0
                            # application.symbol_positions[bloomberg_symbol]['position'] = -quantity
                            # quantity = 2 * quantity
                    elif (action == 'update_limit' or last_position == 0):
                        # application.no_trade = 1 # set no_trade = 1 to pass previous quotes
                        no_trade = 0 # set no_trade = 0 to request new quotes
                        # time.sleep(2)
                        # print(f'SLEEPING 2s FOR CATCHING PASSING PREVIOUS QUOTES DUE TO LIMIT UPDATE')
                        if last_position > 0:
                            action = 'sell'
                        else:
                            action = 'buy'
                    else:
                        no_trade = 0
                        continue

                    quantity = quantity
                    application.no_trade[bloomberg_symbol] = no_trade
                    # application.no_trade = no_trade
                    application.limit_price[bloomberg_symbol] = limit_price
                    # application.limit_price = limit_price
                    order_type = 1

                    if action == "buy":
                        side = 1
                    elif action == 'sell':
                        side = 2
                    else: #get two way quotes
                        side = 0

                    print ("Putin Order")
                    print(f'Current position of {bloomberg_symbol} is {application.symbol_positions[bloomberg_symbol]["position"]}')
                    application.quote_request(symbol=symbol, currency=currency, quantity=quantity,
                                              side=side, order_type=order_type,dealers_dict=DEALERS_DICT)
        else:
            while True:
                symbol = str(input('Symbol = ' ))
                currency = str(input('Currency = '))
                lot = int(input('Lot = '))
                limit_pips = int(input('Limit Pips = '))


                gc.collect()
                time.sleep(10)
                now = datetime.datetime.now()
                print(now)
                hdf_path = f'C:/Data/minute_data{symbol}.h5'
                # hdf_path = 'minute_data' + symbol + currency + '.h5'
                lock = filelock.FileLock(hdf_path + ".lock")

                executed_period = None
                last_period = None
                decimals = np.where("JPY" in currency, 100, 10000)

                position = 0

                with lock.acquire(poll_intervall=0.005):
                    store = pd.HDFStore(hdf_path,
                                        mode='r')
                    df = store[symbol]
                    # df = store[symbol + currency]

                    store.close()

                ask = df.copy()
                ask.index = ask.index + pd.Timedelta(hours=7)
                del df

                print('Last Period : ' + str(last_period) + " while mext period : " + str(
                    (ask.index[-1] + pd.to_timedelta('1min')).ceil(
                        str(timeframe) + 'T')) + " - ASK INDEX" + str(
                    ask.index[-1]) + '- ASK INDDEX PREVIOUS : ' + str(ask.index[-2]))

                new_period = (ask.index[-1] + pd.to_timedelta('1min')).ceil(str(timeframe) + 'T')
                if (last_period != new_period) & (new_period != executed_period):
                    executed_period = new_period

                    ask = ask.resample(str(timeframe) + 'T', label='right', closed='right', base=0).agg(
                        {'open': 'first', 'low': 'min', 'high': 'max', 'close': 'last'})

                    ask = ask.dropna()
                    print('Strategy run')
                    print("Close Price : " + str(ask.iloc[-1].close))
                    ask_price = ask.iloc[-1].close

                    if np.logical_or(position == 0, position < 0):
                        limit_price = ask_price - limit_pips/decimals
                        position = 1
                    elif position > 0:
                        limit_price = ask_price + limit_pips/decimals
                        position = -1
                    application.limit_price = limit_price
                    application.quote_request(symbol=symbol, currency=currency, quantity=lot, side=position,
                                              order_type=1,
                                              price=None)

    except (fix.ConfigError or fix.RuntimeError) as error:
        print(f'ERROR\n{error}')

    sleep(0.1)
コード例 #11
0
def main(config_file):


    interval_types_dict = {'2':'min'}
    order_type_dict = {'MARKET':1,'LIMIT':2}
    side_dict = {'BUY_OPEN':1,
                 'SELL_OPEN':2,
                 'SELL_CLOSE':2,
    }


    # path = 'C:/Users/ak\Downloads\quickfix_example/'
    # order = pd.read_csv(f'{path}speedlab_orders.csv')
    # timeframe = '1h'
    timeframe = 1
    # symbol = ''.join([a for a in order.iloc[1][0] if a.isalnum()])
    # strategy = ''.join([a for a in order.iloc[1][1] if a.isalnum()])
    # action = ''.join([a for a in order.iloc[1][5] if a.isalnum()])
    # account = ''.join([a for a in order.iloc[1][7] if a.isalnum()])
    # exec_time = ''.join([a for a in order.iloc[1][15] if a.isalnum()])
    # price = None
    # quantity = ''.join([a for a in order.iloc[1][30] if a.isalnum()])
    # tag_55 = symbol[6:9] #Symbol
    # tag_15 = symbol[9:12] #Currency
    # tag_54 = str(np.where('BUY' in action,1,2)) #Side
    # security_type = 'CASH' #tag 167
    # symbol = 'EUR' #tag 55
    # currency = 'AUD' #tag 15
    # quantity = 10000 #tag 38
    # side = 1 #tag 54
    # order_type = 2 #tag 40
    # account = 'U01049' #tag 1
    # if order_type == 1:
    #     price = None
    # else:
    #     price = 1.68 #limit

    try:
        path = "//10.10.1.13/Omni/"
        read_file = 'fix_json.txt'

        #start session
        settings = fix.SessionSettings(config_file)
        application = Application()
        storeFactory = fix.FileStoreFactory(settings)
        logFactory = fix.FileLogFactory(settings)
        initiator = fix.SocketInitiator(application, storeFactory, settings, logFactory)
        initiator.start()
        print(f'INITIATOR STARTED...\nSLEEPING 10 SECONDS...')
        time.sleep(10)
        previous_bar = datetime.datetime.now().minute

        # run = True
        while True:
            # if run:
            if (datetime.datetime.now().minute%int(timeframe) == 0) and (datetime.datetime.now().minute != previous_bar):

                print(f'RUNNING TIME : {datetime.datetime.now()}')
                time.sleep(5) # to fix_json be updated
                previous_bar = datetime.datetime.now().minute
            #     current_time = datetime.datetime.now()
            #     next_bar = current_time + datetime.timedelta(seconds=timeframe*60-10)
                # read data from multicharts
                # get timeframe
                with open(path+read_file,'r') as f:
                    lines = f.readlines()
                    f.close()
                    last_entry = json.loads(lines[-1].rstrip().strip(r"\'"))
                # data_from_mc = pd.read_csv(f'{path+read_file}',error_bad_lines=False)
                timeframe = last_entry['timeframe']
                interval_type = last_entry['intervaltype']

                security_type = 'CASH'  # tag 167
                account = 'U01049'  # tag 1
                price = None
                order_type = order_type_dict[last_entry['limit']['type']] # tag 40
                if order_type == 2:
                    price =  float(last_entry['limit']['Limit price'])
                quantity = int(last_entry['volume']['quantity'])  # tag 38
                symbol = last_entry['symbol'][:3] # tag 55
                currency = last_entry['symbol'][4:] # tag 15
                side = side_dict[last_entry['orderAction']]  # tag 54
                time_id = last_entry['time'].replace(':','')

                #
                # order_type = '1'
                # symbol = 'EUR'
                # currency = 'USD'
                # side = '1'
                # time_id = '1'
                # quantity = 10000

                # if True: #check if last entry is up to date
                if pd.to_datetime(last_entry['time']) + datetime.timedelta(seconds=15) > datetime.datetime.now(): #check if last entry is up to date

                # if quantity != 0:
                #     print("PUTTING ORDER")
                    application.put_order(security_type=security_type, symbol=symbol, currency=currency, quantity=quantity, side=side, order_type=order_type,
                                  account=account,price=price,time_id = time_id)
                else:
                    print('LAST BAR IN FIX JSON IS NOT CURRENT!')
                run = False
                # else:
                #     print(f'QUANTITY = 0 - WAIT TILL NEXT BAR')
                #     time.sleep(100)
                #     continue
            # else:
            #     continue
                # order = pd.read_csv(f'{path}speedlab_orders.csv')
                # symbol_ = ''.join([a for a in order.iloc[1][0] if a.isalnum()]).strip('symbol')
                # strategy_ = ''.join([a for a in order.iloc[1][1] if a.isalnum()])
                # action_ = ''.join([a for a in order.iloc[1][5] if a.isalnum()]).strip('orderAction')
                # account_ = ''.join([a for a in order.iloc[1][7] if a.isalnum()]).strip('accountSegmentatityType')
                # exec_time = ''.join([a for a in order.iloc[1][15] if a.isalnum()])
                # price = None
                # quantity_ = ''.join([a for a in order.iloc[1][30] if a.isalnum()]).strip('volumequantity')
                #
                # security_type = 'CASH'
                # symbol = symbol_[:3]
                # currency = symbol_[3:6]
                # side = np.where('BUY' in action_,1,np.where('SELL' in action_,2,0))
                # order_type = 1 #1:MARKET, 2:LIMIT
                # quantity = quantity_
                # if order_type == 1:
                #     price = None
                # else:
                #     price = 1.89  # limit
                # account = 'U01049'


                # input_ = input('enter 1 for order, 2 for exit, 3 for order status update, 4 for order cancel request test for test request :\n ')
                # print('\n')
                # if input_ == '1':
                #     print ("Putin Order")
                #     application.put_order(security_type=security_type, symbol=symbol, currency=currency, quantity=quantity, side=side, order_type=order_type,
                #                   account=account,price=price)
                #     # initiator.stop()
                # if input_ == '2':
                #     sys.exit(0)
                # if input_ == 'test':
                #     application.test_req()
                # if input_ == '3':
                #     print('requesting order status...')
                #     application.order_status_request()
                # if input_ == '4':
                #     print('order cancel request...')
                #     application.order_cancel_request(account=account,symbol=symbol,side=side,quantity=quantity)
                # if input_ == '5':
                #     print('order cancel replace...')
                #     application.order_cancel_replace(account=account,symbol=symbol,side=side,quantity=quantity,
                #                                      order_type=2,price=1.1)
                #
                # if input_ == 'd':
                #     import pdb
                #     pdb.set_trace()
                # else:
                #     print ("Valid input is 1 for order, 2 for exit")
                #     continue
    # except (fix.ConfigError, fix.RuntimeError), e:
    except (fix.ConfigError or fix.RuntimeError) as error:
        print(f'ERROR\n{error}')