@vtxmacro/cli 2026.10.73 → 2026.10.75
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/vtx-mcp.js +1 -1
- package/bin/vtx-service-bootstrap.js +1 -1
- package/bin/vtx.js +619 -420
- package/package.json +1 -1
package/bin/vtx.js
CHANGED
|
@@ -122,7 +122,7 @@ var init_routing = __esm({
|
|
|
122
122
|
var agent_cli_release_default;
|
|
123
123
|
var init_agent_cli_release = __esm({
|
|
124
124
|
"agent-cli-release.json"() {
|
|
125
|
-
agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.
|
|
125
|
+
agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.75", codex_package_name: "@openai/codex", codex_version: "0.155.0", copilot_sdk_package_name: "@github/copilot-sdk", copilot_sdk_version: "1.0.0-beta.8", copilot_cli_package_name: "@github/copilot", copilot_cli_version: "1.0.80", deepseek_harness_version: "0.1.1-rc.2", deepseek_harness_packages: ["@deepseek-ai/dsh-agent", "@deepseek-ai/dsh-agent-instructions", "@deepseek-ai/dsh-agent-loop", "@deepseek-ai/dsh-agent-spine-demo", "@deepseek-ai/dsh-anonymous-user-id", "@deepseek-ai/dsh-atomic-write", "@deepseek-ai/dsh-attachment", "@deepseek-ai/dsh-brand", "@deepseek-ai/dsh-code-runtime", "@deepseek-ai/dsh-credentials", "@deepseek-ai/dsh-fs", "@deepseek-ai/dsh-goal", "@deepseek-ai/dsh-goal-round-driver", "@deepseek-ai/dsh-home-paths", "@deepseek-ai/dsh-invariants", "@deepseek-ai/dsh-jobs", "@deepseek-ai/dsh-jobs-local", "@deepseek-ai/dsh-launch-environment", "@deepseek-ai/dsh-llm", "@deepseek-ai/dsh-llm-deepseek", "@deepseek-ai/dsh-llm-retry", "@deepseek-ai/dsh-output-retention", "@deepseek-ai/dsh-sandbox", "@deepseek-ai/dsh-sandbox-policy", "@deepseek-ai/dsh-scope", "@deepseek-ai/dsh-session", "@deepseek-ai/dsh-session-checkpoint-policy", "@deepseek-ai/dsh-session-persistence", "@deepseek-ai/dsh-session-persistence-jsonl", "@deepseek-ai/dsh-session-projection", "@deepseek-ai/dsh-session-title", "@deepseek-ai/dsh-settings", "@deepseek-ai/dsh-shell", "@deepseek-ai/dsh-shell-env", "@deepseek-ai/dsh-skill", "@deepseek-ai/dsh-skill-filesystem", "@deepseek-ai/dsh-subprocess", "@deepseek-ai/dsh-system-prompt", "@deepseek-ai/dsh-timeout", "@deepseek-ai/dsh-tool-bash", "@deepseek-ai/dsh-tool-goal", "@deepseek-ai/dsh-tool-jobs", "@deepseek-ai/dsh-tool-skill", "@deepseek-ai/dsh-tools", "@deepseek-ai/dsh-typert-protocol", "@deepseek-ai/dsh-user-approval"], deepseek_cordis_package_name: "@deepseek-ai/cordis", deepseek_cordis_version: "4.0.1", deepseek_support_packages: { "@deepseek-ai/cordis-plugin-timer": "1.1.3" }, platforms: { "linux-x64": { package_name: "@openai/codex-linux-x64", target: "x86_64-unknown-linux-musl", binary_name: "codex", sha256: "660e159a49e823ac8e5986cb238f73158ce4b957d40d9292f8de90862644b501" }, "win32-x64": { package_name: "@openai/codex-win32-x64", target: "x86_64-pc-windows-msvc", binary_name: "codex.exe", sha256: "e4c11374bd9de8ad5c3b7617fd4654bb7839901edb0863f9930666863c7a021b" } }, pi_coding_agent_package_name: "@earendil-works/pi-coding-agent", pi_ai_package_name: "@earendil-works/pi-ai", pi_version: "0.85.1", pi_support_packages: ["@earendil-works/pi-agent-core", "@earendil-works/pi-telemetry", "@earendil-works/pi-tui", "@earendil-works/chord"], grok_version: "1.0.30", grok_platforms: { "linux-x64": { package_name: "@xai-official/grok-linux-x64", binary_name: "grok", sha256: "504dd6546ab991b75d36698242875ce461489cd1f8cd84285873cb55bd5c7d54" }, "win32-x64": { package_name: "@xai-official/grok-win32-x64", binary_name: "grok.exe", sha256: "48736d1a4342a801ea26d0ecde4c516b653f791399065adaa55973f83abd8867" } } };
|
|
126
126
|
}
|
|
127
127
|
});
|
|
128
128
|
|
|
@@ -3262,7 +3262,8 @@ var init_shared_contracts_generated = __esm({
|
|
|
3262
3262
|
"position_changed": "Your {symbol} position changed just before VTX sent this, so nothing was sent. Check the position and try again.",
|
|
3263
3263
|
"trailing_stop_unavailable": "MetaTrader 5 has no trailing stop loss.",
|
|
3264
3264
|
"trading_unavailable": "Trading on MetaTrader 5 is not available yet.",
|
|
3265
|
-
"action_unavailable": "This action isn't available for MetaTrader 5 bots."
|
|
3265
|
+
"action_unavailable": "This action isn't available for MetaTrader 5 bots.",
|
|
3266
|
+
"account_currency_unavailable": "VTX bots trade MetaTrader 5 accounts in US dollars. Connect an account in US dollars to run this bot."
|
|
3266
3267
|
};
|
|
3267
3268
|
}
|
|
3268
3269
|
});
|
|
@@ -62129,6 +62130,17 @@ var init_open_orders = __esm({
|
|
|
62129
62130
|
}
|
|
62130
62131
|
});
|
|
62131
62132
|
|
|
62133
|
+
// lib/api/positions.ts
|
|
62134
|
+
var init_positions = __esm({
|
|
62135
|
+
"lib/api/positions.ts"() {
|
|
62136
|
+
"use strict";
|
|
62137
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
62138
|
+
init_define_VTX_EXO_POLICY();
|
|
62139
|
+
init_define_VTX_GROK_POLICY();
|
|
62140
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
62141
|
+
}
|
|
62142
|
+
});
|
|
62143
|
+
|
|
62132
62144
|
// lib/api/screener.ts
|
|
62133
62145
|
var init_screener = __esm({
|
|
62134
62146
|
"lib/api/screener.ts"() {
|
|
@@ -99883,7 +99895,7 @@ async function recordServerHostExecutionAudit(profileId, payload, signal, requir
|
|
|
99883
99895
|
{ ...authority.requestOptions, signal }
|
|
99884
99896
|
);
|
|
99885
99897
|
}
|
|
99886
|
-
async function checkServerHostExecutionCapacity(profileId, plans, signal, requiredRuntimeSessionId, explicitRuntimeLeaseToken, explicitRuntimeDeviceId, explicitSchedulerInstanceId, cycleStartedAt) {
|
|
99898
|
+
async function checkServerHostExecutionCapacity(profileId, plans, signal, requiredRuntimeSessionId, explicitRuntimeLeaseToken, explicitRuntimeDeviceId, explicitSchedulerInstanceId, cycleStartedAt, positions) {
|
|
99887
99899
|
const authority = resolveClientExchangeMutationAuthority(
|
|
99888
99900
|
profileId,
|
|
99889
99901
|
requiredRuntimeSessionId,
|
|
@@ -99897,6 +99909,7 @@ async function checkServerHostExecutionCapacity(profileId, plans, signal, requir
|
|
|
99897
99909
|
JSON.stringify({
|
|
99898
99910
|
...clientExchangeMutationAuthorityBody(authority),
|
|
99899
99911
|
plans,
|
|
99912
|
+
positions,
|
|
99900
99913
|
cycle_started_at: cycleStartedAt || void 0
|
|
99901
99914
|
// an order VTX sent since then refuses the batch
|
|
99902
99915
|
}),
|
|
@@ -100533,6 +100546,7 @@ var init_api2 = __esm({
|
|
|
100533
100546
|
init_billing();
|
|
100534
100547
|
init_market_data();
|
|
100535
100548
|
init_open_orders();
|
|
100549
|
+
init_positions();
|
|
100536
100550
|
init_screener();
|
|
100537
100551
|
init_client_host_commands();
|
|
100538
100552
|
init_client_exchange_mutation_begin();
|
|
@@ -104645,7 +104659,7 @@ var init_rejection = __esm({
|
|
|
104645
104659
|
});
|
|
104646
104660
|
|
|
104647
104661
|
// lib/runtime/exchange-executor/mt5/market.ts
|
|
104648
|
-
var mt5AccountOf, decimalPlaces, fixedDecimals, toScaled, fromScaled, multiplyDecimals, addDecimals, negateDecimal, lotsToUnits, roundSteps, unitsToLots, formatLots, lotsWithinLimits, formatMt5Price, symbolRefused, readMt5Market;
|
|
104662
|
+
var mt5AccountOf, decimalPlaces, fixedDecimals, toScaled, fromScaled, multiplyDecimals, addDecimals, negateDecimal, lotsToUnits, roundSteps, unitsToLots, formatLots, lotsWithinLimits, formatMt5Price, symbolRefused, mt5QuoteRate, mt5ValuationRefused, readMt5Market;
|
|
104649
104663
|
var init_market = __esm({
|
|
104650
104664
|
"lib/runtime/exchange-executor/mt5/market.ts"() {
|
|
104651
104665
|
"use strict";
|
|
@@ -104714,15 +104728,18 @@ var init_market = __esm({
|
|
|
104714
104728
|
return fromScaled(BigInt(ticks) * BigInt(tickScaled), market.priceDecimals);
|
|
104715
104729
|
};
|
|
104716
104730
|
symbolRefused = (message, reason = "invalid_order") => new Mt5RefusalError(message, { definitive: true, reason, metadataRetry: null }, { applied: false });
|
|
104731
|
+
mt5QuoteRate = (calc, pricedInAccountCurrency) => {
|
|
104732
|
+
if (pricedInAccountCurrency) return 1;
|
|
104733
|
+
const rate = Number(calc.tick_value) / (Number(calc.tick_size) * Number(calc.contract_size));
|
|
104734
|
+
return Number.isFinite(rate) && rate > 0 ? rate : null;
|
|
104735
|
+
};
|
|
104736
|
+
mt5ValuationRefused = (name) => symbolRefused(`MetaTrader 5 cannot value ${name} in the account's currency.`, "other");
|
|
104717
104737
|
readMt5Market = async (profileId, symbol2, accountState, signal) => {
|
|
104718
104738
|
const [[listed], state2] = await Promise.all([getMt5Markets(profileId, signal, symbol2), accountState(signal)]);
|
|
104719
104739
|
if (!listed) throw symbolRefused(`MetaTrader 5 does not list ${symbol2} for this account.`);
|
|
104720
104740
|
const name = listed.symbol;
|
|
104721
104741
|
const accountCurrency = String(state2.account.currency ?? "").trim();
|
|
104722
|
-
const
|
|
104723
|
-
if (!accountCurrency || profitCurrency !== accountCurrency) {
|
|
104724
|
-
throw symbolRefused(`${name} is not quoted in the account's currency; VTX trades only such MetaTrader 5 symbols.`, "other");
|
|
104725
|
-
}
|
|
104742
|
+
const pricedInAccountCurrency = accountCurrency !== "" && String(listed.quote_symbol ?? "").trim() === accountCurrency;
|
|
104726
104743
|
const stepDecimals = Number(listed.sz_decimals);
|
|
104727
104744
|
if (!Number.isInteger(stepDecimals) || stepDecimals < 0) {
|
|
104728
104745
|
throw new RuntimeReasonError(`MetaTrader 5 market figures for ${name} are malformed.`, "internal_data_error");
|
|
@@ -104734,6 +104751,7 @@ var init_market = __esm({
|
|
|
104734
104751
|
if (!(contractSize > 0) || !(Number(calc.volume_step) > 0) || !(Number(calc.tick_size) > 0)) {
|
|
104735
104752
|
throw new RuntimeReasonError(`MetaTrader 5 market figures for ${name} are malformed.`, "internal_data_error");
|
|
104736
104753
|
}
|
|
104754
|
+
if (mt5QuoteRate(calc, pricedInAccountCurrency) === null) throw mt5ValuationRefused(name);
|
|
104737
104755
|
return {
|
|
104738
104756
|
exchange: "mt5",
|
|
104739
104757
|
// The name the bridge reads and writes the market by.
|
|
@@ -104754,6 +104772,7 @@ var init_market = __esm({
|
|
|
104754
104772
|
point: DECIMAL_RADIX ** -priceDecimals,
|
|
104755
104773
|
stopsLevel: Number.isSafeInteger(calc.stops_level) && calc.stops_level > 0 ? calc.stops_level : 0,
|
|
104756
104774
|
accountCurrency,
|
|
104775
|
+
pricedInAccountCurrency,
|
|
104757
104776
|
marginMode: state2.account.margin_mode
|
|
104758
104777
|
};
|
|
104759
104778
|
};
|
|
@@ -104762,7 +104781,7 @@ var init_market = __esm({
|
|
|
104762
104781
|
|
|
104763
104782
|
// lib/runtime/exchange-executor/mt5/positions.ts
|
|
104764
104783
|
var OPENED_EARLIER, LOOKBACK_MS, CLOCK_ALLOWANCE_MS, CLOSING_ENTRIES, signed2, heldLots, readLookbackDeals, lookbackOnce, isTrade, mt5PositionOwners, vtxTradeDeals, mt5LegClosedBy, walkMt5Positions, mergeDeals, symbolTickets, createMt5Positions;
|
|
104765
|
-
var
|
|
104784
|
+
var init_positions2 = __esm({
|
|
104766
104785
|
"lib/runtime/exchange-executor/mt5/positions.ts"() {
|
|
104767
104786
|
"use strict";
|
|
104768
104787
|
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
@@ -105256,7 +105275,7 @@ var init_refusal_messages = __esm({
|
|
|
105256
105275
|
});
|
|
105257
105276
|
|
|
105258
105277
|
// lib/runtime/exchange-executor/mt5/reads.ts
|
|
105259
|
-
var mt5MarketKey, accountAndMarket, LEG_ORDER_TYPES, MT5_LEGS, vtxTickets, vtxOrders, legLevel, closingSide, signed3, signedUnits, latestUpdateMs, ticketsPosition, readMt5Position, readLeg, shownLevel, legRow, mt5HistoryBehindMessage, heldOpening, readMt5OpenOrders, terminalStatuses, evidence, unresolved, unknownOrder, legEnded, readHeldLegStatus, opensElsewhere, beginsInside, readLegStatus, HISTORY_ORDER_STATUSES, orderShape, filledEvidence, readTicketStatus, readClientIdStatus, readMt5OrderStatus, lookbackTradeDeals, readMt5Fills, readMt5Mark, readMt5BidAsk, readMt5Quote;
|
|
105278
|
+
var mt5MarketKey, accountAndMarket, LEG_ORDER_TYPES, MT5_LEGS, vtxTickets, vtxOrders, legLevel, closingSide, signed3, signedUnits, latestUpdateMs, ticketsPosition, readMt5Position, readLeg, shownLevel, legRow, mt5HistoryBehindMessage, heldOpening, readMt5OpenOrders, terminalStatuses, evidence, unresolved, unknownOrder, legEnded, readHeldLegStatus, opensElsewhere, beginsInside, readLegStatus, HISTORY_ORDER_STATUSES, orderShape, filledEvidence, readTicketStatus, readClientIdStatus, readMt5OrderStatus, lookbackTradeDeals, readMt5Fills, readMt5Mark, readMt5BidAsk, readMt5QuoteRate, readMt5Quote;
|
|
105260
105279
|
var init_reads = __esm({
|
|
105261
105280
|
"lib/runtime/exchange-executor/mt5/reads.ts"() {
|
|
105262
105281
|
"use strict";
|
|
@@ -105275,7 +105294,7 @@ var init_reads = __esm({
|
|
|
105275
105294
|
init_deal_fills();
|
|
105276
105295
|
init_refusal_messages();
|
|
105277
105296
|
init_market();
|
|
105278
|
-
|
|
105297
|
+
init_positions2();
|
|
105279
105298
|
mt5MarketKey = (name) => normalizeHyperliquidMarketSymbol(name);
|
|
105280
105299
|
accountAndMarket = async (deps, symbol2, signal) => {
|
|
105281
105300
|
const [state2, market] = await Promise.all([deps.accountState(signal), deps.market(symbol2, signal)]);
|
|
@@ -105312,7 +105331,8 @@ var init_reads = __esm({
|
|
|
105312
105331
|
};
|
|
105313
105332
|
readMt5Position = async (deps, symbol2, signal) => {
|
|
105314
105333
|
const [state2, market] = await accountAndMarket(deps, symbol2, signal);
|
|
105315
|
-
|
|
105334
|
+
const position = ticketsPosition(state2, market, await vtxTickets(deps, state2, symbol2, signal));
|
|
105335
|
+
return { ...position, quoteRate: await readMt5QuoteRate(deps, market, signal) };
|
|
105316
105336
|
};
|
|
105317
105337
|
readLeg = async (deps, symbol2, tickets, leg) => {
|
|
105318
105338
|
const levels = tickets.map((ticket) => legLevel(ticket[leg]));
|
|
@@ -105356,6 +105376,7 @@ var init_reads = __esm({
|
|
|
105356
105376
|
readMt5OpenOrders = async (deps, symbol2, signal) => {
|
|
105357
105377
|
const [state2, market] = await accountAndMarket(deps, symbol2, signal);
|
|
105358
105378
|
const orders = vtxOrders(state2, deps.profileId, symbol2);
|
|
105379
|
+
const rate = orders.length > 0 ? await readMt5QuoteRate(deps, market, signal) : 1;
|
|
105359
105380
|
const pending3 = mt5OpenOrderRows(orders, market.accountCurrency).map((row) => {
|
|
105360
105381
|
const order = orders.find((candidate) => candidate.ticket === row.oid);
|
|
105361
105382
|
const size = Number(lotsToUnits(market, String(order?.volume_current ?? "0")));
|
|
@@ -105364,7 +105385,8 @@ var init_reads = __esm({
|
|
|
105364
105385
|
coin: mt5MarketKey(row.coin),
|
|
105365
105386
|
sz: size,
|
|
105366
105387
|
orig_sz: Number(lotsToUnits(market, String(order?.volume_initial ?? "0"))),
|
|
105367
|
-
|
|
105388
|
+
// In the account's money (./market.ts mt5QuoteRate).
|
|
105389
|
+
order_value: row.limit_px * size * rate,
|
|
105368
105390
|
...row.is_trigger ? { trigger_px: row.limit_px } : {}
|
|
105369
105391
|
};
|
|
105370
105392
|
});
|
|
@@ -105621,9 +105643,10 @@ var init_reads = __esm({
|
|
|
105621
105643
|
hash: "",
|
|
105622
105644
|
crossed: true
|
|
105623
105645
|
}));
|
|
105646
|
+
const rate = trades.length > 0 ? await readMt5QuoteRate(deps, market, signal) : 1;
|
|
105624
105647
|
const tradeHistory = trades.map((trade, index) => {
|
|
105625
105648
|
const size = Number(rawFills[index].sz);
|
|
105626
|
-
return { ...trade, coin: mt5MarketKey(trade.coin), size, value: trade.price * size };
|
|
105649
|
+
return { ...trade, coin: mt5MarketKey(trade.coin), size, value: trade.price * size * rate };
|
|
105627
105650
|
});
|
|
105628
105651
|
return {
|
|
105629
105652
|
rawFills,
|
|
@@ -105643,6 +105666,13 @@ var init_reads = __esm({
|
|
|
105643
105666
|
const calc = await calcMt5Symbol(deps.profileId, { symbol: market.symbol, side: "buy", volume: market.volumeMin }, signal);
|
|
105644
105667
|
return { bid: calc.bid, ask: calc.ask };
|
|
105645
105668
|
};
|
|
105669
|
+
readMt5QuoteRate = async (deps, market, signal) => {
|
|
105670
|
+
if (market.pricedInAccountCurrency) return 1;
|
|
105671
|
+
const calc = await calcMt5Symbol(deps.profileId, { symbol: market.symbol, side: "buy", volume: market.volumeMin }, signal);
|
|
105672
|
+
const rate = mt5QuoteRate(calc, false);
|
|
105673
|
+
if (rate === null) throw mt5ValuationRefused(market.symbol);
|
|
105674
|
+
return rate;
|
|
105675
|
+
};
|
|
105646
105676
|
readMt5Quote = async (deps, symbol2, signal) => {
|
|
105647
105677
|
const market = await deps.market(symbol2, signal);
|
|
105648
105678
|
const calc = await calcMt5Symbol(deps.profileId, { symbol: market.symbol, side: "buy", volume: market.volumeMin }, signal);
|
|
@@ -105662,8 +105692,9 @@ var init_account = __esm({
|
|
|
105662
105692
|
init_define_VTX_PI_MODEL_POLICY();
|
|
105663
105693
|
init_mt5_trading();
|
|
105664
105694
|
init_constants();
|
|
105695
|
+
init_hyperliquid_account_contract();
|
|
105665
105696
|
init_market();
|
|
105666
|
-
|
|
105697
|
+
init_positions2();
|
|
105667
105698
|
init_reads();
|
|
105668
105699
|
amount = (text2) => {
|
|
105669
105700
|
const value = Number(text2);
|
|
@@ -105688,12 +105719,15 @@ var init_account = __esm({
|
|
|
105688
105719
|
leverage: state2.account.leverage,
|
|
105689
105720
|
margin_used: null,
|
|
105690
105721
|
liquidation_price: null,
|
|
105691
|
-
funding_usdc: tickets.reduce((total, ticket) => total + (amount(ticket.swap) ?? 0), 0)
|
|
105722
|
+
funding_usdc: tickets.reduce((total, ticket) => total + (amount(ticket.swap) ?? 0), 0),
|
|
105723
|
+
quote_rate: await readMt5QuoteRate(deps, market, signal)
|
|
105692
105724
|
};
|
|
105693
105725
|
};
|
|
105694
105726
|
tradable = async (deps, freeMargin, symbol2, signal) => {
|
|
105695
105727
|
const market = await deps.market(symbol2, signal);
|
|
105696
105728
|
const calc = await calcMt5Symbol(deps.profileId, { symbol: market.symbol, side: "buy", volume: market.volumeStep }, signal);
|
|
105729
|
+
const rate = mt5QuoteRate(calc, market.pricedInAccountCurrency);
|
|
105730
|
+
if (rate === null) throw mt5ValuationRefused(market.symbol);
|
|
105697
105731
|
const stepMargin = Number(calc.margin);
|
|
105698
105732
|
const mark = (Number(calc.bid) + Number(calc.ask)) / MIDPOINT_DIVISOR;
|
|
105699
105733
|
const steps = stepMargin > 0 ? Math.floor(Math.max(0, freeMargin) / stepMargin) : 0;
|
|
@@ -105702,28 +105736,48 @@ var init_account = __esm({
|
|
|
105702
105736
|
return {
|
|
105703
105737
|
symbol: mt5MarketKey(market.symbol),
|
|
105704
105738
|
market_type: "mt5",
|
|
105705
|
-
available_to_trade_buy: size * mark,
|
|
105706
|
-
available_to_trade_sell: size * mark,
|
|
105739
|
+
available_to_trade_buy: size * mark * rate,
|
|
105740
|
+
available_to_trade_sell: size * mark * rate,
|
|
105707
105741
|
max_trade_size_buy: size,
|
|
105708
105742
|
max_trade_size_sell: size,
|
|
105709
105743
|
mark_price: Number.isFinite(mark) ? mark : 0,
|
|
105744
|
+
quote_rate: rate,
|
|
105710
105745
|
source: "exchange"
|
|
105711
105746
|
};
|
|
105712
105747
|
};
|
|
105713
105748
|
mt5AccountSummary = (account) => {
|
|
105714
105749
|
const equity = amount(account.equity) ?? 0;
|
|
105715
105750
|
const freeMargin = amount(account.margin_free);
|
|
105751
|
+
const margin = amount(account.margin);
|
|
105752
|
+
const profit = amount(account.profit);
|
|
105716
105753
|
return {
|
|
105754
|
+
// The account is one margin pool on the default venue, which the prompt's
|
|
105755
|
+
// account and positions blocks read its figures from (prompt-collateral-contract.ts).
|
|
105756
|
+
// MetaTrader reports no maintenance margin or exposure, so those stay unknown.
|
|
105757
|
+
...margin !== null && freeMargin !== null && profit !== null ? {
|
|
105758
|
+
perp_dex_accounts: [{
|
|
105759
|
+
dex: "",
|
|
105760
|
+
account_value: equity,
|
|
105761
|
+
total_margin_used: margin,
|
|
105762
|
+
// As every pool's: equity less margin used, never below zero (MetaTrader's
|
|
105763
|
+
// free margin goes negative below a 100% margin level).
|
|
105764
|
+
available_margin: canonicalAvailableMargin(equity, margin),
|
|
105765
|
+
withdrawable: freeMargin,
|
|
105766
|
+
maintenance_margin: null,
|
|
105767
|
+
cross_account_leverage: null,
|
|
105768
|
+
total_unrealized_pnl: profit
|
|
105769
|
+
}]
|
|
105770
|
+
} : {},
|
|
105717
105771
|
account_value: equity,
|
|
105718
105772
|
venue_equity_usd: equity,
|
|
105719
105773
|
market_type: "mt5",
|
|
105720
|
-
total_margin_used:
|
|
105774
|
+
total_margin_used: margin,
|
|
105721
105775
|
available_margin: freeMargin,
|
|
105722
105776
|
withdrawable: freeMargin,
|
|
105723
105777
|
cross_margin_ratio: null,
|
|
105724
105778
|
maintenance_margin: null,
|
|
105725
105779
|
cross_account_leverage: null,
|
|
105726
|
-
total_unrealized_pnl:
|
|
105780
|
+
total_unrealized_pnl: profit,
|
|
105727
105781
|
// MetaTrader has no Hyperliquid account modes: its account is one margin account.
|
|
105728
105782
|
account_mode: "default",
|
|
105729
105783
|
mode_source: "canonical",
|
|
@@ -106049,7 +106103,7 @@ var init_account_scope = __esm({
|
|
|
106049
106103
|
init_define_VTX_EXO_POLICY();
|
|
106050
106104
|
init_define_VTX_GROK_POLICY();
|
|
106051
106105
|
init_define_VTX_PI_MODEL_POLICY();
|
|
106052
|
-
|
|
106106
|
+
init_positions2();
|
|
106053
106107
|
init_reads();
|
|
106054
106108
|
init_refusal_messages();
|
|
106055
106109
|
init_ticket_sides();
|
|
@@ -106071,7 +106125,7 @@ var init_account_scope = __esm({
|
|
|
106071
106125
|
};
|
|
106072
106126
|
readMt5AccountPosition = async (deps, symbol2, signal) => {
|
|
106073
106127
|
const [state2, market] = await accountAndMarket(deps, symbol2, signal);
|
|
106074
|
-
return ticketsPosition(state2, market, accountScopeTickets(state2, symbol2));
|
|
106128
|
+
return { ...ticketsPosition(state2, market, accountScopeTickets(state2, symbol2)), quoteRate: await readMt5QuoteRate(deps, market, signal) };
|
|
106075
106129
|
};
|
|
106076
106130
|
readMt5AccountOpenOrders = async (deps, symbol2, signal) => {
|
|
106077
106131
|
const state2 = await deps.accountState(signal);
|
|
@@ -106166,7 +106220,7 @@ var init_operations = __esm({
|
|
|
106166
106220
|
init_exchange();
|
|
106167
106221
|
init_identity();
|
|
106168
106222
|
init_market();
|
|
106169
|
-
|
|
106223
|
+
init_positions2();
|
|
106170
106224
|
init_account_scope();
|
|
106171
106225
|
init_reads();
|
|
106172
106226
|
init_stop_distance();
|
|
@@ -106442,6 +106496,16 @@ var init_operations = __esm({
|
|
|
106442
106496
|
members: placed.members.map((member, index) => index > 0 && refused ? { ...member, state: "rejected", refusal: PARTLY_SET } : member)
|
|
106443
106497
|
};
|
|
106444
106498
|
};
|
|
106499
|
+
const valued = async (input, answer2) => {
|
|
106500
|
+
if (!answer2.members.some((member) => member.state === "filled")) return answer2;
|
|
106501
|
+
try {
|
|
106502
|
+
const figures = await deps.market(input.symbol, input.signal);
|
|
106503
|
+
const quoteRate = await readMt5QuoteRate(deps, figures, input.signal);
|
|
106504
|
+
return { ...answer2, members: answer2.members.map((member) => member.state === "filled" ? { ...member, quoteRate } : member) };
|
|
106505
|
+
} catch {
|
|
106506
|
+
return answer2;
|
|
106507
|
+
}
|
|
106508
|
+
};
|
|
106445
106509
|
const placeOrder = async (input) => {
|
|
106446
106510
|
const { symbol: symbol2, side, intent } = input;
|
|
106447
106511
|
if (intent.kind === "trigger") {
|
|
@@ -106456,9 +106520,9 @@ var init_operations = __esm({
|
|
|
106456
106520
|
}
|
|
106457
106521
|
if (input.reduceOnly) {
|
|
106458
106522
|
if (intent.kind !== "market") throw refuseMt5Write("MetaTrader 5 has no reduce-only resting orders.", { reason: "reduce_only" });
|
|
106459
|
-
return closeTickets(input, intent);
|
|
106523
|
+
return valued(input, await closeTickets(input, intent));
|
|
106460
106524
|
}
|
|
106461
|
-
return enter(input, intent);
|
|
106525
|
+
return valued(input, await enter(input, intent));
|
|
106462
106526
|
};
|
|
106463
106527
|
const placeGroup = async (input) => {
|
|
106464
106528
|
const legOf = (member) => member.reduceOnly && member.intent.kind === "trigger" ? member.intent.isTakeProfit ? "tp" : "sl" : null;
|
|
@@ -106620,7 +106684,8 @@ var init_runtime_writes = __esm({
|
|
|
106620
106684
|
memberStatus = (member) => {
|
|
106621
106685
|
if (member.state === "filled") {
|
|
106622
106686
|
const oids = member.filledOrderIds ? { oids: member.filledOrderIds.map(Number) } : {};
|
|
106623
|
-
|
|
106687
|
+
const rate = member.quoteRate != null ? { quote_rate: member.quoteRate } : {};
|
|
106688
|
+
return { filled: { totalSz: String(member.filledSize), avgPx: String(member.avgPx), oid: Number(member.orderId), ...oids, ...rate } };
|
|
106624
106689
|
}
|
|
106625
106690
|
if (member.state === "open") return { resting: { oid: Number(member.orderId) } };
|
|
106626
106691
|
if (member.withheld) return { withheld: member.withheld };
|
|
@@ -106875,7 +106940,7 @@ var init_mt5 = __esm({
|
|
|
106875
106940
|
init_runtime_writes();
|
|
106876
106941
|
init_leg_writes();
|
|
106877
106942
|
init_market();
|
|
106878
|
-
|
|
106943
|
+
init_positions2();
|
|
106879
106944
|
init_account_scope();
|
|
106880
106945
|
init_reads();
|
|
106881
106946
|
refuse = refuseMt5Capability;
|
|
@@ -107017,7 +107082,8 @@ var init_mt5 = __esm({
|
|
|
107017
107082
|
realized_pnl: null,
|
|
107018
107083
|
leverage: null,
|
|
107019
107084
|
margin_used: null,
|
|
107020
|
-
liquidation_price: null
|
|
107085
|
+
liquidation_price: null,
|
|
107086
|
+
quote_rate: snapshot.quoteRate
|
|
107021
107087
|
};
|
|
107022
107088
|
},
|
|
107023
107089
|
orderStatusEvidence: async (input) => readMt5OrderStatus(deps, await listed(marketOf(input.symbol, "order-status"), input.signal), input.orderId, input.signal),
|
|
@@ -108080,6 +108146,24 @@ var init_protective_user_cancels = __esm({
|
|
|
108080
108146
|
}
|
|
108081
108147
|
});
|
|
108082
108148
|
|
|
108149
|
+
// lib/runtime/position-value.ts
|
|
108150
|
+
var quoteRateOf;
|
|
108151
|
+
var init_position_value = __esm({
|
|
108152
|
+
"lib/runtime/position-value.ts"() {
|
|
108153
|
+
"use strict";
|
|
108154
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
108155
|
+
init_define_VTX_EXO_POLICY();
|
|
108156
|
+
init_define_VTX_GROK_POLICY();
|
|
108157
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
108158
|
+
init_runtime_error_reason_rules();
|
|
108159
|
+
quoteRateOf = (rate) => {
|
|
108160
|
+
if (rate == null) return 1;
|
|
108161
|
+
if (!(Number.isFinite(rate) && rate > 0)) throw new RuntimeReasonError(`A market's quote rate is invalid (${rate}).`, "internal_data_error");
|
|
108162
|
+
return rate;
|
|
108163
|
+
};
|
|
108164
|
+
}
|
|
108165
|
+
});
|
|
108166
|
+
|
|
108083
108167
|
// lib/runtime/prompt-number-contract.ts
|
|
108084
108168
|
var finiteNumber3, roundPromptFixed, roundPromptSignificant, roundPromptRelativeVolume, roundPromptNonnegativeUnits;
|
|
108085
108169
|
var init_prompt_number_contract = __esm({
|
|
@@ -108148,7 +108232,7 @@ var init_prompt_number_contract = __esm({
|
|
|
108148
108232
|
});
|
|
108149
108233
|
|
|
108150
108234
|
// lib/runtime/execution-guard-contract.ts
|
|
108151
|
-
var unitsFromPosition, signedUnitsFromPosition, signedUnitsFromEntryPosition, classifyExecutionIntent, reductionFirstOrder, orderMetadataRetryReason, copyClosingSize, copyOrderClosingSize, copyOrderNotionalCap, resolveExecutionTarget, decisionOrderSizeAsset, flipExecutionLegs, executedOrderPositionEvent;
|
|
108235
|
+
var unitsFromPosition, signedUnitsFromPosition, signedUnitsFromEntryPosition, contextSignedUnits, signedUnitsOfPosition, classifyExecutionIntent, reductionFirstOrder, orderMetadataRetryReason, copyClosingSize, copyOrderClosingSize, copyOrderNotionalCap, resolveExecutionTarget, decisionOrderSizeAsset, flipExecutionLegs, executedOrderPositionEvent;
|
|
108152
108236
|
var init_execution_guard_contract = __esm({
|
|
108153
108237
|
"lib/runtime/execution-guard-contract.ts"() {
|
|
108154
108238
|
"use strict";
|
|
@@ -108157,8 +108241,9 @@ var init_execution_guard_contract = __esm({
|
|
|
108157
108241
|
init_define_VTX_GROK_POLICY();
|
|
108158
108242
|
init_define_VTX_PI_MODEL_POLICY();
|
|
108159
108243
|
init_constants();
|
|
108244
|
+
init_position_value();
|
|
108160
108245
|
init_prompt_number_contract();
|
|
108161
|
-
unitsFromPosition = (size, price, unitSizeUsdc) => {
|
|
108246
|
+
unitsFromPosition = (size, price, unitSizeUsdc, quoteRate) => {
|
|
108162
108247
|
const sizeValue = Number(size ?? 0);
|
|
108163
108248
|
const priceValue = Number(price ?? 0);
|
|
108164
108249
|
const unitSizeValue = Number(unitSizeUsdc ?? 0);
|
|
@@ -108168,17 +108253,17 @@ var init_execution_guard_contract = __esm({
|
|
|
108168
108253
|
if (sizeValue === 0 || priceValue <= 0 || unitSizeValue <= 0) {
|
|
108169
108254
|
return 0;
|
|
108170
108255
|
}
|
|
108171
|
-
return Math.max(1, roundPromptNonnegativeUnits(Math.abs(sizeValue * priceValue) / unitSizeValue));
|
|
108256
|
+
return Math.max(1, roundPromptNonnegativeUnits(Math.abs(sizeValue * priceValue * quoteRateOf(quoteRate)) / unitSizeValue));
|
|
108172
108257
|
};
|
|
108173
|
-
signedUnitsFromPosition = (size, price, unitSizeUsdc) => {
|
|
108174
|
-
const units = unitsFromPosition(size, price, unitSizeUsdc);
|
|
108258
|
+
signedUnitsFromPosition = (size, price, unitSizeUsdc, quoteRate) => {
|
|
108259
|
+
const units = unitsFromPosition(size, price, unitSizeUsdc, quoteRate);
|
|
108175
108260
|
const sizeValue = Number(size ?? 0);
|
|
108176
108261
|
if (!Number.isFinite(sizeValue)) {
|
|
108177
108262
|
return 0;
|
|
108178
108263
|
}
|
|
108179
108264
|
return sizeValue < 0 ? -units : units;
|
|
108180
108265
|
};
|
|
108181
|
-
signedUnitsFromEntryPosition = (size, entryPrice, unitSizeUsdc) => {
|
|
108266
|
+
signedUnitsFromEntryPosition = (size, entryPrice, unitSizeUsdc, quoteRate) => {
|
|
108182
108267
|
const sizeValue = Number(size);
|
|
108183
108268
|
if (!Number.isFinite(sizeValue)) throw new Error("Position size is invalid for execution unit classification.");
|
|
108184
108269
|
if (sizeValue === 0) return 0;
|
|
@@ -108187,8 +108272,15 @@ var init_execution_guard_contract = __esm({
|
|
|
108187
108272
|
if (!Number.isFinite(entry) || entry <= 0 || !Number.isFinite(unit) || unit <= 0) {
|
|
108188
108273
|
throw new Error("Position entry price and unit size must be positive for execution unit classification.");
|
|
108189
108274
|
}
|
|
108190
|
-
return signedUnitsFromPosition(sizeValue, entry, unit);
|
|
108275
|
+
return signedUnitsFromPosition(sizeValue, entry, unit, quoteRate);
|
|
108191
108276
|
};
|
|
108277
|
+
contextSignedUnits = (context) => signedUnitsFromEntryPosition(
|
|
108278
|
+
Number.isFinite(context.currentPositionSize) ? context.currentPositionSize : 0,
|
|
108279
|
+
context.currentPositionEntryPrice,
|
|
108280
|
+
context.unitSizeUsdc,
|
|
108281
|
+
quoteRateOf(context.currentPositionQuoteRate)
|
|
108282
|
+
);
|
|
108283
|
+
signedUnitsOfPosition = (position, unitSize) => signedUnitsFromEntryPosition(position.size, position.entry_price, unitSize, quoteRateOf(position.quote_rate));
|
|
108192
108284
|
classifyExecutionIntent = (action, requestedUnits, snapshotSignedUnits) => {
|
|
108193
108285
|
const actionNormalized = String(action ?? "HOLD").trim().toUpperCase();
|
|
108194
108286
|
const parsedUnits = Number.parseInt(String(Number(requestedUnits ?? 0)), DECIMAL_RADIX);
|
|
@@ -108417,7 +108509,7 @@ var init_execution_guard_contract = __esm({
|
|
|
108417
108509
|
};
|
|
108418
108510
|
decisionOrderSizeAsset = (input) => {
|
|
108419
108511
|
const units = Number(input.orderUnits);
|
|
108420
|
-
const unitSize = Number(input.unitSizeUsdc);
|
|
108512
|
+
const unitSize = Number(input.unitSizeUsdc) / quoteRateOf(input.quoteRate);
|
|
108421
108513
|
if (!(Number.isFinite(units) && units > 0 && Number.isFinite(unitSize) && unitSize > 0)) return 0;
|
|
108422
108514
|
if (input.intent === "reduce") {
|
|
108423
108515
|
const entry = Number(input.entryPrice);
|
|
@@ -109169,14 +109261,15 @@ var init_execution_capacity = __esm({
|
|
|
109169
109261
|
init_define_VTX_PI_MODEL_POLICY();
|
|
109170
109262
|
init_constraint_contract();
|
|
109171
109263
|
init_execution_guard_contract();
|
|
109264
|
+
init_position_value();
|
|
109172
109265
|
init_hyperliquid_market_symbol();
|
|
109173
|
-
capacityUnitsUsedForPosition = (
|
|
109266
|
+
capacityUnitsUsedForPosition = (position, unitSize) => unitsFromPosition(position.size, position.entry_price, unitSize, quoteRateOf(position.quote_rate));
|
|
109174
109267
|
openCapacityRoom = (positions, limits) => {
|
|
109175
109268
|
let globalUnits = 0;
|
|
109176
109269
|
const exchangeUsage = /* @__PURE__ */ new Map();
|
|
109177
109270
|
for (const position of positions) {
|
|
109178
109271
|
if (Number(position.size) === 0) continue;
|
|
109179
|
-
const used = capacityUnitsUsedForPosition(position
|
|
109272
|
+
const used = capacityUnitsUsedForPosition(position, limits.capacity_unit_size);
|
|
109180
109273
|
globalUnits += used;
|
|
109181
109274
|
if (position.symbol) {
|
|
109182
109275
|
const dex = getHyperliquidMarketDex(position.symbol);
|
|
@@ -109191,7 +109284,7 @@ var init_execution_capacity = __esm({
|
|
|
109191
109284
|
const signedUnits2 = (symbol2) => {
|
|
109192
109285
|
const normalized = normalizeHyperliquidMarketSymbol(symbol2);
|
|
109193
109286
|
const position = positions.find((candidate) => normalizeHyperliquidMarketSymbol(candidate.symbol) === normalized);
|
|
109194
|
-
return position ?
|
|
109287
|
+
return position ? signedUnitsOfPosition(position, limits.unit_size) : 0;
|
|
109195
109288
|
};
|
|
109196
109289
|
const remainingExchange = (symbol2) => remainingExchangeByDex.get(getHyperliquidMarketDex(symbol2)) ?? exchangeLimit;
|
|
109197
109290
|
return {
|
|
@@ -109246,6 +109339,74 @@ var init_execution_capacity = __esm({
|
|
|
109246
109339
|
}
|
|
109247
109340
|
});
|
|
109248
109341
|
|
|
109342
|
+
// lib/runtime/server-execution-capacity.ts
|
|
109343
|
+
var runtimeReadPositions, allocateServerExecutionCapacity;
|
|
109344
|
+
var init_server_execution_capacity = __esm({
|
|
109345
|
+
"lib/runtime/server-execution-capacity.ts"() {
|
|
109346
|
+
"use strict";
|
|
109347
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
109348
|
+
init_define_VTX_EXO_POLICY();
|
|
109349
|
+
init_define_VTX_GROK_POLICY();
|
|
109350
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
109351
|
+
init_api2();
|
|
109352
|
+
init_abort();
|
|
109353
|
+
init_exchange_executor();
|
|
109354
|
+
init_execution_capacity();
|
|
109355
|
+
init_network_debug();
|
|
109356
|
+
runtimeReadPositions = async (authority, symbol2) => {
|
|
109357
|
+
if (executorOf(authority.config).exchange !== "mt5") return void 0;
|
|
109358
|
+
const { positions } = await exchangeReads.accountState({
|
|
109359
|
+
publicRequestPriority: "trading_execute",
|
|
109360
|
+
config: authority.config ?? {},
|
|
109361
|
+
walletAddress: "",
|
|
109362
|
+
symbol: symbol2,
|
|
109363
|
+
tickerPrice: 0,
|
|
109364
|
+
leverage: 1,
|
|
109365
|
+
forceRefresh: true,
|
|
109366
|
+
sessionId: authority.sessionId,
|
|
109367
|
+
signal: authority.signal
|
|
109368
|
+
});
|
|
109369
|
+
return positions.map((position) => ({
|
|
109370
|
+
symbol: position.symbol,
|
|
109371
|
+
size: Number(position.size),
|
|
109372
|
+
entry_price: position.entry_price ?? null,
|
|
109373
|
+
// What its price times its size is worth in the account's money (web/lib/api/positions.ts).
|
|
109374
|
+
...position.quote_rate != null ? { quote_rate: position.quote_rate } : {}
|
|
109375
|
+
}));
|
|
109376
|
+
};
|
|
109377
|
+
allocateServerExecutionCapacity = async (authority, plans, cycleStartedAt) => {
|
|
109378
|
+
if (plans.length === 0) return [];
|
|
109379
|
+
try {
|
|
109380
|
+
const positions = await runtimeReadPositions(authority, plans[0].symbol);
|
|
109381
|
+
const answer2 = await checkServerHostExecutionCapacity(
|
|
109382
|
+
authority.profileId,
|
|
109383
|
+
plans,
|
|
109384
|
+
authority.signal,
|
|
109385
|
+
authority.sessionId,
|
|
109386
|
+
authority.runtimeLeaseToken,
|
|
109387
|
+
authority.runtimeDeviceId,
|
|
109388
|
+
authority.schedulerInstanceId,
|
|
109389
|
+
cycleStartedAt,
|
|
109390
|
+
...positions ? [positions] : []
|
|
109391
|
+
);
|
|
109392
|
+
if (!answer2.positions || !answer2.limits) return answer2.results;
|
|
109393
|
+
const judged = allocatePlanCapacity(answer2.positions, plans, answer2.limits);
|
|
109394
|
+
const shadow = answer2.results.map((result) => `${result.symbol}:${result.accepted}:${result.units}`).join(",");
|
|
109395
|
+
const own = judged.map((result) => `${result.symbol}:${result.accepted}:${result.units}`).join(",");
|
|
109396
|
+
if (shadow !== own) {
|
|
109397
|
+
const note = `profile_id=${authority.profileId} runtime=${own} server=${shadow}`;
|
|
109398
|
+
appendRuntimeDebugEvent({ label: "server_capacity_shadow_differs", note, outcome: "error" });
|
|
109399
|
+
console.warn(`event=server_capacity_shadow_differs service=vtx-server-runtime-host ${note}`);
|
|
109400
|
+
}
|
|
109401
|
+
return judged;
|
|
109402
|
+
} catch (error48) {
|
|
109403
|
+
throwIfAborted(authority.signal);
|
|
109404
|
+
return plans.map(() => ({ unavailable: error48 }));
|
|
109405
|
+
}
|
|
109406
|
+
};
|
|
109407
|
+
}
|
|
109408
|
+
});
|
|
109409
|
+
|
|
109249
109410
|
// lib/runtime/owed-protection-warnings.ts
|
|
109250
109411
|
var storageKey, configuredStorage2, owedStorage, isWarning, identity2, owesProtectionWarning, owesProtectionRecord, distinctProtectionWarnings, owedProtectionWarnings, store, oweProtectionWarnings, forgetProtectionWarnings;
|
|
109251
109412
|
var init_owed_protection_warnings = __esm({
|
|
@@ -109424,6 +109585,7 @@ var init_native_position_protection = __esm({
|
|
|
109424
109585
|
init_constants();
|
|
109425
109586
|
init_hyperliquid_client();
|
|
109426
109587
|
init_hyperliquid_market_symbol();
|
|
109588
|
+
init_position_value();
|
|
109427
109589
|
init_hyperliquid_order_status();
|
|
109428
109590
|
init_order_identity();
|
|
109429
109591
|
init_protective_stop_replacement();
|
|
@@ -109449,7 +109611,7 @@ var init_native_position_protection = __esm({
|
|
|
109449
109611
|
}
|
|
109450
109612
|
};
|
|
109451
109613
|
nativePositionTriggerPrice = (input) => {
|
|
109452
|
-
const size = Math.abs(input.positionSize);
|
|
109614
|
+
const size = Math.abs(input.positionSize) * quoteRateOf(input.quoteRate);
|
|
109453
109615
|
if (!(input.averageEntry > 0) || !(input.value > 0) || input.mode === "usdc" && !(size > 0)) return null;
|
|
109454
109616
|
const away = input.kind === "tp" === input.isLong;
|
|
109455
109617
|
const raw = input.mode === "percent" ? away ? input.averageEntry * (1 + input.value / PERCENT_SCALE) : input.averageEntry * (1 - input.value / PERCENT_SCALE) : away ? input.averageEntry + input.value / size : input.averageEntry - input.value / size;
|
|
@@ -109471,7 +109633,8 @@ var init_native_position_protection = __esm({
|
|
|
109471
109633
|
kind,
|
|
109472
109634
|
mode: setting2.mode,
|
|
109473
109635
|
value: setting2.value,
|
|
109474
|
-
sizeDecimals: input.sizeDecimals
|
|
109636
|
+
sizeDecimals: input.sizeDecimals,
|
|
109637
|
+
quoteRate: input.quoteRate
|
|
109475
109638
|
});
|
|
109476
109639
|
if (trigger !== null) children.push({ kind, trigger });
|
|
109477
109640
|
}
|
|
@@ -109516,7 +109679,8 @@ var init_native_position_protection = __esm({
|
|
|
109516
109679
|
kind,
|
|
109517
109680
|
mode: setting2.mode,
|
|
109518
109681
|
value: setting2.value,
|
|
109519
|
-
sizeDecimals: input.sizeDecimals
|
|
109682
|
+
sizeDecimals: input.sizeDecimals,
|
|
109683
|
+
quoteRate: input.position.quoteRate
|
|
109520
109684
|
});
|
|
109521
109685
|
if (trigger === null) continue;
|
|
109522
109686
|
const resting = input.resting[kind];
|
|
@@ -110727,6 +110891,7 @@ var init_native_protection_device = __esm({
|
|
|
110727
110891
|
sizeDecimals: input.sizeDecimals,
|
|
110728
110892
|
referencePrice: input.referencePrice,
|
|
110729
110893
|
entrySize: input.entrySize,
|
|
110894
|
+
quoteRate: input.quoteRate,
|
|
110730
110895
|
positionBefore: input.positionBefore,
|
|
110731
110896
|
positionHasLegacyLegs: input.positionHasLegacyLegs
|
|
110732
110897
|
});
|
|
@@ -111200,7 +111365,7 @@ var init_native_protection_device = __esm({
|
|
|
111200
111365
|
settings: { ...input.settings, stopLoss: input.settings.stopLoss && { ...input.settings.stopLoss, trailing: false } },
|
|
111201
111366
|
isLong: record6.isLong,
|
|
111202
111367
|
sizeDecimals: input.sizeDecimals,
|
|
111203
|
-
position: { size: position.size, entryPrice: position.entryPrice },
|
|
111368
|
+
position: { size: position.size, entryPrice: position.entryPrice, quoteRate: position.quoteRate },
|
|
111204
111369
|
fillSize: input.fillSize,
|
|
111205
111370
|
resting: { sl: restingTrigger("sl"), tp: restingTrigger("tp") }
|
|
111206
111371
|
});
|
|
@@ -111498,7 +111663,8 @@ var init_native_protection_device = __esm({
|
|
|
111498
111663
|
kind: member.kind,
|
|
111499
111664
|
mode: setting2.mode,
|
|
111500
111665
|
value: setting2.value,
|
|
111501
|
-
sizeDecimals: input.sizeDecimals
|
|
111666
|
+
sizeDecimals: input.sizeDecimals,
|
|
111667
|
+
quoteRate: position.quoteRate
|
|
111502
111668
|
}) : null;
|
|
111503
111669
|
};
|
|
111504
111670
|
const kindEnabled = (member) => (member.kind === "sl" ? input.settings.stopLoss : input.settings.takeProfit) != null;
|
|
@@ -111516,7 +111682,7 @@ var init_native_protection_device = __esm({
|
|
|
111516
111682
|
settings: { ...input.settings, stopLoss: input.settings.stopLoss && { ...input.settings.stopLoss, trailing: false } },
|
|
111517
111683
|
isLong: record6.isLong,
|
|
111518
111684
|
sizeDecimals: input.sizeDecimals,
|
|
111519
|
-
position: { size: position.size, entryPrice: position.entryPrice },
|
|
111685
|
+
position: { size: position.size, entryPrice: position.entryPrice, quoteRate: position.quoteRate },
|
|
111520
111686
|
fillSize: "0",
|
|
111521
111687
|
resting: { sl: restingTrigger("sl"), tp: restingTrigger("tp") }
|
|
111522
111688
|
})) {
|
|
@@ -112177,7 +112343,7 @@ var init_native_protection_device = __esm({
|
|
|
112177
112343
|
});
|
|
112178
112344
|
|
|
112179
112345
|
// lib/runtime/runtime-execution.ts
|
|
112180
|
-
var executionQueueTimeout, withClientProtectivePlanSetMutation2, clientProtectiveMutationAuthority, executionReadPriority, serverEntryLeverageAlreadyHeld, createRuntimeId, trailingStopMemory, protectiveGroupMemory, protectiveGroupReadFailures, windowHandoffCleanupAttempts, clientRuntimeProtectionStorage, resolveClientRuntimeProtectionStorage, setClientRuntimeProtectionStorage, readTrackedTrailingStops, writeTrackedTrailingStops, rememberTrailingStop, LOST_LEG_EVIDENCE_MAX_AGE_MS, EPISODE_END_FILL_LOOKBACK_MS, readClientProtectiveGroups, writeClientProtectiveGroups, hasClientProtectiveGroupReadFailure, readFreshClientProtectiveGroups, exactClientProtectiveGroupSnapshot, exactClientProtectiveGroupSetSnapshot, storableClientProtectiveGroup, replaceExactClientProtectiveGroup, replaceExactClientProtectiveGroupSet, isClientRuntimeLeaseOwnershipError, hasClientRuntimeProtectionState, clearClientRuntimeVetoedProtectiveIntent, rethrowWindowHandoffAfterProtectiveReplacementVeto, canPersistClientProtectiveGroups, removeTrackedTrailingStop, replaceTrackedTrailingStop, replacementJournalEntryOrderId, buildProtectiveReplacementJournalGroup, isProtectiveReplacementJournalGroup, reserveProtectiveLegReplacement, ensureProtectiveReplacementJournalCompanion, buildVetoedProtectiveReplacementCleanup, assertExactProtectiveReplacementDispatchAuthority, transitionProtectiveReplacementAcknowledgement, transitionTerminalProtectiveReplacement, isConfiguredProtectionRequested, protectiveAction, isExactClientPositionTpslPair, deviceOwnsClientProtectiveLegKind, isAdoptionNarrowedPositionTpslLeg, hasAmbiguousClientPositionTpslAuthority, protectiveTerminalShapeMatches, cancelClientProtectiveLeg, persistPendingClientProtectiveGroup, readAttachEvidence, attachClientProtectivePlan, resolveJournaledAttachmentContinuity, journaledAttachmentNeverLanded, recoverJournaledClientProtectiveAttachments, readClientOrderMutation, readPendingEntryMutation, replacePendingEntryRecovery, recoverPendingClientProtectiveGroups, recoverPendingProtectiveReplacements, observedStandaloneProtectiveGroup, migrateTrackedTrailingStopsToStandalone, nativeSettingsOf, nativePassEnded, nativeProtectionIo, nativeStorageReport, reconcileNativeProtectionForDecision, reconcileClientProtectiveGroups, cancelAllClientProtectiveGroups, modifyClientTrailingLeg, trailingRatchetIo, resolveExchangeSizeDecimals, readServerOrderMarkPrice, serverOrderMetadataRetry, resolveCurrentPositionSize, buildPositionSnapshot, serverUserCancelLookup, passUserCancelsFor, verifyNoLiveClientProtectiveTriggers,
|
|
112346
|
+
var executionQueueTimeout, withClientProtectivePlanSetMutation2, clientProtectiveMutationAuthority, executionReadPriority, serverEntryLeverageAlreadyHeld, createRuntimeId, trailingStopMemory, protectiveGroupMemory, protectiveGroupReadFailures, windowHandoffCleanupAttempts, clientRuntimeProtectionStorage, resolveClientRuntimeProtectionStorage, setClientRuntimeProtectionStorage, readTrackedTrailingStops, writeTrackedTrailingStops, rememberTrailingStop, LOST_LEG_EVIDENCE_MAX_AGE_MS, EPISODE_END_FILL_LOOKBACK_MS, readClientProtectiveGroups, writeClientProtectiveGroups, hasClientProtectiveGroupReadFailure, readFreshClientProtectiveGroups, exactClientProtectiveGroupSnapshot, exactClientProtectiveGroupSetSnapshot, storableClientProtectiveGroup, replaceExactClientProtectiveGroup, replaceExactClientProtectiveGroupSet, isClientRuntimeLeaseOwnershipError, hasClientRuntimeProtectionState, clearClientRuntimeVetoedProtectiveIntent, rethrowWindowHandoffAfterProtectiveReplacementVeto, canPersistClientProtectiveGroups, removeTrackedTrailingStop, replaceTrackedTrailingStop, replacementJournalEntryOrderId, buildProtectiveReplacementJournalGroup, isProtectiveReplacementJournalGroup, reserveProtectiveLegReplacement, ensureProtectiveReplacementJournalCompanion, buildVetoedProtectiveReplacementCleanup, assertExactProtectiveReplacementDispatchAuthority, transitionProtectiveReplacementAcknowledgement, transitionTerminalProtectiveReplacement, isConfiguredProtectionRequested, protectiveAction, isExactClientPositionTpslPair, deviceOwnsClientProtectiveLegKind, isAdoptionNarrowedPositionTpslLeg, hasAmbiguousClientPositionTpslAuthority, protectiveTerminalShapeMatches, cancelClientProtectiveLeg, persistPendingClientProtectiveGroup, readAttachEvidence, attachClientProtectivePlan, resolveJournaledAttachmentContinuity, journaledAttachmentNeverLanded, recoverJournaledClientProtectiveAttachments, readClientOrderMutation, readPendingEntryMutation, replacePendingEntryRecovery, recoverPendingClientProtectiveGroups, recoverPendingProtectiveReplacements, observedStandaloneProtectiveGroup, migrateTrackedTrailingStopsToStandalone, nativeSettingsOf, nativePassEnded, nativeProtectionIo, nativeStorageReport, reconcileNativeProtectionForDecision, reconcileClientProtectiveGroups, cancelAllClientProtectiveGroups, modifyClientTrailingLeg, trailingRatchetIo, resolveExchangeSizeDecimals, readServerOrderMarkPrice, serverOrderMetadataRetry, resolveCurrentPositionSize, buildPositionSnapshot, serverUserCancelLookup, passUserCancelsFor, verifyNoLiveClientProtectiveTriggers, executeClientRuntimeDecisionLocked, unsentDecisionOrderReport, SERVER_AUDIT_RECORDED_ELSEWHERE, serverExecutionAuditOutcome, decisionLegOf, withExecutionAuditId, executeClientRuntimeDecision, waitForFlipCloseFreshness, nextClientTrailingStopDueAtMs, ratchetClientTrailingStopsBetweenCycles, handedOverPlan, listPendingClientProtectiveSymbols, hasPendingClientProtectiveGroups, recoverManualClientProtectiveGroups, listStoredClientProtectionSymbols, clientRuntimeDecisionSizesOrders, COMMITTED_EXECUTION_REPORTS, COMMITTED_DECISION_ORDER, getCommittedExecutionReports, getCommittedDecisionOrder, withCommittedExecutionReports, executeClientRuntimeDecisionUnlocked;
|
|
112181
112347
|
var init_runtime_execution = __esm({
|
|
112182
112348
|
"lib/runtime/runtime-execution.ts"() {
|
|
112183
112349
|
"use strict";
|
|
@@ -112201,6 +112367,7 @@ var init_runtime_execution = __esm({
|
|
|
112201
112367
|
init_protective_user_cancels();
|
|
112202
112368
|
init_hyperliquid_order_status();
|
|
112203
112369
|
init_execution_capacity();
|
|
112370
|
+
init_server_execution_capacity();
|
|
112204
112371
|
init_pending_entry_fill_proof();
|
|
112205
112372
|
init_owed_protection_warnings();
|
|
112206
112373
|
init_protective_group_snapshot();
|
|
@@ -112209,6 +112376,7 @@ var init_runtime_execution = __esm({
|
|
|
112209
112376
|
init_manual_order_children();
|
|
112210
112377
|
init_execution_sizes();
|
|
112211
112378
|
init_execution_guard_contract();
|
|
112379
|
+
init_position_value();
|
|
112212
112380
|
init_hyperliquid_client();
|
|
112213
112381
|
init_exchange_rejection();
|
|
112214
112382
|
init_hyperliquid_market_symbol();
|
|
@@ -112243,12 +112411,7 @@ var init_runtime_execution = __esm({
|
|
|
112243
112411
|
}
|
|
112244
112412
|
);
|
|
112245
112413
|
executionReadPriority = (input) => {
|
|
112246
|
-
const
|
|
112247
|
-
const classified = classifyExecutionIntent(
|
|
112248
|
-
input.decision,
|
|
112249
|
-
input.units,
|
|
112250
|
-
signedUnitsFromEntryPosition(context.currentPositionSize, context.currentPositionEntryPrice, context.unitSizeUsdc)
|
|
112251
|
-
);
|
|
112414
|
+
const classified = classifyExecutionIntent(input.decision, input.units, contextSignedUnits(input.executionContext));
|
|
112252
112415
|
return classified.reduceOnly ? "trading_reduce" : "trading_execute";
|
|
112253
112416
|
};
|
|
112254
112417
|
serverEntryLeverageAlreadyHeld = async (input) => {
|
|
@@ -113360,7 +113523,7 @@ var init_runtime_execution = __esm({
|
|
|
113360
113523
|
candidate.mode,
|
|
113361
113524
|
candidate.mode === "percent" ? candidate.value : void 0,
|
|
113362
113525
|
candidate.mode === "usdc" ? candidate.value : void 0,
|
|
113363
|
-
fill.averagePrice * size
|
|
113526
|
+
fill.averagePrice * size * quoteRateOf(snapshot.quoteRate)
|
|
113364
113527
|
),
|
|
113365
113528
|
isLong,
|
|
113366
113529
|
candidate.kind === "tp"
|
|
@@ -116991,6 +117154,7 @@ var init_runtime_execution = __esm({
|
|
|
116991
117154
|
return {
|
|
116992
117155
|
currentPositionSize: Number.isFinite(refreshedPosition) ? refreshedPosition : snapshotPositionSize,
|
|
116993
117156
|
currentPositionEntryPrice: refreshedPositionSnapshot?.entry_price ?? null,
|
|
117157
|
+
currentQuoteRate: quoteRateOf(refreshedPositionSnapshot?.quote_rate ?? refreshed.availableToTrade.quote_rate),
|
|
116994
117158
|
currentMarkPrice: refreshedPrice,
|
|
116995
117159
|
executionPrice: refreshedPrice ?? decisionPrice,
|
|
116996
117160
|
executionSnapshotId: createRuntimeId(),
|
|
@@ -117019,6 +117183,7 @@ var init_runtime_execution = __esm({
|
|
|
117019
117183
|
return {
|
|
117020
117184
|
currentPositionSize: Number.isFinite(parsedLiveSize) ? parsedLiveSize : snapshotPositionSize,
|
|
117021
117185
|
currentPositionEntryPrice: liveBrowserSnapshot.entryPrice,
|
|
117186
|
+
currentQuoteRate: quoteRateOf(liveBrowserSnapshot.quoteRate),
|
|
117022
117187
|
currentMarkPrice: liveMarkPrice,
|
|
117023
117188
|
executionPrice,
|
|
117024
117189
|
executionSnapshotId: createRuntimeId(),
|
|
@@ -117087,34 +117252,6 @@ var init_runtime_execution = __esm({
|
|
|
117087
117252
|
return { blocksEntry: false, reports: [] };
|
|
117088
117253
|
}
|
|
117089
117254
|
};
|
|
117090
|
-
allocateServerExecutionCapacity = async (authority, plans, cycleStartedAt) => {
|
|
117091
|
-
if (plans.length === 0) return [];
|
|
117092
|
-
try {
|
|
117093
|
-
const answer2 = await checkServerHostExecutionCapacity(
|
|
117094
|
-
authority.profileId,
|
|
117095
|
-
plans,
|
|
117096
|
-
authority.signal,
|
|
117097
|
-
authority.sessionId,
|
|
117098
|
-
authority.runtimeLeaseToken,
|
|
117099
|
-
authority.runtimeDeviceId,
|
|
117100
|
-
authority.schedulerInstanceId,
|
|
117101
|
-
cycleStartedAt
|
|
117102
|
-
);
|
|
117103
|
-
if (!answer2.positions || !answer2.limits) return answer2.results;
|
|
117104
|
-
const judged = allocatePlanCapacity(answer2.positions, plans, answer2.limits);
|
|
117105
|
-
const shadow = answer2.results.map((result) => `${result.symbol}:${result.accepted}:${result.units}`).join(",");
|
|
117106
|
-
const own = judged.map((result) => `${result.symbol}:${result.accepted}:${result.units}`).join(",");
|
|
117107
|
-
if (shadow !== own) {
|
|
117108
|
-
const note = `profile_id=${authority.profileId} runtime=${own} server=${shadow}`;
|
|
117109
|
-
appendRuntimeDebugEvent({ label: "server_capacity_shadow_differs", note, outcome: "error" });
|
|
117110
|
-
console.warn(`event=server_capacity_shadow_differs service=vtx-server-runtime-host ${note}`);
|
|
117111
|
-
}
|
|
117112
|
-
return judged;
|
|
117113
|
-
} catch (error48) {
|
|
117114
|
-
throwIfAborted(authority.signal);
|
|
117115
|
-
return plans.map(() => ({ unavailable: error48 }));
|
|
117116
|
-
}
|
|
117117
|
-
};
|
|
117118
117255
|
executeClientRuntimeDecisionLocked = (input) => withClientProtectivePlanSetMutation2(input, input.executionContext.symbol, async () => {
|
|
117119
117256
|
const progress = { committedReports: null };
|
|
117120
117257
|
try {
|
|
@@ -117512,11 +117649,7 @@ var init_runtime_execution = __esm({
|
|
|
117512
117649
|
side: null,
|
|
117513
117650
|
reduceOnly: false,
|
|
117514
117651
|
requestedUnits,
|
|
117515
|
-
targetSignedUnits:
|
|
117516
|
-
Number.isFinite(unsizedInput.executionContext.currentPositionSize) ? Number(unsizedInput.executionContext.currentPositionSize) : 0,
|
|
117517
|
-
unsizedInput.executionContext.currentPositionEntryPrice,
|
|
117518
|
-
unsizedInput.executionContext.unitSizeUsdc
|
|
117519
|
-
),
|
|
117652
|
+
targetSignedUnits: contextSignedUnits(unsizedInput.executionContext),
|
|
117520
117653
|
executedSizeAsset: 0,
|
|
117521
117654
|
executionReports: [],
|
|
117522
117655
|
message: unsizedInput.decision === "HOLD" ? "Hold (No Action)" : "Unsupported decision",
|
|
@@ -117584,12 +117717,7 @@ var init_runtime_execution = __esm({
|
|
|
117584
117717
|
}
|
|
117585
117718
|
};
|
|
117586
117719
|
throwIfAborted(input.signal);
|
|
117587
|
-
const
|
|
117588
|
-
const decisionSnapshotSignedUnits = signedUnitsFromEntryPosition(
|
|
117589
|
-
decisionSnapshotPositionSize,
|
|
117590
|
-
input.executionContext.currentPositionEntryPrice,
|
|
117591
|
-
input.executionContext.unitSizeUsdc
|
|
117592
|
-
);
|
|
117720
|
+
const decisionSnapshotSignedUnits = contextSignedUnits(input.executionContext);
|
|
117593
117721
|
const profileId = String(input.profileId).trim();
|
|
117594
117722
|
const hasTrackedProtection = readClientProtectiveGroups(
|
|
117595
117723
|
profileId,
|
|
@@ -117626,6 +117754,7 @@ var init_runtime_execution = __esm({
|
|
|
117626
117754
|
const {
|
|
117627
117755
|
currentPositionSize,
|
|
117628
117756
|
currentPositionEntryPrice,
|
|
117757
|
+
currentQuoteRate,
|
|
117629
117758
|
currentMarkPrice,
|
|
117630
117759
|
executionPrice: resolvedExecutionPrice,
|
|
117631
117760
|
executionSnapshotId,
|
|
@@ -117654,7 +117783,8 @@ var init_runtime_execution = __esm({
|
|
|
117654
117783
|
const liveSignedUnits = signedUnitsFromEntryPosition(
|
|
117655
117784
|
currentPositionSize,
|
|
117656
117785
|
currentPositionEntryPrice,
|
|
117657
|
-
input.executionContext.unitSizeUsdc
|
|
117786
|
+
input.executionContext.unitSizeUsdc,
|
|
117787
|
+
currentQuoteRate
|
|
117658
117788
|
);
|
|
117659
117789
|
const classified = classifyExecutionIntent(
|
|
117660
117790
|
input.decision,
|
|
@@ -118028,7 +118158,8 @@ var init_runtime_execution = __esm({
|
|
|
118028
118158
|
unitSizeUsdc: input.executionContext.unitSizeUsdc,
|
|
118029
118159
|
marketPrice: executionPrice,
|
|
118030
118160
|
entryPrice: currentPositionEntryPrice,
|
|
118031
|
-
livePositionSize: currentPositionSize
|
|
118161
|
+
livePositionSize: currentPositionSize,
|
|
118162
|
+
quoteRate: currentQuoteRate
|
|
118032
118163
|
});
|
|
118033
118164
|
let sizeAsset = Number.isFinite(intendedSizeAsset) && intendedSizeAsset > 0 ? quantizeHyperliquidOrderSizeValue(intendedSizeAsset, input.executionContext.sizeDecimals, "nearest") : 0;
|
|
118034
118165
|
appendRuntimeDebugEvent({
|
|
@@ -118110,6 +118241,7 @@ var init_runtime_execution = __esm({
|
|
|
118110
118241
|
settings: nativeSettingsOf(input.executionContext),
|
|
118111
118242
|
isLong: classified.side === "buy",
|
|
118112
118243
|
sizeDecimals: input.executionContext.sizeDecimals,
|
|
118244
|
+
quoteRate: currentQuoteRate,
|
|
118113
118245
|
positionHasLegacyLegs: readClientProtectiveGroups(nativeProfileId, input.executionContext.symbol).length > 0,
|
|
118114
118246
|
entryMutationId,
|
|
118115
118247
|
entryClientOrderId,
|
|
@@ -118519,7 +118651,7 @@ var init_runtime_execution = __esm({
|
|
|
118519
118651
|
const protectionEntryPrice = protectionFill == null ? 0 : protectionFill.averagePrice;
|
|
118520
118652
|
const isLong = classified.side === "buy";
|
|
118521
118653
|
const exitSide = isLong ? "sell" : "buy";
|
|
118522
|
-
const positionNotional = Math.abs(protectionEntryPrice * protectionSize);
|
|
118654
|
+
const positionNotional = Math.abs(protectionEntryPrice * protectionSize * currentQuoteRate);
|
|
118523
118655
|
const slPct = input.executionContext.stopLossEnabled === false ? 0 : resolveRiskPct(
|
|
118524
118656
|
input.executionContext.stopLossMode,
|
|
118525
118657
|
input.executionContext.stopLossPct,
|
|
@@ -119686,7 +119818,7 @@ var init_browser_observability = __esm({
|
|
|
119686
119818
|
init_define_VTX_GROK_POLICY();
|
|
119687
119819
|
init_define_VTX_PI_MODEL_POLICY();
|
|
119688
119820
|
init_runtime_policy_generated2();
|
|
119689
|
-
CLIENT_SOURCE_VERSION = typeof process !== "undefined" && true && "
|
|
119821
|
+
CLIENT_SOURCE_VERSION = typeof process !== "undefined" && true && "296b02cab2d20168659356bd1d28011685e5b358".trim() && "296b02cab2d20168659356bd1d28011685e5b358".trim() !== "unstamped" ? "296b02cab2d20168659356bd1d28011685e5b358".trim() : null;
|
|
119690
119822
|
listenersInstalled = false;
|
|
119691
119823
|
state = {
|
|
119692
119824
|
loadedAtMs: Date.now(),
|
|
@@ -122782,79 +122914,22 @@ var init_review_failure_wording = __esm({
|
|
|
122782
122914
|
}
|
|
122783
122915
|
});
|
|
122784
122916
|
|
|
122785
|
-
// lib/runtime/
|
|
122786
|
-
var
|
|
122787
|
-
var
|
|
122788
|
-
"lib/runtime/
|
|
122917
|
+
// lib/runtime/trader-max-tokens.ts
|
|
122918
|
+
var traderMainMaxTokens;
|
|
122919
|
+
var init_trader_max_tokens = __esm({
|
|
122920
|
+
"lib/runtime/trader-max-tokens.ts"() {
|
|
122789
122921
|
"use strict";
|
|
122790
122922
|
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
122791
122923
|
init_define_VTX_EXO_POLICY();
|
|
122792
122924
|
init_define_VTX_GROK_POLICY();
|
|
122793
122925
|
init_define_VTX_PI_MODEL_POLICY();
|
|
122794
122926
|
init_runtime_error_reason_rules();
|
|
122795
|
-
|
|
122796
|
-
|
|
122797
|
-
|
|
122798
|
-
|
|
122799
|
-
"runtime_config_missing"
|
|
122800
|
-
);
|
|
122801
|
-
booleanField = (resolved, key) => {
|
|
122802
|
-
const value = resolved[key];
|
|
122803
|
-
if (typeof value !== "boolean") throw invalid2(key);
|
|
122804
|
-
return value;
|
|
122805
|
-
};
|
|
122806
|
-
numberField = (resolved, key) => {
|
|
122807
|
-
const value = resolved[key];
|
|
122808
|
-
if (typeof value !== "number" || !Number.isFinite(value)) throw invalid2(key);
|
|
122809
|
-
return value;
|
|
122810
|
-
};
|
|
122811
|
-
enumField = (resolved, key, allowed) => {
|
|
122812
|
-
const value = resolved[key];
|
|
122813
|
-
if (!allowed.includes(value)) throw invalid2(key);
|
|
122814
|
-
return value;
|
|
122815
|
-
};
|
|
122816
|
-
buildRuntimeSlTpExecutionSettings = (settings, _config) => {
|
|
122817
|
-
const error48 = settings.sl_tp_execution_settings_error;
|
|
122818
|
-
if (typeof error48 === "string" && error48.trim()) throw new Error(error48);
|
|
122819
|
-
const resolved = settings.sl_tp_execution_settings;
|
|
122820
|
-
if (!resolved || typeof resolved !== "object" || Array.isArray(resolved)) {
|
|
122821
|
-
throw new RuntimeReasonError("The bot's preferences carry no resolved Auto SL/TP settings.", "runtime_config_missing");
|
|
122927
|
+
traderMainMaxTokens = (maxTokens, config2) => {
|
|
122928
|
+
const minimum = Number(config2.max_tokens_min);
|
|
122929
|
+
if (!Number.isFinite(minimum) || minimum <= 0) {
|
|
122930
|
+
throw new RuntimeReasonError("Missing required positive prompt contract field: max_tokens_min", "runtime_config_missing");
|
|
122822
122931
|
}
|
|
122823
|
-
|
|
122824
|
-
return {
|
|
122825
|
-
tpSlEnabled: booleanField(values, "tp_sl_enabled"),
|
|
122826
|
-
stopLossEnabled: booleanField(values, "sl_enabled"),
|
|
122827
|
-
stopLossType: enumField(values, "stop_loss_type", STOP_LOSS_TYPES),
|
|
122828
|
-
stopLossMode: enumField(values, "stop_loss_mode", RISK_MODES),
|
|
122829
|
-
stopLossPct: numberField(values, "stop_loss_pct"),
|
|
122830
|
-
stopLossUsdc: numberField(values, "stop_loss_usdc"),
|
|
122831
|
-
takeProfitEnabled: booleanField(values, "tp_enabled"),
|
|
122832
|
-
takeProfitMode: enumField(values, "take_profit_mode", RISK_MODES),
|
|
122833
|
-
takeProfitPct: numberField(values, "take_profit_pct"),
|
|
122834
|
-
takeProfitUsdc: numberField(values, "take_profit_usdc")
|
|
122835
|
-
};
|
|
122836
|
-
};
|
|
122837
|
-
}
|
|
122838
|
-
});
|
|
122839
|
-
|
|
122840
|
-
// lib/runtime/agent-instruction-carry.ts
|
|
122841
|
-
var carryAgentInstruction, carriedAgentInstruction;
|
|
122842
|
-
var init_agent_instruction_carry = __esm({
|
|
122843
|
-
"lib/runtime/agent-instruction-carry.ts"() {
|
|
122844
|
-
"use strict";
|
|
122845
|
-
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
122846
|
-
init_define_VTX_EXO_POLICY();
|
|
122847
|
-
init_define_VTX_GROK_POLICY();
|
|
122848
|
-
init_define_VTX_PI_MODEL_POLICY();
|
|
122849
|
-
carryAgentInstruction = (error48, binding) => {
|
|
122850
|
-
if (!binding || !error48 || typeof error48 !== "object" && typeof error48 !== "function") return error48;
|
|
122851
|
-
error48.runtimeExternalAgentInstruction = binding;
|
|
122852
|
-
return error48;
|
|
122853
|
-
};
|
|
122854
|
-
carriedAgentInstruction = (error48) => {
|
|
122855
|
-
if (!error48 || typeof error48 !== "object" && typeof error48 !== "function") return null;
|
|
122856
|
-
const binding = error48.runtimeExternalAgentInstruction;
|
|
122857
|
-
return binding && typeof binding === "object" ? binding : null;
|
|
122932
|
+
return Math.max(maxTokens, Math.trunc(minimum));
|
|
122858
122933
|
};
|
|
122859
122934
|
}
|
|
122860
122935
|
});
|
|
@@ -122986,6 +123061,312 @@ var init_model_output_gate = __esm({
|
|
|
122986
123061
|
}
|
|
122987
123062
|
});
|
|
122988
123063
|
|
|
123064
|
+
// lib/runtime/decision-plans.ts
|
|
123065
|
+
var SERVER_UNREADABLE_REPLY_HOLD_REASONING, normalizeDecisionLabel, decodeDecisionTracePayload, extractDecisionSymbolTrace, buildMissingDecisionHold, buildDecisionPlansFromResponse, readTraderReplyContent, traderDecisionPlans;
|
|
123066
|
+
var init_decision_plans = __esm({
|
|
123067
|
+
"lib/runtime/decision-plans.ts"() {
|
|
123068
|
+
"use strict";
|
|
123069
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
123070
|
+
init_define_VTX_EXO_POLICY();
|
|
123071
|
+
init_define_VTX_GROK_POLICY();
|
|
123072
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
123073
|
+
init_decision_contract();
|
|
123074
|
+
init_hyperliquid_market_symbol();
|
|
123075
|
+
init_model_output_gate();
|
|
123076
|
+
SERVER_UNREADABLE_REPLY_HOLD_REASONING = "Configured symbol was omitted from the model response. Defaulted to HOLD.";
|
|
123077
|
+
normalizeDecisionLabel = (value) => {
|
|
123078
|
+
const normalized = String(value ?? "").trim().toUpperCase();
|
|
123079
|
+
if (normalized === "BUY" || normalized === "SELL") {
|
|
123080
|
+
return normalized;
|
|
123081
|
+
}
|
|
123082
|
+
return "HOLD";
|
|
123083
|
+
};
|
|
123084
|
+
decodeDecisionTracePayload = (rawText, allowedSymbols = []) => {
|
|
123085
|
+
const text2 = String(rawText ?? "").trim();
|
|
123086
|
+
const fencedMatch = text2.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?```$/i);
|
|
123087
|
+
const content = fencedMatch ? String(fencedMatch[1] ?? "").trim() : text2;
|
|
123088
|
+
const candidates = [];
|
|
123089
|
+
const contentVariants = Array.from(/* @__PURE__ */ new Set([content, repairJsonStringSyntax(content)]));
|
|
123090
|
+
for (const candidateContent of contentVariants) {
|
|
123091
|
+
for (let startIndex = 0; startIndex < candidateContent.length; startIndex += 1) {
|
|
123092
|
+
if (candidateContent[startIndex] !== "{") {
|
|
123093
|
+
continue;
|
|
123094
|
+
}
|
|
123095
|
+
let depth = 0;
|
|
123096
|
+
let inString = false;
|
|
123097
|
+
let escaped = false;
|
|
123098
|
+
for (let cursor = startIndex; cursor < candidateContent.length; cursor += 1) {
|
|
123099
|
+
const ch2 = candidateContent[cursor];
|
|
123100
|
+
if (inString) {
|
|
123101
|
+
if (escaped) {
|
|
123102
|
+
escaped = false;
|
|
123103
|
+
} else if (ch2 === "\\") {
|
|
123104
|
+
escaped = true;
|
|
123105
|
+
} else if (ch2 === '"') {
|
|
123106
|
+
inString = false;
|
|
123107
|
+
}
|
|
123108
|
+
continue;
|
|
123109
|
+
}
|
|
123110
|
+
if (ch2 === '"') {
|
|
123111
|
+
inString = true;
|
|
123112
|
+
continue;
|
|
123113
|
+
}
|
|
123114
|
+
if (ch2 === "{") {
|
|
123115
|
+
depth += 1;
|
|
123116
|
+
continue;
|
|
123117
|
+
}
|
|
123118
|
+
if (ch2 === "}") {
|
|
123119
|
+
depth -= 1;
|
|
123120
|
+
if (depth === 0) {
|
|
123121
|
+
candidates.push(candidateContent.slice(startIndex, cursor + 1));
|
|
123122
|
+
break;
|
|
123123
|
+
}
|
|
123124
|
+
}
|
|
123125
|
+
}
|
|
123126
|
+
}
|
|
123127
|
+
}
|
|
123128
|
+
let bestPayload = null;
|
|
123129
|
+
let bestAllowedScore = -1;
|
|
123130
|
+
let bestScore = 0;
|
|
123131
|
+
const allowedSymbolSet = new Set(allowedSymbols);
|
|
123132
|
+
for (const candidate of candidates) {
|
|
123133
|
+
if (!candidate || !candidate.startsWith("{") || !candidate.endsWith("}")) {
|
|
123134
|
+
continue;
|
|
123135
|
+
}
|
|
123136
|
+
try {
|
|
123137
|
+
const parsed = JSON.parse(candidate);
|
|
123138
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
123139
|
+
const record6 = parsed;
|
|
123140
|
+
const decisionEntries = Object.entries(record6).filter(([, value]) => value && typeof value === "object" && !Array.isArray(value) && Object.prototype.hasOwnProperty.call(value, "decision"));
|
|
123141
|
+
const score = Object.prototype.hasOwnProperty.call(record6, "decision") ? 1 : decisionEntries.length;
|
|
123142
|
+
const allowedScore = decisionEntries.filter(([key]) => allowedSymbolSet.has(key)).length;
|
|
123143
|
+
if (allowedScore > bestAllowedScore || allowedScore === bestAllowedScore && score > bestScore) {
|
|
123144
|
+
bestPayload = record6;
|
|
123145
|
+
bestAllowedScore = allowedScore;
|
|
123146
|
+
bestScore = score;
|
|
123147
|
+
}
|
|
123148
|
+
}
|
|
123149
|
+
} catch {
|
|
123150
|
+
}
|
|
123151
|
+
}
|
|
123152
|
+
return bestPayload;
|
|
123153
|
+
};
|
|
123154
|
+
extractDecisionSymbolTrace = (rawText, allowedSymbols = []) => {
|
|
123155
|
+
const parsed = decodeDecisionTracePayload(rawText, allowedSymbols);
|
|
123156
|
+
if (!parsed) {
|
|
123157
|
+
return [];
|
|
123158
|
+
}
|
|
123159
|
+
if (Object.prototype.hasOwnProperty.call(parsed, "decision")) {
|
|
123160
|
+
return [{
|
|
123161
|
+
symbol: "direct",
|
|
123162
|
+
decision: normalizeDecisionLabel(parsed.decision),
|
|
123163
|
+
units: Math.max(0, Math.trunc(Number(parsed.units) || 0))
|
|
123164
|
+
}];
|
|
123165
|
+
}
|
|
123166
|
+
return Object.entries(parsed).flatMap(([symbol2, value]) => {
|
|
123167
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
123168
|
+
return [];
|
|
123169
|
+
}
|
|
123170
|
+
const scoped = value;
|
|
123171
|
+
if (!Object.prototype.hasOwnProperty.call(scoped, "decision")) {
|
|
123172
|
+
return [];
|
|
123173
|
+
}
|
|
123174
|
+
return [{
|
|
123175
|
+
symbol: symbol2,
|
|
123176
|
+
decision: normalizeDecisionLabel(scoped.decision),
|
|
123177
|
+
units: Math.max(0, Math.trunc(Number(scoped.units) || 0))
|
|
123178
|
+
}];
|
|
123179
|
+
});
|
|
123180
|
+
};
|
|
123181
|
+
buildMissingDecisionHold = (symbol2, reasoning = `No valid model decision was returned for configured symbol ${symbol2}.`) => ({
|
|
123182
|
+
symbol: symbol2,
|
|
123183
|
+
decision: "HOLD",
|
|
123184
|
+
units: 0,
|
|
123185
|
+
tradability: null,
|
|
123186
|
+
reasoning
|
|
123187
|
+
});
|
|
123188
|
+
buildDecisionPlansFromResponse = (rawText, promptSymbols, fallbackSymbol, fallbackDecision, fallbackUnits, fallbackTradability, fallbackReasoning) => {
|
|
123189
|
+
const normalizedPromptSymbols = normalizePromptSymbols(promptSymbols);
|
|
123190
|
+
const allowedSymbols = new Set(normalizedPromptSymbols);
|
|
123191
|
+
const payload = decodeDecisionTracePayload(rawText, normalizedPromptSymbols);
|
|
123192
|
+
const trace = extractDecisionSymbolTrace(rawText, normalizedPromptSymbols);
|
|
123193
|
+
const scopedTraceBySymbol = /* @__PURE__ */ new Map();
|
|
123194
|
+
for (const entry of trace) {
|
|
123195
|
+
const normalizedSymbol = String(entry.symbol || "").trim();
|
|
123196
|
+
if (normalizedSymbol && normalizedSymbol !== "DIRECT" && allowedSymbols.has(normalizedSymbol) && !scopedTraceBySymbol.has(normalizedSymbol)) {
|
|
123197
|
+
scopedTraceBySymbol.set(normalizedSymbol, entry);
|
|
123198
|
+
}
|
|
123199
|
+
}
|
|
123200
|
+
if (scopedTraceBySymbol.size > 0) {
|
|
123201
|
+
return normalizedPromptSymbols.map((normalizedSymbol) => {
|
|
123202
|
+
const entry = scopedTraceBySymbol.get(normalizedSymbol);
|
|
123203
|
+
if (!entry) {
|
|
123204
|
+
return buildMissingDecisionHold(normalizedSymbol);
|
|
123205
|
+
}
|
|
123206
|
+
const scopedPayload = payload?.[entry.symbol];
|
|
123207
|
+
const scopedText = scopedPayload && typeof scopedPayload === "object" && !Array.isArray(scopedPayload) ? JSON.stringify(scopedPayload) : rawText;
|
|
123208
|
+
const parsed = extractNormalizedDecision(scopedText, null, entry.symbol);
|
|
123209
|
+
const units = parsed.decision === "HOLD" ? 0 : parsed.units > 0 ? parsed.units : entry.units;
|
|
123210
|
+
return {
|
|
123211
|
+
symbol: normalizedSymbol,
|
|
123212
|
+
decision: parsed.decision,
|
|
123213
|
+
units,
|
|
123214
|
+
tradability: parsed.tradability,
|
|
123215
|
+
reasoning: parsed.reasoning
|
|
123216
|
+
};
|
|
123217
|
+
});
|
|
123218
|
+
}
|
|
123219
|
+
const directTrace = trace.find((entry) => normalizeHyperliquidMarketSymbol(entry.symbol) === "DIRECT");
|
|
123220
|
+
if (directTrace && normalizedPromptSymbols.length === 1) {
|
|
123221
|
+
return normalizedPromptSymbols.map((normalizedSymbol, index) => index === 0 ? {
|
|
123222
|
+
symbol: normalizedSymbol,
|
|
123223
|
+
decision: fallbackDecision,
|
|
123224
|
+
units: fallbackDecision === "HOLD" ? 0 : Math.max(0, Math.trunc(Number(fallbackUnits) || 0)),
|
|
123225
|
+
tradability: fallbackTradability,
|
|
123226
|
+
reasoning: fallbackReasoning
|
|
123227
|
+
} : buildMissingDecisionHold(normalizedSymbol));
|
|
123228
|
+
}
|
|
123229
|
+
if (directTrace && normalizedPromptSymbols.length > 1) {
|
|
123230
|
+
return normalizedPromptSymbols.map((normalizedSymbol) => buildMissingDecisionHold(
|
|
123231
|
+
normalizedSymbol,
|
|
123232
|
+
`Model response did not provide a symbol-keyed decision for configured symbol ${normalizedSymbol}.`
|
|
123233
|
+
));
|
|
123234
|
+
}
|
|
123235
|
+
const hasForeignSymbolDecision = trace.some((entry) => {
|
|
123236
|
+
const normalizedSymbol = String(entry.symbol || "").trim();
|
|
123237
|
+
return normalizedSymbol && normalizedSymbol !== "DIRECT" && !allowedSymbols.has(normalizedSymbol);
|
|
123238
|
+
});
|
|
123239
|
+
if (hasForeignSymbolDecision) {
|
|
123240
|
+
return normalizedPromptSymbols.map((normalizedSymbol) => buildMissingDecisionHold(
|
|
123241
|
+
normalizedSymbol,
|
|
123242
|
+
`Model response contained no decision for configured symbol ${normalizedSymbol}.`
|
|
123243
|
+
));
|
|
123244
|
+
}
|
|
123245
|
+
const normalizedFallbackSymbol = normalizedPromptSymbols.find(
|
|
123246
|
+
(promptSymbol) => promptSymbol === String(fallbackSymbol || "").trim()
|
|
123247
|
+
) ?? String(fallbackSymbol || "").trim();
|
|
123248
|
+
const fallbackPlan = {
|
|
123249
|
+
symbol: normalizedFallbackSymbol || fallbackSymbol,
|
|
123250
|
+
decision: fallbackDecision,
|
|
123251
|
+
units: fallbackDecision === "HOLD" ? 0 : Math.max(0, Math.trunc(Number(fallbackUnits) || 0)),
|
|
123252
|
+
tradability: fallbackTradability,
|
|
123253
|
+
reasoning: fallbackReasoning
|
|
123254
|
+
};
|
|
123255
|
+
if (normalizedPromptSymbols.length === 0) {
|
|
123256
|
+
return [fallbackPlan];
|
|
123257
|
+
}
|
|
123258
|
+
return normalizedPromptSymbols.map((normalizedSymbol) => normalizedSymbol === fallbackPlan.symbol ? fallbackPlan : buildMissingDecisionHold(normalizedSymbol));
|
|
123259
|
+
};
|
|
123260
|
+
readTraderReplyContent = (content, promptSymbols) => {
|
|
123261
|
+
const validationErrors = currentModelOutputValidationErrors(content, promptSymbols);
|
|
123262
|
+
if (validationErrors.length > 0) {
|
|
123263
|
+
return {
|
|
123264
|
+
validationErrors,
|
|
123265
|
+
decisionContent: JSON.stringify(Object.fromEntries(promptSymbols.map((promptSymbol) => [promptSymbol, {
|
|
123266
|
+
decision: "HOLD",
|
|
123267
|
+
units: 0,
|
|
123268
|
+
tradability: null,
|
|
123269
|
+
reasoning: SERVER_UNREADABLE_REPLY_HOLD_REASONING
|
|
123270
|
+
}])))
|
|
123271
|
+
};
|
|
123272
|
+
}
|
|
123273
|
+
return { validationErrors, decisionContent: projectCurrentModelDecisionContent(String(content)) };
|
|
123274
|
+
};
|
|
123275
|
+
traderDecisionPlans = (decisionContent, promptSymbols, symbol2) => {
|
|
123276
|
+
const parsed = extractNormalizedDecision(decisionContent, null, symbol2);
|
|
123277
|
+
return {
|
|
123278
|
+
parsed,
|
|
123279
|
+
plans: buildDecisionPlansFromResponse(
|
|
123280
|
+
decisionContent,
|
|
123281
|
+
promptSymbols,
|
|
123282
|
+
symbol2,
|
|
123283
|
+
parsed.decision,
|
|
123284
|
+
parsed.units,
|
|
123285
|
+
parsed.tradability,
|
|
123286
|
+
parsed.reasoning
|
|
123287
|
+
)
|
|
123288
|
+
};
|
|
123289
|
+
};
|
|
123290
|
+
}
|
|
123291
|
+
});
|
|
123292
|
+
|
|
123293
|
+
// lib/runtime/sl-tp-execution-settings.ts
|
|
123294
|
+
var RISK_MODES, STOP_LOSS_TYPES, invalid2, booleanField, numberField, enumField, buildRuntimeSlTpExecutionSettings;
|
|
123295
|
+
var init_sl_tp_execution_settings = __esm({
|
|
123296
|
+
"lib/runtime/sl-tp-execution-settings.ts"() {
|
|
123297
|
+
"use strict";
|
|
123298
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
123299
|
+
init_define_VTX_EXO_POLICY();
|
|
123300
|
+
init_define_VTX_GROK_POLICY();
|
|
123301
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
123302
|
+
init_runtime_error_reason_rules();
|
|
123303
|
+
RISK_MODES = ["percent", "usdc"];
|
|
123304
|
+
STOP_LOSS_TYPES = ["fixed", "trailing"];
|
|
123305
|
+
invalid2 = (key) => new RuntimeReasonError(
|
|
123306
|
+
`The bot's resolved Auto SL/TP settings have no valid ${key}.`,
|
|
123307
|
+
"runtime_config_missing"
|
|
123308
|
+
);
|
|
123309
|
+
booleanField = (resolved, key) => {
|
|
123310
|
+
const value = resolved[key];
|
|
123311
|
+
if (typeof value !== "boolean") throw invalid2(key);
|
|
123312
|
+
return value;
|
|
123313
|
+
};
|
|
123314
|
+
numberField = (resolved, key) => {
|
|
123315
|
+
const value = resolved[key];
|
|
123316
|
+
if (typeof value !== "number" || !Number.isFinite(value)) throw invalid2(key);
|
|
123317
|
+
return value;
|
|
123318
|
+
};
|
|
123319
|
+
enumField = (resolved, key, allowed) => {
|
|
123320
|
+
const value = resolved[key];
|
|
123321
|
+
if (!allowed.includes(value)) throw invalid2(key);
|
|
123322
|
+
return value;
|
|
123323
|
+
};
|
|
123324
|
+
buildRuntimeSlTpExecutionSettings = (settings, _config) => {
|
|
123325
|
+
const error48 = settings.sl_tp_execution_settings_error;
|
|
123326
|
+
if (typeof error48 === "string" && error48.trim()) throw new Error(error48);
|
|
123327
|
+
const resolved = settings.sl_tp_execution_settings;
|
|
123328
|
+
if (!resolved || typeof resolved !== "object" || Array.isArray(resolved)) {
|
|
123329
|
+
throw new RuntimeReasonError("The bot's preferences carry no resolved Auto SL/TP settings.", "runtime_config_missing");
|
|
123330
|
+
}
|
|
123331
|
+
const values = resolved;
|
|
123332
|
+
return {
|
|
123333
|
+
tpSlEnabled: booleanField(values, "tp_sl_enabled"),
|
|
123334
|
+
stopLossEnabled: booleanField(values, "sl_enabled"),
|
|
123335
|
+
stopLossType: enumField(values, "stop_loss_type", STOP_LOSS_TYPES),
|
|
123336
|
+
stopLossMode: enumField(values, "stop_loss_mode", RISK_MODES),
|
|
123337
|
+
stopLossPct: numberField(values, "stop_loss_pct"),
|
|
123338
|
+
stopLossUsdc: numberField(values, "stop_loss_usdc"),
|
|
123339
|
+
takeProfitEnabled: booleanField(values, "tp_enabled"),
|
|
123340
|
+
takeProfitMode: enumField(values, "take_profit_mode", RISK_MODES),
|
|
123341
|
+
takeProfitPct: numberField(values, "take_profit_pct"),
|
|
123342
|
+
takeProfitUsdc: numberField(values, "take_profit_usdc")
|
|
123343
|
+
};
|
|
123344
|
+
};
|
|
123345
|
+
}
|
|
123346
|
+
});
|
|
123347
|
+
|
|
123348
|
+
// lib/runtime/agent-instruction-carry.ts
|
|
123349
|
+
var carryAgentInstruction, carriedAgentInstruction;
|
|
123350
|
+
var init_agent_instruction_carry = __esm({
|
|
123351
|
+
"lib/runtime/agent-instruction-carry.ts"() {
|
|
123352
|
+
"use strict";
|
|
123353
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
123354
|
+
init_define_VTX_EXO_POLICY();
|
|
123355
|
+
init_define_VTX_GROK_POLICY();
|
|
123356
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
123357
|
+
carryAgentInstruction = (error48, binding) => {
|
|
123358
|
+
if (!binding || !error48 || typeof error48 !== "object" && typeof error48 !== "function") return error48;
|
|
123359
|
+
error48.runtimeExternalAgentInstruction = binding;
|
|
123360
|
+
return error48;
|
|
123361
|
+
};
|
|
123362
|
+
carriedAgentInstruction = (error48) => {
|
|
123363
|
+
if (!error48 || typeof error48 !== "object" && typeof error48 !== "function") return null;
|
|
123364
|
+
const binding = error48.runtimeExternalAgentInstruction;
|
|
123365
|
+
return binding && typeof binding === "object" ? binding : null;
|
|
123366
|
+
};
|
|
123367
|
+
}
|
|
123368
|
+
});
|
|
123369
|
+
|
|
122989
123370
|
// lib/runtime/perp-dex-scope.ts
|
|
122990
123371
|
var perpDexScopeForSymbols, equityVenuesForSymbols, profileEquityVenues, profileExchanges, positionsOnVenues;
|
|
122991
123372
|
var init_perp_dex_scope = __esm({
|
|
@@ -123724,6 +124105,7 @@ var init_client_panel_reads = __esm({
|
|
|
123724
124105
|
init_define_VTX_GROK_POLICY();
|
|
123725
124106
|
init_define_VTX_PI_MODEL_POLICY();
|
|
123726
124107
|
init_api2();
|
|
124108
|
+
init_profiles();
|
|
123727
124109
|
init_constants();
|
|
123728
124110
|
init_executionMode();
|
|
123729
124111
|
init_runtime_policy_generated2();
|
|
@@ -126331,6 +126713,39 @@ var init_render = __esm({
|
|
|
126331
126713
|
}
|
|
126332
126714
|
});
|
|
126333
126715
|
|
|
126716
|
+
// lib/runtime/runtime-cycle-observation.ts
|
|
126717
|
+
var observeRuntimeCycle, observeAccountState;
|
|
126718
|
+
var init_runtime_cycle_observation = __esm({
|
|
126719
|
+
"lib/runtime/runtime-cycle-observation.ts"() {
|
|
126720
|
+
"use strict";
|
|
126721
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
126722
|
+
init_define_VTX_EXO_POLICY();
|
|
126723
|
+
init_define_VTX_GROK_POLICY();
|
|
126724
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
126725
|
+
observeRuntimeCycle = (input, observation) => {
|
|
126726
|
+
try {
|
|
126727
|
+
input.onCycleObservation?.(observation);
|
|
126728
|
+
} catch {
|
|
126729
|
+
}
|
|
126730
|
+
};
|
|
126731
|
+
observeAccountState = (input, state2) => {
|
|
126732
|
+
const evidence2 = state2.evidence;
|
|
126733
|
+
observeRuntimeCycle(input, {
|
|
126734
|
+
account_state: {
|
|
126735
|
+
source: evidence2 ? `browser_hl_${evidence2.source}` : "browser_hl_unknown",
|
|
126736
|
+
observed_at: new Date(evidence2?.observedAtMs ?? Date.now()).toISOString(),
|
|
126737
|
+
fetched_at: evidence2 ? new Date(evidence2.fetchedAtMs).toISOString() : null,
|
|
126738
|
+
source_timestamp: null,
|
|
126739
|
+
cache_age_ms: evidence2?.cacheAgeMs ?? null,
|
|
126740
|
+
node_lag_ms: null,
|
|
126741
|
+
freshness_limit_ms: evidence2?.freshnessLimitMs ?? null,
|
|
126742
|
+
position_state: Array.isArray(state2.positions) ? state2.positions.some((position) => Number(position.size) !== 0) ? "open" : "flat" : "unknown"
|
|
126743
|
+
}
|
|
126744
|
+
});
|
|
126745
|
+
};
|
|
126746
|
+
}
|
|
126747
|
+
});
|
|
126748
|
+
|
|
126334
126749
|
// lib/runtime/client-account-report.ts
|
|
126335
126750
|
var sumPositionUnrealizedPnl2, resolveTotalUnrealizedPnl2, buildPromptParityAccountContext, finiteOrNull4, buildClientExchangeSnapshot;
|
|
126336
126751
|
var init_client_account_report = __esm({
|
|
@@ -126376,7 +126791,9 @@ var init_client_account_report = __esm({
|
|
|
126376
126791
|
symbol: normalizeHyperliquidMarketSymbol(position.symbol),
|
|
126377
126792
|
size: Number(position.size),
|
|
126378
126793
|
entry_price: Number(position.entry_price),
|
|
126379
|
-
unrealized_pnl: Number(position.unrealized_pnl)
|
|
126794
|
+
unrealized_pnl: Number(position.unrealized_pnl),
|
|
126795
|
+
// What its price money is worth in the account's money (web/lib/api/positions.ts); none on Hyperliquid.
|
|
126796
|
+
...position.quote_rate != null ? { quote_rate: position.quote_rate } : {}
|
|
126380
126797
|
}));
|
|
126381
126798
|
}
|
|
126382
126799
|
if (input.totalUnrealizedPnl !== null && input.totalUnrealizedPnl !== void 0) {
|
|
@@ -126418,7 +126835,8 @@ var init_client_account_report = __esm({
|
|
|
126418
126835
|
leverage: finiteOrNull4(position.leverage),
|
|
126419
126836
|
margin_used: finiteOrNull4(position.margin_used),
|
|
126420
126837
|
liquidation_price: finiteOrNull4(position.liquidation_price),
|
|
126421
|
-
funding_usdc: finiteOrNull4(position.funding_usdc)
|
|
126838
|
+
funding_usdc: finiteOrNull4(position.funding_usdc),
|
|
126839
|
+
...position.quote_rate != null ? { quote_rate: position.quote_rate } : {}
|
|
126422
126840
|
}))
|
|
126423
126841
|
});
|
|
126424
126842
|
}
|
|
@@ -131552,6 +131970,7 @@ var init_prompt_positions_block = __esm({
|
|
|
131552
131970
|
init_define_VTX_PI_MODEL_POLICY();
|
|
131553
131971
|
init_constants();
|
|
131554
131972
|
init_execution_capacity();
|
|
131973
|
+
init_position_value();
|
|
131555
131974
|
init_hyperliquid_market_symbol();
|
|
131556
131975
|
init_position_prompt_contract();
|
|
131557
131976
|
init_prompt_collateral_contract();
|
|
@@ -131609,8 +132028,8 @@ var init_prompt_positions_block = __esm({
|
|
|
131609
132028
|
if (!Number.isFinite(unrealizedPnl)) {
|
|
131610
132029
|
throw new RuntimeReasonError(`Active position PnL is unavailable for ${position.symbol}`, "internal_data_error");
|
|
131611
132030
|
}
|
|
131612
|
-
const notionalValue = Math.abs(size * entryPrice);
|
|
131613
|
-
const unitsUsed = capacityUnitsUsedForPosition(
|
|
132031
|
+
const notionalValue = Math.abs(size * entryPrice * quoteRateOf(position.quote_rate));
|
|
132032
|
+
const unitsUsed = capacityUnitsUsedForPosition(position, input.unitSize);
|
|
131614
132033
|
globalUnitsUsed += unitsUsed;
|
|
131615
132034
|
assetUsage.set(position.symbol, unitsUsed);
|
|
131616
132035
|
const venue = getHyperliquidMarketDex(position.symbol);
|
|
@@ -132206,7 +132625,7 @@ __export(local_analysis_exports, {
|
|
|
132206
132625
|
toPositiveFinite: () => toPositiveFinite2,
|
|
132207
132626
|
unwrapRuntimeCycleSettledResult: () => unwrapRuntimeCycleSettledResult
|
|
132208
132627
|
});
|
|
132209
|
-
var cycleCandles, CYCLE_TIMEOUT_FLOOR_MS, DECISION_SETTLEMENT_RESERVE_MAX_BUDGET_DIVISOR, MIN_AGENT_INSTRUCTION_RETRY_AFTER_MS, PROMPT_PARITY_ERROR_DETAIL_MAX_CHARS, EXTERNAL_INFERENCE_RUNTIME_POLL_INTERVAL_MS, EXTERNAL_INFERENCE_RESULT_WAIT_MS, assertPromptModelController, resolveRuntimeReasoningControlsForModel,
|
|
132628
|
+
var cycleCandles, CYCLE_TIMEOUT_FLOOR_MS, DECISION_SETTLEMENT_RESERVE_MAX_BUDGET_DIVISOR, MIN_AGENT_INSTRUCTION_RETRY_AFTER_MS, PROMPT_PARITY_ERROR_DETAIL_MAX_CHARS, EXTERNAL_INFERENCE_RUNTIME_POLL_INTERVAL_MS, EXTERNAL_INFERENCE_RESULT_WAIT_MS, assertPromptModelController, resolveRuntimeReasoningControlsForModel, aiOrderSlippageFraction, buildServerBehaviorStateArtifacts, ClientRuntimeAgentInstructionEmpty, isClientRuntimeAgentInstructionEmpty, ClientRuntimeAiSchedulePaused, ClientRuntimeAiScheduleStillActive, isClientRuntimeAiScheduleStillActive, ServerDispatchAccountStateStale, isServerDispatchAccountStateStale, isClientRuntimeAiSchedulePaused, judgesPositionCaps, NO_POSITION_CAPS, POSITION_CAP_REFUSALS, judgeCyclePlans, capacityTrimOf, tradabilityExecutionBlock, accountSnapshotCapturedAt, buildClaimedAgentRuntimeCycleResult, resolveRuntimeMarginModePreference, resolveRuntimeLeveragePreference, resolveBooleanSetting, CLIENT_RUNTIME_LIVE_CONTEXT_UNAVAILABLE_ERRORS, BEHAVIOR_STATE_UNAVAILABLE_ERROR, CriticalBehaviorStateError, BEHAVIOR_MEMORY_UNAVAILABLE_ERROR, BehaviorMemoryUnavailableError, clampNumber, resolveExternalInferenceRuntimeTimeoutSeconds, toPositiveFinite2, EFFECTIVE_INPUT_MANIFEST_SCHEMA_VERSION, PROMPT_ASSEMBLY_DEFINITION_VERSION, RUNTIME_SOURCE_DEFINITION_VERSION, DECISION_INPUT_DEFINITION_VERSION, CONTEXT_ENVELOPE_DEFINITION_VERSION, CLIENT_RUNTIME_SOURCE_VERSION, CLIENT_MAIN_PROMPT_RENDERER, CLIENT_REVIEW_PROMPT_RENDERER, resolveEffectivePromptRuntimeProvenance, canonicalManifestValue, canonicalManifestJson, sha256ManifestHex, effectiveInputComponent, buildEffectiveInputManifest, MANIFEST_COMPONENT_NAME, derivePromptVisibleSections, formatDecisionSymbolTrace, formatActionableDecisionSymbols, decisionRecordsBySymbol, buildReviewCandidatePlansFromResponse, forceUnavailableSymbolsToHold, extractTemplatePlaceholders, requireReviewPrimaryUserPromptTemplate, containsCompetingBehaviorStateMarkup, containsCompetingMainBehaviorStateMarkup, requireStrategyReviewTemplates, preflightStrategyReviewPromptContract, extractRuntimeReasoningSelection, isAbortError, isRuntimeTimeoutAbortReason, createAbortError2, settleRuntimeCyclePromise, unwrapRuntimeCycleSettledResult, normalizeRuntimeSymbol, PromptContractFetchError, isLivePromptContextUnavailableError, buildFailClosedHoldResult, buildPromptConstructionFailureResult, buildLivePromptContextUnavailableFailureResult, pickFirstString, normalizeRuntimeStringList, requirePositiveRuntimeLimit, resolveRuntimeTradingScope, normalizeRuntimeProviderAlias, resolveCatalogModelEntry, createClientRuntimeProviderSetupError, createProviderSetupRejectionError, evaluateModelEligibility, extractReviewRuntimeReasoningSelection, isUsableRuntimeSettingsFallback, resolveRuntimeSettings, formatRuntimeDurationMs, normalizeRuntimeTimingNote, appendRuntimeTimingEvent, reportPromptParityTelemetry, resolveLocalRuntimeSecretRequirements, resolveLocalRuntimeSecretProvider, AI_INDICATOR_KEYS_NEWER_THAN_SOME_SERVERS, sortTradingTimeframes, normalizePromptIdentityTimestamp, resolveCompletedCandleBoundary, normalizeAiIndicatorFlags, getPromptLookback, resolvePromptRelativeVolumeContext, promptRelativeVolumeBaseline, CANDLE_CLOSE_TICKER_TIMEFRAME, candleCloseTicker, promptMarketAsOfTimestamp, deviceMarketReads, buildPromptCandlesPayload, capacityUnitSize, sanitizePromptSymbol, fillTimeMs, fillSize, normalizeFillSide, normalizeFillOrderId, normalizeFillRiskOrderIdentity, fillStartPosition, fillSortValue, sortFillsAscending, sortFillsDescending, inferEntryFromStartPositionChain, inferEntryFromCurrentPositionSize, calculateCurrentPositionState, calculatePositionEntryTimes, countPositionAdds, latestPositionRiskIncreaseTimeMs, latestPositionRiskIncreaseEvidence, roundPositiveDecimalHalfUp, compactPromptLastTrade, requireRenderedStrategyBehaviorState, canonicalFillSideForRiskEvidence, isValidRiskEvidenceFill, isValidCampaignBoundaryFill, normalizeFillHistoryCoverage, resolveFillHistoryCoverageForSymbol, buildPromptBehaviorStateArtifacts, buildReviewSystemPrompt, formatReviewUserPrompt, assemblePromptContextVars, buildPromptBehaviorStateValue, buildLocalRuntimePromptArtifacts2, createRuntimeId2, asRecord, buildRuntimeConstraintRejectionMessage, hasDeviceProviderSecret, requireNonEmptyStringField, requirePositiveIntegerField, compareContractVersion, parsePromptContractTimestamp, assertPromptContractCompatibility, assertPromptContractTemporalBounds, sleepWithAbort, requireAgentPollRetryAfterMs, materializeClaimedClientRuntimeAgentInstruction, attachClientRuntimeErrorProvenance, isExternalRuntimeProviderResult, invokeClientExternalInference, assertPromptContractBindingTupleEqual, assertPromptContractScopeMatch, fetchBoundPromptContracts, carryReturnedModelCalls, requireRuntimePositionsInstructions2, resolveRuntimePromptDerivedBlocks, requireRuntimePromptLane, requireRuntimeAccountMarginNote, runLocalRuntimeCycle;
|
|
132210
132629
|
var init_local_analysis = __esm({
|
|
132211
132630
|
"lib/runtime/local-analysis.ts"() {
|
|
132212
132631
|
"use strict";
|
|
@@ -132215,6 +132634,9 @@ var init_local_analysis = __esm({
|
|
|
132215
132634
|
init_define_VTX_GROK_POLICY();
|
|
132216
132635
|
init_define_VTX_PI_MODEL_POLICY();
|
|
132217
132636
|
init_review_failure_wording();
|
|
132637
|
+
init_trader_max_tokens();
|
|
132638
|
+
init_decision_plans();
|
|
132639
|
+
init_decision_plans();
|
|
132218
132640
|
init_sl_tp_execution_settings();
|
|
132219
132641
|
init_execution_capacity();
|
|
132220
132642
|
init_agent_instruction_carry();
|
|
@@ -132240,6 +132662,7 @@ var init_local_analysis = __esm({
|
|
|
132240
132662
|
init_decision_contract();
|
|
132241
132663
|
init_constraint_contract();
|
|
132242
132664
|
init_execution_guard_contract();
|
|
132665
|
+
init_runtime_cycle_observation();
|
|
132243
132666
|
init_exchange_executor();
|
|
132244
132667
|
init_client_account_report();
|
|
132245
132668
|
init_hyperliquid_public_read();
|
|
@@ -132304,27 +132727,6 @@ var init_local_analysis = __esm({
|
|
|
132304
132727
|
resolveRuntimeReasoningControlsForModel = (modelConfig, provider, source) => {
|
|
132305
132728
|
return normalizeReasoningControls(null);
|
|
132306
132729
|
};
|
|
132307
|
-
observeRuntimeCycle = (input, observation) => {
|
|
132308
|
-
try {
|
|
132309
|
-
input.onCycleObservation?.(observation);
|
|
132310
|
-
} catch {
|
|
132311
|
-
}
|
|
132312
|
-
};
|
|
132313
|
-
observeAccountState = (input, state2) => {
|
|
132314
|
-
const evidence2 = state2.evidence;
|
|
132315
|
-
observeRuntimeCycle(input, {
|
|
132316
|
-
account_state: {
|
|
132317
|
-
source: evidence2 ? `browser_hl_${evidence2.source}` : "browser_hl_unknown",
|
|
132318
|
-
observed_at: new Date(evidence2?.observedAtMs ?? Date.now()).toISOString(),
|
|
132319
|
-
fetched_at: evidence2 ? new Date(evidence2.fetchedAtMs).toISOString() : null,
|
|
132320
|
-
source_timestamp: null,
|
|
132321
|
-
cache_age_ms: evidence2?.cacheAgeMs ?? null,
|
|
132322
|
-
node_lag_ms: null,
|
|
132323
|
-
freshness_limit_ms: evidence2?.freshnessLimitMs ?? null,
|
|
132324
|
-
position_state: Array.isArray(state2.positions) ? state2.positions.some((position) => Number(position.size) !== 0) ? "open" : "flat" : "unknown"
|
|
132325
|
-
}
|
|
132326
|
-
});
|
|
132327
|
-
};
|
|
132328
132730
|
aiOrderSlippageFraction = (config2, executionMode) => executionMode === "server" ? Number(config2.server_ai_max_slippage) / PERCENT_SCALE : clampNumber(void 0, config2.default_max_slippage) / PERCENT_SCALE;
|
|
132329
132731
|
buildServerBehaviorStateArtifacts = (inputs, options) => buildPromptBehaviorStateArtifacts({
|
|
132330
132732
|
fills: inputs.fills,
|
|
@@ -132378,7 +132780,7 @@ var init_local_analysis = __esm({
|
|
|
132378
132780
|
isClientRuntimeAiScheduleStillActive = (value) => value instanceof ClientRuntimeAiScheduleStillActive;
|
|
132379
132781
|
ServerDispatchAccountStateStale = class extends Error {
|
|
132380
132782
|
constructor() {
|
|
132381
|
-
super("VTX couldn't refresh this bot's
|
|
132783
|
+
super("VTX couldn't refresh this bot's account data in time, so it skipped this cycle safely and will try again at the next one");
|
|
132382
132784
|
this.name = "ServerDispatchAccountStateStale";
|
|
132383
132785
|
}
|
|
132384
132786
|
};
|
|
@@ -132542,7 +132944,7 @@ var init_local_analysis = __esm({
|
|
|
132542
132944
|
const signedUnitsForSymbol = (planSymbol) => {
|
|
132543
132945
|
const position = positionBySymbol.get(normalizeRuntimeSymbol(planSymbol));
|
|
132544
132946
|
if (!position) return 0;
|
|
132545
|
-
return
|
|
132947
|
+
return signedUnitsOfPosition(position, tradeSize);
|
|
132546
132948
|
};
|
|
132547
132949
|
for (const positionSymbol of positionBySymbol.keys()) signedUnitsForSymbol(positionSymbol);
|
|
132548
132950
|
const maxTradesPerPrompt = Math.max(0, Math.trunc(clampNumber(
|
|
@@ -132574,14 +132976,16 @@ var init_local_analysis = __esm({
|
|
|
132574
132976
|
if (price === null) {
|
|
132575
132977
|
throw new Error(`Missing required positive market price for Agent Client runtime execution context: ${planSymbol}`);
|
|
132576
132978
|
}
|
|
132577
|
-
const
|
|
132979
|
+
const position = positionBySymbol.get(normalizeRuntimeSymbol(planSymbol));
|
|
132980
|
+
const positionSize = Number(position?.size ?? 0);
|
|
132578
132981
|
return {
|
|
132579
132982
|
symbol: planSymbol,
|
|
132580
132983
|
timeframe,
|
|
132581
132984
|
decisionSnapshotId: input.decisionSnapshotId,
|
|
132582
132985
|
decisionSnapshotCapturedAt: input.decisionSnapshotCapturedAt,
|
|
132583
132986
|
currentPositionSize: Number.isFinite(positionSize) ? positionSize : 0,
|
|
132584
|
-
currentPositionEntryPrice:
|
|
132987
|
+
currentPositionEntryPrice: position?.entry_price ?? null,
|
|
132988
|
+
currentPositionQuoteRate: position?.quote_rate,
|
|
132585
132989
|
walletAddress,
|
|
132586
132990
|
lastPrice: price,
|
|
132587
132991
|
unitSizeUsdc: tradeSize,
|
|
@@ -132845,9 +133249,9 @@ var init_local_analysis = __esm({
|
|
|
132845
133249
|
RUNTIME_SOURCE_DEFINITION_VERSION = "runtime-source-v1";
|
|
132846
133250
|
DECISION_INPUT_DEFINITION_VERSION = "decision-input-v1";
|
|
132847
133251
|
CONTEXT_ENVELOPE_DEFINITION_VERSION = "context-envelope-v2.1";
|
|
132848
|
-
CLIENT_RUNTIME_SOURCE_VERSION = typeof process !== "undefined" && true && "
|
|
132849
|
-
"
|
|
132850
|
-
) ? "
|
|
133252
|
+
CLIENT_RUNTIME_SOURCE_VERSION = typeof process !== "undefined" && true && "296b02cab2d20168659356bd1d28011685e5b358".trim() && !["unknown", "unstamped", "development"].includes(
|
|
133253
|
+
"296b02cab2d20168659356bd1d28011685e5b358".trim().toLowerCase()
|
|
133254
|
+
) ? "296b02cab2d20168659356bd1d28011685e5b358".trim() : null;
|
|
132851
133255
|
CLIENT_MAIN_PROMPT_RENDERER = "client_runtime.buildLocalRuntimePromptArtifacts:v1";
|
|
132852
133256
|
CLIENT_REVIEW_PROMPT_RENDERER = "client_runtime.review_prompt_assembly:v1";
|
|
132853
133257
|
resolveEffectivePromptRuntimeProvenance = (input) => ({
|
|
@@ -132980,103 +133384,6 @@ var init_local_analysis = __esm({
|
|
|
132980
133384
|
return Boolean(renderedValue) && finalPromptText.includes(renderedValue);
|
|
132981
133385
|
}).map(([name]) => name));
|
|
132982
133386
|
};
|
|
132983
|
-
decodeDecisionTracePayload = (rawText, allowedSymbols = []) => {
|
|
132984
|
-
const text2 = String(rawText ?? "").trim();
|
|
132985
|
-
const fencedMatch = text2.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?```$/i);
|
|
132986
|
-
const content = fencedMatch ? String(fencedMatch[1] ?? "").trim() : text2;
|
|
132987
|
-
const candidates = [];
|
|
132988
|
-
const contentVariants = Array.from(/* @__PURE__ */ new Set([content, repairJsonStringSyntax(content)]));
|
|
132989
|
-
for (const candidateContent of contentVariants) {
|
|
132990
|
-
for (let startIndex = 0; startIndex < candidateContent.length; startIndex += 1) {
|
|
132991
|
-
if (candidateContent[startIndex] !== "{") {
|
|
132992
|
-
continue;
|
|
132993
|
-
}
|
|
132994
|
-
let depth = 0;
|
|
132995
|
-
let inString = false;
|
|
132996
|
-
let escaped = false;
|
|
132997
|
-
for (let cursor = startIndex; cursor < candidateContent.length; cursor += 1) {
|
|
132998
|
-
const ch2 = candidateContent[cursor];
|
|
132999
|
-
if (inString) {
|
|
133000
|
-
if (escaped) {
|
|
133001
|
-
escaped = false;
|
|
133002
|
-
} else if (ch2 === "\\") {
|
|
133003
|
-
escaped = true;
|
|
133004
|
-
} else if (ch2 === '"') {
|
|
133005
|
-
inString = false;
|
|
133006
|
-
}
|
|
133007
|
-
continue;
|
|
133008
|
-
}
|
|
133009
|
-
if (ch2 === '"') {
|
|
133010
|
-
inString = true;
|
|
133011
|
-
continue;
|
|
133012
|
-
}
|
|
133013
|
-
if (ch2 === "{") {
|
|
133014
|
-
depth += 1;
|
|
133015
|
-
continue;
|
|
133016
|
-
}
|
|
133017
|
-
if (ch2 === "}") {
|
|
133018
|
-
depth -= 1;
|
|
133019
|
-
if (depth === 0) {
|
|
133020
|
-
candidates.push(candidateContent.slice(startIndex, cursor + 1));
|
|
133021
|
-
break;
|
|
133022
|
-
}
|
|
133023
|
-
}
|
|
133024
|
-
}
|
|
133025
|
-
}
|
|
133026
|
-
}
|
|
133027
|
-
let bestPayload = null;
|
|
133028
|
-
let bestAllowedScore = -1;
|
|
133029
|
-
let bestScore = 0;
|
|
133030
|
-
const allowedSymbolSet = new Set(allowedSymbols);
|
|
133031
|
-
for (const candidate of candidates) {
|
|
133032
|
-
if (!candidate || !candidate.startsWith("{") || !candidate.endsWith("}")) {
|
|
133033
|
-
continue;
|
|
133034
|
-
}
|
|
133035
|
-
try {
|
|
133036
|
-
const parsed = JSON.parse(candidate);
|
|
133037
|
-
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
133038
|
-
const record6 = parsed;
|
|
133039
|
-
const decisionEntries = Object.entries(record6).filter(([, value]) => value && typeof value === "object" && !Array.isArray(value) && Object.prototype.hasOwnProperty.call(value, "decision"));
|
|
133040
|
-
const score = Object.prototype.hasOwnProperty.call(record6, "decision") ? 1 : decisionEntries.length;
|
|
133041
|
-
const allowedScore = decisionEntries.filter(([key]) => allowedSymbolSet.has(key)).length;
|
|
133042
|
-
if (allowedScore > bestAllowedScore || allowedScore === bestAllowedScore && score > bestScore) {
|
|
133043
|
-
bestPayload = record6;
|
|
133044
|
-
bestAllowedScore = allowedScore;
|
|
133045
|
-
bestScore = score;
|
|
133046
|
-
}
|
|
133047
|
-
}
|
|
133048
|
-
} catch {
|
|
133049
|
-
}
|
|
133050
|
-
}
|
|
133051
|
-
return bestPayload;
|
|
133052
|
-
};
|
|
133053
|
-
extractDecisionSymbolTrace = (rawText, allowedSymbols = []) => {
|
|
133054
|
-
const parsed = decodeDecisionTracePayload(rawText, allowedSymbols);
|
|
133055
|
-
if (!parsed) {
|
|
133056
|
-
return [];
|
|
133057
|
-
}
|
|
133058
|
-
if (Object.prototype.hasOwnProperty.call(parsed, "decision")) {
|
|
133059
|
-
return [{
|
|
133060
|
-
symbol: "direct",
|
|
133061
|
-
decision: normalizeDecisionLabel(parsed.decision),
|
|
133062
|
-
units: Math.max(0, Math.trunc(Number(parsed.units) || 0))
|
|
133063
|
-
}];
|
|
133064
|
-
}
|
|
133065
|
-
return Object.entries(parsed).flatMap(([symbol2, value]) => {
|
|
133066
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
133067
|
-
return [];
|
|
133068
|
-
}
|
|
133069
|
-
const scoped = value;
|
|
133070
|
-
if (!Object.prototype.hasOwnProperty.call(scoped, "decision")) {
|
|
133071
|
-
return [];
|
|
133072
|
-
}
|
|
133073
|
-
return [{
|
|
133074
|
-
symbol: symbol2,
|
|
133075
|
-
decision: normalizeDecisionLabel(scoped.decision),
|
|
133076
|
-
units: Math.max(0, Math.trunc(Number(scoped.units) || 0))
|
|
133077
|
-
}];
|
|
133078
|
-
});
|
|
133079
|
-
};
|
|
133080
133387
|
formatDecisionSymbolTrace = (symbols) => symbols.length > 0 ? symbols.map((entry) => `${entry.symbol}:${entry.decision}/${entry.units}`).join(",") : "none";
|
|
133081
133388
|
formatActionableDecisionSymbols = (symbols) => formatDecisionSymbolTrace(symbols.filter((entry) => entry.decision !== "HOLD" && entry.units > 0));
|
|
133082
133389
|
decisionRecordsBySymbol = (plans) => Object.fromEntries(plans.map((plan) => [plan.symbol, {
|
|
@@ -133085,86 +133392,6 @@ var init_local_analysis = __esm({
|
|
|
133085
133392
|
units: plan.units,
|
|
133086
133393
|
tradability: plan.tradability
|
|
133087
133394
|
}]));
|
|
133088
|
-
SERVER_UNREADABLE_REPLY_HOLD_REASONING = "Configured symbol was omitted from the model response. Defaulted to HOLD.";
|
|
133089
|
-
buildMissingDecisionHold = (symbol2, reasoning = `No valid model decision was returned for configured symbol ${symbol2}.`) => ({
|
|
133090
|
-
symbol: symbol2,
|
|
133091
|
-
decision: "HOLD",
|
|
133092
|
-
units: 0,
|
|
133093
|
-
tradability: null,
|
|
133094
|
-
reasoning
|
|
133095
|
-
});
|
|
133096
|
-
buildDecisionPlansFromResponse = (rawText, promptSymbols, fallbackSymbol, fallbackDecision, fallbackUnits, fallbackTradability, fallbackReasoning) => {
|
|
133097
|
-
const normalizedPromptSymbols = normalizePromptSymbols(promptSymbols);
|
|
133098
|
-
const allowedSymbols = new Set(normalizedPromptSymbols);
|
|
133099
|
-
const payload = decodeDecisionTracePayload(rawText, normalizedPromptSymbols);
|
|
133100
|
-
const trace = extractDecisionSymbolTrace(rawText, normalizedPromptSymbols);
|
|
133101
|
-
const scopedTraceBySymbol = /* @__PURE__ */ new Map();
|
|
133102
|
-
for (const entry of trace) {
|
|
133103
|
-
const normalizedSymbol = String(entry.symbol || "").trim();
|
|
133104
|
-
if (normalizedSymbol && normalizedSymbol !== "DIRECT" && allowedSymbols.has(normalizedSymbol) && !scopedTraceBySymbol.has(normalizedSymbol)) {
|
|
133105
|
-
scopedTraceBySymbol.set(normalizedSymbol, entry);
|
|
133106
|
-
}
|
|
133107
|
-
}
|
|
133108
|
-
if (scopedTraceBySymbol.size > 0) {
|
|
133109
|
-
return normalizedPromptSymbols.map((normalizedSymbol) => {
|
|
133110
|
-
const entry = scopedTraceBySymbol.get(normalizedSymbol);
|
|
133111
|
-
if (!entry) {
|
|
133112
|
-
return buildMissingDecisionHold(normalizedSymbol);
|
|
133113
|
-
}
|
|
133114
|
-
const scopedPayload = payload?.[entry.symbol];
|
|
133115
|
-
const scopedText = scopedPayload && typeof scopedPayload === "object" && !Array.isArray(scopedPayload) ? JSON.stringify(scopedPayload) : rawText;
|
|
133116
|
-
const parsed = extractNormalizedDecision(scopedText, null, entry.symbol);
|
|
133117
|
-
const units = parsed.decision === "HOLD" ? 0 : parsed.units > 0 ? parsed.units : entry.units;
|
|
133118
|
-
return {
|
|
133119
|
-
symbol: normalizedSymbol,
|
|
133120
|
-
decision: parsed.decision,
|
|
133121
|
-
units,
|
|
133122
|
-
tradability: parsed.tradability,
|
|
133123
|
-
reasoning: parsed.reasoning
|
|
133124
|
-
};
|
|
133125
|
-
});
|
|
133126
|
-
}
|
|
133127
|
-
const directTrace = trace.find((entry) => normalizeHyperliquidMarketSymbol(entry.symbol) === "DIRECT");
|
|
133128
|
-
if (directTrace && normalizedPromptSymbols.length === 1) {
|
|
133129
|
-
return normalizedPromptSymbols.map((normalizedSymbol, index) => index === 0 ? {
|
|
133130
|
-
symbol: normalizedSymbol,
|
|
133131
|
-
decision: fallbackDecision,
|
|
133132
|
-
units: fallbackDecision === "HOLD" ? 0 : Math.max(0, Math.trunc(Number(fallbackUnits) || 0)),
|
|
133133
|
-
tradability: fallbackTradability,
|
|
133134
|
-
reasoning: fallbackReasoning
|
|
133135
|
-
} : buildMissingDecisionHold(normalizedSymbol));
|
|
133136
|
-
}
|
|
133137
|
-
if (directTrace && normalizedPromptSymbols.length > 1) {
|
|
133138
|
-
return normalizedPromptSymbols.map((normalizedSymbol) => buildMissingDecisionHold(
|
|
133139
|
-
normalizedSymbol,
|
|
133140
|
-
`Model response did not provide a symbol-keyed decision for configured symbol ${normalizedSymbol}.`
|
|
133141
|
-
));
|
|
133142
|
-
}
|
|
133143
|
-
const hasForeignSymbolDecision = trace.some((entry) => {
|
|
133144
|
-
const normalizedSymbol = String(entry.symbol || "").trim();
|
|
133145
|
-
return normalizedSymbol && normalizedSymbol !== "DIRECT" && !allowedSymbols.has(normalizedSymbol);
|
|
133146
|
-
});
|
|
133147
|
-
if (hasForeignSymbolDecision) {
|
|
133148
|
-
return normalizedPromptSymbols.map((normalizedSymbol) => buildMissingDecisionHold(
|
|
133149
|
-
normalizedSymbol,
|
|
133150
|
-
`Model response contained no decision for configured symbol ${normalizedSymbol}.`
|
|
133151
|
-
));
|
|
133152
|
-
}
|
|
133153
|
-
const normalizedFallbackSymbol = normalizedPromptSymbols.find(
|
|
133154
|
-
(promptSymbol) => promptSymbol === String(fallbackSymbol || "").trim()
|
|
133155
|
-
) ?? String(fallbackSymbol || "").trim();
|
|
133156
|
-
const fallbackPlan = {
|
|
133157
|
-
symbol: normalizedFallbackSymbol || fallbackSymbol,
|
|
133158
|
-
decision: fallbackDecision,
|
|
133159
|
-
units: fallbackDecision === "HOLD" ? 0 : Math.max(0, Math.trunc(Number(fallbackUnits) || 0)),
|
|
133160
|
-
tradability: fallbackTradability,
|
|
133161
|
-
reasoning: fallbackReasoning
|
|
133162
|
-
};
|
|
133163
|
-
if (normalizedPromptSymbols.length === 0) {
|
|
133164
|
-
return [fallbackPlan];
|
|
133165
|
-
}
|
|
133166
|
-
return normalizedPromptSymbols.map((normalizedSymbol) => normalizedSymbol === fallbackPlan.symbol ? fallbackPlan : buildMissingDecisionHold(normalizedSymbol));
|
|
133167
|
-
};
|
|
133168
133395
|
buildReviewCandidatePlansFromResponse = (rawText, promptSymbols, fallbackPlans) => {
|
|
133169
133396
|
const normalizedPromptSymbols = normalizePromptSymbols(promptSymbols);
|
|
133170
133397
|
const allowedSymbols = new Set(normalizedPromptSymbols);
|
|
@@ -133400,13 +133627,6 @@ ${reviewOutputContract}`;
|
|
|
133400
133627
|
}
|
|
133401
133628
|
throw result.error;
|
|
133402
133629
|
};
|
|
133403
|
-
normalizeDecisionLabel = (value) => {
|
|
133404
|
-
const normalized = String(value ?? "").trim().toUpperCase();
|
|
133405
|
-
if (normalized === "BUY" || normalized === "SELL") {
|
|
133406
|
-
return normalized;
|
|
133407
|
-
}
|
|
133408
|
-
return "HOLD";
|
|
133409
|
-
};
|
|
133410
133630
|
normalizeRuntimeSymbol = normalizeHyperliquidMarketSymbol;
|
|
133411
133631
|
PromptContractFetchError = class extends Error {
|
|
133412
133632
|
constructor(message, metadata) {
|
|
@@ -135760,6 +135980,7 @@ ${stringifyPromptJson(withUtcCandleOpenTimes(parts.candlesPayload))}
|
|
|
135760
135980
|
const accountStateStartedAtMs = Date.now();
|
|
135761
135981
|
let promptRescueSequence = input.dispatchContextRebuild === true ? PROMPT_RESCUE_ASKS_PER_CYCLE_BUILD : 0;
|
|
135762
135982
|
observeRuntimeCycle(input, { stage: "market_context" });
|
|
135983
|
+
const rescues = input.executionMode === "server" && executorOf(config2).exchange === "hyperliquid";
|
|
135763
135984
|
const rescueAccountState = async (serverReason) => {
|
|
135764
135985
|
promptRescueSequence += 1;
|
|
135765
135986
|
try {
|
|
@@ -135792,7 +136013,7 @@ ${stringifyPromptJson(withUtcCandleOpenTimes(parts.candlesPayload))}
|
|
|
135792
136013
|
}
|
|
135793
136014
|
};
|
|
135794
136015
|
const browserAccountStateTask = (async () => {
|
|
135795
|
-
if (
|
|
136016
|
+
if (rescues && input.dispatchContextRebuild !== true && await hyperliquidPrivateInfoHeldOff()) {
|
|
135796
136017
|
try {
|
|
135797
136018
|
return await rescueAccountState(SERVER_PROMPT_RESCUE_NODE_OUTAGE_REASON);
|
|
135798
136019
|
} catch (rescueError) {
|
|
@@ -135821,7 +136042,7 @@ ${stringifyPromptJson(withUtcCandleOpenTimes(parts.candlesPayload))}
|
|
|
135821
136042
|
signal: timeoutController.signal
|
|
135822
136043
|
});
|
|
135823
136044
|
})().catch(async (error48) => {
|
|
135824
|
-
if (
|
|
136045
|
+
if (!rescues || !(error48 instanceof HyperliquidPublicReadError)) throw error48;
|
|
135825
136046
|
try {
|
|
135826
136047
|
return await rescueAccountState(error48.code);
|
|
135827
136048
|
} catch (rescueError) {
|
|
@@ -136528,16 +136749,16 @@ ${stringifyPromptJson(withUtcCandleOpenTimes(parts.candlesPayload))}
|
|
|
136528
136749
|
if (planPrice == null) {
|
|
136529
136750
|
throw new Error(`Missing required positive market price for client runtime execution context: ${planSymbol}`);
|
|
136530
136751
|
}
|
|
136531
|
-
const
|
|
136532
|
-
|
|
136533
|
-
);
|
|
136752
|
+
const planPosition = positions.find((position) => normalizeRuntimeSymbol(position.symbol) === normalizeRuntimeSymbol(planSymbol));
|
|
136753
|
+
const planPositionSize = Number(planPosition?.size ?? 0);
|
|
136534
136754
|
return {
|
|
136535
136755
|
symbol: planSymbol,
|
|
136536
136756
|
timeframe,
|
|
136537
136757
|
decisionSnapshotId,
|
|
136538
136758
|
decisionSnapshotCapturedAt,
|
|
136539
136759
|
currentPositionSize: Number.isFinite(planPositionSize) ? planPositionSize : 0,
|
|
136540
|
-
currentPositionEntryPrice:
|
|
136760
|
+
currentPositionEntryPrice: planPosition?.entry_price ?? null,
|
|
136761
|
+
currentPositionQuoteRate: planPosition?.quote_rate,
|
|
136541
136762
|
walletAddress: botAccountAddress(settings) || void 0,
|
|
136542
136763
|
lastPrice: planPrice,
|
|
136543
136764
|
unitSizeUsdc: metadataTradeSize,
|
|
@@ -136712,10 +136933,7 @@ ${stringifyPromptJson(withUtcCandleOpenTimes(parts.candlesPayload))}
|
|
|
136712
136933
|
temperature: entryParameters?.temperature ?? temperature,
|
|
136713
136934
|
// Every Main model gets at least the configured output budget, as in
|
|
136714
136935
|
// the Server loop (ai_trading_service.py _execute_llm_request).
|
|
136715
|
-
maxTokens:
|
|
136716
|
-
entryParameters?.max_tokens ?? maxTokens,
|
|
136717
|
-
requirePositiveIntegerField(config2.max_tokens_min, "max_tokens_min")
|
|
136718
|
-
),
|
|
136936
|
+
maxTokens: traderMainMaxTokens(entryParameters?.max_tokens ?? maxTokens, config2),
|
|
136719
136937
|
reasoningPayload: modelIndex === 0 ? reasoningPayload : buildRuntimeReasoningPayload(controls, extractRuntimeReasoningSelection({ runtime_reasoning: entryParameters?.runtime_reasoning }, controls.control_type, controls.control_type === "toggle" ? controls.toggle_behavior : "disable_reasoning")),
|
|
136720
136938
|
nativeRequestParameters: entryConfig?.native_request_parameters,
|
|
136721
136939
|
nativeRequestParameterValues: modelIndex === 0 ? nativeRequestParameterValues : filterNativeRequestParameterValues(entryConfig?.native_request_parameters, entryParameters?.native_request_parameter_values),
|
|
@@ -136784,21 +137002,12 @@ ${stringifyPromptJson(withUtcCandleOpenTimes(parts.candlesPayload))}
|
|
|
136784
137002
|
let primaryDecisionContent = providerResponse.content;
|
|
136785
137003
|
let mainReplyUnreadable = false;
|
|
136786
137004
|
if (!allPromptSymbolsUnavailable && !isExternalRuntimeProviderResult(providerResponse)) {
|
|
136787
|
-
const
|
|
136788
|
-
if (validationErrors.length > 0 && input.executionMode !== "server") {
|
|
136789
|
-
throw modelOutputValidationError("Main", providerResponse.invocations, validationErrors, promptSymbols);
|
|
136790
|
-
}
|
|
136791
|
-
if (validationErrors.length > 0) {
|
|
136792
|
-
mainReplyUnreadable = true;
|
|
136793
|
-
primaryDecisionContent = JSON.stringify(Object.fromEntries(promptSymbols.map((promptSymbol) => [promptSymbol, {
|
|
136794
|
-
decision: "HOLD",
|
|
136795
|
-
units: 0,
|
|
136796
|
-
tradability: null,
|
|
136797
|
-
reasoning: SERVER_UNREADABLE_REPLY_HOLD_REASONING
|
|
136798
|
-
}])));
|
|
136799
|
-
} else {
|
|
136800
|
-
primaryDecisionContent = projectCurrentModelDecisionContent(providerResponse.content);
|
|
137005
|
+
const read2 = readTraderReplyContent(providerResponse.content, promptSymbols);
|
|
137006
|
+
if (read2.validationErrors.length > 0 && input.executionMode !== "server") {
|
|
137007
|
+
throw modelOutputValidationError("Main", providerResponse.invocations, read2.validationErrors, promptSymbols);
|
|
136801
137008
|
}
|
|
137009
|
+
mainReplyUnreadable = read2.validationErrors.length > 0;
|
|
137010
|
+
primaryDecisionContent = read2.decisionContent;
|
|
136802
137011
|
}
|
|
136803
137012
|
const primaryParseOutcome = mainReplyUnreadable ? {
|
|
136804
137013
|
status: "failed",
|
|
@@ -136818,17 +137027,10 @@ ${stringifyPromptJson(withUtcCandleOpenTimes(parts.candlesPayload))}
|
|
|
136818
137027
|
}
|
|
136819
137028
|
);
|
|
136820
137029
|
if (invocationAttempts.length) input.onModelCallsReturned?.(invocationAttempts);
|
|
136821
|
-
const
|
|
137030
|
+
const primaryRead = traderDecisionPlans(primaryDecisionContent, promptSymbols, symbol2);
|
|
137031
|
+
const parsed = primaryRead.parsed;
|
|
136822
137032
|
const primaryDecisionSymbolTrace = extractDecisionSymbolTrace(primaryDecisionContent, promptSymbols);
|
|
136823
|
-
const primaryDecisionPlans = forceUnavailableSymbolsToHold(
|
|
136824
|
-
primaryDecisionContent,
|
|
136825
|
-
promptSymbols,
|
|
136826
|
-
symbol2,
|
|
136827
|
-
parsed.decision,
|
|
136828
|
-
parsed.units,
|
|
136829
|
-
parsed.tradability,
|
|
136830
|
-
parsed.reasoning
|
|
136831
|
-
), unavailablePromptSymbols);
|
|
137033
|
+
const primaryDecisionPlans = forceUnavailableSymbolsToHold(primaryRead.plans, unavailablePromptSymbols);
|
|
136832
137034
|
const primaryReviewCandidatePlans = forceUnavailableSymbolsToHold(buildReviewCandidatePlansFromResponse(
|
|
136833
137035
|
primaryDecisionContent,
|
|
136834
137036
|
promptSymbols,
|
|
@@ -136904,7 +137106,7 @@ ${stringifyPromptJson(withUtcCandleOpenTimes(parts.candlesPayload))}
|
|
|
136904
137106
|
const computePlanSignedUnits = (planSymbol) => {
|
|
136905
137107
|
const position = positionBySymbol.get(normalizeRuntimeSymbol(planSymbol));
|
|
136906
137108
|
if (!position) return 0;
|
|
136907
|
-
return
|
|
137109
|
+
return signedUnitsOfPosition(position, metadataTradeSize);
|
|
136908
137110
|
};
|
|
136909
137111
|
const reviewCandidatePlans = primaryReviewCandidatePlans.filter((entry) => {
|
|
136910
137112
|
if (unavailablePromptSymbols.has(normalizeRuntimeSymbol(entry.symbol))) return false;
|
|
@@ -144119,8 +144321,9 @@ var init_engine = __esm({
|
|
|
144119
144321
|
const serverCapacityByPlan = /* @__PURE__ */ new Map();
|
|
144120
144322
|
if (this._expectedExecutionMode === "server") {
|
|
144121
144323
|
const capacityPlans = executionPlans.map((plan, planIndex) => ({ plan, planIndex, decision: String(plan.decision || "").toUpperCase() })).filter(({ plan, decision }) => !plan.executionBlock && (decision === "BUY" || decision === "SELL") && Math.trunc(Number(plan.units)) > 0);
|
|
144122
|
-
const allocations =
|
|
144324
|
+
const allocations = await allocateServerExecutionCapacity({
|
|
144123
144325
|
profileId,
|
|
144326
|
+
config: config2,
|
|
144124
144327
|
sessionId,
|
|
144125
144328
|
runtimeLeaseToken: executionLeaseToken(),
|
|
144126
144329
|
runtimeDeviceId: deviceId,
|
|
@@ -144453,11 +144656,7 @@ var init_engine = __esm({
|
|
|
144453
144656
|
const cycleSupersededWithoutExecution = () => !this._executionFinalizationRequired && (analysisAbortController.signal.aborted || this._isStopping || this._analysisRequestId !== requestId);
|
|
144454
144657
|
const advisorySignedUnits = (context) => {
|
|
144455
144658
|
try {
|
|
144456
|
-
return
|
|
144457
|
-
context.currentPositionSize,
|
|
144458
|
-
context.currentPositionEntryPrice,
|
|
144459
|
-
context.unitSizeUsdc
|
|
144460
|
-
);
|
|
144659
|
+
return contextSignedUnits(context);
|
|
144461
144660
|
} catch {
|
|
144462
144661
|
return 0;
|
|
144463
144662
|
}
|