@adaptic/backend 0.0.1056 → 0.0.1057

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.
Files changed (184) hide show
  1. package/Account.cjs +14 -0
  2. package/AccountLinkingRequest.cjs +14 -0
  3. package/AccountRiskMetrics.cjs +11 -0
  4. package/AdaConversation.cjs +14 -0
  5. package/Alert.cjs +11 -0
  6. package/Allocation.cjs +11 -0
  7. package/AlpacaAccount.cjs +36 -0
  8. package/Authenticator.cjs +14 -0
  9. package/AutoFollowRule.cjs +14 -0
  10. package/BrokerageAccount.cjs +11 -0
  11. package/Customer.cjs +14 -0
  12. package/DeskDecision.cjs +11 -0
  13. package/FeatureFlagOverride.cjs +14 -0
  14. package/Follow.cjs +14 -0
  15. package/Fund.cjs +56 -0
  16. package/FundAssignment.cjs +14 -0
  17. package/Investor.cjs +14 -0
  18. package/LinkedProvider.cjs +14 -0
  19. package/LlmConfiguration.cjs +14 -0
  20. package/Mandate.cjs +14 -0
  21. package/MandateApproval.cjs +14 -0
  22. package/MandateVersion.cjs +14 -0
  23. package/NotificationDelivery.cjs +14 -0
  24. package/NotificationPreference.cjs +14 -0
  25. package/OrgMembership.cjs +14 -0
  26. package/PolicyOverlay.cjs +64 -0
  27. package/PushSubscription.cjs +14 -0
  28. package/RiskEscalationEvent.cjs +33 -0
  29. package/Session.cjs +14 -0
  30. package/Strategy.cjs +28 -0
  31. package/StrategyHealthSnapshot.cjs +11 -0
  32. package/StrategySubscription.cjs +11 -0
  33. package/TradingPolicy.cjs +6 -0
  34. package/User.cjs +11 -0
  35. package/UserTotp.cjs +14 -0
  36. package/WaitlistEntry.cjs +14 -0
  37. package/esm/Account.mjs +14 -0
  38. package/esm/AccountLinkingRequest.mjs +14 -0
  39. package/esm/AccountRiskMetrics.mjs +11 -0
  40. package/esm/AdaConversation.mjs +14 -0
  41. package/esm/Alert.mjs +11 -0
  42. package/esm/Allocation.mjs +11 -0
  43. package/esm/AlpacaAccount.mjs +36 -0
  44. package/esm/Authenticator.mjs +14 -0
  45. package/esm/AutoFollowRule.mjs +14 -0
  46. package/esm/BrokerageAccount.mjs +11 -0
  47. package/esm/Customer.mjs +14 -0
  48. package/esm/DeskDecision.mjs +11 -0
  49. package/esm/FeatureFlagOverride.mjs +14 -0
  50. package/esm/Follow.mjs +14 -0
  51. package/esm/Fund.mjs +56 -0
  52. package/esm/FundAssignment.mjs +14 -0
  53. package/esm/Investor.mjs +14 -0
  54. package/esm/LinkedProvider.mjs +14 -0
  55. package/esm/LlmConfiguration.mjs +14 -0
  56. package/esm/Mandate.mjs +14 -0
  57. package/esm/MandateApproval.mjs +14 -0
  58. package/esm/MandateVersion.mjs +14 -0
  59. package/esm/NotificationDelivery.mjs +14 -0
  60. package/esm/NotificationPreference.mjs +14 -0
  61. package/esm/OrgMembership.mjs +14 -0
  62. package/esm/PolicyOverlay.mjs +64 -0
  63. package/esm/PushSubscription.mjs +14 -0
  64. package/esm/RiskEscalationEvent.mjs +33 -0
  65. package/esm/Session.mjs +14 -0
  66. package/esm/Strategy.mjs +28 -0
  67. package/esm/StrategyHealthSnapshot.mjs +11 -0
  68. package/esm/StrategySubscription.mjs +11 -0
  69. package/esm/TradingPolicy.mjs +6 -0
  70. package/esm/User.mjs +11 -0
  71. package/esm/UserTotp.mjs +14 -0
  72. package/esm/WaitlistEntry.mjs +14 -0
  73. package/esm/generated/typeStrings/PolicyOverlay.d.ts +1 -1
  74. package/esm/generated/typeStrings/PolicyOverlay.mjs +18 -0
  75. package/esm/generated/typeStrings/TradingPolicy.d.ts +1 -1
  76. package/esm/generated/typeStrings/TradingPolicy.mjs +18 -0
  77. package/esm/generated/typeStrings/index.d.ts +2 -2
  78. package/esm/generated/typegraphql-prisma/enhance.mjs +18 -18
  79. package/esm/generated/typegraphql-prisma/enums/TradingPolicyScalarFieldEnum.d.ts +1 -0
  80. package/esm/generated/typegraphql-prisma/enums/TradingPolicyScalarFieldEnum.mjs +1 -0
  81. package/esm/generated/typegraphql-prisma/models/TradingPolicy.d.ts +20 -0
  82. package/esm/generated/typegraphql-prisma/models/TradingPolicy.mjs +27 -0
  83. package/esm/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindFirstTradingPolicyArgs.d.ts +1 -1
  84. package/esm/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindFirstTradingPolicyOrThrowArgs.d.ts +1 -1
  85. package/esm/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindManyTradingPolicyArgs.d.ts +1 -1
  86. package/esm/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/GroupByTradingPolicyArgs.d.ts +1 -1
  87. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCountOrderByAggregateInput.d.ts +1 -0
  88. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCountOrderByAggregateInput.mjs +7 -0
  89. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateInput.d.ts +1 -0
  90. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateInput.mjs +7 -0
  91. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateManyInput.d.ts +1 -0
  92. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateManyInput.mjs +7 -0
  93. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutAlpacaAccountInput.d.ts +1 -0
  94. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutAlpacaAccountInput.mjs +7 -0
  95. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutOverlaysInput.d.ts +1 -0
  96. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutOverlaysInput.mjs +7 -0
  97. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithAggregationInput.d.ts +1 -0
  98. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithAggregationInput.mjs +7 -0
  99. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithRelationInput.d.ts +1 -0
  100. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithRelationInput.mjs +7 -0
  101. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyScalarWhereWithAggregatesInput.d.ts +1 -0
  102. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyScalarWhereWithAggregatesInput.mjs +7 -0
  103. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateInput.d.ts +1 -0
  104. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateInput.mjs +7 -0
  105. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateManyMutationInput.d.ts +1 -0
  106. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateManyMutationInput.mjs +7 -0
  107. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutAlpacaAccountInput.d.ts +1 -0
  108. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutAlpacaAccountInput.mjs +7 -0
  109. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutOverlaysInput.d.ts +1 -0
  110. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutOverlaysInput.mjs +7 -0
  111. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereInput.d.ts +1 -0
  112. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereInput.mjs +7 -0
  113. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereUniqueInput.d.ts +1 -0
  114. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereUniqueInput.mjs +7 -0
  115. package/esm/generated/typegraphql-prisma/resolvers/outputs/CreateManyAndReturnTradingPolicy.d.ts +1 -0
  116. package/esm/generated/typegraphql-prisma/resolvers/outputs/CreateManyAndReturnTradingPolicy.mjs +7 -0
  117. package/esm/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyCountAggregate.d.ts +1 -0
  118. package/esm/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyCountAggregate.mjs +7 -0
  119. package/esm/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyGroupBy.d.ts +1 -0
  120. package/esm/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyGroupBy.mjs +7 -0
  121. package/esm/index.d.ts +1 -0
  122. package/esm/index.mjs +2 -0
  123. package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +5 -0
  124. package/esm/middleware/mutation-account-facts.d.ts +3 -0
  125. package/esm/middleware/mutation-account-facts.mjs +2 -0
  126. package/esm/middleware/trading-policy-audit.d.ts +16 -4
  127. package/esm/middleware/trading-policy-audit.mjs +40 -11
  128. package/esm/readers/index.d.ts +10 -0
  129. package/esm/readers/index.mjs +10 -0
  130. package/esm/readers/intraday-lane-prefs.d.ts +45 -0
  131. package/esm/readers/intraday-lane-prefs.mjs +71 -0
  132. package/esm/tests/trading-policy-lane-fields-roundtrip.harness.d.ts +14 -0
  133. package/esm/tests/trading-policy-lane-fields-roundtrip.harness.mjs +107 -0
  134. package/generated/typeStrings/PolicyOverlay.cjs +18 -0
  135. package/generated/typeStrings/PolicyOverlay.d.ts +1 -1
  136. package/generated/typeStrings/TradingPolicy.cjs +18 -0
  137. package/generated/typeStrings/TradingPolicy.d.ts +1 -1
  138. package/generated/typeStrings/index.d.ts +2 -2
  139. package/generated/typegraphql-prisma/enhance.cjs +18 -18
  140. package/generated/typegraphql-prisma/enums/TradingPolicyScalarFieldEnum.cjs +1 -0
  141. package/generated/typegraphql-prisma/enums/TradingPolicyScalarFieldEnum.d.ts +1 -0
  142. package/generated/typegraphql-prisma/models/TradingPolicy.cjs +7 -0
  143. package/generated/typegraphql-prisma/models/TradingPolicy.d.ts +20 -0
  144. package/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindFirstTradingPolicyArgs.d.ts +1 -1
  145. package/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindFirstTradingPolicyOrThrowArgs.d.ts +1 -1
  146. package/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindManyTradingPolicyArgs.d.ts +1 -1
  147. package/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/GroupByTradingPolicyArgs.d.ts +1 -1
  148. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCountOrderByAggregateInput.cjs +6 -0
  149. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCountOrderByAggregateInput.d.ts +1 -0
  150. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateInput.cjs +6 -0
  151. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateInput.d.ts +1 -0
  152. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateManyInput.cjs +6 -0
  153. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateManyInput.d.ts +1 -0
  154. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutAlpacaAccountInput.cjs +6 -0
  155. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutAlpacaAccountInput.d.ts +1 -0
  156. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutOverlaysInput.cjs +6 -0
  157. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutOverlaysInput.d.ts +1 -0
  158. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithAggregationInput.cjs +6 -0
  159. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithAggregationInput.d.ts +1 -0
  160. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithRelationInput.cjs +6 -0
  161. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithRelationInput.d.ts +1 -0
  162. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyScalarWhereWithAggregatesInput.cjs +6 -0
  163. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyScalarWhereWithAggregatesInput.d.ts +1 -0
  164. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateInput.cjs +6 -0
  165. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateInput.d.ts +1 -0
  166. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateManyMutationInput.cjs +6 -0
  167. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateManyMutationInput.d.ts +1 -0
  168. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutAlpacaAccountInput.cjs +6 -0
  169. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutAlpacaAccountInput.d.ts +1 -0
  170. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutOverlaysInput.cjs +6 -0
  171. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutOverlaysInput.d.ts +1 -0
  172. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereInput.cjs +6 -0
  173. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereInput.d.ts +1 -0
  174. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereUniqueInput.cjs +6 -0
  175. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereUniqueInput.d.ts +1 -0
  176. package/generated/typegraphql-prisma/resolvers/outputs/CreateManyAndReturnTradingPolicy.cjs +6 -0
  177. package/generated/typegraphql-prisma/resolvers/outputs/CreateManyAndReturnTradingPolicy.d.ts +1 -0
  178. package/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyCountAggregate.cjs +6 -0
  179. package/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyCountAggregate.d.ts +1 -0
  180. package/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyGroupBy.cjs +6 -0
  181. package/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyGroupBy.d.ts +1 -0
  182. package/index.cjs +2 -0
  183. package/index.d.ts +1 -0
  184. package/package.json +1 -1
