Riscrivi completamente questo listato in calce 1 indentandolo correttamente 2 togliendo tutti i messaggi di errore che sono specificati da throw 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 separator = "---------------------------------------------------\r\n";

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

StateManager.prototype.updateLastValues = function(state) {
    this.setValue('BID', 'price', state.bidPrice);
    this.setValue('BID', 'quantity', state.bidQuantity);
    this.setValue('ASK', 'price', state.askPrice);
    this.setValue('ASK', 'quantity', state.askQuantity);
};

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();

// 1. Definizione delle Interfacce e Classi Astratte
function BookStateStrategy() {}
BookStateStrategy.prototype.getBookState = function(book) { throw new Error("Metodo getBookState non implementato."); };
BookStateStrategy.prototype.hasBookStateChanged = function(newState, oldState) { throw new Error("Metodo hasBookStateChanged non implementato."); };

function BookDataAccess() {}
BookDataAccess.prototype.getData = function(book, side, level, type) { throw new Error("Metodo getData non implementato."); };
BookDataAccess.prototype.createSideData = function(book, side, levels) { throw new Error("Metodo createSideData non implementato."); };

function BookComparisonStrategy() {}
BookComparisonStrategy.prototype.compareArrays = function(arr1, arr2, max) { throw new Error("Metodo compareArrays non implementato."); };
BookComparisonStrategy.prototype.isTypeChanged = function(cachedArray, newArray, maxLevel) { throw new Error("Metodo isTypeChanged non implementato."); };
BookComparisonStrategy.prototype.isSideChanged = function(side, newState, cachedState) { throw new Error("Metodo isSideChanged non implementato."); };

// 2. Implementazioni Concrete
function DefaultBookDataAccess() {}
DefaultBookDataAccess.prototype = new BookDataAccess();
DefaultBookDataAccess.prototype.getData = function(book, side, level, type) {
    return book && book[side] && book[side][type + 's'] ? book[side][type + 's'][level] : undefined;
};
DefaultBookDataAccess.prototype.createSideData = function(book, side, levels) {
    return { book: book, P: this.getData(book, side, levels, 'Price'), Q: this.getData(book, side, levels, 'Quantity') };
};

function DefaultBookComparisonStrategy() {}
DefaultBookComparisonStrategy.prototype = new BookComparisonStrategy();
DefaultBookComparisonStrategy.prototype.compareArrays = function(arr1, arr2, max) {
    for (var i = 0; i < max; i++) { if (arr1[i] !== arr2[i]) { return true; } } return false;
};
DefaultBookComparisonStrategy.prototype.isTypeChanged = function(cachedArray, newArray, maxLevel) {
    return this.compareArrays(cachedArray, newArray, maxLevel);
};
DefaultBookComparisonStrategy.prototype.isSideChanged = function(side, newState, cachedState) {
    var maxLevel = CONFIG.LEVELS[side];
    var cachedSide = cachedState[side];
    var newSide = newState[side];
    return this.isTypeChanged(cachedSide.P, newSide.P, maxLevel) || this.isTypeChanged(cachedSide.Q, newSide.Q, maxLevel);
};

function FullCachingBookStateStrategy(dataAccess, comparisonStrategy) {
    this.dataAccess = dataAccess;
    this.comparisonStrategy = comparisonStrategy;
    this.cachedBookState = null;
    this.cachedBookData = { BID: null, ASK: null };
}
FullCachingBookStateStrategy.prototype = new BookStateStrategy();
FullCachingBookStateStrategy.prototype.getBookState = function(book) {
    var newState = {
      BID: this.dataAccess.createSideData(book, 'BID', CONFIG.LEVELS.BID),
      ASK: this.dataAccess.createSideData(book, 'ASK', CONFIG.LEVELS.ASK)
    };
    var stateChanged = this.cachedBookState ? this.comparisonStrategy.hasBookStateChanged(newState, this.cachedBookState) : true;
    if (stateChanged) {
        this.cachedBookState = newState;
        this.cachedBookData = newState;
        stateManager.updateLastValues({
          bidPrice: newState.BID.P[0], bidQuantity: newState.BID.Q[0],
          askPrice: newState.ASK.P[0], askQuantity: newState.ASK.Q[0]
        });
    }
    return this.cachedBookState;
};
FullCachingBookStateStrategy.prototype.hasBookStateChanged = function(newState, oldState) {
    return this.comparisonStrategy.isSideChanged('BID', newState, oldState) || this.comparisonStrategy.isSideChanged('ASK', newState, oldState);
};

