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
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(); vorrei scrivere una funzione costruttore per BookUtils riorganizzando il codice per accettare le dipendenze come parametri, riducendo le dipendenze globali. Riscrivi poi il codice intero
Certo! Di seguito troverai il codice riscritto con BookUtils come funzione costruttore che accetta le dipendenze come parametri, riducendo le dipendenze globali. Ho riorganizzato l'intero codice per aderire a questa struttura modulare. Ogni modulo ora è una funzione che accetta le dipendenze necessarie come parametri.
javascript
(function() {
// Configurazione
var CONFIG = {
ORDER_SIDE: 'BID',
SIZE: 1,
MAX_OPERATIONS: 3,
LEVELS: { BID: 6, ASK: 6 },
SECONDS: 5,
TICK: 1,
MONITORING_MODE: 'MONITORA_yourlevel'
};
// Funzione costruttore per StateManager
function createStateManager() {
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;
}
};
}
// Funzione costruttore per BookStateManager
function createBookStateManager(CONFIG, StateManager) {
var cachedBookState = null;
var SIDES = ['BID', 'ASK'];
var TYPES = ['Price', 'Quantity'];
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 !cachedBookState || 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 this.compareArrays(cachedSide.Prices, newSide.Prices, maxLevel) ||
this.compareArrays(cachedSide.Quantities, newSide.Quantities, maxLevel);
},
compareArrays: function(arr1, arr2, max) {
for (var i = 0; i < max; i++) {
if (arr1[i] !== arr2[i]) {
return true;
}
}
return false;
},
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;
},
getData: function(book, side, level, type) {
return book && book[side] && book[side][type + 's'] ? book[side][type + 's'][level] : undefined;
}
};
}
// Funzione costruttore per BookUtils
function createBookUtils(BookStateManager) {
var KEYS = ['bidPrice', 'bidQuantity', 'askPrice', 'askQuantity'];
var SIDES = { BID: 'BID', ASK: 'ASK' };
var TYPES = { PRICE: 'Price', QUANTITY: 'Quantity' };
function getData(book, side, level, type) {
return BookStateManager.getData(book, side, level, type);
}
return {
KEYS: KEYS,
SIDES: SIDES,
TYPES: TYPES,
getData: getData
};
}
// Funzione costruttore per OrderUtils
function createOrderUtils(OrderManager, UserContext, CONFIG) {
return {
execOrder: function(side, stock, price, size) {
return (side === 'BID') ? OrderManager.Buy(stock, price, size) : OrderManager.Sell(stock, price, size);
},
updateOrderContext: function(order, side, price) {
UserContext.order.current = order;
UserContext.prices[side].oldLevel = price;
return order;
},
processOrModOrder: function(side, stock, price) {
var currentOrder = UserContext.order.current;
return currentOrder
? (currentOrder.Price === price ? currentOrder : this.updateOrderContext(OrderManager.Modify(currentOrder.OrderCode, price), side, price))
: this.updateOrderContext(this.execOrder(side, stock, price, CONFIG.SIZE), side, price);
},
deleteOrder: function(orderCode) {
return OrderManager.Delete(orderCode);
}
};
}
// Funzione costruttore per il logger
function createLogger() {
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,
'message': "{message}\r\n" + separator
};
function formatMessage(template, data) {
return template.replace(/{(\w+)}/g, function(match, key) {
return typeof data[key] !== 'undefined' ? data[key] : match;
});
}
function formatState(bookState, UserContext) {
var book = UserContext.book;
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: " + UserContext.status.numOperazione + "\r\n" +
separator;
}
return {
log: function(type, data, includeFormattedState, bookState, UserContext) {
includeFormattedState = includeFormattedState !== false;
var template = messages[type];
if (!template) return;
var message = separator + formatMessage(template, data || {});
if (includeFormattedState && (type === 'Initialization Complete' || type === 'LevelChange')) {
message += formatState(bookState, UserContext);
}
Log(message);
}
};
}
// Funzione costruttore per Helper
function createHelper() {
return {
priceDirection: function(targetPrice, oldPrice) {
return (targetPrice > oldPrice) ? 1 : (targetPrice < oldPrice) ? -1 : 0;
}
};
}
// Funzione principale
function main() {
var ps = {}; // Sostituisci con il tuo strumento finanziario o simbolo
var UserContext = {
book: null,
order: { current: null },
status: { run: true, secondCount: 0, numOperazione: 0 },
prices: {},
targetPriceLevels: {}
};
// Creazione dei singoli componenti passando le dipendenze
var StateManager = createStateManager();
var BookStateManager = createBookStateManager(CONFIG, StateManager);
var BookUtils = createBookUtils(BookStateManager);
var Logger = createLogger();
var Helper = createHelper();
var OrderUtils = createOrderUtils(OrderManager, UserContext, CONFIG);
// Funzioni di supporto
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') {
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 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; i++) {
var bidDiff = Math.abs(bidPrices[i + 1] - bidPrices[i]);
var askDiff = Math.abs(askPrices[i + 1] - askPrices[i]);
var currentMin = (bidDiff < askDiff) ? bidDiff : askDiff;
if (currentMin > 0 && currentMin < minDiff) {
minDiff = currentMin;
if (minDiff <= MINIMUM_TICK) break;
}
}
if (minDiff === Infinity) {
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);
}
// Funzione per impostare il contesto di trading
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.book = originalBook;
UserContext.prices = {
BID: { current: pricesBID[0], oldLevel: pricesBID[sideLevels.BID] },
ASK: { current: pricesASK[0], oldLevel: pricesASK[sideLevels.ASK] }
};
UserContext.targetPriceLevels = sideLevels;
initializeOrderAndLog();
manageCycle();
}
function initializeOrderAndLog() {
var initialOrder = initializeOrder();
logInitialization(initialOrder);
}
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, ps, initialPrice);
return initialOrder;
}
function logInitialization(initialOrder) {
Logger.log('Initialization Complete', {
bidPrice: UserContext.prices.BID.current,
askPrice: UserContext.prices.ASK.current
}, true, null, UserContext);
Logger.log('Order Action', { action: 'inserito', orderCode: initialOrder.OrderCode }, false);
logFullBook();
}
function logFullBook() {
var book = UserContext.book;
var logParts = collectBookLogParts(book);
Logger.log('message', { message: logParts.join('') }, false);
}
function collectBookLogParts(book) {
var logParts = ["BID:\n"];
addLevels(logParts, 'BID', book);
logParts.push("---------------------------------------------------\n", "ASK:\n");
addLevels(logParts, 'ASK', book);
var tick = calculateTick(book.BID.Prices, book.ASK.Prices);
return logParts;
}
function addLevels(logParts, side, book) {
for (var level = 0, len = CONFIG.LEVELS[side] + 1; level < len; level++) {
logParts.push("Level " + level + ": Price = " + book[side].Prices[level] + ", Quantity = " + book[side].Quantities[level] + "\n");
}
}
// Gestione del ciclo operativo
function manageCycle() {
var status = UserContext.status;
if (checkOperations()) return;
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;
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, null, UserContext);
status.secondCount = 0;
status.numOperazione++;
}
function checkOperations() {
var status = UserContext.status;
if (status.numOperazione < CONFIG.MAX_OPERATIONS) {
return false;
}
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;
}
// Gestione degli eventi
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.log('PriceChange', {
previousPrice: ctx.lastPrice,
currentPrice: price,
currentTime: Now().ToString("HH:mm:ss.ff")
});
ctx.lastPrice = price;
}
function onTimeEvent(ctx) {
ctx.status.secondCount++;
manageCycle();
}
// Inizializzazione
if (SystemContext.IsFirst) {
setupTradeContext();
}
if (UserContext.status.run) {
var originalBook = Book(ps);
var mappedBook = mapBookData(originalBook);
UserContext.book = mappedBook;
handleEvent(UserContext, SystemContext.EventType);
}
}
// Avvio del programma
main();
})();
In questa riscrittura:
Ogni modulo (BookUtils, BookStateManager, OrderUtils, ecc.) è una funzione costruttore che accetta le sue dipendenze come parametri.
Le dipendenze globali sono state ridotte al minimo, passandole esplicitamente ai moduli che ne hanno bisogno.
Il codice è stato riorganizzato in modo che tutte le funzioni e variabili siano incapsulate all'interno dell'IIFE (Immediately Invoked Function Expression), evitando così la contaminazione dello spazio dei nomi globale.
La funzione main() gestisce il flusso principale del programma, creando le istanze dei moduli con le dipendenze necessarie e avviando il processo.
Questo approccio migliora la modularità e la testabilità del codice, facilitando la manutenzione e l'estensibilità futura.