function collectBookLogParts(book) {
var logParts = ["BID:\n"];
addLevels(logParts, 'BID', book);
logParts.push(separator, "ASK:\n");
addLevels(logParts, 'ASK', book);
var tick = calculateTick(book.BID.Prices, book.ASK.Prices);
return logParts;
}
function logFullBook() {
var book = UserContext.book;
var logParts = collectBookLogParts(book);
logger.log('message', { message: logParts.join('') }, false); // Utilizza logger invece di Log
}
function manageCycle() {
var status = UserContext.status;
if (checkOperations()) return;
code
status.secondCount += 1;
if (status.secondCount < CONFIG.SECONDS) return;
var book = mapBookData(Book(ps));
UserContext.book = book;
priceUpdate(CONFIG.ORDER_SIDE, book, status);
status.secondCount = 0;
}
function priceUpdate(side, book, status) {
var prices = UserContext.prices[side];
var targetPriceLevel = UserContext.targetPriceLevels[side];
var targetPrice = book[side].Prices[targetPriceLevel];
var oldPrice = prices.oldLevel;
code
if (targetPrice === oldPrice) return;
var newOrder = OrderUtils.processOrModOrder(side, ps, targetPrice);
if (!newOrder) return;
prices.current = targetPrice;
var direction = Helper.priceDirection(targetPrice, oldPrice);
var levelDifference = (direction === 1) ? (CONFIG.LEVELS[side] + 1) :
(direction === -1) ? (CONFIG.LEVELS[side] - 1) :
CONFIG.LEVELS[side];
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 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 marketEvent(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 = marketEvent(Book, mapBookData, handleEvent, UserContext, SystemContext);
marketEventInstance(); Ho pensato di modificare la funzione CreatebookState presente che chiamo A con la variante B createBookState: function(book) {
var state = { book: book };
code
for (var i = 0, len = SIDES.length; i < len; i++) {
var side = SIDES[i].toLowerCase();
state[side + 'Prices'] = this.getData(book, SIDES[i], CONFIG.LEVELS[SIDES[i]], 'Price');
state[side + 'Quantities'] = this.getData(book, SIDES[i], CONFIG.LEVELS[SIDES[i]], 'Quantity');
}
return state;
}, che pero' non funziona, in quanto non immette l'ordine iniziale. Riusciresti a capire il motivo ?
Il problema che stai riscontrando deriva principalmente dalla modifica della struttura dell'oggetto state nella funzione createBookState. Vediamo più in dettaglio cosa sta accadendo e come risolverlo.
Analisi del Problema
1. Cambiamento delle Chiavi nell'Oggetto state
Nella versione originale della funzione createBookState, le chiavi dell'oggetto state vengono create in modo specifico per ogni lato (BID e ASK) e per ogni tipo (Price e Quantity). Ad esempio:
Queste chiavi risultano in proprietà come bidPrice, bidQuantity, askPrice e askQuantity.
2. Modifica Introduce Chiavi Diverse
Quando hai modificato la funzione in:
javascript
createBookState: function(book) {
var state = { book: book };
for (var i = 0, len = SIDES.length; i < len; i++) {
var side = SIDES[i].toLowerCase();
state[side + 'Prices'] = this.getData(book, SIDES[i], CONFIG.LEVELS[SIDES[i]], 'Price');
state[side + 'Quantities'] = this.getData(book, SIDES[i], CONFIG.LEVELS[SIDES[i]], 'Quantity');
}
return state;
},
Le chiavi ora diventano bidPrices, bidQuantities, askPrices e askQuantities. Questo cambiamento di nomenclatura porta a una mancata corrispondenza con altre parti del codice che si aspettano le chiavi originali (bidPrice e bidQuantity).
3. Impatto sulle Altre Parti del Codice
Diverse parti del tuo codice dipendono dalle chiavi specifiche per funzionare correttamente. Ad esempio:
Qui, il StateManager cerca di accedere a state.bidPrice e state.askPrice, che non esistono più dopo la tua modifica. Invece, esistono state.bidPrices e state.askPrices, il che provoca un comportamento inaspettato e può far fallire la logica di aggiornamento dello stato.
Se book.BID.Prices e book.BID.Quantities non sono correttamente popolati o non esistono a causa della modifica, il logger non funzionerà come previsto.
Altre Funzioni Dipendenti dal state:
Funzioni come BookStateManager.hasBookStateChanged e BookUtils.getData dipendono dal formato specifico del state. Qualsiasi discrepanza nelle chiavi causerà la rottura di queste funzioni.
Soluzione Proposta
Per risolvere il problema, devi assicurarti che la struttura dell'oggetto state rimanga coerente con ciò che è atteso dal resto del sistema. Ecco alcuni passaggi che puoi seguire:
1. Ripristinare le Chiavi Originali
Modifica la funzione createBookState in modo che crei nuovamente le chiavi bidPrice, bidQuantity, askPrice e askQuantity:
javascript
createBookState: function(book) {
var state = { book: book };
for (var i = 0; i < SIDES.length; i++) {
var side = SIDES[i];
for (var j = 0; j < TYPES.length; j++) {
var type = TYPES[j];
var key = side.toLowerCase() + type;
state[key] = this.getData(book, side, CONFIG.LEVELS[side], type);
}
}
return state;
},
Questo ripristina la coerenza con il resto del codice che dipende da queste chiavi specifiche.
2. Aggiornare Tutte le Parti del Codice Consistemente
Se desideri effettivamente utilizzare chiavi come bidPrices e bidQuantities, dovrai aggiornare tutte le parti del codice che accedono a queste chiavi. Questo include:
StateManager.updateLastValues:
javascript
lastValues.BID.price = state.bidPrices; // Aggiorna in base alla nuova struttura
lastValues.BID.quantity = state.bidQuantities;
lastValues.ASK.price = state.askPrices;
lastValues.ASK.quantity = state.askQuantities;
logger.formatState:
Modifica come segue per accedere correttamente alle nuove chiavi:
Altre funzioni:
Assicurati che tutte le funzioni che accedono al state utilizzino le nuove chiavi corrette.
3. Verifica Consistenza nel cachedBookState
Nel BookStateManager, assicurati che la logica per confrontare gli stati (hasBookStateChanged) sia aggiornata per riflettere le nuove chiavi. Se le chiavi sono cambiate, potrebbe essere necessario aggiornare anche questa logica.
4. Debug e Logging
Aggiungi dei log temporanei nella funzione createBookState e nelle funzioni correlate per verificare che le chiavi siano create correttamente e che il state venga aggiornato come previsto.
javascript
createBookState: function(book) {
var state = { book: book };
for (var i = 0, len = SIDES.length; i < len; i++) {
var side = SIDES[i].toLowerCase();
state[side + 'Prices'] = this.getData(book, SIDES[i], CONFIG.LEVELS[SIDES[i]], 'Price');
state[side + 'Quantities'] = this.getData(book, SIDES[i], CONFIG.LEVELS[SIDES[i]], 'Quantity');
}
console.log("Created book state:", state); // Log per debug
return state;
},
Conclusione
La modifica della funzione createBookState ha introdotto una discrepanza tra le chiavi create e quelle attese nel resto del sistema. Per risolvere il problema, è necessario garantire che la struttura dell'oggetto state rimanga coerente o, in alternativa, aggiornare tutte le parti del codice che interagiscono con questo oggetto per riflettere le nuove chiavi. Assicurati di mantenere una coerenza nella nomenclatura delle chiavi e verifica che tutte le funzioni dipendenti siano aggiornate di conseguenza.
Se hai bisogno di ulteriori dettagli o assistenza con specifiche modifiche, fammi sapere!