function NoCachingBookStateStrategy(dataAccess, comparisonStrategy) {
    this.dataAccess = dataAccess;
    this.comparisonStrategy = comparisonStrategy;
}
NoCachingBookStateStrategy.prototype = new BookStateStrategy();
NoCachingBookStateStrategy.prototype.getBookState = function(book) {
    var newState = {
        BID: this.dataAccess.createSideData(book, 'BID', CONFIG.LEVELS.BID),
        ASK: this.dataAccess.createSideData(book, 'ASK', CONFIG.LEVELS.ASK)
    };
    stateManager.updateLastValues({
        bidPrice: newState.BID.P[0], bidQuantity: newState.BID.Q[0],
        askPrice: newState.ASK.P[0], askQuantity: newState.ASK.Q[0]
    });
    return newState;
};
NoCachingBookStateStrategy.prototype.hasBookStateChanged = function(newState, oldState) {
    return this.comparisonStrategy.isSideChanged('BID', newState, oldState) || this.comparisonStrategy.isSideChanged('ASK', newState, oldState);
};

// 3. Utilizzo delle Implementazioni
var BookStateManager = (function() {
    var dataAccess = new DefaultBookDataAccess();
    var comparisonStrategy = new DefaultBookComparisonStrategy();
    //var stateStrategy = new FullCachingBookStateStrategy(dataAccess, comparisonStrategy); // Scegli la strategia desiderata
    var stateStrategy = new NoCachingBookStateStrategy(dataAccess, comparisonStrategy);

    return {
        getBookState: function(book) { return stateStrategy.getBookState(book); },
        hasBookStateChanged: function(newState, cachedState) { return stateStrategy.hasBookStateChanged(newState, cachedState); },
        compareArrays: function(arr1, arr2, max) { return comparisonStrategy.compareArrays(arr1, arr2, max); },
        isTypeChanged: function(cachedArray, newArray, maxLevel) { return comparisonStrategy.isTypeChanged(cachedArray, newArray, maxLevel); },
        isSideChanged: function(side, newState, cachedState) { return comparisonStrategy.isSideChanged(side, newState, cachedState); },
        getData: function(book, side, level, type) { return dataAccess.getData(book, side, level, type); },
        createSideData: function(book, side, levels) { return dataAccess.createSideData(book, side, levels); }
    };
})();
var BookUtils = {
  getData: function(book, side, level, type) {
      return BookStateManager.getData(book, side, level, type);
  }
};

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

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

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

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

var logger = {
    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,
        'message': "{message}\r\n" + separator
    },
    messageTemplates: {},
    init: function() {
        for (var type in this.messages) {
            this.messageTemplates[type] = this.messages[type];
        }
    },
    formatMessage: function(template, data) {
        return template.replace(/{(\w+)}/g, function(match, key) {
            return typeof data[key] !== 'undefined' ? data[key] : match;
        });
    },
    formatState: function(bookState) {
        var book = bookState ? bookState.book : UserContext.book; 
        var status = UserContext.status;
        return 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 +
            "Numero Operazione: " + status.numOperazione + "\r\n" +
            separator;
    },
    log: function(type, data, includeFormattedState) {
        includeFormattedState = includeFormattedState !== false; 
        var template = this.messageTemplates[type];
        if (!template) return; 
        var message = separator + this.formatMessage(template, data || {});
        if (includeFormattedState && (type === 'Initialization Complete' || type === 'LevelChange')) {
            message += this.formatState();
        }
        Log(message);
    }
};

