如何将Java实现的VWAP计算代码改写为JavaScript并正确处理PriceData类
Java转JavaScript正确实现方案
原有代码问题说明
- JavaScript 不支持在类内部声明非静态嵌套类,原写法中直接在Tain类内部定义PriceData不符合语法规范
- PriceData的setter实现错误,赋值时没有写入私有属性
#volume/#price,导致getter永远返回初始值0.0 - Java的List对应JavaScript的普通数组,直接传入PriceData实例组成的数组即可调用计算方法
完整正确代码
class Tain { // 静态内部类,对应Java的private内部类,仅能通过Tain.PriceData访问 static PriceData = class { // 私有属性 #volume = 0.0; #price = 0.0; getVolume() { return this.#volume; } setVolume(volume) { // 修正:赋值给私有属性 this.#volume = volume; } getPrice() { return this.#price; } setPrice(price) { // 修正:赋值给私有属性 this.#price = price; } } static main(args) {} calculateBaseValueVwap(side, positionStep) { let cumSum = 0.0; let totalVolume = 0.0; let amountLeft = positionStep; for (const level of side) { if (totalVolume >= positionStep || amountLeft <= 0) { break; } let amountForPriceLevel = 0.0; if (amountLeft > level.getVolume()) { amountForPriceLevel = level.getVolume(); cumSum += level.getPrice() * level.getVolume(); totalVolume += level.getVolume(); } else { amountForPriceLevel = amountLeft; // 注:原Java代码此处逻辑存在问题,当剩余量小于档位成交量时,应该取剩余量计算而非档位成交量减剩余量,已修正 cumSum += level.getPrice() * amountForPriceLevel; totalVolume += amountForPriceLevel; } amountLeft -= amountForPriceLevel; } // 兼容除零情况 return totalVolume === 0 ? 0 : cumSum / totalVolume; } } Tain.main([]);
使用示例
// 实例化主类 const tain = new Tain(); // 构造PriceData实例数组(对应Java的List<PriceData>) const priceDataList = []; // 添加第一个价格档位:量100,价2.3 const level1 = new Tain.PriceData(); level1.setVolume(100); level1.setPrice(2.3); priceDataList.push(level1); // 添加第二个价格档位:量200,价2.5 const level2 = new Tain.PriceData(); level2.setVolume(200); level2.setPrice(2.5); priceDataList.push(level2); // 调用计算方法,传入数组和目标仓位150 const vwapResult = tain.calculateBaseValueVwap(priceDataList, 150); console.log('计算得到的VWAP值:', vwapResult);
简化方案(符合JS使用习惯)
如果不需要严格的私有属性封装,可直接用普通对象代替PriceData类,代码更简洁:
// 直接构造普通对象数组 const priceDataList = [ { volume: 100, price: 2.3 }, { volume: 200, price: 2.5 } ]; // 简化后的计算方法 function calculateBaseValueVwap(side, positionStep) { let cumSum = 0.0; let totalVolume = 0.0; let amountLeft = positionStep; for (const level of side) { if (totalVolume >= positionStep || amountLeft <= 0) break; const takeVolume = Math.min(level.volume, amountLeft); cumSum += level.price * takeVolume; totalVolume += takeVolume; amountLeft -= takeVolume; } return totalVolume === 0 ? 0 : cumSum / totalVolume; } // 调用 console.log(calculateBaseValueVwap(priceDataList, 150));
内容的提问来源于stack exchange,提问作者user1285928
相关产品推荐
相关产品推荐

