@@ -8,6 +8,9 @@ import { SYMBOL, LEVELS } from './constants';
88import { round2 , fatTailRandom } from './utils' ;
99import { getNextPhase , getPhaseDuration } from './wyckoff' ;
1010
11+ /** 最小价格限制,防止负数或过小的价格 */
12+ const MIN_PRICE = 0.01 ;
13+
1114/**
1215 * 生成订单簿数据
1316 */
@@ -38,6 +41,11 @@ export function generateOrderBook(): OrderBook {
3841 const random = fatTailRandom ( ) * baseVol ;
3942 const changePercent = drift + random + state . momentum * 0.0001 ;
4043 state . currentPrice = prevPrice * ( 1 + changePercent ) ;
44+
45+ // 价格保护:确保价格不会变成负数或过小
46+ if ( state . currentPrice < MIN_PRICE ) {
47+ state . currentPrice = Math . max ( MIN_PRICE , prevPrice * 0.99 ) ; // 最多下跌 1%
48+ }
4149
4250 // 更新动量
4351 state . momentum = state . momentum * 0.98 + changePercent * 50 ;
@@ -56,20 +64,32 @@ export function generateOrderBook(): OrderBook {
5664 const bids : [ number , number ] [ ] = [ ] ;
5765 const asks : [ number , number ] [ ] = [ ] ;
5866
59- let bidSpread = 0 ;
60- let askSpread = 0 ;
67+ // 确保当前价格不低于最小价格
68+ const currentPrice = Math . max ( state . currentPrice , MIN_PRICE ) ;
69+
70+ // 使用百分比 spread,适应不同价格水平
71+ // 每层 spread: 0.05% - 0.3%,累加后最多约 15% 的深度
72+ let bidSpreadPercent = 0 ;
73+ let askSpreadPercent = 0 ;
6174
6275 for ( let i = 0 ; i < LEVELS ; i ++ ) {
6376 const depthMultiplier = 1 + i * 0.15 ;
6477 const baseQty = Math . floor ( Math . random ( ) * 99 ) + 1 ;
6578
66- bidSpread += 0.01 + Math . random ( ) * 0.49 ;
67- const bidPrice = state . currentPrice - bidSpread ;
68- bids . push ( [ round2 ( bidPrice ) , Math . round ( baseQty * depthMultiplier ) ] ) ;
69-
70- askSpread += 0.01 + Math . random ( ) * 0.49 ;
71- const askPrice = state . currentPrice + askSpread ;
72- asks . push ( [ round2 ( askPrice ) , Math . round ( baseQty * depthMultiplier ) ] ) ;
79+ // 百分比 spread,每层增加 0.05% - 0.3%
80+ bidSpreadPercent += ( 0.0005 + Math . random ( ) * 0.0025 ) ;
81+ const bidPrice = currentPrice * ( 1 - bidSpreadPercent ) ;
82+
83+ // 确保买单价格不低于最小价格,且低于当前价格
84+ const safeBidPrice = Math . max ( MIN_PRICE , Math . min ( bidPrice , currentPrice * 0.999 ) ) ;
85+ bids . push ( [ round2 ( safeBidPrice ) , Math . round ( baseQty * depthMultiplier ) ] ) ;
86+
87+ askSpreadPercent += ( 0.0005 + Math . random ( ) * 0.0025 ) ;
88+ const askPrice = currentPrice * ( 1 + askSpreadPercent ) ;
89+
90+ // 确保卖单价格高于当前价格
91+ const safeAskPrice = Math . max ( askPrice , currentPrice * 1.001 ) ;
92+ asks . push ( [ round2 ( safeAskPrice ) , Math . round ( baseQty * depthMultiplier ) ] ) ;
7393 }
7494
7595 bids . sort ( ( a , b ) => b [ 0 ] - a [ 0 ] ) ;
@@ -78,7 +98,7 @@ export function generateOrderBook(): OrderBook {
7898 return {
7999 symbol : SYMBOL ,
80100 timestamp : Date . now ( ) ,
81- price : round2 ( state . currentPrice ) ,
101+ price : round2 ( currentPrice ) ,
82102 bids,
83103 asks,
84104 } ;
0 commit comments