In questo listato var CONFIG = { ORDERSIDE: 'BID', SIZE: 1, MAXOPERATIONS: 3, LEVELS: {…
- User
In questo listato 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'] };
var ChangeType = { ARRAY: 'array', PRICE: 'price' };
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" }; }
codeMessageFormatter.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; } };})();
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 maxIndex = bidPrices.length < askPrices.length ? bidPrices.length : askPrices.length; for (var i = 0; i < maxIndex - 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; }
var StateManager = (function () { function checkStateChange(context, newState, changeType, type) { var hasChanged = hasStateChanged(context, newState, changeType); if (hasChanged) { context = updateContextWithHandlers(context, type, 'update', { data: newState }); } return hasChanged; }
codereturn { checkStateChange: checkStateChange };})();
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 (arr1 == null || arr2 == null) return false; 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) { switch (type) { case ChangeType.ARRAY: return !isArrayEqual(oldState, newState); case ChangeType.PRICE: return oldState !== newState; default: return false; } }
function updateContextWithHandlers(context, type, action, params) { var updateHandlers = { order: handleOrderUpdate, book: handleBookUpdate };
codeif (updateHandlers[type]) { updateHandlers[type](context, action, params); } return context;}
function handleOrderUpdate(context, action, params) { 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; } } }
function handleBookUpdate(context, action, params) { 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]; } }
var BookUtils = (function () {
codefunction 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 updateContextWithHandlers(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 };})();
var OrderStateManager = (function () { function updateOrderContext(side, action, order, price) { return updateContextWithHandlers(UserContext.prices[side], 'order', action, { order: order, price: price }); }
codefunction manageOrderState(action, params) { UserContext.order.current = updateOrderContext(params.side, action, params.order, params.price).currentOrder; return UserContext.order.current; } return { manageOrderState: manageOrderState };})();
var OrderCreationUtils = (function () { function createOrder(stock, price, quantity) { return OrderManager.Buy(stock, price, quantity); }
codefunction modifyOrder(order, newPrice) { return OrderManager.Modify(order.OrderCode, newPrice); } function cancelOrder(orderCode) { return OrderManager.Delete(orderCode); } return { createOrder: createOrder, modifyOrder: modifyOrder, cancelOrder: cancelOrder };})();
var OrderProcessor = (function (orderCreationUtils, orderStateManager, logger) {
codefunction 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());
var PriceHelper = { priceDirection: function (targetPrice, oldPrice) { return (targetPrice > oldPrice) - (targetPrice < oldPrice); } };
function getTargetPriceLevel(side, config) { return config.MONITORING_MODE === 'MONITORA_NLevels' ? config.LEVELS[side] - 1 : 0; }
var OrderContextManager = (function (logger, OrderProcessor, OrderStateManager) {
codefunction 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);
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;
codeif (!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); } }
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] = updateContextWithHandlers(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); }
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); } }; }
var logger = LogManager.getLogger();
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(); imortante e' var StateManager = (function (). Si potrebbe rifattorizzare il codice informato riportato sopra in ES5 per fare in modo che StateManager centralizzi tutto, cioe' price, order e updateState ? Pensavo ad uno schema simile.: var StateManager = { price: { update(side, newPrice) { return this.updateState('price', side, newPrice); } }, order: { update(newOrder) { return this.updateState('order', null, newOrder); } }, updateState(type, side, value) { // Logica centralizzata per l'aggiornamento degli stati } };
- Assistant
Certamente! Rifattorizzare lo
StateManagerper centralizzare la gestione degli stati (prezzi, ordini, ecc.) può migliorare la manutenibilità e la chiarezza del codice. Di seguito, ti fornirò una versione rifattorizzata delloStateManagerin ES5, che segue lo schema suggerito, e mostrerò come adattare le parti rilevanti del tuo codice esistente per integrarlo correttamente.Rifattorizzazione di
StateManagerNuova Implementazione di
StateManagerjavascriptvar StateManager = (function () { // Utilità per confrontare array function isArrayEqual(arr1, arr2) { if (arr1 === arr2) return true; if (arr1 == null || arr2 == null) return false; 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; } // Determina se c'è stato un cambiamento nello stato function hasStateChanged(oldState, newState, type) { switch (type) { case 'array': return !isArrayEqual(oldState, newState); case 'price': return oldState !== newState; default: return false; } } return { price: { update: function (side, newPrice) { return this.updateState('price', side, newPrice); }, updateState: function (type, side, newPrice) { var priceContext = UserContext.prices[side]; var hasChanged = hasStateChanged(priceContext.current, newPrice, type); if (hasChanged) { // Aggiorna lo stato con i nuovi valori priceContext.previous = priceContext.current; priceContext.current = newPrice; // Esegui eventuali handler di aggiornamento priceContext = updateContextWithHandlers(priceContext, type, 'update', { data: newPrice }); } return hasChanged; } }, order: { update: function (newOrder) { return this.updateState('order', null, newOrder); }, updateState: function (type, side, newOrder) { var orderContext = UserContext.order; var hasChanged = hasStateChanged(orderContext.current, newOrder, type); if (hasChanged) { // Aggiorna lo stato con i nuovi valori orderContext.previous = orderContext.current; orderContext.current = newOrder; // Esegui eventuali handler di aggiornamento orderContext = updateContextWithHandlers(orderContext, type, 'update', { data: newOrder }); } return hasChanged; } }, updateState: function (type, side, value) { // Logica centralizzata per l'aggiornamento degli stati // Questo metodo può essere utilizzato per tipi di stato aggiuntivi var context; if (type === 'price') { context = UserContext.prices[side]; } else if (type === 'order') { context = UserContext.order; } if (!context) { return false; } var hasChanged = hasStateChanged(context.current, value, type); if (hasChanged) { context.previous = context.current; context.current = value; context = updateContextWithHandlers(context, type, 'update', { data: value }); } return hasChanged; }, checkAndUpdate: function (type, side, newValue) { if (type === 'price') { return this.price.update(side, newValue); } else if (type === 'order') { return this.order.update(newValue); } return false; } }; })();Spiegazione delle Modifiche
-
Struttura Gerarchica:
StateManagerora possiede sottosezioni perpriceeorder, ognuna con il proprio metodoupdate. Questo permette una gestione più chiara e organizzata dei diversi tipi di stati. -
Metodo
updateState: Un metodo centralizzato che gestisce l'aggiornamento dello stato in base al tipo (priceoorder) e alla parte interessata (sideper i prezzi). -
Metodo
checkAndUpdate: Fornisce un'interfaccia unificata per aggiornare diversi tipi di stati senza dover chiamare specificamenteprice.updateoorder.update. -
Funzionalità di Confronto e Aggiornamento: Utilizza le funzioni
isArrayEqualehasStateChangedper determinare se uno stato è cambiato prima di eseguire l'aggiornamento, evitando aggiornamenti inutili. -
Compatibilità con
updateContextWithHandlers: Mantiene la logica per aggiornare il contesto con gli eventuali handler già esistenti.
Adeguamenti nel Codice Esistente
Dopo aver rifattorizzato lo
StateManager, è necessario aggiornare le parti del codice che lo utilizzano per sfruttare la nuova struttura centralizzata.Aggiornamento di
BookUtilsjavascriptvar 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) { // Utilizza StateManager per aggiornare il prezzo StateManager.checkAndUpdate('price', side, newBookSide.Prices); // Utilizza StateManager per aggiornare le quantità StateManager.checkAndUpdate('quantity', side, newBookSide.Quantities); return context; } function checkAndUpdateSideState(side, newBookSide, config) { var hasPriceChanged = StateManager.checkAndUpdate('price', side, newBookSide.Prices); var hasQuantityChanged = StateManager.checkAndUpdate('quantity', side, newBookSide.Quantities); return hasPriceChanged || hasQuantityChanged; } 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 }; })();Note:
- Aggiornamento dello Stato dei Prezzi: Utilizza
StateManager.checkAndUpdateper aggiornare i prezzi e le quantità per ogni lato (BID e ASK). - Rimozione delle Vecchie Logiche di Stato: Poiché
StateManagerora gestisce gli aggiornamenti, le vecchie logiche specifiche sono state rimosse o adattate.
Aggiornamento di
OrderStateManagerjavascriptvar OrderStateManager = (function () { function updateOrderContext(side, action, order, price) { if (action === 'delete') { // Elimina l'ordine corrente utilizzando StateManager StateManager.checkAndUpdate('order', null, null); } else if (action === 'update') { if (!order || order.Price !== price) { StateManager.checkAndUpdate('order', null, order); } } } function manageOrderState(action, params) { updateOrderContext(params.side, action, params.order, params.price); return UserContext.order.current; } return { manageOrderState: manageOrderState }; })();Note:
- Utilizzo di
StateManagerper gli Ordini: UsaStateManager.checkAndUpdateper aggiornare lo stato degli ordini in modo centralizzato.
Aggiornamento di Altre Parti del Codice
Assicurati che tutte le altre parti del codice che interagiscono con lo stato utilizzino lo
StateManagerrifattorizzato. Ad esempio, nella funzioneupdatePrice:javascriptfunction 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].current; if (!StateManager.price.update(side, targetPrice)) return; var orderPlaced = OrderProcessor.placeOrder(side, ps, targetPrice, book, UserContext.prices, config); handlePriceUpdate(orderPlaced, side, targetPriceLevel, targetPrice, oldPrice, logger); }Note:
- Chiamata a
StateManager.price.update: Aggiorna il prezzo utilizzando il metodo specifico per i prezzi.
Considerazioni Finali
-
Estendibilità: La nuova struttura di
StateManagerfacilita l'aggiunta di nuovi tipi di stato in futuro. Basta aggiungere una nuova sezione all'interno diStateManagere definire i metodi di aggiornamento necessari. -
Manutenibilità: Centralizzando la logica di aggiornamento dello stato, riduci la duplicazione del codice e semplifichi il tracciamento dei cambiamenti dello stato.
-
Coerenza: Assicurati che tutte le parti del codice che modificano lo stato passino attraverso
StateManagerper mantenere la coerenza e sfruttare i controlli di cambiamento integrati.
Se ci sono altre sezioni del codice che necessitano di essere adattate alla nuova struttura di
StateManager, ti consiglio di esaminarle e applicare un approccio simile per garantire una gestione degli stati centralizzata e coerente. -