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_yourlevel', SIDES: ['BID', 'ASK'], TYPES: ['Price', 'Quantity'] };
var separator = "---------------------------------------------------\r\n";
var StateManager = (function() { var lastValues = { BID: { price: null, quantity: null }, ASK: { price: null, quantity: null } };
return { updateLastValues: function(state) { lastValues.BID.price = state.bidPrice; lastValues.BID.quantity = state.bidQuantity; lastValues.ASK.price = state.askPrice; lastValues.ASK.quantity = state.askQuantity; }, getValue: function(side, type) { return lastValues[side][type]; }, setValue: function(side, type, value) { lastValues[side][type] = value; } };})();
var BookStateManager = (function() { var cachedBookState = null;
return { getBookState: function(book) { var newState = this.createBookState(book); var stateChanged = cachedBookState ? this.hasBookStateChanged(newState) : true; if (stateChanged) { cachedBookState = newState; StateManager.updateLastValues(newState); } return cachedBookState; }, hasBookStateChanged: function(newState) { return this.isSideChanged('BID', newState) || this.isSideChanged('ASK', newState); }, isSideChanged: function(side, newState) { var maxLevel = CONFIG.LEVELS[side]; var cachedSide = cachedBookState.book[side]; var newSide = newState.book[side]; return ['Prices', 'Quantities'].some(function(type) { return this.compareArrays(cachedSide[type], newSide[type], maxLevel); }, this); }, compareArrays: function(arr1, arr2, max) { return arr1.slice(0, max).join(',') !== arr2.slice(0, max).join(','); }, createBookState: function(book) {return { book: book, BID: { Prices: this.getData(book, 'BID', CONFIG.LEVELS.BID, 'Price'), Quantities: this.getData(book, 'BID', CONFIG.LEVELS.BID, 'Quantity') }, ASK: { Prices: this.getData(book, 'ASK', CONFIG.LEVELS.ASK, 'Price'), Quantities: this.getData(book, 'ASK', CONFIG.LEVELS.ASK, 'Quantity') } }; },
getData: function(book, side, level, type) { return book && book[side] && book[side][type + 's'] ? book[side][type + 's'][level] : undefined; } };})();
function BookUtilsConstructor(BookStateManager) { this.KEYS = ['bidPrice', 'bidQuantity', 'askPrice', 'askQuantity']; this.SIDES = { BID: 'BID', ASK: 'ASK' }; this.TYPES = { PRICE: 'Price', QUANTITY: 'Quantity' }; this.getData = function(book, side, level, type) { return BookStateManager.getData(book, side, level, type); }; }
var BookUtils = new BookUtilsConstructor(BookStateManager);
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) { return order; // Nessun cambiamento se il prezzo è lo stesso } UserContext.order.current = order; UserContext.prices[side].oldLevel = price; return order; }, processOrModOrder: function(side, stock, price) { var currentOrder = UserContext.order.current; if (currentOrder) { return this.updateOrderContext(OrderManager.Modify(currentOrder.OrderCode, price), side, price); } else { return this.updateOrderContext(this.execOrder(side, stock, price, CONFIG.SIZE), side, price); } }, deleteOrder: function(orderCode) { return OrderManager.Delete(orderCode); } };
- Assistant
- User
Ok. nel BookStateManager preferisci la versione A presente hasBookStateChanged: function(newState) { return this.isSideChanged('BID', newState) || this.isSideChanged('ASK', newState); },
oppure l'alternativa B che ti propongo ? hasBookStateChanged: function(newState) { return this.isSideChanged('BID', newState) || (cachedBookState && this.isSideChanged('ASK', newState)); // Aggiunto controllo cachedBookState },
- Assistant
- User
Preferisci la versione A presente getValue: function(side, type) { return lastValues[side][type]; }, setValue: function(side, type, value) { lastValues[side][type] = value; }
oppure la versione B che propongo in alternativa ? value: function(side, type, value) { if (typeof value !== 'undefined') { lastValues[side][type] = value; } else { return lastValues[side][type]; } }
- Assistant
Esaminiamo entrambe le versioni della funzione per capire i loro vantaggi e svantaggi, così da decidere quale sia più adatta in base al contesto.
- User
Preferisci la versione A presente function mapSide(sideData, maxLevel) { var result = { Prices: [], Quantities: [] }; 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; }
oppure la versione B alternativa ? 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; }
- Assistant
- User
Ok. Ora analizza se il controllo if (order && order.Price === price) è ridondante se order è null o undefined.
Questa e' la versione A presente in OrderUtils) updateOrderContext: function(order, side, price) { if (order && order.Price === price) { return order; } UserContext.order.current = order; UserContext.prices[side].oldLevel = price; return order; },
e questa e' la proposta che ti invito a valutare, la B updateOrderContext: function(order, side, price) { if (order && order.Price !== price) { UserContext.order.current = order; UserContext.prices[side].oldLevel = price; } return order; },
- Assistant
- User
Nella versione A initializeOrderAndLog chiama initializeOrder e poi passa il risultato a logInitialization
Nella versione B si Integra la logica di initializeOrder direttamente in logInitialization per ridurre la chiamata extra.
A function initializeOrderAndLog() { var initialOrder = initializeOrder(); logInitialization(initialOrder); }
B function logInitialization() { 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); // Logica spostata qui
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();} Quale scegliere tra A e B ?
- Assistant
- User
Accesso alle proprietà di CONFIG:
Versione A presente : Le proprietà di CONFIG (es. CONFIG.LEVELS.BID) sono accedute ripetutamente all'interno delle funzioni.
Versione B proposta alternativa: Memorizzare queste proprietà in variabili locali all'inizio delle funzioni per ridurre il tempo di accesso.
A (in BookStateManager.createBookState) createBookState: function(book) { return { // ... BID: { Prices: this.getData(book, 'BID', CONFIG.LEVELS.BID, 'Price'), Quantities: this.getData(book, 'BID', CONFIG.LEVELS.BID, 'Quantity') }, // ... }; },
B (in BookStateManager.createBookState) createBookState: function(book) { var bidLevels = CONFIG.LEVELS.BID; // Memorizzazione in variabile locale var askLevels = CONFIG.LEVELS.ASK; return { // ... BID: { Prices: this.getData(book, 'BID', bidLevels, 'Price'), // Uso della variabile locale Quantities: this.getData(book, 'BID', bidLevels, 'Quantity') }, // ... }; },
- Assistant
- User
Mi riscrivi createBookState: function(book) intera con le modifiche proposte ed accettate in B ?
- Assistant
Certo! Ecco come potrebbe apparire la funzione
createBookStatecon le modifiche proposte nella versione B, che includono la memorizzazione delle proprietà diCONFIGin variabili locali:createBookState: function(book) { var bidLevels = CONFIG.LEVELS.BID; // Memorizzazione in variabile locale var askLevels = CONFIG.LEVELS.ASK; // Memorizzazione in variabile locale return { book: book, BID: { Prices: this.getData(book, 'BID', bidLevels, 'Price'), // Uso della variabile locale Quantities: this.getData(book, 'BID', bidLevels, 'Quantity') // Uso della variabile locale }, ASK: { Prices: this.getData(book, 'ASK', askLevels, 'Price'), // Uso della variabile locale Quantities: this.getData(book, 'ASK', askLevels, 'Quantity') // Uso della variabile locale } }; },In questa versione della funzione:
- Ho memorizzato
CONFIG.LEVELS.BIDeCONFIG.LEVELS.ASKin variabili locali e all'inizio della funzione.
- Ho memorizzato
- User
Ok. Preferisci la versione A presente, in cui si verifica la presenza del template ad ogni chiamata, oppure la versione B alternativa in cui potremmo ottimizzare memorizzando in una variabile inizializzata una volta se i template sono fissi, assumendo che i template non cambino durante l'esecuzione del programma.
VERSIONE A (in logger) log: function(type, data, includeFormattedState) { includeFormattedState = includeFormattedState !== false; var template = this.messages[type]; if (!template) return; // Verifica ad ogni chiamata
// ... resto della funzione},
VERSIONE B (in logger, assumendo che i template siano fissi e inizializzati all'avvio) init: function() { this.messageTemplates = {}; for (var type in this.messages) { this.messageTemplates[type] = this.messages[type]; // Pre-memorizzazione dei template } },
log: function(type, data, includeFormattedState) { includeFormattedState = includeFormattedState !== false; var template = this.messageTemplates[type]; // Accesso diretto if (!template) return;
// ... resto della funzione},
- Assistant
- User
OK ACCETTO LA B riscrivimi la va logger intera con le modifiche proposte ed accettare in B
- Assistant
- User
- Assistant
- User
BookStateManager.isSideChanged:
VERSIONE A PRESENTE usa una funzione anonima con some per comparare array.
VERSIONE B ALTERNATIVA: Estrarrre la logica di comparazione in una funzione separata.
versione A PRESENTE NEL CODICE isSideChanged: function(side, newState) { var maxLevel = CONFIG.LEVELS[side]; var cachedSide = cachedBookState.book[side]; var newSide = newState.book[side];
return ['Prices', 'Quantities'].some(function(type) { return this.compareArrays(cachedSide[type], newSide[type], maxLevel); }, this);},
VERSIONE B ALTERNATIVA isTypeChanged: function(cachedArray, newArray, maxLevel) { // Funzione separata return this.compareArrays(cachedArray, newArray, maxLevel); },
isSideChanged: function(side, newState) { var maxLevel = CONFIG.LEVELS[side]; var cachedSide = cachedBookState.book[side]; var newSide = newState.book[side];
return this.isTypeChanged(cachedSide.Prices, newSide.Prices, maxLevel) || this.isTypeChanged(cachedSide.Quantities, newSide.Quantities, maxLevel); // Chiamate dirette}, QUALE PREFERISCI ?
- Assistant
- User
Versione A presente Esegue OrderUtils.processOrModOrder e poi aggiorna lo stato.
Versione B alternativa: Controllare il risultato di processOrModOrder e aggiornare lo stato solo se l'ordine è stato effettivamente modificato o creato.
Versione A presente (in priceUpdate) priceUpdate: function(side, book, status, userCtx) { // ... var newOrder = OrderUtils.processOrModOrder(side, ps, priceData.targetPrice); priceData.prices.current = priceData.targetPrice; // Aggiorna sempre // ... },
Versione B alternativa (in priceUpdate) priceUpdate: function(side, book, status, userCtx) { // ... var newOrder = OrderUtils.processOrModOrder(side, ps, priceData.targetPrice); if (newOrder) { // Aggiorna solo se newOrder esiste priceData.prices.current = priceData.targetPrice; // ... } }, quale e' da preferire ?
- Assistant
- User
ok. mi riscrivi la priceUpdate completa in versione B ?
- Assistant
Certamente! Ecco come potrebbe apparire la funzione
priceUpdateintera nella sua versione B, che aggiorna lo stato solo se l'ordine è stato effettivamente creato o modificato:priceUpdate: function(side, book, status, userCtx) { var priceData = { prices: userCtx.prices[side], targetPrice: book[side].Prices[userCtx.targetPriceLevels[side]], oldPrice: userCtx.prices[side].oldLevel }; if (priceData.targetPrice === priceData.oldPrice) return; var newOrder = OrderUtils.processOrModOrder(side, ps, priceData.targetPrice); if (newOrder) { // Aggiorna solo se newOrder esiste priceData.prices.current = priceData.targetPrice; var direction = Helper.priceDirection(priceData.targetPrice, priceData.oldPrice); var levelDifference = CONFIG.LEVELS[side] + direction; logger.log('LevelChange', { lastLevel: levelDifference, priceLevel: userCtx.targetPriceLevels[side] }, true); status.secondCount = 0; status.numOperazione++; } } - User
l'EDITOR MI SEGNALA ERRORE: PREVISTO IDENTIFICATORE
- Assistant