Ho sviluppato questo listato utilizzando JavaScript ES5 e desidero evitare l’uso delle funzionalità moderne di ES6. Vorrei un’analisi dettagliata di questo codice in italiano, focalizzandoti su aspetti di miglioramento ai criteri S.O.D. dell'acronimo S.O.L.I.D., OVVERO I PUNTI 1,2 E 5:
Per ciascuno dei punti 1,2, e 5, sarebbero graditi suggerimenti specifici indicando il PRIMA, cioe' il codice orginale e il DOPO, con le modifiche da te proposte. var CONFIG = {
ORDER_SIDE: 'BID',
SIZE: 1,
MAX_OPERATIONS: 3,
LEVELS: { BID: 6, ASK: 6 },
SECONDS: 5,
TICK: 1,
MONITORING_MODE: 'MONITORA_yourlevel',
SIDES: ['BID', 'ASK'],
TYPES: ['Price', 'Quantity']
};

var logger = (function() {
var separator = "---------------------------------------------------\r\n";
var 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" + separator,
'Operation Number': "Numero Operazione: {numOperazione}\r\n",
'message': "{message}\r\n" + separator
};


function formatMessage(template, data) {
    var cache = this.templateCache || (this.templateCache = {});
    if (!cache[template]) {
        cache[template] = new RegExp(/{(\w+)}/g);
    }
    return template.replace(cache[template], function(match, key) {
        return typeof data[key] !== 'undefined' ? data[key] : match;
    });
}

function formatState(bookState) {
    var book = bookState ? bookState.book : UserContext.book;
    var status = UserContext.status;
    var stateMessage = separator +
        "Bid Price \tBid Quant.\tAsk Price \tAsk Quant.\r\n" +
        separator +
        book.BID.Prices[0] + "\t\t" + book.BID.Quantities[0] +
        "\t\t" + book.ASK.Prices[0] + "\t\t" + book.ASK.Quantities[0] + "\r\n" +
        separator;
    stateMessage += formatMessage(messages['Operation Number'], { numOperazione: status.numOperazione });
    return stateMessage + separator;
}

function log(type, data, includeFormattedState) {
    includeFormattedState = includeFormattedState !== false;
    var template = messages[type];
    if (!template) return;
    var requiresState = { 'Initialization Complete': true, 'LevelChange': true };
    var message = separator + formatMessage(template, data || {});
    if (includeFormattedState && requiresState[type]) {
        message += formatState();
    }
    Log(message);
}

function logFullBook() {
    var book = UserContext.book;
    var levels = { BID: CONFIG.LEVELS.BID + 1, ASK: CONFIG.LEVELS.ASK + 1 };
    var message = "BID:\n";

    function logSide(side, maxLevel) {
        for (var level = 0; level < maxLevel; level++) {
            message += "Level " + level + ": Price = " + book[side].Prices[level] + ", Quantity = " + book[side].Quantities[level] + "\n";
        }
    }
    logSide('BID', levels.BID);
    message += separator + "ASK:\n";
    logSide('ASK', levels.ASK);
    log('message', { message: message }, false);
}

function logLevelChange(lastLevel, priceLevel) {
    log('LevelChange', { lastLevel: lastLevel, priceLevel: priceLevel }, true);
}

function logOrderAction(action, orderCode) {
    log('Order Action', { action: action, orderCode: orderCode });
}

function initializeOrderAndLog() {
    var userCtx = UserContext;
    var configLevels = CONFIG.LEVELS;
    var originalBook = userCtx.book;
    var sideLevels = userCtx.targetPriceLevels;
    var orderSide = CONFIG.ORDER_SIDE;
    var initialPrice = BookUtils.getData(originalBook, orderSide, sideLevels[orderSide], 'Price');
    var initialOrder = OrderUtils.processOrModOrder(orderSide, stock, initialPrice);
    var prices = userCtx.prices;
    log('Initialization Complete', {
        bidPrice: prices.BID.current,
        askPrice: prices.ASK.current
    }, true);
    logOrderAction('inserito', initialOrder.OrderCode);
    logFullBook();
    return initialOrder;
}

function logPriceChange(ctx, price) {
    log('PriceChange', {
        previousPrice: ctx.lastPrice,
        currentPrice: price,
        currentTime: Now().ToString("HH:mm:ss.ff")
    });
    ctx.lastPrice = price;
}

return {
    log: log,
    logFullBook: logFullBook,
    logLevelChange: logLevelChange,
    logOrderAction: logOrderAction,
    initializeOrderAndLog: initializeOrderAndLog,
    logPriceChange: logPriceChange
};
})();