logger.init();

var Helper = {
    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: [], Quantities: [] };
        if (sideData && typeof sideData.Price === 'function') {
            var prices = [], quantities = []; 
            for (var level = 0; level <= maxLevel; level++) {
                prices[level] = sideData.Price(level);
                quantities[level] = sideData.Quantity(level);
            }
            result.Prices = prices;
            result.Quantities = quantities;
        }
        return result;
    }

    return {
        BID: mapSide(BID, levels.BID),
        ASK: mapSide(ASK, levels.ASK)
    };
}

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];
        if (bidDiff > 0 && bidDiff < minDiff) minDiff = bidDiff;
        if (askDiff > 0 && askDiff < minDiff) minDiff = askDiff;
    }

    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 logFullBook() {
    var book = UserContext.book;
    var logParts = ["BID:\n"];
    var bidLevels = CONFIG.LEVELS.BID + 1;
    for (var level = 0; level < bidLevels; level++) {
        logParts.push("Level " + level + ": Price = " + book.BID.Prices[level] + ", Quantity = " + book.BID.Quantities[level] + "\n");
    }
    logParts.push(separator, "ASK:\n");
    var askLevels = CONFIG.LEVELS.ASK + 1;
    for (var level = 0; level < askLevels; level++) {
        logParts.push("Level " + level + ": Price = " + book.ASK.Prices[level] + ", Quantity = " + book.ASK.Quantities[level] + "\n");
    }
    logger.log('message', { message: logParts.join('') }, false);
}

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

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

function initializeOrder() {
    var originalBook = UserContext.book;
    var sideLevels = UserContext.targetPriceLevels;
    var initialPrice = BookUtils.getData(originalBook, CONFIG.ORDER_SIDE, sideLevels[CONFIG.ORDER_SIDE], 'Price');
    var initialOrder = OrderUtils.processOrModOrder(CONFIG.ORDER_SIDE, stock, initialPrice);
    return initialOrder;
}

function logInitialization(initialOrder) {
    logger.log('Initialization Complete', {
        bidPrice: UserContext.prices.BID.current,
        askPrice: UserContext.prices.ASK.current
    }, true);
    logger.log('Order Action', { action: 'inserito', orderCode: initialOrder.OrderCode });
    logFullBook();
}

function initializeOrderAndLog() {
    var initialOrder = initializeOrder();
    logInitialization(initialOrder);
}

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

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

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

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

	if (targetPrice === oldPrice) return;
    var newOrder = updateOrderAndContext(side, book, userCtx, ps, targetPrice); 
    if (!newOrder) return;
    var direction = Helper.priceDirection(targetPrice, oldPrice);
    var levelDifference = CONFIG.LEVELS[side] + direction;
    logger.log('LevelChange', { lastLevel: levelDifference, priceLevel: targetPriceLevel }, true);
    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) {
        OrderUtils.deleteOrder(currentOrder.OrderCode);
        logger.log('Order Deleted', { orderCode: currentOrder.OrderCode });
        status.run = false;
        return true;
    }
    return false;
}

function onPriceEvent(ctx) {
    var price = Val(ps, "LAST");
    if (ctx.lastPrice === price) return;
    logger.log('PriceChange', {
        previousPrice: ctx.lastPrice,
        currentPrice: price,
        currentTime: Now().ToString("HH:mm:ss.ff")
    });
    ctx.lastPrice = price;
}

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

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

function marketEventFactory(ps, Book, mapBookData, handleEvent, UserContext, SystemContext) {
    return function() {
        if (!UserContext.status.run) return;
        var originalBook = Book(ps);
        var mappedBook = mapBookData(originalBook);
        UserContext.book = mappedBook;
        handleEvent(UserContext, SystemContext.EventType);
    };
}

if (SystemContext.IsFirst) {
    setupTradeContext();
}

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

marketEventInstance();