// INIZIO PARTE NON MODIFICABILE class ESNUOVO7TSClass extends TSBaseClass { var…
- User
// INIZIO PARTE NON MODIFICABILE
class ES_NUOVO_7_TS_Class extends TSBaseClass { var SystemContext; var UserContext; var SafeContext; var stock; var Par1; var Secondi; var ps;
function ES_NUOVO_7_TS_Class() { this.stock = null; this.Par1 = 0; this.Secondi = 0; this.SystemContext = null; this.UserContext = null; this.SafeContext = null; this.ps = null; } function Init(stock, Par1, Secondi, ps, systemContext, safeContext) { this.SystemContext = systemContext; this.UserContext = new Object(); this.SafeContext = safeContext; this.stock = stock; this.Par1 = Number(Par1); this.Secondi = Number(Secondi); this.ps = ps; this.UserContext.Clear = function () { for (var prop in this) { if (prop != 'Clear') { delete this[prop]; } } } this.SafeContext.Clear = function () { for (var prop in this) { if (prop != 'Clear') { delete this[prop]; } } } } function Evaluate() { // FINE PARTE NON MODIFICABILE // INIZIO PARTE MODIFICABILE CHE SI PUO' MODIFICARE FINO AL TERMINE// 1. Configurazione var CONFIG = { ORDER_SIDE: 'BID', SIZE: 1, MAX_OPERATIONS: 3, LEVELS: { BID: 6, ASK: 6 }, SECONDS: 5, TICK: 1, MONITORING_MODE: 'MONITORA_NLevels', SIDES: ['BID', 'ASK'], TYPES: ['Price', 'Quantity'] };
// 2. ChangeType var ChangeType = { ARRAY: 'array', PRICE: 'price' };
// 3. LogManager var LogManager = (function () { function MessageFormatter() { this.separator = "---------------------------------------------------\r\n"; this.messages = { 'Initialization Complete': "Inizializzazione completata:\nBid Price 0: {bidPrice}\nAsk Price 0: {askPrice}\n", 'Order Action': 'Ordine {action}: {orderCode}\n', 'Order Deleted': 'Ordine cancellato: {orderCode}\n', 'LevelChange': "Livello da {lastLevel} all'attuale livello {priceLevel}\n", 'PriceChange': "Prezzo da {previousPrice} all'attuale prezzo {currentPrice}\nOra: {currentTime}\r\n", 'Operation Number': "Numero Operazione: {numOperazione}\r\n", 'message': "{message}\r\n" }; }
MessageFormatter.prototype.format = function (template, data) { return template.replace(/{(\w+)}/g, function (match, key) { return data.hasOwnProperty(key) ? data[key] : match; }); }; function formatBookSide(bookSide, sideName, levels, separator) { var sideMessage = separator + sideName + ":\n"; var pricesLength = bookSide.Prices.length; for (var level = 0; level < levels && pricesLength > level; level++) { sideMessage += "Level " + level + ": Price = " + bookSide.Prices[level] + ", Quantity = " + bookSide.Quantities[level] + "\n"; } return sideMessage; } function formatBookState(book, prices, numOperazione, separator) { var formattedState = separator; formattedState += "Bid Price \tBid Quant.\tAsk Price \tAsk Quant.\r\n"; formattedState += separator; formattedState += getSideData(book, 'BID', 0, 'Prices') + "\t\t" + getSideData(book, 'BID', 0, 'Quantities') + "\t\t"; formattedState += prices.ASK.current + "\t\t" + prices.ASK.lastQuantity + "\r\n"; formattedState += separator; formattedState += "Numero Operazione: " + numOperazione + "\r\n"; formattedState += separator; return formattedState; } function Logger(formatter) { this.formatter = formatter; } Logger.prototype.log = function (type, data, includeFormattedState, book, prices, numOperazione) { if (!this.formatter.messages.hasOwnProperty(type)) return; var message = this.formatter.separator + this.formatter.format(this.formatter.messages[type], data || {}); if (includeFormattedState !== false && (type === 'Initialization Complete' || type === 'LevelChange')) { message += formatBookState(book, prices, numOperazione, this.formatter.separator); } Log(message); }; Logger.prototype.logFullBook = function (book, config) { var message = [ formatBookSide(book.BID, 'BID', config.LEVELS.BID, this.formatter.separator), this.formatter.separator, formatBookSide(book.ASK, 'ASK', config.LEVELS.ASK, this.formatter.separator) ]; Log(message.join('')); }; Logger.prototype.initializeOrderAndLog = function (OrderProcessor, BookUtils, book, prices, config) { var initialPrice = BookUtils.getData(book, config.ORDER_SIDE, getTargetPriceLevel(config.ORDER_SIDE, config), 'Price'); OrderProcessor.placeOrder(config.ORDER_SIDE, stock, initialPrice, book, prices, config); this.log('Initialization Complete', { bidPrice: prices.BID.current, askPrice: prices.ASK.current }, true, book, prices, UserContext.status.numOperazione); this.logFullBook(book, config); }; Logger.prototype.logPriceChange = function (ctx) { this.log('PriceChange', { previousPrice: ctx.lastPrice, currentPrice: ctx.currentPrice, currentTime: Now().ToString("HH:mm:ss.ff") }); ctx.lastPrice = ctx.currentPrice; }; Logger.prototype.logTickCalculation = function (tick) { this.log('message', { message: 'Tick calcolato: ' + tick }, false); }; var messageFormatter = new MessageFormatter(); var logger = new Logger(messageFormatter); return { getLogger: function () { return logger; } };})();
// 4. calculateTick function calculateTick(bidPrices, askPrices, config, logger) { var MINIMUM_TICK = 0.005; if (!bidPrices || !askPrices || bidPrices.length < 2 || askPrices.length < 2) { logger.logTickCalculation('0'); return 0; } var minDiff = Infinity; var len = Math.min(bidPrices.length, askPrices.length); for (var i = 0; i < len - 1; i++) { var bidDiff = Math.abs(bidPrices[i + 1] - bidPrices[i]); var askDiff = Math.abs(askPrices[i + 1] - askPrices[i]); if (bidDiff < minDiff && bidDiff >= MINIMUM_TICK) minDiff = bidDiff; if (askDiff < minDiff && askDiff >= MINIMUM_TICK) minDiff = askDiff; if (minDiff === MINIMUM_TICK) break; } if (minDiff === Infinity) { logger.logTickCalculation('0'); return 0; } var tick = Math.round(minDiff * 1000) / 1000; logger.logTickCalculation(tick.toString()); return tick; }
// 5. StateManager var StateManager = (function () { function checkStateChange(context, newState, changeType, type) { var hasChanged = hasStateChanged(context, newState, changeType); if (hasChanged) { context = updateContext(context, type, 'update', { data: newState }); } return hasChanged; }
return { checkStateChange: checkStateChange };})();
// Funzioni di utility per la gestione del book function getSideData(book, side, level, dataType) { if (typeof book === 'object' && book !== null && side in book && level >= 0) { var sideData = book[side]; if (Object.prototype.toString.call(sideData[dataType]) === '[object Array]' && sideData[dataType].length > level) { return sideData[dataType][level]; } } return undefined; }
function extractPricesQuantities(source, levels, isFunc) { var prices, quantities; if (isFunc) { prices = new Array(levels); quantities = new Array(levels); for (var i = 0; i < levels; i++) { prices[i] = source.Price(i); quantities[i] = source.Quantity(i); } } else { prices = (source.Prices || []).slice(0, levels); quantities = (source.Quantities || []).slice(0, levels); } return { Prices: prices, Quantities: quantities }; }
function isArrayEqual(arr1, arr2) { if (arr1 === arr2) return true; if (Object.prototype.toString.call(arr1) !== '[object Array]' || Object.prototype.toString.call(arr2) !== '[object Array]') { return false; } if (arr1.length !== arr2.length) return false; for (var i = 0, len = arr1.length; i < len; i++) { if (arr1[i] !== arr2[i]) return false; } return true; }
function hasStateChanged(oldState, newState, type) { if (type === ChangeType.ARRAY) { return !isArrayEqual(oldState, newState); } else if (type === ChangeType.PRICE) { return oldState !== newState; } return false; }
function updateState(context, type, action, params) { var updateHandlers = { order: function () { if (action === 'delete') { context.currentOrder = null; context.oldLevel = undefined; } else if (action === 'update') { if (!params.order || params.order.Price !== params.price) { context.currentOrder = params.order; context.oldLevel = params.price; } } }, book: function () { if (action === 'update' && params.data) { context.P = params.data.Prices; context.Q = params.data.Quantities; context.current = params.data.Prices[0]; context.lastQuantity = params.data.Quantities[0]; } } };
if (updateHandlers[type]) { updateHandlers[type](); } return context;}
function updateContext(context, type, action, params) { updateState(context, type, action, params); return context; }
// BookUtils var BookUtils = (function () {
function mapBookData(originalBook, config) { return { BID: extractPricesQuantities(originalBook.Bid, config.LEVELS.BID, true), ASK: extractPricesQuantities(originalBook.Ask, config.LEVELS.ASK, true) }; } function updateBookContext(side, newBookSide, context) { return updateContext(context, 'book', 'update', { data: newBookSide }); } function checkAndUpdateSideState(side, newBookSide, config) { var priceContext = UserContext.prices[side]; var hasPriceChanged = StateManager.checkStateChange(priceContext.P, newBookSide.Prices, ChangeType.ARRAY, 'price'); var hasQuantityChanged = StateManager.checkStateChange(priceContext.Q, newBookSide.Quantities, ChangeType.ARRAY, 'quantity'); if (hasPriceChanged || hasQuantityChanged) { UserContext.prices[side] = updateBookContext(side, newBookSide, priceContext); return true; } return false; } function updateStateIfChanged(book, config) { var newBook = mapBookData(book, config); var changesDetected = false; for (var i = 0; i < config.SIDES.length; i++) { var side = config.SIDES[i]; if (checkAndUpdateSideState(side, newBook[side], config)) { changesDetected = true; } } UserContext.book = newBook; return changesDetected; } return { getData: function (book, side, level, type) { return getSideData(book, side, level, type === 'Price' ? 'Prices' : 'Quantities'); }, getBookState: function () { return UserContext.prices; }, mapBookData: mapBookData, hasChanges: updateStateIfChanged };})();
// OrderStateManager var OrderStateManager = (function () { function updateOrderContext(side, action, order, price) { return updateContext(UserContext.prices[side], 'order', action, { order: order, price: price }); }
function manageOrderState(action, params) { UserContext.order.current = updateOrderContext(params.side, action, params.order, params.price).currentOrder; return UserContext.order.current; } return { manageOrderState: manageOrderState };})();
// OrderCreationUtils var OrderCreationUtils = (function () { function createOrder(stock, price, quantity) { return OrderManager.Buy(stock, price, quantity); }
function modifyOrder(order, newPrice) { return OrderManager.Modify(order.OrderCode, newPrice); } function cancelOrder(orderCode) { return OrderManager.Delete(orderCode); } return { createOrder: createOrder, modifyOrder: modifyOrder, cancelOrder: cancelOrder };})();
// OrderProcessor var OrderProcessor = (function (orderCreationUtils, orderStateManager, logger) {
function handleOrderAction(actionType, params) { var orderResult; var logMessage; var logData; if (actionType === 'create') { orderResult = orderCreationUtils.createOrder(params.stock, params.price, params.size); logMessage = 'Order Action'; logData = { action: 'inserito', orderCode: orderResult.OrderCode }; orderStateManager.manageOrderState('update', { side: params.side, order: orderResult, price: params.price }); } else if (actionType === 'modify') { orderResult = orderCreationUtils.modifyOrder(params.order, params.newPrice); logMessage = 'Order Action'; logData = { action: 'modificato', orderCode: orderResult.OrderCode }; orderStateManager.manageOrderState('update', { side: params.side, order: orderResult, price: params.newPrice }); } else if (actionType === 'cancel') { orderCreationUtils.cancelOrder(params.orderCode); logMessage = 'Order Deleted'; logData = { orderCode: params.orderCode }; orderStateManager.manageOrderState('delete', { side: params.side, order: null, price: undefined }); } logger.log(logMessage, logData, false, params.book, params.prices, UserContext.status.numOperazione); return orderResult; } function placeOrder(side, stock, price, book, prices, config) { var actionType = UserContext.order.current ? 'modify' : 'create'; var params = { side: side, stock: stock, price: price, size: config.SIZE, order: UserContext.order.current, newPrice: price, book: book, prices: prices }; return handleOrderAction(actionType, params); } function removeOrder(orderCode, book, prices, config) { var params = { side: config.ORDER_SIDE, orderCode: orderCode, book: book, prices: prices }; handleOrderAction('cancel', params); return null; } return { placeOrder: placeOrder, removeOrder: removeOrder, handleOrderAction: handleOrderAction };})(OrderCreationUtils, OrderStateManager, LogManager.getLogger());
// PriceHelper var PriceHelper = { priceDirection: function (targetPrice, oldPrice) { return (targetPrice > oldPrice) - (targetPrice < oldPrice); } };
// Funzione per determinare il livello del prezzo target function getTargetPriceLevel(side, config) { return config.MONITORING_MODE === 'MONITORA_NLevels' ? config.LEVELS[side] - 1 : 0; }
// OrderContextManager var OrderContextManager = (function (logger, OrderProcessor, OrderStateManager) {
function executeOrderCancellation(order, status, config) { var params = { side: config.ORDER_SIDE, orderCode: order.OrderCode, book: UserContext.book, prices: UserContext.prices }; OrderProcessor.handleOrderAction('cancel', params); status.run = false; } function cancelCurrentOrder(status, config) { if (!UserContext.order.current) return false; executeOrderCancellation(UserContext.order.current, status, config); return true; } return { cancelCurrentOrder: cancelCurrentOrder };})(LogManager.getLogger(), OrderProcessor, OrderStateManager);
// Funzioni di gestione degli eventi e del ciclo principale
function updatePrice(side, config, OrderProcessor, logger) { var book = UserContext.book; var targetPriceLevel = getTargetPriceLevel(side, config); var targetPrice = getSideData(book, side, targetPriceLevel, 'Prices'); var oldPrice = UserContext.prices[side].oldLevel;
if (!StateManager.checkStateChange(oldPrice, targetPrice, ChangeType.PRICE, 'price')) return; var orderPlaced = OrderProcessor.placeOrder(side, ps, targetPrice, book, UserContext.prices, config); handlePriceUpdate(orderPlaced, side, targetPriceLevel, targetPrice, oldPrice, logger);}
function handlePriceUpdate(orderPlaced, side, targetPriceLevel, targetPrice, oldPrice, logger) { if (orderPlaced) { var priceDir = PriceHelper.priceDirection(targetPrice, oldPrice); logger.log('LevelChange', { lastLevel: targetPriceLevel + priceDir, priceLevel: targetPriceLevel }, true, UserContext.book, UserContext.prices, UserContext.status.numOperazione); UserContext.status.secondCount = 0; UserContext.status.numOperazione++; } }
function isMaxOperationsReached(status, maxOperations) { return status.numOperazione >= maxOperations; }
function manageOrderCancellation(config) { var maxOperationsReached = UserContext.status.numOperazione >= config.MAX_OPERATIONS; if (maxOperationsReached) { OrderContextManager.cancelCurrentOrder(UserContext.status, config); } }
function processCycle(status, manageOrderCancellation, BookUtils, config, OrderProcessor, logger) { status.secondCount++; if (status.secondCount >= config.SECONDS) { status.secondCount = 0; manageOrderCancellation(config); if (status.run) { var updatedBook = BookUtils.mapBookData(Book(ps), config); UserContext.book = updatedBook; updatePrice(config.ORDER_SIDE, config, OrderProcessor, logger); } } }
function onPrice(ctx, price, logger) { if (ctx.lastPrice !== price) { ctx.currentPrice = price; logger.logPriceChange(ctx); } }
function onTime(ctx, manageOrderCancellation, BookUtils, config, OrderProcessor, logger) { processCycle(ctx.status, manageOrderCancellation, BookUtils, config, OrderProcessor, logger); }
function onEvent(context, type, onPrice, onTime, manageOrderCancellation, BookUtils, config, OrderProcessor, logger) { if (type === TSEventType.Price) { onPrice(context, Val(ps, "LAST"), logger); } else if (type === TSEventType.Time) { onTime(context, manageOrderCancellation, BookUtils, config, OrderProcessor, logger); } }
// Inizializzazione function initializeUserContext(book, sideLevels, config) { var prices = {}; for (var i = 0, len = config.SIDES.length; i < len; i++) { var side = config.SIDES[i]; prices[side] = { P: [], Q: [], current: undefined, lastQuantity: undefined }; if (book.hasOwnProperty(side)) { prices[side] = updateContext(prices[side], 'book', 'update', { data: book[side] }); } } return { book: book, order: { current: null }, status: { run: true, secondCount: 0, numOperazione: 0 }, prices: prices, targetPriceLevels: sideLevels }; }
function setupTradeContext(OrderProcessor, BookUtils, calculateTick, logger, manageOrderCancellation, getTargetPriceLevelFunc, ps, config) { var book = Book(ps); var initialBook = BookUtils.mapBookData(book, config); var sideLevels = { BID: getTargetPriceLevelFunc('BID', config), ASK: getTargetPriceLevelFunc('ASK', config) }; UserContext = initializeUserContext(initialBook, sideLevels, config); calculateTick(initialBook.BID.Prices, initialBook.ASK.Prices, config, logger); logger.initializeOrderAndLog(OrderProcessor, BookUtils, UserContext.book, UserContext.prices, config); processCycle(UserContext.status, manageOrderCancellation, BookUtils, config, OrderProcessor, logger); }
// Factory per la gestione degli eventi di mercato function marketEventFactory(ps, bookProvider, bookMapper, eventHandler, userContext, systemContext, onEvent, BookUtils, config, OrderProcessor, logger) { return function () { if (userContext.status.run) { BookUtils.hasChanges(Book(ps), config); onEvent(userContext, systemContext.EventType, onPrice, onTime, manageOrderCancellation, BookUtils, config, OrderProcessor, logger); } }; }
// Inizializzazione del logger var logger = LogManager.getLogger();
// Punto di ingresso if (SystemContext.IsFirst) { setupTradeContext(OrderProcessor, BookUtils, calculateTick, logger, manageOrderCancellation, getTargetPriceLevel, ps, CONFIG); }
// Creazione e invocazione dell'istanza dell'evento di mercato var marketEventInstance = marketEventFactory(ps, Book, BookUtils.mapBookData, onEvent, UserContext, SystemContext, onEvent, BookUtils, CONFIG, OrderProcessor, logger);
marketEventInstance();// 1. Configurazione var CONFIG = { ORDER_SIDE: 'BID', SIZE: 1, MAX_OPERATIONS: 3, LEVELS: { BID: 6, ASK: 6 }, SECONDS: 5, TICK: 1, MONITORING_MODE: 'MONITORA_NLevels', SIDES: ['BID', 'ASK'], TYPES: ['Price', 'Quantity'] };
// 2. ChangeType var ChangeType = { ARRAY: 'array', PRICE: 'price' };
// 3. LogManager var LogManager = (function () { function MessageFormatter() { this.separator = "---------------------------------------------------\r\n"; this.messages = { 'Initialization Complete': "Inizializzazione completata:\nBid Price 0: {bidPrice}\nAsk Price 0: {askPrice}\n", 'Order Action': 'Ordine {action}: {orderCode}\n', 'Order Deleted': 'Ordine cancellato: {orderCode}\n', 'LevelChange': "Livello da {lastLevel} all'attuale livello {priceLevel}\n", 'PriceChange': "Prezzo da {previousPrice} all'attuale prezzo {currentPrice}\nOra: {currentTime}\r\n", 'Operation Number': "Numero Operazione: {numOperazione}\r\n", 'message': "{message}\r\n" }; }
MessageFormatter.prototype.format = function (template, data) { return template.replace(/{(\w+)}/g, function (match, key) { return data.hasOwnProperty(key) ? data[key] : match; }); }; function formatBookSide(bookSide, sideName, levels, separator) { var sideMessage = separator + sideName + ":\n"; var pricesLength = bookSide.Prices.length; for (var level = 0; level < levels && pricesLength > level; level++) { sideMessage += "Level " + level + ": Price = " + bookSide.Prices[level] + ", Quantity = " + bookSide.Quantities[level] + "\n"; } return sideMessage; } function formatBookState(book, prices, numOperazione, separator) { var formattedState = separator; formattedState += "Bid Price \tBid Quant.\tAsk Price \tAsk Quant.\r\n"; formattedState += separator; formattedState += getSideData(book, 'BID', 0, 'Prices') + "\t\t" + getSideData(book, 'BID', 0, 'Quantities') + "\t\t"; formattedState += prices.ASK.current + "\t\t" + prices.ASK.lastQuantity + "\r\n"; formattedState += separator; formattedState += "Numero Operazione: " + numOperazione + "\r\n"; formattedState += separator; return formattedState; } function Logger(formatter) { this.formatter = formatter; } Logger.prototype.log = function (type, data, includeFormattedState, book, prices, numOperazione) { if (!this.formatter.messages.hasOwnProperty(type)) return; var message = this.formatter.separator + this.formatter.format(this.formatter.messages[type], data || {}); if (includeFormattedState !== false && (type === 'Initialization Complete' || type === 'LevelChange')) { message += formatBookState(book, prices, numOperazione, this.formatter.separator); } Log(message); }; Logger.prototype.logFullBook = function (book, config) { var message = [ formatBookSide(book.BID, 'BID', config.LEVELS.BID, this.formatter.separator), this.formatter.separator, formatBookSide(book.ASK, 'ASK', config.LEVELS.ASK, this.formatter.separator) ]; Log(message.join('')); }; Logger.prototype.initializeOrderAndLog = function (OrderProcessor, BookUtils, book, prices, config) { var initialPrice = BookUtils.getData(book, config.ORDER_SIDE, getTargetPriceLevel(config.ORDER_SIDE, config), 'Price'); OrderProcessor.placeOrder(config.ORDER_SIDE, stock, initialPrice, book, prices, config); this.log('Initialization Complete', { bidPrice: prices.BID.current, askPrice: prices.ASK.current }, true, book, prices, UserContext.status.numOperazione); this.logFullBook(book, config); }; Logger.prototype.logPriceChange = function (ctx) { this.log('PriceChange', { previousPrice: ctx.lastPrice, currentPrice: ctx.currentPrice, currentTime: Now().ToString("HH:mm:ss.ff") }); ctx.lastPrice = ctx.currentPrice; }; Logger.prototype.logTickCalculation = function (tick) { this.log('message', { message: 'Tick calcolato: ' + tick }, false); }; var messageFormatter = new MessageFormatter(); var logger = new Logger(messageFormatter); return { getLogger: function () { return logger; } };})();
// 4. calculateTick function calculateTick(bidPrices, askPrices, config, logger) { var MINIMUM_TICK = 0.005; if (!bidPrices || !askPrices || bidPrices.length < 2 || askPrices.length < 2) { logger.logTickCalculation('0'); return 0; } var minDiff = Infinity; var len = Math.min(bidPrices.length, askPrices.length); for (var i = 0; i < len - 1; i++) { var bidDiff = Math.abs(bidPrices[i + 1] - bidPrices[i]); var askDiff = Math.abs(askPrices[i + 1] - askPrices[i]); if (bidDiff < minDiff && bidDiff >= MINIMUM_TICK) minDiff = bidDiff; if (askDiff < minDiff && askDiff >= MINIMUM_TICK) minDiff = askDiff; if (minDiff === MINIMUM_TICK) break; } if (minDiff === Infinity) { logger.logTickCalculation('0'); return 0; } var tick = Math.round(minDiff * 1000) / 1000; logger.logTickCalculation(tick.toString()); return tick; }
// 5. StateManager var StateManager = (function () { function checkStateChange(context, newState, changeType, type) { var hasChanged = hasStateChanged(context, newState, changeType); if (hasChanged) { context = updateContext(context, type, 'update', { data: newState }); } return hasChanged; }
return { checkStateChange: checkStateChange };})();
// Funzioni di utility per la gestione del book function getSideData(book, side, level, dataType) { if (typeof book === 'object' && book !== null && side in book && level >= 0) { var sideData = book[side]; if (Object.prototype.toString.call(sideData[dataType]) === '[object Array]' && sideData[dataType].length > level) { return sideData[dataType][level]; } } return undefined; }
function extractPricesQuantities(source, levels, isFunc) { var prices, quantities; if (isFunc) { prices = new Array(levels); quantities = new Array(levels); for (var i = 0; i < levels; i++) { prices[i] = source.Price(i); quantities[i] = source.Quantity(i); } } else { prices = (source.Prices || []).slice(0, levels); quantities = (source.Quantities || []).slice(0, levels); } return { Prices: prices, Quantities: quantities }; }
function isArrayEqual(arr1, arr2) { if (arr1 === arr2) return true; if (Object.prototype.toString.call(arr1) !== '[object Array]' || Object.prototype.toString.call(arr2) !== '[object Array]') { return false; } if (arr1.length !== arr2.length) return false; for (var i = 0, len = arr1.length; i < len; i++) { if (arr1[i] !== arr2[i]) return false; } return true; }
function hasStateChanged(oldState, newState, type) { if (type === ChangeType.ARRAY) { return !isArrayEqual(oldState, newState); } else if (type === ChangeType.PRICE) { return oldState !== newState; } return false; }
function updateState(context, type, action, params) { var updateHandlers = { order: function () { if (action === 'delete') { context.currentOrder = null; context.oldLevel = undefined; } else if (action === 'update') { if (!params.order || params.order.Price !== params.price) { context.currentOrder = params.order; context.oldLevel = params.price; } } }, book: function () { if (action === 'update' && params.data) { context.P = params.data.Prices; context.Q = params.data.Quantities; context.current = params.data.Prices[0]; context.lastQuantity = params.data.Quantities[0]; } } };
if (updateHandlers[type]) { updateHandlers[type](); } return context;}
function updateContext(context, type, action, params) { updateState(context, type, action, params); return context; }
// BookUtils var BookUtils = (function () {
function mapBookData(originalBook, config) { return { BID: extractPricesQuantities(originalBook.Bid, config.LEVELS.BID, true), ASK: extractPricesQuantities(originalBook.Ask, config.LEVELS.ASK, true) }; } function updateBookContext(side, newBookSide, context) { return updateContext(context, 'book', 'update', { data: newBookSide }); } function checkAndUpdateSideState(side, newBookSide, config) { var priceContext = UserContext.prices[side]; var hasPriceChanged = StateManager.checkStateChange(priceContext.P, newBookSide.Prices, ChangeType.ARRAY, 'price'); var hasQuantityChanged = StateManager.checkStateChange(priceContext.Q, newBookSide.Quantities, ChangeType.ARRAY, 'quantity'); if (hasPriceChanged || hasQuantityChanged) { UserContext.prices[side] = updateBookContext(side, newBookSide, priceContext); return true; } return false; } function updateStateIfChanged(book, config) { var newBook = mapBookData(book, config); var changesDetected = false; for (var i = 0; i < config.SIDES.length; i++) { var side = config.SIDES[i]; if (checkAndUpdateSideState(side, newBook[side], config)) { changesDetected = true; } } UserContext.book = newBook; return changesDetected; } return { getData: function (book, side, level, type) { return getSideData(book, side, level, type === 'Price' ? 'Prices' : 'Quantities'); }, getBookState: function () { return UserContext.prices; }, mapBookData: mapBookData, hasChanges: updateStateIfChanged };})();
// OrderStateManager var OrderStateManager = (function () { function updateOrderContext(side, action, order, price) { return updateContext(UserContext.prices[side], 'order', action, { order: order, price: price }); }
function manageOrderState(action, params) { UserContext.order.current = updateOrderContext(params.side, action, params.order, params.price).currentOrder; return UserContext.order.current; } return { manageOrderState: manageOrderState };})();
// OrderCreationUtils var OrderCreationUtils = (function () { function createOrder(stock, price, quantity) { return OrderManager.Buy(stock, price, quantity); }
function modifyOrder(order, newPrice) { return OrderManager.Modify(order.OrderCode, newPrice); } function cancelOrder(orderCode) { return OrderManager.Delete(orderCode); } return { createOrder: createOrder, modifyOrder: modifyOrder, cancelOrder: cancelOrder };})();
// OrderProcessor var OrderProcessor = (function (orderCreationUtils, orderStateManager, logger) {
function handleOrderAction(actionType, params) { var orderResult; var logMessage; var logData; if (actionType === 'create') { orderResult = orderCreationUtils.createOrder(params.stock, params.price, params.size); logMessage = 'Order Action'; logData = { action: 'inserito', orderCode: orderResult.OrderCode }; orderStateManager.manageOrderState('update', { side: params.side, order: orderResult, price: params.price }); } else if (actionType === 'modify') { orderResult = orderCreationUtils.modifyOrder(params.order, params.newPrice); logMessage = 'Order Action'; logData = { action: 'modificato', orderCode: orderResult.OrderCode }; orderStateManager.manageOrderState('update', { side: params.side, order: orderResult, price: params.newPrice }); } else if (actionType === 'cancel') { orderCreationUtils.cancelOrder(params.orderCode); logMessage = 'Order Deleted'; logData = { orderCode: params.orderCode }; orderStateManager.manageOrderState('delete', { side: params.side, order: null, price: undefined }); } logger.log(logMessage, logData, false, params.book, params.prices, UserContext.status.numOperazione); return orderResult; } function placeOrder(side, stock, price, book, prices, config) { var actionType = UserContext.order.current ? 'modify' : 'create'; var params = { side: side, stock: stock, price: price, size: config.SIZE, order: UserContext.order.current, newPrice: price, book: book, prices: prices }; return handleOrderAction(actionType, params); } function removeOrder(orderCode, book, prices, config) { var params = { side: config.ORDER_SIDE, orderCode: orderCode, book: book, prices: prices }; handleOrderAction('cancel', params); return null; } return { placeOrder: placeOrder, removeOrder: removeOrder, handleOrderAction: handleOrderAction };})(OrderCreationUtils, OrderStateManager, LogManager.getLogger());
// PriceHelper var PriceHelper = { priceDirection: function (targetPrice, oldPrice) { return (targetPrice > oldPrice) - (targetPrice < oldPrice); } };
// Funzione per determinare il livello del prezzo target function getTargetPriceLevel(side, config) { return config.MONITORING_MODE === 'MONITORA_NLevels' ? config.LEVELS[side] - 1 : 0; }
// OrderContextManager var OrderContextManager = (function (logger, OrderProcessor, OrderStateManager) {
function executeOrderCancellation(order, status, config) { var params = { side: config.ORDER_SIDE, orderCode: order.OrderCode, book: UserContext.book, prices: UserContext.prices }; OrderProcessor.handleOrderAction('cancel', params); status.run = false; } function cancelCurrentOrder(status, config) { if (!UserContext.order.current) return false; executeOrderCancellation(UserContext.order.current, status, config); return true; } return { cancelCurrentOrder: cancelCurrentOrder };})(LogManager.getLogger(), OrderProcessor, OrderStateManager);
// Funzioni di gestione degli eventi e del ciclo principale
function updatePrice(side, config, OrderProcessor, logger) { var book = UserContext.book; var targetPriceLevel = getTargetPriceLevel(side, config); var targetPrice = getSideData(book, side, targetPriceLevel, 'Prices'); var oldPrice = UserContext.prices[side].oldLevel;
if (!StateManager.checkStateChange(oldPrice, targetPrice, ChangeType.PRICE, 'price')) return; var orderPlaced = OrderProcessor.placeOrder(side, ps, targetPrice, book, UserContext.prices, config); handlePriceUpdate(orderPlaced, side, targetPriceLevel, targetPrice, oldPrice, logger);}
function handlePriceUpdate(orderPlaced, side, targetPriceLevel, targetPrice, oldPrice, logger) { if (orderPlaced) { var priceDir = PriceHelper.priceDirection(targetPrice, oldPrice); logger.log('LevelChange', { lastLevel: targetPriceLevel + priceDir, priceLevel: targetPriceLevel }, true, UserContext.book, UserContext.prices, UserContext.status.numOperazione); UserContext.status.secondCount = 0; UserContext.status.numOperazione++; } }
function isMaxOperationsReached(status, maxOperations) { return status.numOperazione >= maxOperations; }
function manageOrderCancellation(config) { var maxOperationsReached = UserContext.status.numOperazione >= config.MAX_OPERATIONS; if (maxOperationsReached) { OrderContextManager.cancelCurrentOrder(UserContext.status, config); } }
function processCycle(status, manageOrderCancellation, BookUtils, config, OrderProcessor, logger) { status.secondCount++; if (status.secondCount >= config.SECONDS) { status.secondCount = 0; manageOrderCancellation(config); if (status.run) { var updatedBook = BookUtils.mapBookData(Book(ps), config); UserContext.book = updatedBook; updatePrice(config.ORDER_SIDE, config, OrderProcessor, logger); } } }
function onPrice(ctx, price, logger) { if (ctx.lastPrice !== price) { ctx.currentPrice = price; logger.logPriceChange(ctx); } }
function onTime(ctx, manageOrderCancellation, BookUtils, config, OrderProcessor, logger) { processCycle(ctx.status, manageOrderCancellation, BookUtils, config, OrderProcessor, logger); }
function onEvent(context, type, onPrice, onTime, manageOrderCancellation, BookUtils, config, OrderProcessor, logger) { if (type === TSEventType.Price) { onPrice(context, Val(ps, "LAST"), logger); } else if (type === TSEventType.Time) { onTime(context, manageOrderCancellation, BookUtils, config, OrderProcessor, logger); } }
// Inizializzazione function initializeUserContext(book, sideLevels, config) { var prices = {}; for (var i = 0, len = config.SIDES.length; i < len; i++) { var side = config.SIDES[i]; prices[side] = { P: [], Q: [], current: undefined, lastQuantity: undefined }; if (book.hasOwnProperty(side)) { prices[side] = updateContext(prices[side], 'book', 'update', { data: book[side] }); } } return { book: book, order: { current: null }, status: { run: true, secondCount: 0, numOperazione: 0 }, prices: prices, targetPriceLevels: sideLevels }; }
function setupTradeContext(OrderProcessor, BookUtils, calculateTick, logger, manageOrderCancellation, getTargetPriceLevelFunc, ps, config) { var book = Book(ps); var initialBook = BookUtils.mapBookData(book, config); var sideLevels = { BID: getTargetPriceLevelFunc('BID', config), ASK: getTargetPriceLevelFunc('ASK', config) }; UserContext = initializeUserContext(initialBook, sideLevels, config); calculateTick(initialBook.BID.Prices, initialBook.ASK.Prices, config, logger); logger.initializeOrderAndLog(OrderProcessor, BookUtils, UserContext.book, UserContext.prices, config); processCycle(UserContext.status, manageOrderCancellation, BookUtils, config, OrderProcessor, logger); }
// Factory per la gestione degli eventi di mercato function marketEventFactory(ps, bookProvider, bookMapper, eventHandler, userContext, systemContext, onEvent, BookUtils, config, OrderProcessor, logger) { return function () { if (userContext.status.run) { BookUtils.hasChanges(Book(ps), config); onEvent(userContext, systemContext.EventType, onPrice, onTime, manageOrderCancellation, BookUtils, config, OrderProcessor, logger); } }; }
// Inizializzazione del logger var logger = LogManager.getLogger();
// Punto di ingresso if (SystemContext.IsFirst) { setupTradeContext(OrderProcessor, BookUtils, calculateTick, logger, manageOrderCancellation, getTargetPriceLevel, ps, CONFIG); }
// Creazione e invocazione dell'istanza dell'evento di mercato var marketEventInstance = marketEventFactory(ps, Book, BookUtils.mapBookData, onEvent, UserContext, SystemContext, onEvent, BookUtils, CONFIG, OrderProcessor, logger);
marketEventInstance();
- Assistant
Certainly! Let's delve into the provided code to understand its structure, functionality, and identify areas for improvement. The code appears to implement a trading system with components for managing orders, logging, state management, and handling market events. Below is a comprehensive analysis:
Overview
The code defines a class
ES_NUOVO_7_TS_Classthat extendsTSBaseClass. The main functionality is encapsulated within theEvaluatemethod, which consists of both non-modifiable and modifiable sections. The modifiable part includes configurations, change types, logging mechanisms, tick calculations, state management, order processing, price handling, and event management.Detailed Breakdown
1. Class Definition and Initialization
class ES_NUOVO_7_TS_Class extends TSBaseClass { var SystemContext; var UserContext; var SafeContext; var stock; var Par1; var Secondi; var ps; function ES_NUOVO_7_TS_Class() { // Initialization of variables } function Init(stock, Par1, Secondi, ps, systemContext, safeContext) { // Initialization logic } function Evaluate() { // Main evaluation logic // MODIFICABILE part starts here // ... } }- Purpose: Initializes the trading system with necessary contexts and parameters.
- Variables:
SystemContext,UserContext,SafeContext: Different contexts for system, user, and safe operations.stock,Par1,Secondi,ps: Parameters likely related to trading specifics.
2. Configurations
var CONFIG = { ORDER_SIDE: 'BID', SIZE: 1, MAX_OPERATIONS: 3, LEVELS: { BID: 6, ASK: 6 }, SECONDS: 5, TICK: 1, MONITORING_MODE: 'MONITORA_NLevels', SIDES: ['BID', 'ASK'], TYPES: ['Price', 'Quantity'] };- Description: Defines various configurations for order placement, monitoring levels, time intervals, etc.
- Key Parameters:
ORDER_SIDE: Side of the order (BIDorASK).LEVELS: Number of price levels to monitor for both bids and asks.SECONDS: Time interval for processing cycles.MAX_OPERATIONS: Maximum number of operations before taking specific actions.
3. Change Types
var ChangeType = { ARRAY: 'array', PRICE: 'price' };- Purpose: Enumerates the types of changes that can occur, facilitating state change detection.
4. LogManager
var LogManager = (function () { // MessageFormatter and Logger definitions // Logging methods for various events return { getLogger: function () { return logger; } }; })();- Components:
- MessageFormatter: Formats log messages based on templates.
- Logger: Provides methods to log different types of events such as initialization, order actions, price changes, etc.
- Usage: Centralized logging mechanism to track system activities and states.
5. Tick Calculation
function calculateTick(bidPrices, askPrices, config, logger) { // Logic to calculate the minimum tick difference between bid and ask prices }- Functionality: Determines the smallest price movement (tick) based on bid and ask price differences.
- Considerations: Ensures the tick meets a minimum threshold (
MINIMUM_TICK) to avoid negligible price changes.
6. StateManager
var StateManager = (function () { function checkStateChange(context, newState, changeType, type) { // Checks and updates state if changes are detected } return { checkStateChange: checkStateChange }; })();- Purpose: Monitors and manages state changes in the system, ensuring that the system responds appropriately to updates in market data or order states.
7. Utility Functions
- getSideData: Retrieves specific data (price or quantity) for a given side (
BIDorASK) and level. - extractPricesQuantities: Extracts price and quantity data from the book.
- isArrayEqual: Compares two arrays for equality.
- hasStateChanged: Determines if a state has changed based on the type of change.
- updateState & updateContext: Updates the context based on detected changes.
8. BookUtils
var BookUtils = (function () { function mapBookData(originalBook, config) { // Maps the original book data based on configuration } function updateBookContext(side, newBookSide, context) { // Updates the book context for a specific side } function checkAndUpdateSideState(side, newBookSide, config) { // Checks and updates the state for a specific side } function updateStateIfChanged(book, config) { // Updates the overall book state if changes are detected } return { getData: function (book, side, level, type) { /* ... */ }, getBookState: function () { /* ... */ }, mapBookData: mapBookData, hasChanges: updateStateIfChanged }; })();- Functionality: Handles mapping and updating of the order book data, ensuring that the system maintains an accurate view of the current market state.
9. Order Management
- OrderStateManager: Manages the current order's state, handling updates and deletions.
- OrderCreationUtils: Provides utilities to create, modify, and cancel orders using the
OrderManager. - OrderProcessor: Processes order actions (create, modify, cancel) and logs these actions using the
Logger.
10. Price Handling
var PriceHelper = { priceDirection: function (targetPrice, oldPrice) { return (targetPrice > oldPrice) - (targetPrice < oldPrice); } };- Purpose: Determines the direction of the price movement (increase, decrease, or no change).
11. Event Management
- onPrice & onTime: Handlers for price and time events, respectively.
- onEvent: Determines which event handler to invoke based on the event type.
- processCycle: Manages the main processing loop, handling order placements and cancellations based on configurations and elapsed time.
12. Initialization and Market Event Factory
function initializeUserContext(book, sideLevels, config) { /* ... */ } function setupTradeContext(OrderProcessor, BookUtils, calculateTick, logger, manageOrderCancellation, getTargetPriceLevelFunc, ps, config) { /* ... */ } function marketEventFactory(ps, bookProvider, bookMapper, eventHandler, userContext, systemContext, onEvent, BookUtils, config, OrderProcessor, logger) { /* ... */ }- initializeUserContext: Sets up the initial user context with book data and order statuses.
- setupTradeContext: Initializes the trading context, including mapping the book data and calculating initial ticks.
- marketEventFactory: Creates a factory function to handle market events based on the current state and configurations.
13. Main Execution Flow
if (SystemContext.IsFirst) { setupTradeContext(OrderProcessor, BookUtils, calculateTick, logger, manageOrderCancellation, getTargetPriceLevel, ps, CONFIG); } var marketEventInstance = marketEventFactory(ps, Book, BookUtils.mapBookData, onEvent, UserContext, SystemContext, onEvent, BookUtils, CONFIG, OrderProcessor, logger); marketEventInstance();- Initialization: Checks if it's the first run and sets up the trading context accordingly.
- Market Event Invocation: Creates and invokes an instance to handle market events.
Identified Issues and Areas for Improvement
-
Code Duplication:
- Observation: After the initial
marketEventInstance()call, the code repeats the definitions ofCONFIG,ChangeType,LogManager, etc. - Impact: Redundancy can lead to maintenance challenges and potential inconsistencies.
- Recommendation: Remove duplicated code to ensure a single source of truth for configurations and utility definitions.
- Observation: After the initial
-
Variable Declarations:
- Observation: The use of
varfor variable declarations is prevalent. - Impact: Using
varcan lead to scope-related issues due to hoisting. - Recommendation: Use
letandconstfor block-scoped and immutable variables, respectively, enhancing code clarity and preventing accidental reassignments.
- Observation: The use of
-
Encapsulation and Module Structure:
- Observation: While utilities are encapsulated within Immediately Invoked Function Expressions (IIFEs), there’s a mix of global and local variables.
- Recommendation: Further encapsulate modules to limit the exposure of internal variables and functions. Consider using ES6 modules if the environment supports them.
-
Error Handling:
- Observation: The code lacks comprehensive error handling mechanisms.
- Impact: Potential runtime errors might not be gracefully managed, leading to system instability.
- Recommendation: Implement try-catch blocks around critical sections, especially those interacting with external systems (e.g.,
OrderManageroperations).
-
Logging Enhancements:
- Observation: The
LogManagerhandles various logging scenarios, but the verbosity and logging levels aren’t configurable. - Recommendation: Introduce logging levels (e.g., INFO, DEBUG, ERROR) to control the granularity of logs, aiding in debugging and monitoring.
- Observation: The
-
Magic Numbers and Strings:
- Observation: Some values like
MINIMUM_TICK = 0.005are hard-coded. - Recommendation: Parameterize such values or include them in the configuration object for flexibility.
- Observation: Some values like
-
Performance Considerations:
- Observation: Functions like
isArrayEqualperform deep comparisons which might be inefficient for large datasets. - Recommendation: Optimize these functions or leverage existing libraries optimized for such operations.
- Observation: Functions like
-
Documentation and Comments:
- Observation: While there are comments, especially in Italian, some complex functions lack detailed explanations.
- Recommendation: Enhance documentation with function descriptions, parameter explanations, and expected outcomes. Consider providing translations for non-English comments to make the codebase more accessible.
-
Consistency in Coding Style:
- Observation: There’s an inconsistency in function declarations, use of semicolons, and code formatting.
- Recommendation: Adopt a consistent coding style, possibly enforced by linters like ESLint, to enhance readability and maintainability.
-
Potential Logical Errors:
- Observation: In
handleOrderUpdate, when checking if the price has changed, it determines ifUserContext.order.currentexists to decide betweenmodifyorcreate. However, there might be edge cases where an order exists but the price hasn't actually changed. - Recommendation: Refine the logic to ensure that orders are only modified when there’s a genuine change in price or intended action.
- Observation: In
Refactored Code Snippet
Below is a refactored snippet addressing some of the identified issues. Due to the extensive nature of the original code, only key areas are showcased.
class ES_NUOVO_7_TS_Class extends TSBaseClass { constructor() { super(); this.SystemContext = null; this.UserContext = null; this.SafeContext = null; this.stock = null; this.Par1 = 0; this.Secondi = 0; this.ps = null; } Init(stock, Par1, Secondi, ps, systemContext, safeContext) { this.SystemContext = systemContext; this.UserContext = { Clear: function () { /* ... */ }, // Other initializations }; this.SafeContext = safeContext; this.stock = stock; this.Par1 = Number(Par1); this.Secondi = Number(Secondi); this.ps = ps; } Evaluate() { // MODIFICABILE part // Configuration const CONFIG = { /* ... */ }; // ChangeType const ChangeType = { /* ... */ }; // LogManager const LogManager = (() => { // MessageFormatter and Logger definitions using ES6 classes return { getLogger: () => logger }; })(); // Further initializations and function definitions // ... // Initialization at first run if (this.SystemContext.IsFirst) { setupTradeContext(/* parameters */); } // Create and invoke market event const marketEventInstance = marketEventFactory(/* parameters */); marketEventInstance(); } }Key Changes:
- Class Constructor: Utilizes
constructorfor proper class initialization. - Use of
constandlet: Replacesvarwithconstandletfor better scoping. - Encapsulation: Further encapsulates modules and utilities within their respective scopes.
- Avoiding Duplication: Ensures configurations and utilities are defined once and reused.
Conclusion
The provided code is a comprehensive implementation of a trading system with several interdependent components. While it covers essential functionalities such as order management, logging, and state handling, there are areas where enhancements can be made to improve performance, maintainability, and scalability.
Recommendations for Moving Forward:
- Code Cleanup: Remove duplicated sections and ensure single definitions for configurations and utilities.
- Modern JavaScript Practices: Adopt ES6+ features for cleaner and more efficient code.
- Testing: Implement unit tests for critical functions to ensure reliability.
- Documentation: Enhance code comments and provide detailed documentation for better understanding and maintenance.
- Error Handling: Incorporate robust error handling to manage unexpected scenarios gracefully.
- Performance Optimization: Review and optimize functions that may hinder performance, especially those handling large datasets or frequent operations.
By addressing these areas, the trading system can achieve higher reliability, easier maintenance, and better performance in live trading environments.