function calculateTick(bidPrices, askPrices) {
var MINIMUM_TICK = 0.005, DECIMAL_PLACES = 3;
if (!bidPrices || !askPrices || bidPrices.length < 2 || askPrices.length < 2) {
logger.log('message', { message: 'Tick calcolato: 0' });
return 0;
}
var minDiff = Infinity;
var len = Math.min(bidPrices.length, askPrices.length);
for (var i = 0; i < len - 1 && minDiff > MINIMUM_TICK; i++) {
var bidDiff = bidPrices[i + 1] - bidPrices[i];
var askDiff = askPrices[i + 1] - askPrices[i];
minDiff = Math.min(minDiff, bidDiff > 0 ? bidDiff : Infinity, askDiff > 0 ? askDiff : Infinity);
}


if (minDiff === Infinity || minDiff < MINIMUM_TICK) {
    logger.log('message', { message: 'Tick calcolato: 0' });
    return 0;
}
var tick = (Math.floor(minDiff / MINIMUM_TICK) * MINIMUM_TICK).toFixed(DECIMAL_PLACES);
logger.log('message', { message: 'Tick calcolato: ' + tick });
return parseFloat(tick);
}

function StateManager() {
this.lastValues = { BID: {}, ASK: {} };
}

StateManager.prototype.updateLastValues = function(state) {
CONFIG.SIDES.forEach(function(side) {
var sideKey = side.toLowerCase();
this.setValue(side, 'price', state[sideKey + 'Price']);
this.setValue(side, 'quantity', state[sideKey + 'Quantity']);
}, this);
};

StateManager.prototype.getValue = function(side, type) {
return this.lastValues[side][type];
};

StateManager.prototype.setValue = function(side, type, value) {
this.lastValues[side][type] = value;
};

var stateManager = new StateManager();

var BookDataManager = (function() {
function getData(book, side, level, type) {
var sideData = book && book[side];
return sideData && sideData[type + 's'] ? sideData[type + 's'][level] : undefined;
}
return {
getData: getData
};
})();

var BookStateManager = (function() {
var cachedBookData = { BID: null, ASK: null };


function createSideData(book, side, levels) {
    if (!cachedBookData[side] || cachedBookData[side].book !== book) {
        var bookData = cachedBookData[side] = { book: book };
        ['Price', 'Quantity'].forEach(function(type) {
            bookData[type.charAt(0)] = BookDataManager.getData(book, side, levels, type);
        });
    }
    return cachedBookData[side];
}
return {
    createSideData: createSideData
};
})();

var BookStateChecker = (function() {
function isArrayChanged(type, side, newState, cachedState, maxLevel) {
var cachedArray = cachedState[side][type];
var newArray = newState[side][type];
for (var i = 0; i < maxLevel; i++) {
if (cachedArray[i] !== newArray[i]) return true;
}
return false;
}


function isSideChanged(side, newState, cachedState) {
    var maxLevel = CONFIG.LEVELS[side];
    return ['P', 'Q'].some(function(type) {
        return isArrayChanged(type, side, newState, cachedState, maxLevel);
    });
}

function hasBookStateChanged(newState, cachedState) {
    return isSideChanged('BID', newState, cachedState) || isSideChanged('ASK', newState, cachedState);
}
return {
    isArrayChanged: isArrayChanged,
    isSideChanged: isSideChanged,
    hasBookStateChanged: hasBookStateChanged
};
})();

var BookStateUpdater = (function() {
var cachedBookState = null;


function getBookState(book) {
    if (cachedBookState && !BookStateChecker.hasBookStateChanged(book, cachedBookState)) {
        return cachedBookState;
    }

    cachedBookState = {
        BID: BookStateManager.createSideData(book, 'BID', CONFIG.LEVELS.BID),
        ASK: BookStateManager.createSideData(book, 'ASK', CONFIG.LEVELS.ASK)
    };
    stateManager.updateLastValues({
        bidPrice: cachedBookState.BID.P[0],
        bidQuantity: cachedBookState.BID.Q[0],
        askPrice: cachedBookState.ASK.P[0],
        askQuantity: cachedBookState.ASK.Q[0]
    });
    return cachedBookState;
}
return {
    getBookState: getBookState
};
})();

var BookUtils = {
getData: BookDataManager.getData
};

var OrderUtils = (function() {
var OrderUpdater = {
updateOrderContext: function(order, side, price) {
if (order == null || order.Price !== price) {
UserContext.order.current = order;
UserContext.prices[side].oldLevel = price;
}
return order;
}
};


var OrderExecutor = {
    execOrder: function(side, stock, price, size) {
        return (side === 'BID') ? OrderManager.Buy(stock, price, size) : OrderManager.Sell(stock, price, size);
    }
};

var OrderProcessor = {
    processOrModOrder: function(side, stock, price) {
        var currentOrder = UserContext.order.current;
        var order = currentOrder
            ? OrderManager.Modify(currentOrder.OrderCode, price)
            : OrderExecutor.execOrder(side, stock, price, CONFIG.SIZE);
        return OrderUpdater.updateOrderContext(order, side, price);
    }
};

var OrderDeleter = {
    deleteOrder: function(orderCode) {
        return OrderManager.Delete(orderCode);
    }
};

return {
    execOrder: OrderExecutor.execOrder,
    updateOrderContext: OrderUpdater.updateOrderContext,
    processOrModOrder: OrderProcessor.processOrModOrder,
    deleteOrder: OrderDeleter.deleteOrder
};
})();

var PriceHelper = {
priceDirection: function(targetPrice, oldPrice) {
return (targetPrice > oldPrice) ? 1 : (targetPrice < oldPrice) ? -1 : 0;
}
};

