Intelligence, Advanced Charting & Trading Platform
feat(paper): add deterministic simulated position SL TP trailing risk engine
davoodmehraban89 committed
Oct 14, 2026 at 22:38 UTC
bc8494f006e8dd7bbb91f5dd052114cb5437ff59
1 file changed
+150
packages/market-domain/src/paper-position.mjs
new
+150
@@ -0,0 +1,150 @@
1
+/**
2
+ * VELYQOR paper-only position risk simulation.
3
+ * NO BROKER, WALLET, EXCHANGE, NETWORK, DATABASE or LIVE ORDER calls.
4
+ * Price inputs are caller-supplied scenarios, NEVER claimed as executable market quotes.
5
+ */
6
+const MAX_BPS = 500;
7
+const asPositive = (value, name) => {
8
+ const x = Number(value);
9
+ if (!Number.isFinite(x) || x <= 0) throw new RangeError(name + ' must be positive and finite');
10
+ return x;
11
+};
12
+const asPercent = (value, name) => {
13
+ const x = asPositive(value, name);
14
+ if (x >= 100) throw new RangeError(name + ' must be below 100%');
15
+ return x;
16
+};
17
+const asBps = (value, name) => {
18
+ const x = Number(value);
19
+ if (!Number.isFinite(x) || x < 0 || x > MAX_BPS) {
20
+ throw new RangeError(name + ' must be in [0, 500] basis points');
21
+ }
22
+ return x;
23
+};
24
+const asTimestamp = (timestamp, name) => {
25
+ if (typeof timestamp !== 'string' ||
26
+ !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(timestamp) ||
27
+ !Number.isFinite(Date.parse(timestamp))) {
28
+ throw new TypeError(name + ' must be a valid ISO timestamp with timezone');
29
+ }
30
+ return new Date(timestamp).toISOString();
31
+};
32
+const decimal = (x) => Math.round(x * 1e10) / 1e10;
33
+const sideSign = (side) => side === 'LONG' ? 1 : -1;
34
+
35
+export function openPaperPosition({
36
+ symbol, side = 'LONG', entryPrice, capital, stopLossPercent,
37
+ takeProfitPercent, trailingStopPercent = null, commissionBps = 0,
38
+ slippageBps = 0, at
39
+}) {
40
+ if (typeof symbol !== 'string' || !/^[A-Z0-9_]{3,48}$/.test(symbol)) {
41
+ throw new TypeError('invalid canonical symbol');
42
+ }
43
+ if (!['LONG', 'SHORT'].includes(side)) throw new TypeError('side must be LONG or SHORT');
44
+ const entry = asPositive(entryPrice, 'entryPrice');
45
+ const budget = asPositive(capital, 'capital');
46
+ const loss = asPercent(stopLossPercent, 'stopLossPercent');
47
+ const profit = asPercent(takeProfitPercent, 'takeProfitPercent');
48
+ const trailing = trailingStopPercent === null || trailingStopPercent === '' ?
49
+ null : asPercent(trailingStopPercent, 'trailingStopPercent');
50
+ const fee = asBps(commissionBps, 'commissionBps');
51
+ const slip = asBps(slippageBps, 'slippageBps');
52
+ const enteredAt = asTimestamp(at, 'at');
53
+ const direction = sideSign(side);
54
+ const initialStop = decimal(entry * (1 - direction * loss / 100));
55
+ const takeProfit = decimal(entry * (1 + direction * profit / 100));
56
+ const trailStop = trailing === null ? null : decimal(entry * (1 - direction * trailing / 100));
57
+ const stopPrice = trailing === null ? initialStop :
58
+ side === 'LONG' ? Math.max(initialStop, trailStop) : Math.min(initialStop, trailStop);
59
+ const quantity = budget / entry;
60
+ return {
61
+ kind: 'PAPER_POSITION', version: 1, symbol, side, status: 'OPEN',
62
+ currency: 'QUOTE_UNIT', capital: budget, entryPrice: entry, quantity,
63
+ entryAt: enteredAt, lastAt: enteredAt, markPrice: entry,
64
+ highestPrice: entry, lowestPrice: entry,
65
+ rules: { stopLossPercent: loss, takeProfitPercent: profit,
66
+ trailingStopPercent: trailing, commissionBps: fee, slippageBps: slip },
67
+ initialStop, stopPrice, takeProfitPrice: takeProfit,
68
+ estimatedPnL: decimal(-budget * fee / 10000 * 2),
69
+ realizedPnL: null, exit: null,
70
+ events: [{ type: 'OPEN', at: enteredAt, price: entry, source: 'MANUAL_SCENARIO' }]
71
+ };
72
+}
73
+function checkOpen(position) {
74
+ if (!position || position.kind !== 'PAPER_POSITION' || position.status !== 'OPEN')
75
+ throw new TypeError('an OPEN paper position is required');
76
+}
77
+function outcome(position, price) {
78
+ const sign = sideSign(position.side);
79
+ const { commissionBps, slippageBps } = position.rules;
80
+ const executed = price * (1 - sign * slippageBps / 10000);
81
+ const entryFee = position.entryPrice * position.quantity * commissionBps / 10000;
82
+ const exitFee = executed * position.quantity * commissionBps / 10000;
83
+ return {
84
+ fillPrice: decimal(executed),
85
+ netPnL: decimal(sign * (executed - position.entryPrice) * position.quantity - entryFee - exitFee),
86
+ fees: decimal(entryFee + exitFee)
87
+ };
88
+}
89
+export function markPaperPosition(position, { price, at }) {
90
+ checkOpen(position);
91
+ const quote = asPositive(price, 'scenario price');
92
+ const timestamp = asTimestamp(at, 'at');
93
+ if (Date.parse(timestamp) <= Date.parse(position.lastAt))
94
+ throw new RangeError('scenario timestamps must strictly increase');
95
+ const high = Math.max(position.highestPrice, quote);
96
+ const low = Math.min(position.lowestPrice, quote);
97
+ const { trailingStopPercent } = position.rules;
98
+ let stop = position.initialStop;
99
+ if (trailingStopPercent !== null) {
100
+ const trailingStop = position.side === 'LONG' ?
101
+ high * (1 - trailingStopPercent / 100) :
102
+ low * (1 + trailingStopPercent / 100);
103
+ stop = position.side === 'LONG' ? Math.max(stop, trailingStop) : Math.min(stop, trailingStop);
104
+ }
105
+ stop = decimal(stop);
106
+ const stopHit = position.side === 'LONG' ? quote <= stop : quote >= stop;
107
+ const profitHit = position.side === 'LONG' ? quote >= position.takeProfitPrice : quote <= position.takeProfitPrice;
108
+ const event = { type: 'MARK', at: timestamp, price: quote, source: 'MANUAL_SCENARIO' };
109
+ const changed = {
110
+ ...position, lastAt: timestamp, markPrice: quote,
111
+ highestPrice: high, lowestPrice: low, stopPrice: stop,
112
+ events: [...position.events, event]
113
+ };
114
+ if (stopHit || profitHit) return exitPaperPosition(changed, {
115
+ price: quote, at: timestamp, reason: stopHit ? 'STOP' : 'TAKE_PROFIT', alreadyMarked: true
116
+ });
117
+ return { ...changed, estimatedPnL: outcome(changed, quote).netPnL };
118
+}
119
+function exitPaperPosition(position, { price, at, reason, alreadyMarked = false }) {
120
+ const fill = outcome(position, price);
121
+ return {
122
+ ...position, status: 'CLOSED', markPrice: price,
123
+ lastAt: at, estimatedPnL: fill.netPnL, realizedPnL: fill.netPnL,
124
+ exit: { reason, at, observedPrice: price, fillPrice: fill.fillPrice, fees: fill.fees,
125
+ caution: 'scenario observed price and conservative model slippage; not a guaranteed executable fill' },
126
+ events: [...position.events, { type: 'CLOSE', reason, at, observedPrice: price,
127
+ fillPrice: fill.fillPrice, source: 'MANUAL_SCENARIO' }]
128
+ };
129
+}
130
+export function closePaperPosition(position, { price, at }) {
131
+ checkOpen(position);
132
+ const quote = asPositive(price, 'price');
133
+ const timestamp = asTimestamp(at, 'at');
134
+ if (Date.parse(timestamp) <= Date.parse(position.lastAt)) throw new RangeError('timestamp must increase');
135
+ return exitPaperPosition(position, { price: quote, at: timestamp, reason: 'MANUAL' });
136
+}
137
+export function paperRiskSummary(position) {
138
+ if (!position || position.kind !== 'PAPER_POSITION') throw new TypeError('invalid paper position');
139
+ return {
140
+ symbol: position.symbol, side: position.side, status: position.status,
141
+ entryPrice: position.entryPrice, markPrice: position.markPrice,
142
+ stopPrice: position.stopPrice, takeProfitPrice: position.takeProfitPrice,
143
+ capital: position.capital, quantity: position.quantity,
144
+ netPnL: position.status === 'CLOSED' ? position.realizedPnL : position.estimatedPnL,
145
+ netPnLPct: decimal(100 * (position.status === 'CLOSED' ?
146
+ position.realizedPnL : position.estimatedPnL) / position.capital),
147
+ exitReason: position.exit?.reason ?? null,
148
+ eventCount: position.events.length,
149
+ };
150
+}