@@ -77,6 +77,7 @@ let TradingPolicyGroupBy = class TradingPolicyGroupBy {
77
77
  maxOrdersPerWindow;
78
78
  orderWindowSeconds;
79
79
  dayTradeOnly;
80
+ intradayLanePrefs;
80
81
  riskBudgetPrefs;
81
82
  signalConsumptionPrefs;
82
83
  executionPrefs;
@@ -468,6 +469,12 @@ __decorate([
468
469
  }),
469
470
  __metadata("design:type", Boolean)
470
471
  ], TradingPolicyGroupBy.prototype, "dayTradeOnly", void 0);
472
+ __decorate([
473
+ TypeGraphQL.Field(_type => GraphQLScalars.JSONResolver, {
474
+ nullable: true
475
+ }),
476
+ __metadata("design:type", Object)
477
+ ], TradingPolicyGroupBy.prototype, "intradayLanePrefs", void 0);
471
478
  __decorate([
472
479
  TypeGraphQL.Field(_type => GraphQLScalars.JSONResolver, {
473
480
  nullable: true
package/esm/index.d.ts CHANGED
@@ -3,6 +3,7 @@ export type * as types from './generated/typegraphql-prisma/models/index.d.ts';
3
3
  export * as enums from './generated/typegraphql-prisma/enums/index';
4
4
  export * from './generated/typeStrings/index';
5
5
  export * from './resolvers/custom/index';
6
+ export * from './readers/index';
6
7
  export { getApolloClient, getApolloModules, configureConnectionPool, setTokenProvider, stopClient, getPoolStats, client } from './client';
7
8
  export type { ApolloClientType, InMemoryCacheType, HttpLinkType, NormalizedCacheObject, TokenProvider, PoolStats, } from './client';
8
9
  declare const adaptic: {
package/esm/index.mjs CHANGED
@@ -6,6 +6,8 @@ export * as enums from "./generated/typegraphql-prisma/enums/index.mjs";
6
6
  export * from './generated/typeStrings/index.mjs';
7
7
  // Export custom resolvers
8
8
  export * from "./resolvers/custom/index.mjs";
9
+ // Hand-written narrow reads of fields that no generated selection set carries
10
+ export * from './readers/index.mjs';
9
11
  // Re-export Apollo Client functions from client.ts
10
12
  export { getApolloClient, getApolloModules, configureConnectionPool, setTokenProvider, stopClient, getPoolStats, client } from "./client.mjs";
11
13
  import { ABTest } from './ABTest.mjs';
@@ -218,6 +218,8 @@ const BROKER_BRIDGE_FOREIGN = `mutation { createOneBrokerageAccount(data: { fund
218
218
  const BROKER_ROTATE = (userId) => `mutation { updateOneBrokerageAccount(where: { id: "ba1" }, data: { label: { set: "rotated" }, engineAccount: { upsert: { create: { APIKey: "${API_KEY}", APISecret: "${API_SECRET}", user: { connect: { id: "${userId}" } } }, update: { APIKey: { set: "${API_KEY}" } } } } }) { id } }`;
219
219
  const SUSPEND_UPSERT = 'mutation { upsertOneTradingPolicy(where: { alpacaAccountId: "a2" }, create: { alpacaAccount: { connect: { id: "a2" } } }, update: { killSwitchEnabled: { set: true } }) { id } }';
220
220
  const DISARM_LIVE = 'mutation Disarm { updateOneTradingPolicy(where: { alpacaAccountId: "a1" }, data: { realtimeTradingEnabled: { set: false } }) { id } }';
221
+ const DISARM_LIVE_WITH_LANES = 'mutation DisarmLanes { updateOneTradingPolicy(where: { alpacaAccountId: "a1" }, data: { realtimeTradingEnabled: { set: false }, intradayLanePrefs: { armed: false } }) { id } }';
222
+ const ARM_LANES_LIVE = 'mutation ArmLanes { updateOneTradingPolicy(where: { alpacaAccountId: "a1" }, data: { intradayLanePrefs: { armed: true } }) { id } }';
221
223
  // Credential predicates: a `where` over a stored credential must be refused
222
224
  // before the guard reads a row with it, or the rows it matched land in the
223
225
  // audit trail and the filter becomes an oracle over the credential.
@@ -361,6 +363,8 @@ export const SCENARIOS = [
361
363
  mode: 'enforce',
362
364
  },
363
365
  { name: 'm/disarmAuditDown/server/enforce', query: DISARM_LIVE, principal: 'server', mode: 'enforce', auditDown: true },
366
+ { name: 'm/disarmLanesAuditDown/server/enforce', query: DISARM_LIVE_WITH_LANES, principal: 'server', mode: 'enforce', auditDown: true },
367
+ { name: 'm/armLanesAuditDown/server/enforce', query: ARM_LANES_LIVE, principal: 'server', mode: 'enforce', auditDown: true },
364
368
  { name: 'ctl/brokerCreate/fundUser/enforce', query: BROKER_CREATE, principal: 'fundUser', mode: 'enforce' },
365
369
  { name: 'ctl/brokerCreateOtherOwner/fundUser/enforce', query: BROKER_CREATE_OTHER_OWNER, principal: 'fundUser', mode: 'enforce' },
366
370
  { name: 'ctl/brokerBridgeForeign/fundUser/enforce', query: BROKER_BRIDGE_FOREIGN, principal: 'fundUser', mode: 'enforce' },
@@ -407,6 +411,7 @@ function policyFacts(p) {
407
411
  paperTradingOnly: false,
408
412
  killSwitchEnabled: false,
409
413
  autonomyMode: 'ADVISORY_ONLY',
414
+ intradayLanePrefs: null,
410
415
  alpacaAccount: ACCOUNTS[p.alpacaAccountId],
411
416
  };
412
417
  }
@@ -13,6 +13,7 @@
13
13
  *
14
14
  * @module middleware/mutation-account-facts
15
15
  */
16
+ import type { Prisma } from '@prisma/client';
16
17
  import type { AccountOwnership, MutationTarget } from '../auth/mutation-authorization';
17
18
  import type { NestedWrite } from '../auth/nested-write-inspector';
18
19
  import type { TenantScopePrisma } from './mutation-tenant-facts';
@@ -36,6 +37,7 @@ declare const POLICY_SELECT: {
36
37
  readonly paperTradingOnly: true;
37
38
  readonly killSwitchEnabled: true;
38
39
  readonly autonomyMode: true;
40
+ readonly intradayLanePrefs: true;
39
41
  readonly alpacaAccount: {
40
42
  readonly select: {
41
43
  readonly id: true;
@@ -66,6 +68,7 @@ export interface PolicyFacts {
66
68
  readonly paperTradingOnly: boolean;
67
69
  readonly killSwitchEnabled: boolean;
68
70
  readonly autonomyMode: string;
71
+ readonly intradayLanePrefs: Prisma.JsonValue | null;
69
72
  readonly alpacaAccount: AccountFacts;
70
73
  }
71
74
  type Where = Record<string, unknown>;
@@ -29,6 +29,7 @@ const POLICY_SELECT = {
29
29
  paperTradingOnly: true,
30
30
  killSwitchEnabled: true,
31
31
  autonomyMode: true,
32
+ intradayLanePrefs: true,
32
33
  alpacaAccount: { select: ACCOUNT_SELECT },
33
34
  };
34
35
  function asRecord(value) {
@@ -58,6 +59,7 @@ function policyRow(row, nestedPath = null) {
58
59
  paperTradingOnly: row.paperTradingOnly,
59
60
  killSwitchEnabled: row.killSwitchEnabled,
60
61
  autonomyMode: row.autonomyMode,
62
+ intradayLanePrefs: row.intradayLanePrefs,
61
63
  },
62
64
  };
63
65
  }
@@ -40,15 +40,27 @@
40
40
  *
41
41
  * @module middleware/trading-policy-audit
42
42
  */
43
+ import type { Prisma } from '@prisma/client';
43
44
  import { Counter } from 'prom-client';
44
45
  import type { MutationAction, MutationAuthReason } from '../auth/mutation-authorization';
45
46
  import type { BackendPrincipal } from '../auth/token-verifier';
46
47
  /** Header a caller uses to state why it is changing a policy. */
47
48
  export declare const CHANGE_REASON_HEADER = "x-adaptic-change-reason";
48
- /** The switches whose change arms or disarms an account. */
49
- export declare const TRADING_SWITCH_FIELDS: readonly ["realtimeTradingEnabled", "paperTradingOnly", "killSwitchEnabled", "autonomyMode"];
50
- /** The switch values of one policy as they stood before the write. */
51
- export type TradingSwitches = Partial<Record<(typeof TRADING_SWITCH_FIELDS)[number], boolean | string | null>>;
49
+ /**
50
+ * The switches whose change arms or disarms an account. `intradayLanePrefs`
51
+ * is the single carrier of the account's multi-lane opt-in (its `armed`
52
+ * member), so a write to it can arm the lanes exactly as a write to
53
+ * `realtimeTradingEnabled` can arm the account: it is audited, warned on and
54
+ * classified as a switch like the others.
55
+ */
56
+ export declare const TRADING_SWITCH_FIELDS: readonly ["realtimeTradingEnabled", "paperTradingOnly", "killSwitchEnabled", "autonomyMode", "intradayLanePrefs"];
57
+ /** One trading switch's name. */
58
+ export type TradingSwitchField = (typeof TRADING_SWITCH_FIELDS)[number];
59
+ /**
60
+ * The switch values of one policy as they stood before the write. A JSON
61
+ * switch (`intradayLanePrefs`) is recorded as its stored value.
62
+ */
63
+ export type TradingSwitches = Partial<Record<TradingSwitchField, boolean | string | Prisma.JsonValue | null>>;
52
64
  /**
53
65
  * How a touched policy's account was identified: read from the database
54
66
  * (`resolved`), created by this same mutation (`new_account`), or not
@@ -49,12 +49,19 @@ export const CHANGE_REASON_HEADER = 'x-adaptic-change-reason';
49
49
  const MAX_CHANGE_REASON_LENGTH = 500;
50
50
  /** Longest free-text header value (user agent, origin) recorded. */
51
51
  const MAX_HEADER_LENGTH = 300;
52
- /** The switches whose change arms or disarms an account. */
52
+ /**
53
+ * The switches whose change arms or disarms an account. `intradayLanePrefs`
54
+ * is the single carrier of the account's multi-lane opt-in (its `armed`
55
+ * member), so a write to it can arm the lanes exactly as a write to
56
+ * `realtimeTradingEnabled` can arm the account: it is audited, warned on and
57
+ * classified as a switch like the others.
58
+ */
53
59
  export const TRADING_SWITCH_FIELDS = [
54
60
  'realtimeTradingEnabled',
55
61
  'paperTradingOnly',
56
62
  'killSwitchEnabled',
57
63
  'autonomyMode',
64
+ 'intradayLanePrefs',
58
65
  ];
59
66
  /**
60
67
  * Whether a write may touch a LIVE account's switches: a resolved LIVE
@@ -128,7 +135,7 @@ export function touchesTradingSwitch(requested) {
128
135
  if (requested === null || typeof requested !== 'object')
129
136
  return false;
130
137
  for (const [key, child] of Object.entries(requested)) {
131
- if (TRADING_SWITCH_FIELDS.includes(key))
138
+ if (isTradingSwitchField(key))
132
139
  return true;
133
140
  if (touchesTradingSwitch(child))
134
141
  return true;
@@ -215,13 +222,35 @@ export async function writeResultRow(prisma, entry, attemptId, outcome, errorCod
215
222
  throw error;
216
223
  }
217
224
  }
218
- /** The value each trading switch moves to when a write DISARMS it. */
219
- const DISARMED_VALUES = {
220
- realtimeTradingEnabled: new Set([false]),
221
- killSwitchEnabled: new Set([true]),
222
- paperTradingOnly: new Set([true]),
223
- autonomyMode: new Set(['ADVISORY_ONLY', 'EMERGENCY_SAFE_MODE']),
225
+ /**
226
+ * Whether an `intradayLanePrefs` value leaves the account's lanes disarmed:
227
+ * a null (no preferences, which reads as disarmed) or an object whose `armed`
228
+ * member is exactly `false`. Any other value may arm, so it is not a disarm.
229
+ */
230
+ function isDisarmedLanePrefs(value) {
231
+ if (value === null)
232
+ return true;
233
+ if (typeof value !== 'object' || Array.isArray(value))
234
+ return false;
235
+ return value.armed === false;
236
+ }
237
+ /** Whether a value is the one a write DISARMING each trading switch sets. */
238
+ const DISARMS = {
239
+ realtimeTradingEnabled: (value) => value === false,
240
+ killSwitchEnabled: (value) => value === true,
241
+ paperTradingOnly: (value) => value === true,
242
+ autonomyMode: (value) => value === 'ADVISORY_ONLY' || value === 'EMERGENCY_SAFE_MODE',
243
+ intradayLanePrefs: isDisarmedLanePrefs,
224
244
  };
245
+ /**
246
+ * Switches whose generated update input carries the value itself rather than
247
+ * `{ set: value }`: a JSON column is written as its new value.
248
+ */
249
+ const JSON_SWITCH_FIELDS = new Set(['intradayLanePrefs']);
250
+ /** Whether a data key names a trading switch. */
251
+ function isTradingSwitchField(key) {
252
+ return TRADING_SWITCH_FIELDS.includes(key);
253
+ }
225
254
  /** Bookkeeping fields a disarm write may also set. */
226
255
  const DISARM_BOOKKEEPING_FIELDS = new Set(['lastModifiedBy', 'lastModifiedAt', 'version']);
227
256
  /** The value a generated update input sets: `{ set: v }` → `v`; anything else is not a plain set. */
@@ -254,11 +283,11 @@ export function isDisarmOnlyPolicyWrite(target, args) {
254
283
  for (const [key, raw] of Object.entries(data)) {
255
284
  if (raw === undefined)
256
285
  continue;
257
- const set = setValueOf(raw);
286
+ const set = isTradingSwitchField(key) && JSON_SWITCH_FIELDS.has(key) ? { value: raw } : setValueOf(raw);
258
287
  if (!set)
259
288
  return false;
260
- if (key in DISARMED_VALUES) {
261
- if (!DISARMED_VALUES[key].has(set.value))
289
+ if (isTradingSwitchField(key)) {
290
+ if (!DISARMS[key](set.value))
262
291
  return false;
263
292
  disarmed += 1;
264
293
  }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Narrow, hand-written reads of fields that the generated selection sets
3
+ * deliberately leave out (`GQL.SKIP`). Each read selects only its own field and
4
+ * the row's identity, so it fails alone and cannot take a generated read down
5
+ * with it.
6
+ *
7
+ * @module readers
8
+ */
9
+ export { readIntradayLanePrefs, INTRADAY_LANE_PREFS_SELECTION, type IntradayLanePrefsRow, } from './intraday-lane-prefs';
10
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Narrow, hand-written reads of fields that the generated selection sets
3
+ * deliberately leave out (`GQL.SKIP`). Each read selects only its own field and
4
+ * the row's identity, so it fails alone and cannot take a generated read down
5
+ * with it.
6
+ *
7
+ * @module readers
8
+ */
9
+ export { readIntradayLanePrefs, INTRADAY_LANE_PREFS_SELECTION, } from './intraday-lane-prefs.mjs';
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The read of one account's multi-lane intraday preferences
3
+ * (`TradingPolicy.intradayLanePrefs`).
4
+ *
5
+ * The field is excluded from every generated selection set (`GQL.SKIP`). A
6
+ * GraphQL server whose schema predates the column rejects the WHOLE operation
7
+ * that selects it, and the generated TradingPolicy and AlpacaAccount selection
8
+ * sets carry the engine's order-chokepoint policy read and its broker-credential
9
+ * read. Leaving the field out of those reads keeps them working against a
10
+ * server whether or not the migration has run. This read is the only place the
11
+ * field is selected, so a server without the column fails this read alone.
12
+ *
13
+ * The read never turns a failure into a value. A transport or GraphQL error
14
+ * throws, and so does an answer that omits the field. Only a backend that
15
+ * answers "no policy row" yields `null`. The consumer (the engine's lane-arming
16
+ * resolver) maps every one of these outcomes to "lanes disarmed". It never
17
+ * blocks an exit, because the preferences govern entries only.
18
+ *
19
+ * @module readers/intraday-lane-prefs
20
+ */
21
+ import type { TradingPolicy as TradingPolicyType } from '../generated/typegraphql-prisma/models/TradingPolicy';
22
+ import { type ApolloClientType, type NormalizedCacheObject } from '../client';
23
+ /** The fields this read selects, and nothing else. */
24
+ export declare const INTRADAY_LANE_PREFS_SELECTION = "id alpacaAccountId intradayLanePrefs";
25
+ /** One account's lane preferences, as stored. */
26
+ export interface IntradayLanePrefsRow {
27
+ /** The TradingPolicy row id. */
28
+ readonly policyId: string;
29
+ /** The account the policy governs. */
30
+ readonly alpacaAccountId: string;
31
+ /** The stored preferences; `null` when none are set (lanes disarmed). */
32
+ readonly intradayLanePrefs: Exclude<TradingPolicyType['intradayLanePrefs'], undefined>;
33
+ }
34
+ /**
35
+ * Read one account's lane preferences.
36
+ *
37
+ * @param alpacaAccountId - The account whose TradingPolicy to read.
38
+ * @param globalClient - The backend client; the shared client when omitted.
39
+ * @returns The stored preferences, or `null` when the account has no
40
+ * TradingPolicy row.
41
+ * @throws When the backend fails, answers with errors (including a server
42
+ * whose schema predates the column), or answers without the field.
43
+ */
44
+ export declare function readIntradayLanePrefs(alpacaAccountId: string, globalClient?: ApolloClientType<NormalizedCacheObject>): Promise<IntradayLanePrefsRow | null>;
45
+ //# sourceMappingURL=intraday-lane-prefs.d.ts.map
@@ -0,0 +1,71 @@
1
+ import { getApolloClient, getApolloModules } from '../client.mjs';
2
+ /** The fields this read selects, and nothing else. */
3
+ export const INTRADAY_LANE_PREFS_SELECTION = 'id alpacaAccountId intradayLanePrefs';
4
+ /** The backend's error message when no TradingPolicy row matches. */
5
+ const NO_POLICY_MESSAGE = 'No TradingPolicy found';
6
+ /** The shape of the `getTradingPolicy` answer this read accepts. */
7
+ function rowOf(value) {
8
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
9
+ throw new Error('readIntradayLanePrefs: the backend answered with no policy object');
10
+ }
11
+ const record = value;
12
+ if (typeof record.id !== 'string' || typeof record.alpacaAccountId !== 'string') {
13
+ throw new Error('readIntradayLanePrefs: the policy answer has no id or alpacaAccountId');
14
+ }
15
+ if (!('intradayLanePrefs' in record) || record.intradayLanePrefs === undefined) {
16
+ throw new Error('readIntradayLanePrefs: the policy answer omits intradayLanePrefs');
17
+ }
18
+ return {
19
+ policyId: record.id,
20
+ alpacaAccountId: record.alpacaAccountId,
21
+ intradayLanePrefs: record.intradayLanePrefs,
22
+ };
23
+ }
24
+ /**
25
+ * Read one account's lane preferences.
26
+ *
27
+ * @param alpacaAccountId - The account whose TradingPolicy to read.
28
+ * @param globalClient - The backend client; the shared client when omitted.
29
+ * @returns The stored preferences, or `null` when the account has no
30
+ * TradingPolicy row.
31
+ * @throws When the backend fails, answers with errors (including a server
32
+ * whose schema predates the column), or answers without the field.
33
+ */
34
+ export async function readIntradayLanePrefs(alpacaAccountId, globalClient) {
35
+ const [modules, client] = await Promise.all([
36
+ getApolloModules(),
37
+ globalClient ? Promise.resolve(globalClient) : getApolloClient(),
38
+ ]);
39
+ const query = modules.gql `
40
+ query readIntradayLanePrefs($where: TradingPolicyWhereUniqueInput!) {
41
+ getTradingPolicy(where: $where) {
42
+ ${INTRADAY_LANE_PREFS_SELECTION}
43
+ }
44
+ }`;
45
+ let response;
46
+ try {
47
+ response = await client.query({
48
+ query,
49
+ variables: { where: { alpacaAccountId } },
50
+ fetchPolicy: 'network-only',
51
+ });
52
+ }
53
+ catch (error) {
54
+ if (error instanceof Error && error.message === NO_POLICY_MESSAGE)
55
+ return null;
56
+ throw error;
57
+ }
58
+ if (response.errors && response.errors.length > 0) {
59
+ if (response.errors[0].message === NO_POLICY_MESSAGE)
60
+ return null;
61
+ throw new Error(`readIntradayLanePrefs: ${response.errors[0].message}`);
62
+ }
63
+ const policy = response.data?.getTradingPolicy;
64
+ if (policy === null)
65
+ return null;
66
+ if (policy === undefined) {
67
+ throw new Error('readIntradayLanePrefs: the backend answered with no getTradingPolicy field');
68
+ }
69
+ return rowOf(policy);
70
+ }
71
+ //# sourceMappingURL=intraday-lane-prefs.js.map
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Exercises the TradingPolicy lane-preferences carrier against a real Postgres
3
+ * built from the migration history: a policy created without it reads back
4
+ * null (disarmed) through the generated GraphQL resolvers, a written value
5
+ * round-trips, it can be set to armed:false and cleared back to null, and the
6
+ * migration's own SQL runs down and up again inside a transaction that is
7
+ * rolled back, leaving the database as it was.
8
+ *
9
+ * Assembled like `desk-attribution-roundtrip.harness.ts`. Needs
10
+ * `LANE_IT_DATABASE_URL` pointing at a disposable migrated database. Output is
11
+ * printed between `<<<RESULTS>>>` and `<<<END>>>`; seeded rows are removed.
12
+ */
13
+ import 'reflect-metadata';
14
+ //# sourceMappingURL=trading-policy-lane-fields-roundtrip.harness.d.ts.map
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Exercises the TradingPolicy lane-preferences carrier against a real Postgres
3
+ * built from the migration history: a policy created without it reads back
4
+ * null (disarmed) through the generated GraphQL resolvers, a written value
5
+ * round-trips, it can be set to armed:false and cleared back to null, and the
6
+ * migration's own SQL runs down and up again inside a transaction that is
7
+ * rolled back, leaving the database as it was.
8
+ *
9
+ * Assembled like `desk-attribution-roundtrip.harness.ts`. Needs
10
+ * `LANE_IT_DATABASE_URL` pointing at a disposable migrated database. Output is
11
+ * printed between `<<<RESULTS>>>` and `<<<END>>>`; seeded rows are removed.
12
+ */
13
+ import 'reflect-metadata';
14
+ import { randomUUID } from 'node:crypto';
15
+ import { readFileSync } from 'node:fs';
16
+ import { join } from 'node:path';
17
+ import { PrismaClient } from '@prisma/client';
18
+ import { buildSchema } from 'type-graphql';
19
+ import { graphql } from 'graphql';
20
+ import { resolvers } from '../generated/typegraphql-prisma/index.mjs';
21
+ import { withoutServerOnlyResolvers, withoutServerOnlySchemaSurface, } from '../config/server-only-models.mjs';
22
+ const MIGRATION_SQL = join(__dirname, '..', '..', 'prisma', 'migrations', '20261121130000_trading_policy_lane_fields', 'migration.sql');
23
+ const DOWN_SQL = `ALTER TABLE "trading_policies" DROP COLUMN "intradayLanePrefs"`;
24
+ const LANE_COLUMNS = `('intradayLanePrefs')`;
25
+ const POLICY_FIELDS = 'id intradayLanePrefs maxOpenPositions';
26
+ /** Arms the seeded row inside the transaction, so the down limb has a value to drop. */
27
+ const ARM_ROW_SQL = `UPDATE trading_policies SET "intradayLanePrefs" = '{"armed": true}'::jsonb WHERE id = $1::uuid`;
28
+ /** Raised to roll the down/up transaction back once its snapshots are taken. */
29
+ class RollbackSignal extends Error {
30
+ }
31
+ async function run(schema, prisma, source, variableValues = {}) {
32
+ const result = await graphql({ schema, source, variableValues, contextValue: { prisma } });
33
+ return {
34
+ data: result.data ?? null,
35
+ errors: (result.errors ?? []).map((error) => error.message),
36
+ };
37
+ }
38
+ async function snapshot(tx, policyId) {
39
+ const columns = await tx.$queryRawUnsafe(`SELECT column_name, is_nullable, column_default FROM information_schema.columns
40
+ WHERE table_name = 'trading_policies' AND column_name IN ${LANE_COLUMNS} ORDER BY column_name`);
41
+ const rows = await tx.$queryRawUnsafe(`SELECT row_to_json(t) AS row FROM trading_policies t WHERE id = $1::uuid`, policyId);
42
+ return { columns, row: rows[0]?.row ?? null };
43
+ }
44
+ async function main() {
45
+ const url = process.env.LANE_IT_DATABASE_URL;
46
+ if (!url)
47
+ throw new Error('LANE_IT_DATABASE_URL is not set');
48
+ const prisma = new PrismaClient({ datasourceUrl: url });
49
+ const schema = withoutServerOnlySchemaSurface(await buildSchema({ resolvers: withoutServerOnlyResolvers(resolvers), validate: false }));
50
+ const tag = randomUUID().slice(0, 8);
51
+ const user = await prisma.user.create({ data: { email: `lane-${tag}@example.invalid` } });
52
+ const account = await prisma.alpacaAccount.create({
53
+ data: { userId: user.id, APIKey: `k-${tag}`, APISecret: `s-${tag}` },
54
+ });
55
+ const steps = {};
56
+ const downUp = {};
57
+ try {
58
+ steps.created = await run(schema, prisma, `mutation ($data: TradingPolicyCreateInput!) { createOneTradingPolicy(data: $data) { ${POLICY_FIELDS} } }`, { data: { alpacaAccount: { connect: { id: account.id } }, maxOpenPositions: 7 } });
59
+ const policyId = steps.created.data
60
+ ?.createOneTradingPolicy?.id;
61
+ if (!policyId)
62
+ throw new Error(`policy create failed: ${steps.created.errors.join('; ')}`);
63
+ const UPDATE = `mutation ($id: String!, $data: TradingPolicyUpdateInput!) {
64
+ updateOneTradingPolicy(where: { id: $id }, data: $data) { ${POLICY_FIELDS} }
65
+ }`;
66
+ steps.armed = await run(schema, prisma, UPDATE, {
67
+ id: policyId,
68
+ data: { intradayLanePrefs: { armed: true, perLaneTradesPerDay: 4 } },
69
+ });
70
+ steps.cleared = await run(schema, prisma, UPDATE, {
71
+ id: policyId,
72
+ data: { intradayLanePrefs: { armed: false } },
73
+ });
74
+ // The generated update input types a Json? field as InputJsonValue; this
75
+ // proves a GraphQL null still clears the carrier, so an operator can
76
+ // disarm by unsetting it rather than only by writing armed: false.
77
+ steps.prefsNull = await run(schema, prisma, UPDATE, { id: policyId, data: { intradayLanePrefs: null } });
78
+ const up = readFileSync(MIGRATION_SQL, 'utf8');
79
+ await prisma
80
+ .$transaction(async (tx) => {
81
+ await tx.$executeRawUnsafe(ARM_ROW_SQL, policyId);
82
+ downUp.before = await snapshot(tx, policyId);
83
+ await tx.$executeRawUnsafe(DOWN_SQL);
84
+ downUp.down = await snapshot(tx, policyId);
85
+ await tx.$executeRawUnsafe(up);
86
+ downUp.up = await snapshot(tx, policyId);
87
+ throw new RollbackSignal('roll back the down/up run');
88
+ })
89
+ .catch((error) => {
90
+ if (!(error instanceof RollbackSignal))
91
+ throw error;
92
+ });
93
+ downUp.afterRollback = await snapshot(prisma, policyId);
94
+ }
95
+ finally {
96
+ await prisma.tradingPolicy.deleteMany({ where: { alpacaAccountId: account.id } });
97
+ await prisma.alpacaAccount.delete({ where: { id: account.id } });
98
+ await prisma.user.delete({ where: { id: user.id } });
99
+ await prisma.$disconnect();
100
+ }
101
+ process.stdout.write(`<<<RESULTS>>>${JSON.stringify({ tag, steps, downUp })}<<<END>>>\n`);
102
+ }
103
+ main().catch((error) => {
104
+ process.stderr.write(`harness failed: ${String(error)}\n`);
105
+ process.exit(1);
106
+ });
107
+ //# sourceMappingURL=trading-policy-lane-fields-roundtrip.harness.js.map
@@ -118,6 +118,24 @@ portfolioTrailRungs for the second round.
118
118
  orderWindowSeconds: number;
119
119
  // Enforce intraday-only trading (auto-close all positions before EOD). Default: false.
120
120
  dayTradeOnly: boolean;
121
+ // Per-account multi-lane intraday preferences: the single carrier of the
122
+ account's lane opt-in (\`armed\`) and its per-lane caps, including the
123
+ trades-per-day cap (\`perLaneTradesPerDay\`). It is validated at the engine's
124
+ read boundary by the strict IntradayLanePrefs schema in @adaptic/utils
125
+ (trading-policy/schemas). NULL, a value that fails that schema, or an
126
+ absent cap means the lanes are disarmed for this account. One JSON carrier
127
+ instead of separate arming and cap columns keeps a single arming predicate,
128
+ so there are no two homes for one setting that could disagree.
129
+
130
+ It is left out of every generated selection set (GQL.SKIP) on purpose. A
131
+ GraphQL server that predates the column rejects any operation that
132
+ selects it, and the TradingPolicy selection set feeds the engine's order
133
+ chokepoint and broker-credential reads. Keeping the field out lets a
134
+ consumer of this package run against a server whether or not the
135
+ migration has been applied. It is read through \`readIntradayLanePrefs\`,
136
+ whose failure the lane path treats as disarmed, and written through the
137
+ generated create and update inputs.
138
+ intradayLanePrefs?: any;
121
139
  riskBudgetPrefs?: any;
122
140
  signalConsumptionPrefs?: any;
123
141
  executionPrefs?: any;
@@ -1,2 +1,2 @@
1
- export declare const PolicyOverlayTypeString = "\n// Your response should adhere to the following type definition for the \"PolicyOverlay\" type.\n// Importantly, DO NOT include any annotations in your response (i.e., remove the ones we have provided for your reference below).\n\nexport type PolicyOverlay = {\n // Relation to TradingPolicy.\n tradingPolicy: {\n // Relation to AlpacaAccount.\n alpacaAccount: {\n // The type of Alpaca account (PAPER or LIVE).\n type: AlpacaAccountType;\n // JSON configuration settings for the Alpaca account.\n configuration?: any;\n };\n version: number;\n lastModifiedBy?: string;\n lastModifiedAt: Date;\n autonomyMode: AutonomyMode;\n realtimeTradingEnabled: boolean;\n paperTradingOnly: boolean;\n killSwitchEnabled: boolean;\n autonomyPrefs?: any;\n equitiesEnabled: boolean;\n etfsEnabled: boolean;\n cryptoEnabled: boolean;\n optionsEnabled: boolean;\n futuresEnabled: boolean;\n forexEnabled: boolean;\n shortingEnabled: boolean;\n marginEnabled: boolean;\n fractionalSharesEnabled: boolean;\n assetUniversePrefs?: any;\n maxBuyingPowerUtilPct: number;\n cashFloorPct: number;\n maxGrossExposurePct: number;\n maxNetExposurePct: number;\n maxLeverage: number;\n maxSymbolConcentrationPct: number;\n maxSectorConcentrationPct: number;\n maxOpenPositions: number;\n maxOpenOrders: number;\n // Percentage of account equity (with leverage) allocated per equities trade. Canonical replacement for legacy AlpacaAccount.tradeAllocationPct.\n perTradeEquityAllocationPct: number;\n // Percentage of the crypto allocation slice of account equity allocated per crypto trade. Canonical replacement for legacy AlpacaAccount.cryptoTradeAllocationPct.\n perTradeCryptoAllocationPct: number;\n // Opt-in for enabling the portfolio-level trailing stop service within Adaptic's Realtime Trade Engine. Canonical replacement for legacy AlpacaAccount.enablePortfolioTrailingStop.\n enablePortfolioTrailingStop: boolean;\n // Portfolio-level trailing stop percentage used by the Realtime Trade Engine, if opted into the portfolio-level trailing stop service. Canonical replacement for legacy AlpacaAccount.portfolioTrailPercent.\n portfolioTrailPercent: number;\n // Portfolio-level profit threshold percentage used by the Realtime Trade Engine, if opted into the portfolio-level trailing stop service. Canonical replacement for legacy AlpacaAccount.portfolioProfitThresholdPercent.\n portfolioProfitThresholdPercent: number;\n // Portfolio-level trailing stop percentage used by the Realtime Trade Engine for reducing the trailing stop once the profit threshold is exceeded. Canonical replacement for legacy AlpacaAccount.reducedPortfolioTrailPercent.\n reducedPortfolioTrailPercent: number;\n // Ordered ladder of portfolio trailing-stop rungs, generalising the single\nportfolioProfitThresholdPercent/reducedPortfolioTrailPercent pair above.\nShape: [{ \"thresholdPercent\": 0.35, \"trailPercent\": 0.25 }, ...] in WHOLE\nPERCENT of the session's opening equity (0.35 = 35bp), ordered ascending by\nthreshold. The engine applies min() across every rung whose threshold the\nsession high-water mark has reached, so the trail tightens monotonically and\na mis-ordered or wider rung can never loosen a stop that has already\ntightened. NULL = use the single legacy rung, which reproduces today's\nbehaviour exactly.\n portfolioTrailRungs?: any;\n // Local ET time (\"HH:MM\", 24h) at which the portfolio trailing-stop state\nre-anchors for a SECOND intraday round: open equity re-seeds from that\ntick, the high-water mark resets to zero and the trail returns to base.\nIntended for an afternoon session traded with freshly entered positions.\nNULL = single round per day, which is today's behaviour.\n portfolioAfternoonResetEt?: string;\n // Rung ladder for the afternoon round, same shape as portfolioTrailRungs.\nThe afternoon window is materially shorter than the morning, so the\nthresholds that are reachable within it differ and must be set from the\nafternoon's own distribution rather than inherited. NULL = reuse\nportfolioTrailRungs for the second round.\n portfolioAfternoonTrailRungs?: any;\n // Whether the portfolio-level daily take-profit circuit breaker is enabled for this account.\n enablePortfolioTakeProfit?: boolean;\n // Daily gain target (whole percent, e.g. 1 = 1%) since the 09:30 open that trips the take-profit breaker.\n portfolioTakeProfitThresholdPercent?: number;\n // Initial trailing stop percentage used by the Position Trailing Stop Service. Canonical replacement for legacy AlpacaAccount.defaultTrailingStopPercentage100.\n defaultTrailingStopPercentage100: number;\n // First profit threshold at which the Position Trailing Stop Service reduces the trailing stop. Canonical replacement for legacy AlpacaAccount.firstTrailReductionThreshold100.\n firstTrailReductionThreshold100: number;\n // Second profit threshold at which the Position Trailing Stop Service further reduces the trailing stop. Canonical replacement for legacy AlpacaAccount.secondTrailReductionThreshold100.\n secondTrailReductionThreshold100: number;\n // Trailing stop percentage to use when profit exceeds the first threshold. Canonical replacement for legacy AlpacaAccount.firstReducedTrailPercentage100.\n firstReducedTrailPercentage100: number;\n // Trailing stop percentage to use when profit exceeds the second threshold. Canonical replacement for legacy AlpacaAccount.secondReducedTrailPercentage100.\n secondReducedTrailPercentage100: number;\n // Minimum change in trailing stop percent to warrant an adjustment. Canonical replacement for legacy AlpacaAccount.minimumPriceChangePercent100.\n minimumPriceChangePercent100: number;\n // Wash-trade cooldown period in milliseconds for equities \u2014 minimum elapsed time between opposing-side fills on the same symbol per FINRA Rule 5210. Mirrors the 30s default already enforced for crypto. Default: 30000 (30 seconds).\n equityWashTradeCooldownMs: number;\n // Minimum intraday liquidity threshold (shares traded in last 5 min). Required for scalping. Default: 10000 (10k shares in last 5 min).\n minIntradayLiquidityShares: number;\n // Maximum spread in basis points (1/100ths of 1%) to allow entry. Scalping requires tight spreads; use 1-3 bps. Default: 5 (0.05%).\n maxEntrySpreadBps: number;\n // Minimum time between same-symbol same-side entries (ms). FINRA Rule 5210 requires 30s for opposite-side trades; this controls same-side rapid re-entry. Default: 5000 (5 seconds) for scalping; 30000 for normal trading.\n sameSideReentryDelayMs: number;\n // Volatility filter: only trade if ATR(14) >= minAtrPercentage. Scalping needs moderate volatility; too low = no edge. Default: 0.3 (0.3%).\n minAtrPercentage: number;\n // Volatility filter: only trade if ATR(14) <= maxAtrPercentage. Scalping needs moderate volatility; too high = whipsaws. Default: 2.0 (2.0%).\n maxAtrPercentage: number;\n // Order book depth requirement: minimum shares at best bid/ask to qualify for entry. Scalping needs guaranteed liquidity. Default: 5000 shares.\n minBookDepthShares: number;\n // Maximum market order slippage in basis points before flagging as anomaly. Helps detect liquidity crunches. Default: 10 bps.\n maxAnomalousSlippageBps: number;\n // Intraday session windows allowed (JSON array). Format: [{ startMinutesFromOpen, endMinutesFromOpen, active }]. Example: skip first 5 min and last 10 min of RTH.\n intradayTradingWindows?: any;\n // Hard position exit clock (minutes from entry). 0 = disabled. Forces liquidation regardless of signal. Useful for strict day-trading discipline. Default: 0.\n hardPositionExitMinutes: number;\n // Rapid-fire order-rate limit: max orders within orderWindowSeconds. Default: 10 orders per 5 seconds.\n maxOrdersPerWindow: number;\n // Window size for maxOrdersPerWindow rate limit (seconds). Default: 5.\n orderWindowSeconds: number;\n // Enforce intraday-only trading (auto-close all positions before EOD). Default: false.\n dayTradeOnly: boolean;\n riskBudgetPrefs?: any;\n signalConsumptionPrefs?: any;\n executionPrefs?: any;\n positionManagementPrefs?: any;\n portfolioConstructionPrefs?: any;\n macroOverlayEnabled: boolean;\n sectorOverlayEnabled: boolean;\n volatilityOverlayEnabled: boolean;\n liquidityStressOverlayEnabled: boolean;\n blackSwanProtectionEnabled: boolean;\n drawdownGuardianEnabled: boolean;\n correlationSpikeProtectionEnabled: boolean;\n newsEventRiskOverlayEnabled: boolean;\n exchangeHealthOverlayEnabled: boolean;\n dataQualitySentinelEnabled: boolean;\n overlayResponsePrefs?: any;\n miniModelProvider?: LlmProvider;\n normalModelProvider?: LlmProvider;\n advancedModelProvider?: LlmProvider;\n modelPrefs?: any;\n auditNotificationPrefs?: any;\n // List of policy overlays.\n overlays: PolicyOverlay[];\n escalationPolicyOverrides?: any;\n currentRiskState: AccountRiskState;\n currentRiskStateAt?: Date;\n lastRiskStateChangedBy?: string;\n };\n overlayType: OverlayType;\n source: string;\n reason: string;\n severity: OverlaySeverity;\n version: number;\n mutations: any;\n status: OverlayStatus;\n activatedAt: Date;\n expiresAt?: Date;\n deactivatedAt?: Date;\n deactivatedBy?: string;\n};\n\nenum AlpacaAccountType {\n PAPER\n\n LIVE\n}\n\nenum AutonomyMode {\n ADVISORY_ONLY\n\n EXECUTION_ON_APPROVAL\n\n SEMI_AUTONOMOUS\n\n FULLY_AUTONOMOUS\n\n EMERGENCY_SAFE_MODE\n}\n\nenum LlmProvider {\n OPENAI\n\n ANTHROPIC\n\n DEEPSEEK\n\n KIMI\n\n QWEN\n\n XAI\n\n GEMINI\n\n DEEPINFRA\n}\n\nenum AccountRiskState {\n NORMAL\n\n WARN\n\n THROTTLE\n\n PAUSED\n\n FLATTEN\n\n HALT\n}\n\nenum OverlayType {\n BLACK_SWAN\n\n VOLATILITY_REGIME\n\n SECTOR_DETERIORATION\n\n DRAWDOWN_BREACH\n\n CORRELATION_SPIKE\n\n LIQUIDITY_STRESS\n\n EXCHANGE_DEGRADATION\n\n DATA_QUALITY\n\n NEWS_EVENT_RISK\n\n RATES_BONDS_STRESS\n\n MANUAL_OVERRIDE\n\n INCIDENT_RESPONSE\n}\n\nenum OverlaySeverity {\n LOW\n\n MEDIUM\n\n HIGH\n\n CRITICAL\n}\n\nenum OverlayStatus {\n ACTIVE\n\n EXPIRED\n\n DEACTIVATED\n\n SUPERSEDED\n}\n\n";
1
+ export declare const PolicyOverlayTypeString = "\n// Your response should adhere to the following type definition for the \"PolicyOverlay\" type.\n// Importantly, DO NOT include any annotations in your response (i.e., remove the ones we have provided for your reference below).\n\nexport type PolicyOverlay = {\n // Relation to TradingPolicy.\n tradingPolicy: {\n // Relation to AlpacaAccount.\n alpacaAccount: {\n // The type of Alpaca account (PAPER or LIVE).\n type: AlpacaAccountType;\n // JSON configuration settings for the Alpaca account.\n configuration?: any;\n };\n version: number;\n lastModifiedBy?: string;\n lastModifiedAt: Date;\n autonomyMode: AutonomyMode;\n realtimeTradingEnabled: boolean;\n paperTradingOnly: boolean;\n killSwitchEnabled: boolean;\n autonomyPrefs?: any;\n equitiesEnabled: boolean;\n etfsEnabled: boolean;\n cryptoEnabled: boolean;\n optionsEnabled: boolean;\n futuresEnabled: boolean;\n forexEnabled: boolean;\n shortingEnabled: boolean;\n marginEnabled: boolean;\n fractionalSharesEnabled: boolean;\n assetUniversePrefs?: any;\n maxBuyingPowerUtilPct: number;\n cashFloorPct: number;\n maxGrossExposurePct: number;\n maxNetExposurePct: number;\n maxLeverage: number;\n maxSymbolConcentrationPct: number;\n maxSectorConcentrationPct: number;\n maxOpenPositions: number;\n maxOpenOrders: number;\n // Percentage of account equity (with leverage) allocated per equities trade. Canonical replacement for legacy AlpacaAccount.tradeAllocationPct.\n perTradeEquityAllocationPct: number;\n // Percentage of the crypto allocation slice of account equity allocated per crypto trade. Canonical replacement for legacy AlpacaAccount.cryptoTradeAllocationPct.\n perTradeCryptoAllocationPct: number;\n // Opt-in for enabling the portfolio-level trailing stop service within Adaptic's Realtime Trade Engine. Canonical replacement for legacy AlpacaAccount.enablePortfolioTrailingStop.\n enablePortfolioTrailingStop: boolean;\n // Portfolio-level trailing stop percentage used by the Realtime Trade Engine, if opted into the portfolio-level trailing stop service. Canonical replacement for legacy AlpacaAccount.portfolioTrailPercent.\n portfolioTrailPercent: number;\n // Portfolio-level profit threshold percentage used by the Realtime Trade Engine, if opted into the portfolio-level trailing stop service. Canonical replacement for legacy AlpacaAccount.portfolioProfitThresholdPercent.\n portfolioProfitThresholdPercent: number;\n // Portfolio-level trailing stop percentage used by the Realtime Trade Engine for reducing the trailing stop once the profit threshold is exceeded. Canonical replacement for legacy AlpacaAccount.reducedPortfolioTrailPercent.\n reducedPortfolioTrailPercent: number;\n // Ordered ladder of portfolio trailing-stop rungs, generalising the single\nportfolioProfitThresholdPercent/reducedPortfolioTrailPercent pair above.\nShape: [{ \"thresholdPercent\": 0.35, \"trailPercent\": 0.25 }, ...] in WHOLE\nPERCENT of the session's opening equity (0.35 = 35bp), ordered ascending by\nthreshold. The engine applies min() across every rung whose threshold the\nsession high-water mark has reached, so the trail tightens monotonically and\na mis-ordered or wider rung can never loosen a stop that has already\ntightened. NULL = use the single legacy rung, which reproduces today's\nbehaviour exactly.\n portfolioTrailRungs?: any;\n // Local ET time (\"HH:MM\", 24h) at which the portfolio trailing-stop state\nre-anchors for a SECOND intraday round: open equity re-seeds from that\ntick, the high-water mark resets to zero and the trail returns to base.\nIntended for an afternoon session traded with freshly entered positions.\nNULL = single round per day, which is today's behaviour.\n portfolioAfternoonResetEt?: string;\n // Rung ladder for the afternoon round, same shape as portfolioTrailRungs.\nThe afternoon window is materially shorter than the morning, so the\nthresholds that are reachable within it differ and must be set from the\nafternoon's own distribution rather than inherited. NULL = reuse\nportfolioTrailRungs for the second round.\n portfolioAfternoonTrailRungs?: any;\n // Whether the portfolio-level daily take-profit circuit breaker is enabled for this account.\n enablePortfolioTakeProfit?: boolean;\n // Daily gain target (whole percent, e.g. 1 = 1%) since the 09:30 open that trips the take-profit breaker.\n portfolioTakeProfitThresholdPercent?: number;\n // Initial trailing stop percentage used by the Position Trailing Stop Service. Canonical replacement for legacy AlpacaAccount.defaultTrailingStopPercentage100.\n defaultTrailingStopPercentage100: number;\n // First profit threshold at which the Position Trailing Stop Service reduces the trailing stop. Canonical replacement for legacy AlpacaAccount.firstTrailReductionThreshold100.\n firstTrailReductionThreshold100: number;\n // Second profit threshold at which the Position Trailing Stop Service further reduces the trailing stop. Canonical replacement for legacy AlpacaAccount.secondTrailReductionThreshold100.\n secondTrailReductionThreshold100: number;\n // Trailing stop percentage to use when profit exceeds the first threshold. Canonical replacement for legacy AlpacaAccount.firstReducedTrailPercentage100.\n firstReducedTrailPercentage100: number;\n // Trailing stop percentage to use when profit exceeds the second threshold. Canonical replacement for legacy AlpacaAccount.secondReducedTrailPercentage100.\n secondReducedTrailPercentage100: number;\n // Minimum change in trailing stop percent to warrant an adjustment. Canonical replacement for legacy AlpacaAccount.minimumPriceChangePercent100.\n minimumPriceChangePercent100: number;\n // Wash-trade cooldown period in milliseconds for equities \u2014 minimum elapsed time between opposing-side fills on the same symbol per FINRA Rule 5210. Mirrors the 30s default already enforced for crypto. Default: 30000 (30 seconds).\n equityWashTradeCooldownMs: number;\n // Minimum intraday liquidity threshold (shares traded in last 5 min). Required for scalping. Default: 10000 (10k shares in last 5 min).\n minIntradayLiquidityShares: number;\n // Maximum spread in basis points (1/100ths of 1%) to allow entry. Scalping requires tight spreads; use 1-3 bps. Default: 5 (0.05%).\n maxEntrySpreadBps: number;\n // Minimum time between same-symbol same-side entries (ms). FINRA Rule 5210 requires 30s for opposite-side trades; this controls same-side rapid re-entry. Default: 5000 (5 seconds) for scalping; 30000 for normal trading.\n sameSideReentryDelayMs: number;\n // Volatility filter: only trade if ATR(14) >= minAtrPercentage. Scalping needs moderate volatility; too low = no edge. Default: 0.3 (0.3%).\n minAtrPercentage: number;\n // Volatility filter: only trade if ATR(14) <= maxAtrPercentage. Scalping needs moderate volatility; too high = whipsaws. Default: 2.0 (2.0%).\n maxAtrPercentage: number;\n // Order book depth requirement: minimum shares at best bid/ask to qualify for entry. Scalping needs guaranteed liquidity. Default: 5000 shares.\n minBookDepthShares: number;\n // Maximum market order slippage in basis points before flagging as anomaly. Helps detect liquidity crunches. Default: 10 bps.\n maxAnomalousSlippageBps: number;\n // Intraday session windows allowed (JSON array). Format: [{ startMinutesFromOpen, endMinutesFromOpen, active }]. Example: skip first 5 min and last 10 min of RTH.\n intradayTradingWindows?: any;\n // Hard position exit clock (minutes from entry). 0 = disabled. Forces liquidation regardless of signal. Useful for strict day-trading discipline. Default: 0.\n hardPositionExitMinutes: number;\n // Rapid-fire order-rate limit: max orders within orderWindowSeconds. Default: 10 orders per 5 seconds.\n maxOrdersPerWindow: number;\n // Window size for maxOrdersPerWindow rate limit (seconds). Default: 5.\n orderWindowSeconds: number;\n // Enforce intraday-only trading (auto-close all positions before EOD). Default: false.\n dayTradeOnly: boolean;\n // Per-account multi-lane intraday preferences: the single carrier of the\naccount's lane opt-in (`armed`) and its per-lane caps, including the\ntrades-per-day cap (`perLaneTradesPerDay`). It is validated at the engine's\nread boundary by the strict IntradayLanePrefs schema in @adaptic/utils\n(trading-policy/schemas). NULL, a value that fails that schema, or an\nabsent cap means the lanes are disarmed for this account. One JSON carrier\ninstead of separate arming and cap columns keeps a single arming predicate,\nso there are no two homes for one setting that could disagree.\n\nIt is left out of every generated selection set (GQL.SKIP) on purpose. A\nGraphQL server that predates the column rejects any operation that\nselects it, and the TradingPolicy selection set feeds the engine's order\nchokepoint and broker-credential reads. Keeping the field out lets a\nconsumer of this package run against a server whether or not the\nmigration has been applied. It is read through `readIntradayLanePrefs`,\nwhose failure the lane path treats as disarmed, and written through the\ngenerated create and update inputs.\n intradayLanePrefs?: any;\n riskBudgetPrefs?: any;\n signalConsumptionPrefs?: any;\n executionPrefs?: any;\n positionManagementPrefs?: any;\n portfolioConstructionPrefs?: any;\n macroOverlayEnabled: boolean;\n sectorOverlayEnabled: boolean;\n volatilityOverlayEnabled: boolean;\n liquidityStressOverlayEnabled: boolean;\n blackSwanProtectionEnabled: boolean;\n drawdownGuardianEnabled: boolean;\n correlationSpikeProtectionEnabled: boolean;\n newsEventRiskOverlayEnabled: boolean;\n exchangeHealthOverlayEnabled: boolean;\n dataQualitySentinelEnabled: boolean;\n overlayResponsePrefs?: any;\n miniModelProvider?: LlmProvider;\n normalModelProvider?: LlmProvider;\n advancedModelProvider?: LlmProvider;\n modelPrefs?: any;\n auditNotificationPrefs?: any;\n // List of policy overlays.\n overlays: PolicyOverlay[];\n escalationPolicyOverrides?: any;\n currentRiskState: AccountRiskState;\n currentRiskStateAt?: Date;\n lastRiskStateChangedBy?: string;\n };\n overlayType: OverlayType;\n source: string;\n reason: string;\n severity: OverlaySeverity;\n version: number;\n mutations: any;\n status: OverlayStatus;\n activatedAt: Date;\n expiresAt?: Date;\n deactivatedAt?: Date;\n deactivatedBy?: string;\n};\n\nenum AlpacaAccountType {\n PAPER\n\n LIVE\n}\n\nenum AutonomyMode {\n ADVISORY_ONLY\n\n EXECUTION_ON_APPROVAL\n\n SEMI_AUTONOMOUS\n\n FULLY_AUTONOMOUS\n\n EMERGENCY_SAFE_MODE\n}\n\nenum LlmProvider {\n OPENAI\n\n ANTHROPIC\n\n DEEPSEEK\n\n KIMI\n\n QWEN\n\n XAI\n\n GEMINI\n\n DEEPINFRA\n}\n\nenum AccountRiskState {\n NORMAL\n\n WARN\n\n THROTTLE\n\n PAUSED\n\n FLATTEN\n\n HALT\n}\n\nenum OverlayType {\n BLACK_SWAN\n\n VOLATILITY_REGIME\n\n SECTOR_DETERIORATION\n\n DRAWDOWN_BREACH\n\n CORRELATION_SPIKE\n\n LIQUIDITY_STRESS\n\n EXCHANGE_DEGRADATION\n\n DATA_QUALITY\n\n NEWS_EVENT_RISK\n\n RATES_BONDS_STRESS\n\n MANUAL_OVERRIDE\n\n INCIDENT_RESPONSE\n}\n\nenum OverlaySeverity {\n LOW\n\n MEDIUM\n\n HIGH\n\n CRITICAL\n}\n\nenum OverlayStatus {\n ACTIVE\n\n EXPIRED\n\n DEACTIVATED\n\n SUPERSEDED\n}\n\n";
2
2
  //# sourceMappingURL=PolicyOverlay.d.ts.map
@@ -116,6 +116,24 @@ portfolioTrailRungs for the second round.
116
116
  orderWindowSeconds: number;
117
117
  // Enforce intraday-only trading (auto-close all positions before EOD). Default: false.
118
118
  dayTradeOnly: boolean;
119
+ // Per-account multi-lane intraday preferences: the single carrier of the
120
+ account's lane opt-in (\`armed\`) and its per-lane caps, including the
121
+ trades-per-day cap (\`perLaneTradesPerDay\`). It is validated at the engine's
122
+ read boundary by the strict IntradayLanePrefs schema in @adaptic/utils
123
+ (trading-policy/schemas). NULL, a value that fails that schema, or an
124
+ absent cap means the lanes are disarmed for this account. One JSON carrier
125
+ instead of separate arming and cap columns keeps a single arming predicate,
126
+ so there are no two homes for one setting that could disagree.
127
+
128
+ It is left out of every generated selection set (GQL.SKIP) on purpose. A
129
+ GraphQL server that predates the column rejects any operation that
130
+ selects it, and the TradingPolicy selection set feeds the engine's order
131
+ chokepoint and broker-credential reads. Keeping the field out lets a
132
+ consumer of this package run against a server whether or not the
133
+ migration has been applied. It is read through \`readIntradayLanePrefs\`,
134
+ whose failure the lane path treats as disarmed, and written through the
135
+ generated create and update inputs.
136
+ intradayLanePrefs?: any;
119
137
  riskBudgetPrefs?: any;
120
138
  signalConsumptionPrefs?: any;
121
139
  executionPrefs?: any;