function mapBookData(originalBook) {
var levels = CONFIG.LEVELS;
var BID = originalBook.Bid;
var ASK = originalBook.Ask;


function mapSide(sideData, maxLevel) {
    var result = { Prices: new Array(maxLevel + 1), Quantities: new Array(maxLevel + 1) };
    if (sideData && typeof sideData.Price === 'function') {
        for (var level = 0; level <= maxLevel; level++) {
            result.Prices[level] = sideData.Price(level);
            result.Quantities[level] = sideData.Quantity(level);
        }
    }
    return result;
}
return {
    BID: mapSide(BID, levels.BID),
    ASK: mapSide(ASK, levels.ASK)
};
}

function getTargetPriceLevel(side) {
return (CONFIG.MONITORING_MODE === 'MONITORA_1Level' ? 0 : CONFIG.LEVELS[side] - 1);
}

function initializeUserContext(book, pricesBID, pricesASK, sideLevels) {
return {
book: book,
order: { current: null },
status: { run: true, secondCount: 0, numOperazione: 0 },
prices: {
BID: { current: pricesBID[0], oldLevel: pricesBID[sideLevels.BID] || pricesBID[0] },
ASK: { current: pricesASK[0], oldLevel: pricesASK[sideLevels.ASK] || pricesASK[0] }
},
targetPriceLevels: sideLevels
};
}

function setupTradeContext() {
var originalBook = mapBookData(Book(ps));
var isMonitorOneLevel = (CONFIG.MONITORING_MODE === 'MONITORA_1Level');
var levels = CONFIG.LEVELS;
var sideLevels = {
BID: isMonitorOneLevel ? 0 : levels.BID - 1,
ASK: isMonitorOneLevel ? 0 : levels.ASK - 1
};
var pricesBID = originalBook.BID.Prices;
var pricesASK = originalBook.ASK.Prices;


UserContext = initializeUserContext(originalBook, pricesBID, pricesASK, sideLevels);
logger.initializeOrderAndLog();
manageCycle();
}

function manageCycle() {
if (++UserContext.status.secondCount >= CONFIG.SECONDS) {
if (!checkOperations()) {
UserContext.book = mapBookData(Book(ps));
updatePrice(CONFIG.ORDER_SIDE, UserContext.book, UserContext.status, UserContext);
}
UserContext.status.secondCount = 0;
}
}

function changesDetected() {
var newBook = Book(ps);
return BookStateChecker.hasBookStateChanged(newBook, UserContext.book);
}

function updateOrderAndContext(side, book, userCtx, stock, price) {
var newOrder = OrderUtils.processOrModOrder(side, stock, price);
if (newOrder) {
userCtx.prices[side] = { current: price, oldLevel: price };
}
return newOrder;
}

function updatePrice(side, book, status, userCtx) {
var targetPriceLevel = userCtx.targetPriceLevels[side];
var targetPrice = book[side].Prices[targetPriceLevel];
var oldPrice = userCtx.prices[side].oldLevel;


if (targetPrice !== oldPrice) {
    var newOrder = updateOrderAndContext(side, book, userCtx, ps, targetPrice);
    if (newOrder) {
        var direction = PriceHelper.priceDirection(targetPrice, oldPrice);
        logger.logLevelChange(CONFIG.LEVELS[side] + direction, targetPriceLevel);
        status.secondCount = 0;
        status.numOperazione++;
    }
}
}

function checkOperations() {
var status = UserContext.status;
if (status.numOperazione >= CONFIG.MAX_OPERATIONS) {
return cancelCurrentOrder(status);
}
return false;
}

function cancelCurrentOrder(status) {
var currentOrder = UserContext.order.current;
if (!currentOrder) return false;
OrderUtils.deleteOrder(currentOrder.OrderCode);
logger.log('Order Deleted', { orderCode: currentOrder.OrderCode });
status.run = false;
return true;
}

var eventHandler = (function() {
function handleEvent(context, type) {
if (type === TSEventType.Price) {
onPriceEvent(context);
} else if (type === TSEventType.Time) {
onTimeEvent(context);
}
}


function onPriceEvent(ctx) {
    var price = Val(ps, "LAST");
    if (ctx.lastPrice === price) return;
    logger.logPriceChange(ctx, price);
}

function onTimeEvent(ctx) {
    ctx.status.secondCount++;
    manageCycle();
}

return {
    handleEvent: handleEvent,
    onPriceEvent: onPriceEvent,
    onTimeEvent: onTimeEvent
};
})();

var handleEvent = eventHandler.handleEvent;

function marketEventFactory(ps, bookProvider, bookMapper, eventHandler, userContext, systemContext) {
return function() {
if (!userContext.status.run) return;
var originalBook = bookProvider(ps);
var mappedBook = bookMapper(originalBook);
userContext.book = mappedBook;
eventHandler(userContext, systemContext.EventType);
};
}

if (SystemContext.IsFirst) {
setupTradeContext(logger, OrderUtils);
}

var marketEventInstance = marketEventFactory(ps, Book, mapBookData, handleEvent, UserContext, SystemContext);

marketEventInstance();