plugins/trading-operations/skills/pre-trade-compliance/SKILL.md
Guide the design and implementation of automated pre-trade compliance systems that validate orders before execution. Use when building a compliance rule engine for an RIA or broker-dealer, configuring hard blocks and soft blocks, maintaining restricted and watch lists including MNPI-driven restrictions, setting concentration limits at security/sector/issuer level, implementing position limits or short selling controls, enforcing wash sale detection or free-riding prevention or pattern day trader identification, applying client-specific ESG screens or legal constraints, designing compliance override workflows with authorization and documentation, backtesting compliance rules, or evaluating compliance check latency impact on execution quality.
npx skillsauth add joellewis/finance_skills pre-trade-complianceInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
The pre-trade compliance system intercepts orders after generation by the portfolio management system or order entry interface and before routing to custodians or execution venues. The system evaluates each order against a set of rules and either permits the order to proceed, blocks it entirely (hard block), or flags it for review (soft block).
Rule engine design — sequential vs. parallel evaluation:
Order interception points:
Hard blocks vs. soft blocks:
Compliance check latency requirements:
Pre-trade compliance checks must complete within a timeframe that does not materially impair execution quality. For equity and ETF orders where market prices are moving, compliance latency directly affects execution price risk. Target latency benchmarks: single-order compliance check should complete in under 100 milliseconds for real-time trading workflows; batch compliance checks for model-driven trades (hundreds or thousands of orders) should complete within seconds, not minutes. Rule engines that require real-time database lookups (e.g., checking a restricted list stored in an external system) must use caching strategies to meet latency targets. Caching strategies include: loading restricted lists and concentration thresholds into memory at system startup with incremental refresh on change events, pre-computing portfolio metrics (sector weights, issuer exposures) and updating them incrementally as positions change rather than recalculating from scratch for each compliance check, and maintaining in-memory snapshots of account-level compliance state that are updated after each trade rather than queried from the database on every check.
Rule priority and ordering:
Rules should be organized by priority to ensure that the most critical checks are evaluated first and that rule interactions are handled correctly. A typical priority ordering is: (1) account status checks (frozen, suspended, closed), (2) restricted list screening, (3) regulatory position limits, (4) regulatory compliance rules (wash sale, free-riding), (5) client-specific restrictions, (6) firm-level concentration limits, (7) model and guideline compliance. When multiple rules fire on the same order, the most restrictive outcome governs — a hard block from any rule overrides soft blocks from other rules.
Restricted and watch lists are central compliance tools that control trading in securities where the firm or its personnel have conflicts, information advantages, or regulatory obligations.
Firm restricted list (MNPI-driven):
The firm restricted list contains securities in which the firm or its affiliates possess material non-public information (MNPI). For broker-dealers with investment banking affiliates, the restricted list is populated when the firm is engaged in an advisory assignment (M&A, underwriting, restructuring) involving a public company. Trading in restricted list securities is prohibited across all firm accounts — proprietary, advisory, and personal. The restricted list is maintained by the compliance department, typically with input from the legal department and information barriers (Chinese walls) group. Additions and removals are time-sensitive: a security must be added before MNPI is disseminated within the firm and may only be removed after the information becomes public or the engagement terminates.
Personal trading restricted list:
Access persons — employees with access to non-public information about client trades, portfolio holdings, or investment recommendations — are subject to personal trading restrictions. The personal trading restricted list may include securities that the firm is actively trading for clients (to prevent front-running), securities under active research coverage, and IPO and limited offering securities (which require pre-clearance under SEC Rule 204A-1). Personal trading restrictions operate independently of the firm restricted list and may be more or less restrictive depending on the employee's role.
Client-specific restricted securities:
Individual client accounts may have their own restricted securities lists arising from legal constraints (insider status in a company, divorce decree prohibiting sale of certain holdings), contractual obligations (lock-up agreements), or client preferences (client instructs the firm not to purchase securities of a specific company). These restrictions are maintained at the account level and checked during pre-trade compliance for that specific account.
Issuer restriction propagation (parent/subsidiary):
When a security is added to the restricted list, the restriction must propagate to related securities. If the parent company is restricted, all subsidiaries, affiliates, and related entities should also be restricted. This requires maintaining an issuer hierarchy that maps corporate relationships. The propagation should cover: common stock, preferred stock, convertible securities, options, warrants, debt securities, and any other instruments issued by or linked to the restricted issuer. Failure to propagate restrictions across the corporate family is a common compliance gap that regulators specifically test for.
Watch list vs. restricted list (different actions):
The watch list contains securities that are under heightened surveillance but not subject to an outright trading prohibition. Watch list securities may be traded, but trades generate alerts for compliance review. The watch list is used when the firm has reason to monitor trading in a security but the information or situation does not rise to the level requiring a full restriction — for example, when the firm is in early-stage discussions about a potential engagement, when rumors are circulating about a company the firm covers, or when an employee has reported a potential conflict. Watch list matches produce soft blocks; restricted list matches produce hard blocks.
Gray list (additional surveillance tier):
Some firms maintain a gray list in addition to the restricted and watch lists. The gray list is used for securities where the firm may soon receive MNPI but has not yet — for example, when an investment banking pitch is in progress but no engagement letter has been signed. Gray list securities are not restricted from trading, but all trades are flagged for post-trade review by the compliance surveillance team. The gray list provides an early warning mechanism and helps establish that the firm had surveillance procedures in place before MNPI was received, which can be important in defending against insider trading allegations.
List maintenance and updates:
Restricted and watch lists must be updated promptly as circumstances change. Stale lists create two risks: (1) securities that should be restricted are not, exposing the firm to insider trading liability, and (2) securities that should have been removed remain restricted, unnecessarily blocking legitimate trading. Best practices include: real-time or daily list updates, automated feeds from deal management systems (for investment banking-driven restrictions), regular review cycles to confirm that all entries remain valid, and audit trails documenting every addition, removal, and modification with the reason and authorizing person.
Concentration limits prevent excessive exposure to a single security, issuer, sector, or asset class. These limits serve both risk management and regulatory compliance purposes.
Security-level concentration:
The most common concentration limit restricts the maximum percentage of a portfolio that may be invested in a single security. Typical thresholds range from 5% to 10% of account value for a single equity position. The compliance system must calculate the post-trade position value (current holding plus the proposed order) as a percentage of the account's total value and compare it against the limit. For buy orders, the check is straightforward: will this purchase cause the position to exceed X% of the portfolio? For sell orders in other securities, the check must consider whether the sale changes the denominator (total portfolio value) such that remaining positions now exceed their concentration limits.
Sector and industry limits:
Sector limits restrict aggregate exposure to a single GICS sector (e.g., no more than 25% in Technology) or industry (e.g., no more than 10% in Semiconductors). Implementing sector limits requires mapping every security in the portfolio to its sector and industry classification, which in turn requires a reliable security master database with current classification data. Sector limit checks must aggregate all positions within the sector, including the proposed trade, and compare the total against the limit.
Asset class limits:
Asset class limits restrict exposure across broad categories: equities, fixed income, alternatives, cash. These limits typically derive from the investment policy statement (IPS) and are expressed as ranges (e.g., equity 40-70%, fixed income 20-50%, alternatives 0-15%, cash 1-5%). The pre-trade compliance check verifies that the proposed trade does not push any asset class allocation outside its permitted range.
Issuer limits:
Issuer limits restrict total exposure to a single issuer across all security types. A client may hold common stock, corporate bonds, and convertible notes from the same issuer — the issuer limit aggregates all of these exposures. This is particularly important for credit risk management: if an issuer defaults, all securities are affected regardless of type.
Regulatory limits (registered funds):
The Investment Company Act of 1940 imposes specific diversification requirements on registered investment companies (mutual funds). A diversified fund must meet the 75-5-10 test: at least 75% of the fund's assets must be diversified such that no more than 5% of total assets is invested in any single issuer and no more than 10% of an issuer's outstanding voting securities is held. The remaining 25% of assets is not subject to these limits. These are hard regulatory limits that produce hard blocks.
Aggregation across accounts and households:
Some concentration limits apply not just to individual accounts but across related accounts — a household, a family group, or all accounts managed by the same strategy. Household-level concentration limits require the compliance system to aggregate holdings across all accounts in the household before evaluating the limit. This prevents a situation where each individual account is within limits but the household's total exposure to a single security or sector is excessive. Aggregation adds complexity because accounts may be held at different custodians, in different account types (taxable, IRA, trust), and with different investment policies.
Position and exposure limits control the absolute size and risk exposure of positions, complementing the percentage-based concentration limits.
Maximum position size:
Absolute limits on the number of shares or notional value of a position in a single security. These limits may be set at the account level, strategy level, or firm level. Firm-level position limits prevent the firm's aggregate holdings in a single security from becoming large enough to trigger regulatory reporting thresholds (e.g., Schedule 13D/13G filing requirements at 5% of outstanding shares) or to create market impact and liquidity concerns.
Notional exposure limits:
For derivatives and leveraged instruments, notional exposure limits cap the total economic exposure regardless of the cash outlay. A portfolio with $1 million in assets that holds $5 million in notional futures exposure has 5x leverage. Notional exposure limits are essential for strategies that use derivatives, as a small cash investment can create disproportionate market exposure. The compliance system must calculate notional exposure by multiplying the number of contracts by the contract multiplier and the underlying price.
Options position limits (exchange-imposed):
Securities exchanges impose position limits on listed options that cap the number of contracts on the same side of the market (all calls and short puts, or all puts and short calls) that any person or group of persons acting in concert may hold or write. Position limits vary by underlying security based on trading volume and float. The OCC (Options Clearing Corporation) publishes current position limits. Exceeding exchange-imposed position limits results in regulatory action and potential forced liquidation.
Short selling restrictions:
Regulation SHO governs short selling in the United States and imposes several pre-trade requirements:
Leverage limits:
For margin accounts, Regulation T sets initial margin requirements (generally 50% for equity securities), and FINRA Rule 4210 sets maintenance margin requirements (generally 25% for long positions, 30% for short positions). The pre-trade compliance system must verify that the proposed trade does not cause the account to exceed its margin capacity or fall below maintenance requirements. For portfolio margin accounts, the calculation is more complex and uses a risk-based methodology.
Pre-trade compliance systems must enforce specific regulatory rules that govern trading conduct.
Wash sale detection (30-day window):
IRC Section 1091 disallows a tax loss deduction if the taxpayer purchases a "substantially identical" security within 30 days before or after the sale at a loss (the 61-day window). The pre-trade compliance system should flag potential wash sales by: (1) checking whether the account sold the same or substantially identical security at a loss within the prior 30 days (repurchase triggers wash sale), and (2) checking whether there is a pending or planned purchase of the same security within 30 days after a proposed loss sale. Substantially identical securities include the same stock, options on the same stock, and in some interpretations, ETFs tracking the same index. Wash sale detection across related accounts (spouse, IRA) adds complexity, as the IRS applies wash sale rules across accounts controlled by the same taxpayer.
Free-riding prevention (Regulation T):
In a cash account (non-margin), a customer may not purchase a security and sell it before paying for it in full. If a customer buys a security, the purchase must be paid for by the settlement date (T+1). If the customer sells the security before payment, this constitutes free-riding, and the account is subject to a 90-day freeze (all purchases must be made with settled funds for 90 days). The pre-trade compliance system must track unsettled purchases and prevent sales of unpaid-for securities in cash accounts.
Pattern day trader detection:
FINRA Rule 4210 defines a pattern day trader as a customer who executes four or more day trades (buying and selling the same security on the same day) within five business days, provided the number of day trades is more than 6% of the customer's total trading activity in that period. Pattern day traders must maintain at least $25,000 in equity in their margin account. The pre-trade compliance system should count day trades over the rolling five-day window and alert or block when the threshold is approached.
Mutual fund market timing restrictions:
Frequent trading in mutual fund shares (rapid purchases and redemptions) can harm long-term shareholders through dilution and increased transaction costs. Most mutual fund prospectuses include market timing policies that restrict round-trip transactions within specified periods (often 30 to 90 days). The pre-trade compliance system should track mutual fund purchase and redemption activity and flag transactions that violate the fund's stated market timing policy. SEC Rule 22c-2 requires funds to have agreements with intermediaries to share shareholder transaction data for market timing surveillance.
Insider trading prevention (Section 16, Rule 144):
Section 16 of the Securities Exchange Act requires corporate insiders (officers, directors, and 10% beneficial owners) to report their transactions and disgorge short-swing profits (profits from purchases and sales within a six-month window). Rule 144 restricts the resale of control and restricted securities, imposing holding period requirements and volume limitations. When the firm manages accounts for corporate insiders, the pre-trade compliance system must enforce: (1) pre-clearance requirements before any trade in the insider's company securities, (2) blackout period restrictions (insiders typically cannot trade during the period before earnings announcements), (3) Rule 144 volume limits (sales in any three-month period cannot exceed the greater of 1% of outstanding shares or the average weekly trading volume over the prior four weeks), and (4) Form 4 filing coordination.
ERISA prohibited transaction rules:
For accounts subject to the Employee Retirement Income Security Act (ERISA), certain transactions between the plan and "parties in interest" (fiduciaries, service providers, employers, unions) are prohibited. The pre-trade compliance system must maintain a list of parties in interest for each ERISA plan account and block transactions that would constitute prohibited transactions — for example, purchasing securities issued by the plan sponsor or its affiliates, or engaging in lending or leasing arrangements with parties in interest. Exemptions exist under Prohibited Transaction Exemptions (PTEs) issued by the Department of Labor, and the system should be configurable to recognize applicable exemptions.
Beyond firm-wide and regulatory rules, individual client accounts may carry specific restrictions that the compliance system must enforce.
Investment policy constraints:
The investment policy statement (IPS) for each account may specify exclusions based on industry (no tobacco, no firearms, no gambling), geography (no emerging markets, no specific countries), security type (no derivatives, no structured products, no private placements), quality (investment-grade bonds only, no below-BBB), or other criteria. These constraints are mapped to security attributes and enforced as hard or soft blocks depending on the strength of the restriction. IPS constraints should be coded into the compliance system at account onboarding and updated when the IPS is revised.
Tax-loss harvesting coordination:
Accounts actively engaged in tax-loss harvesting require compliance coordination to avoid wash sales. When one account sells a security at a loss for tax purposes, the compliance system must prevent repurchase of the same or substantially identical security within the 30-day wash sale window — not only in the same account but across all accounts for the same taxpayer (including spouse's accounts and IRAs). This requires cross-account wash sale monitoring with household-level linkage.
Legally restricted securities:
Court orders, divorce decrees, trust provisions, and other legal documents may restrict trading in specific securities or impose conditions on transactions. Examples include: a divorce decree prohibiting the sale of marital property (including securities) during proceedings, a trust provision requiring trustee approval before selling concentrated positions, a court-ordered freeze on assets pending litigation, or restrictions imposed by a regulatory consent order. These restrictions are typically entered manually by compliance and coded as hard blocks.
ESG/SRI screens:
Environmental, social, and governance (ESG) screens and socially responsible investing (SRI) criteria exclude securities based on non-financial factors. Common screens include: fossil fuel exclusion (companies deriving more than a specified percentage of revenue from coal, oil, or gas extraction), weapons exclusion (manufacturers of controversial weapons, civilian firearms), tobacco and alcohol exclusion, animal testing exclusion, and human rights screens. ESG screens require mapping securities to ESG data providers (MSCI ESG, Sustainalytics, ISS ESG) and maintaining current classification data. Because ESG classifications can change as companies evolve, the screening data must be refreshed regularly.
Account-level trading restrictions:
Certain account-level conditions require trading restrictions: frozen accounts (pending regulatory action, suspicious activity investigation, or customer dispute), accounts with pending paperwork (incomplete account opening documentation, unsigned IPS, missing beneficiary designation), accounts in estate settlement (trading freeze pending legal authority confirmation), and accounts subject to garnishment or levy (where outgoing transactions may be prohibited). These account-level flags produce hard blocks on all or specific types of trading activity.
Soft blocks require a structured override process that balances operational efficiency with compliance rigor.
Soft block review process:
When a soft block fires, the order is held in a pending compliance review status. The system presents the compliance officer or authorized reviewer with: the order details, the rule that triggered the block, the current state of the relevant metric (e.g., "this purchase would bring the Technology sector allocation to 27%, exceeding the 25% guideline"), and any relevant context (e.g., the account's IPS permits tactical overweights of up to 5% with advisor approval). The reviewer evaluates whether the trade is justified despite the guideline breach and either approves (overrides) or rejects the order.
Override authorization levels:
Not all overrides should be authorized at the same level. A tiered authorization structure matches the severity of the override to the seniority of the authorizer:
Override documentation requirements:
Every override must be documented with: (1) the order details, (2) the rule that was triggered, (3) the quantitative details of the violation (how far the metric exceeds the threshold), (4) the identity of the person requesting the override, (5) the identity of the person authorizing the override, (6) the timestamp of the authorization, (7) the stated justification for the override, and (8) any conditions attached to the approval (e.g., "approved provided the overweight is reduced within 30 days"). This documentation must be retained as part of the firm's compliance records and is subject to regulatory examination.
Escalation procedures:
When a reviewer is uncertain about whether to approve an override, or when the override involves a particularly sensitive situation (e.g., a trade that raises potential insider trading concerns), the system should provide a clear escalation path. Escalation may route the override to the CCO, the legal department, or a compliance committee. The escalation path and the resolution must be documented.
Post-override audit:
Compliance should periodically audit override activity to identify patterns and systemic issues. The audit should examine: the total volume and frequency of overrides, overrides by rule type (which rules are most frequently overridden), overrides by account or advisor (are certain advisors consistently triggering and overriding the same rules), whether conditions attached to approved overrides were fulfilled (e.g., was the overweight actually reduced within 30 days as required), and whether any overrides resulted in adverse outcomes (client harm, regulatory issues).
Pattern analysis of overrides:
If the same rule is being overridden frequently, it may indicate that the rule threshold is miscalibrated (too tight, generating excessive false positives), that a particular advisor or strategy systematically operates outside the guideline (requiring either a guideline adjustment or a strategy change), or that the rule is no longer appropriate given current market conditions or regulatory requirements. Override pattern analysis feeds directly into the rule tuning process.
The effectiveness of the pre-trade compliance system depends on ongoing rule management — adding new rules, modifying thresholds, retiring obsolete rules, and ensuring that the rule set reflects current regulatory requirements and firm policies.
Adding and modifying rules:
New rules may be required when regulations change, the firm enters a new business line, or compliance identifies a gap in the existing rule set. The rule addition process should include: (1) defining the rule logic (what condition triggers the block, what type of block is produced), (2) setting the threshold or parameter values, (3) determining which accounts or account types the rule applies to, (4) testing the rule against historical order data to assess its impact (how many orders would it have blocked), (5) obtaining approval from the CCO or compliance committee, (6) deploying the rule in a monitoring-only mode before activating blocking (shadow mode), and (7) activating the rule with blocking enabled after the shadow period confirms expected behavior.
Backtesting rules against historical orders:
Before activating a new rule or modifying a threshold, the rule should be backtested against a representative sample of historical orders. Backtesting reveals: the expected block rate (percentage of orders that would be blocked), the false positive rate (orders that would be blocked but are actually legitimate), and the false negative rate (orders that should be blocked but are not caught). This data informs threshold calibration and helps the compliance team anticipate the operational impact of the new rule.
False positive analysis:
A high false positive rate undermines the compliance system's credibility and creates operational friction. If traders and advisors routinely override soft blocks because the blocks are perceived as invalid, they may develop "alert fatigue" and begin overriding blocks without proper evaluation — including blocks that are valid. The compliance team should track the override rate for each rule and investigate rules with override rates above a defined threshold (e.g., rules overridden more than 50% of the time). Remediation may include adjusting the threshold, refining the rule logic, or reclassifying the rule from a soft block to a monitoring alert.
Rule tuning:
Rule tuning is the ongoing process of adjusting thresholds and parameters to optimize the balance between catching genuine violations and minimizing false blocks. Tuning should be data-driven: the compliance team analyzes block rates, override rates, and the outcomes of overridden trades to determine whether thresholds are appropriately calibrated. Tuning decisions should be documented and approved by the CCO.
Rule version control:
The compliance rule set should be subject to version control, similar to software code. Each rule change — addition, modification, threshold adjustment, or retirement — should be recorded with the effective date, the person who made the change, the approval, and the reason. Version control enables the compliance team to reconstruct the rule set that was in effect on any historical date, which is essential for regulatory examinations and investigations that require demonstrating what controls were in place at the time of a particular trade.
Regulatory change management:
When regulations change, the compliance team must assess the impact on the pre-trade compliance rule set and implement necessary modifications. This requires monitoring regulatory developments (SEC releases, FINRA regulatory notices, exchange rule changes), analyzing the impact on existing rules, modifying or adding rules as needed, backtesting the modified rules, and deploying changes before the regulatory effective date. A regulatory change management calendar should track upcoming effective dates and the status of rule modifications.
Three worked examples are in references/examples.md — load for an end-to-end scenario: (1) designing a pre-trade compliance rule engine for a multi-custodian RIA, (2) implementing restricted list management for a broker-dealer with investment banking affiliates, (3) configuring household-level concentration limits around a legacy concentrated position.
testing
Model, forecast, and interpret volatility using time-series models and options-implied measures. Use when the user asks about EWMA, GARCH models, implied volatility, volatility surfaces, volatility term structure, or the VIX. Also trigger when users mention 'volatility smile', 'volatility skew', 'realized vs implied vol', 'volatility risk premium', 'vol clustering', 'mean-reverting volatility', 'options pricing inputs', 'RiskMetrics', 'decay factor', or ask how to forecast future volatility for risk management.
testing
Execute a complete tax-loss harvesting workflow from candidate identification through post-harvest monitoring. Use when the user asks about finding TLH candidates, gain/loss budgeting, replacement security selection, wash-sale compliance, or harvest execution planning. Also trigger when users mention 'unrealized losses in my portfolio', 'swap ETFs for tax purposes', 'harvest losses before year-end', 'substantially identical security', 'wash-sale window', 'NIIT offset', 'loss carryforward', or ask how much tax they can save by harvesting.
testing
Maximizes after-tax returns through strategic asset location, gain/loss management, and withdrawal sequencing. Use when the user asks about asset location, Roth conversions, tax-efficient withdrawals, tax lot selection, or charitable giving with appreciated securities. Also trigger when users mention 'which account should I hold bonds in', 'tax drag', 'Roth vs Traditional', 'RMD planning', 'bracket stuffing', 'HIFO vs FIFO', or ask how to minimize taxes on investments. For tax-loss harvesting execution and wash-sale mechanics, see the tax-loss-harvesting skill.
development
Plan and track savings for specific financial goals including retirement, education, and home purchase. Use when the user asks about required savings rates, 529 plans, retirement accumulation targets, down payment planning, or goal prioritization. Also trigger when users mention 'how much do I need to save each month', 'am I on track for retirement', 'college savings', 'safe withdrawal rate', '4% rule', 'FIRE savings rate', 'catch-up contributions', 'employer match', or ask how to balance competing savings goals.