Intelligence, Advanced Charting & Trading Platform
feat(paper): implement replay-validated local multi-position workspace and CSV audit
davoodmehraban89 committed
Oct 14, 2026 at 23:50 UTC
6132679072210420308463be9e64916e440ec3d2
1 file changed
+143
packages/market-domain/src/paper-workspace.mjs
new
+143
@@ -0,0 +1,143 @@
1
+/**
2
+ * Local paper portfolio for educational/manual price scenarios.
3
+ * This has no real orders, server persistence or user authentication.
4
+ * P&L for different quote currencies MUST NOT be aggregated.
5
+ */
6
+import {
7
+ openPaperPosition, markPaperPosition, closePaperPosition, paperRiskSummary
8
+} from './paper-position.mjs';
9
+
10
+const MAX_POSITIONS=50;
11
+const MAX_OPEN=10;
12
+const MAX_EVENTS=150;
13
+const MAX_BYTES=300_000;
14
+const idFor=(value)=>'P'+String(value).padStart(4,'0');
15
+const validWorkspace=(w)=>{
16
+ if (!w||w.kind!=='PAPER_WORKSPACE'||w.version!==1||
17
+ !Number.isSafeInteger(w.nextId)||w.nextId<1||
18
+ !Array.isArray(w.positions)||w.positions.length>MAX_POSITIONS)
19
+ throw new TypeError('invalid paper workspace');
20
+ return w;
21
+};
22
+export function createPaperWorkspace(){
23
+ return {kind:'PAPER_WORKSPACE',version:1,nextId:1,positions:[]};
24
+}
25
+function copyWithPosition(w,index,position){
26
+ const positions=w.positions.slice();positions[index]={id:w.positions[index].id,position};
27
+ return {...w,positions};
28
+}
29
+function findIndex(w,id){
30
+ const index=w.positions.findIndex(row=>row.id===id);
31
+ if(index<0)throw new RangeError('paper position id not found');
32
+ return index;
33
+}
34
+export function addPaperPosition(w,options){
35
+ validWorkspace(w);
36
+ if(w.positions.length>=MAX_POSITIONS)throw new RangeError('paper workspace history is full; export audit then reset');
37
+ if(w.positions.filter(row=>row.position.status==='OPEN').length>=MAX_OPEN)
38
+ throw new RangeError('maximum 10 simultaneously open paper positions');
39
+ const position=openPaperPosition(options);
40
+ const id=idFor(w.nextId);
41
+ if(w.positions.some(row=>row.id===id))throw new Error('duplicate paper position id');
42
+ return {...w,nextId:w.nextId+1,positions:[...w.positions,{id,position}]};
43
+}
44
+export function markPaperWorkspacePosition(w,id,scenario){
45
+ validWorkspace(w);
46
+ const index=findIndex(w,id),old=w.positions[index].position;
47
+ if(old.events.length>=MAX_EVENTS)throw new RangeError('scenario event history limit');
48
+ return copyWithPosition(w,index,markPaperPosition(old,scenario));
49
+}
50
+export function closePaperWorkspacePosition(w,id,scenario){
51
+ validWorkspace(w);
52
+ const index=findIndex(w,id),old=w.positions[index].position;
53
+ if(old.events.length>=MAX_EVENTS)throw new RangeError('scenario event history limit');
54
+ return copyWithPosition(w,index,closePaperPosition(old,scenario));
55
+}
56
+export function paperWorkspaceSummary(w){
57
+ validWorkspace(w);
58
+ return {
59
+ total:w.positions.length,
60
+ open:w.positions.filter(row=>row.position.status==='OPEN').length,
61
+ closed:w.positions.filter(row=>row.position.status==='CLOSED').length,
62
+ // Important: return PER-POSITION results, never sum EUR, USD, IRR etc.
63
+ positions:w.positions.map(({id,position})=>({id,...paperRiskSummary(position)}))
64
+ };
65
+}
66
+const stable=(o)=>JSON.stringify(o);
67
+function reconstructStoredPosition(original){
68
+ if(!original || original.kind!=='PAPER_POSITION' ||
69
+ !Array.isArray(original.events)||original.events.length<1||
70
+ original.events.length>MAX_EVENTS+1||original.events[0]?.type!=='OPEN')
71
+ throw new TypeError('invalid stored paper position');
72
+ const opening=original.events[0];
73
+ let p=openPaperPosition({
74
+ symbol:original.symbol,side:original.side,
75
+ entryPrice:original.entryPrice,capital:original.capital,
76
+ stopLossPercent:original.rules?.stopLossPercent,
77
+ takeProfitPercent:original.rules?.takeProfitPercent,
78
+ trailingStopPercent:original.rules?.trailingStopPercent,
79
+ commissionBps:original.rules?.commissionBps,
80
+ slippageBps:original.rules?.slippageBps,at:opening.at
81
+ });
82
+ if(opening.source!=='MANUAL_SCENARIO'||opening.price!==p.entryPrice)
83
+ throw new TypeError('invalid opening event');
84
+ for(let i=1;i<original.events.length;i++){
85
+ const event=original.events[i];
86
+ if(event?.type==='MARK' && p.status==='OPEN'){
87
+ if(event.source!=='MANUAL_SCENARIO')throw new TypeError('untrusted price source');
88
+ p=markPaperPosition(p,{price:event.price,at:event.at});
89
+ }else if(event?.type==='CLOSE'){
90
+ if(p.status==='OPEN' && event.reason==='MANUAL'){
91
+ p=closePaperPosition(p,{price:event.observedPrice,at:event.at});
92
+ }
93
+ const predicted=p.events.at(-1);
94
+ if(p.status!=='CLOSED'||predicted.type!=='CLOSE'||predicted.at!==event.at||
95
+ predicted.reason!==event.reason||predicted.observedPrice!==event.observedPrice)
96
+ throw new TypeError('inconsistent closed position');
97
+ }else{
98
+ throw new TypeError('unsupported or conflicting event sequence');
99
+ }
100
+ }
101
+ // Reject altered financial fields/status/fee estimates; derive truth from events.
102
+ if(stable(p)!==stable(original))
103
+ throw new TypeError('paper position history does not match derived state');
104
+ return p;
105
+}
106
+export function restorePaperWorkspace(json){
107
+ if(typeof json!=='string'||json.length>MAX_BYTES||json.length<2)
108
+ throw new TypeError('invalid paper workspace storage payload');
109
+ let parsed;
110
+ try{parsed=JSON.parse(json)}catch{throw new TypeError('invalid paper workspace JSON')}
111
+ validWorkspace(parsed);
112
+ const ids=new Set();
113
+ const positions=parsed.positions.map(row=>{
114
+ if(typeof row?.id!=='string'||!/^P\d{4,12}$/.test(row.id)||ids.has(row.id))
115
+ throw new TypeError('invalid or duplicate paper id');
116
+ ids.add(row.id);
117
+ if(Number(row.id.slice(1))>=parsed.nextId)throw new TypeError('paper id sequence inconsistent');
118
+ const position=reconstructStoredPosition(row.position);
119
+ return {id:row.id,position};
120
+ });
121
+ const restored={...parsed,positions};
122
+ if(stable(restored)!==json)throw new TypeError('paper workspace was altered or has unsupported fields');
123
+ if(positions.filter(row=>row.position.status==='OPEN').length>MAX_OPEN)
124
+ throw new RangeError('too many open positions');
125
+ return restored;
126
+}
127
+function csvCell(value){
128
+ const text=String(value??'');
129
+ return '"'+text.replaceAll('"','""')+'"';
130
+}
131
+export function exportPaperWorkspaceCSV(w){
132
+ validWorkspace(w);
133
+ const result=[['position_id','symbol','side','event_type','event_at','scenario_price','reason','status','net_pnl_quote_units'].map(csvCell).join(',')];
134
+ for(const {id,position} of w.positions){
135
+ for(const event of position.events){
136
+ result.push([id,position.symbol,position.side,event.type,event.at,
137
+ event.price??event.observedPrice??'',event.reason??'',position.status,
138
+ event.type==='CLOSE'?position.realizedPnL:''
139
+ ].map(csvCell).join(','));
140
+ }
141
+ }
142
+ return result.join('\r\n')+'\r\n';
143
+}