Skip to content

feat: add SMC bias agent#264

Open
Ayush441-python wants to merge 1 commit into
Lamatic:mainfrom
Ayush441-python:feat/smc-bias-agent
Open

feat: add SMC bias agent#264
Ayush441-python wants to merge 1 commit into
Lamatic:mainfrom
Ayush441-python:feat/smc-bias-agent

Conversation

@Ayush441-python

@Ayush441-python Ayush441-python commented Jul 17, 2026

Copy link
Copy Markdown

PR Checklist

1. Select Contribution Type

  • Kit (kits/<category>/<kit-name>/)
  • Bundle (bundles/<bundle-name>/)
  • Template (templates/<template-name>/)

2. General Requirements

  • PR is for one project only (no unrelated changes)
  • No secrets, API keys, or real credentials are committed
  • Folder name uses kebab-case and matches the flow ID
  • All changes are documented in README.md (purpose, setup, usage)

3. File Structure (Check what applies)

  • config.json present with valid metadata (name, description, tags, steps, author, env keys)
  • All flows in flows/<flow-name>/ (where applicable) include:
    • config.json (Lamatic flow export)
    • inputs.json
    • meta.json
    • README.md
  • .env.example with placeholder values only (kits only)
  • No hand‑edited flow config.json node graphs (changes via Lamatic Studio export)

4. Validation

  • npm install && npm run dev works locally (kits: UI runs; bundles/templates: flows are valid)
  • PR title is clear (e.g., [kit] Add <name> for <use case>)
  • GitHub Actions workflows pass (all checks are green)
  • All CodeRabbit or other PR review comments are addressed and resolved
  • No unrelated files or projects are modified
  • Added the kits/smc-bias-agent Next.js kit with:
    • SMC/ICT market-structure analysis for Binance OHLCV data.
    • Swing points, BOS/CHoCH events, order blocks, fair value gaps, bias, confidence, and key-level detection.
    • Binance candle fetching with supported interval validation.
    • API endpoint for symbol/timeframe analysis.
    • Interactive UI with symbol and timeframe selection, annotated candlestick chart, bias card, confidence, reasoning, and key levels.
    • Lamatic narrative generation with deterministic local fallback.
    • Shared TypeScript models for candles, market structures, zones, and analysis results.
  • Added project configuration and tooling:
    • Next.js, TypeScript, Tailwind, PostCSS, package scripts, lint/build/start commands, and SMC test command.
    • Lamatic kit metadata via lamatic.config.ts.
    • Environment variable template for Lamatic API, GraphQL, project, and workflow settings.
    • Ignore rules for dependencies, build output, local environment files, and TypeScript artifacts.
    • README covering setup, usage, Lamatic wiring, behavior, and limitations.
  • The requested flow.json was not present in the available repository files, so no flow node types or flow execution details could be verified.

@Ayush441-python

Copy link
Copy Markdown
Author

adding SMC agnet

@akshatvirmani akshatvirmani changed the title add SMC bias agent feat: add SMC bias agent Jul 20, 2026
@github-actions

Copy link
Copy Markdown
Contributor

:robot_face: AgentKit Structural Validation

New Contributions Detected

  • Kit: kits/smc-bias-agent

Check Results

Check Status
No edits to existing kits ✅ Pass
Required root files present ❌ Fail
Flow .ts files present ✅ Pass
lamatic.config.ts valid ❌ Fail
No changes outside kits/ ✅ Pass

❌ Errors

  • Missing agent.md in kits/smc-bias-agent
  • Missing constitutions/default.md in kits/smc-bias-agent
  • Missing flows/ directory in kits/smc-bias-agent
  • Kit kits/smc-bias-agent is missing apps/package.json — kits must include a Next.js app
  • Kit kits/smc-bias-agent is missing apps/.env.example

⚠️ Warnings

  • lamatic.config.ts in kits/smc-bias-agent — links.github should point to kits/smc-bias-agent

🛑 Please fix the errors above before this PR can be merged.

Refer to CONTRIBUTING.md and CLAUDE.md for the expected folder structure.

@github-actions

Copy link
Copy Markdown
Contributor

Failure recorded at 2026-07-20T10:34:25Z UTC. If this PR is not fixed within 4 weeks it will be automatically closed.

@coderabbitai

coderabbitai Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Changes

The pull request adds a complete Next.js SMC Bias Agent kit: Binance candle retrieval, SMC/ICT analysis, Lamatic or fallback narrative generation, an analysis API, and a chart-based frontend with setup documentation.

SMC Bias Agent

Layer / File(s) Summary
Analysis contracts and market data
kits/smc-bias-agent/lib/types.ts, kits/smc-bias-agent/lib/binance.ts, kits/smc-bias-agent/lamatic.config.ts, kits/smc-bias-agent/.env.example
Defines SMC data contracts, validates Binance intervals, fetches candle data, and declares kit and Lamatic configuration.
SMC detection pipeline
kits/smc-bias-agent/lib/smc.ts
Detects swings, BOS/CHoCH events, order blocks, fair value gaps, bias confidence, and key levels, then aggregates them into SMCAnalysis.
Narrative and analysis API
kits/smc-bias-agent/lib/lamatic-client.ts, kits/smc-bias-agent/app/api/analyze/route.ts
Generates Lamatic prompts or deterministic fallback narratives and exposes them with analysis through a POST route.
Chart and bias interface
kits/smc-bias-agent/app/page.tsx, kits/smc-bias-agent/app/layout.tsx, kits/smc-bias-agent/app/globals.css, kits/smc-bias-agent/components/*
Adds the scan form, result states, SVG candlestick chart, bias card, typography, colors, focus styling, and motion rules.
Kit setup and documentation
kits/smc-bias-agent/package.json, kits/smc-bias-agent/tsconfig.json, kits/smc-bias-agent/next.config.js, kits/smc-bias-agent/postcss.config.js, kits/smc-bias-agent/tailwind.config.ts, kits/smc-bias-agent/next-env.d.ts, kits/smc-bias-agent/.gitignore, kits/smc-bias-agent/README.md
Adds project tooling, build configuration, ignored local artifacts, and setup and usage documentation.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is only the checklist template and leaves every required item unchecked or unaddressed. Fill out the checklist with completed selections and add brief details for scope, documentation, files, validation, and review status.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is concise and accurately summarizes the main change: adding an SMC bias agent.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@kits/smc-bias-agent/.env.example`:
- Around line 1-4: Replace the credential-like values in the .env.example
entries LAMATIC_API_KEY, LAMATIC_GRAPHQL_URL, LAMATIC_PROJECT_ID, and
LAMATIC_WORKFLOW_ID with clearly fake placeholders, and rotate or revoke the
exposed Lamatic credentials separately.

In `@kits/smc-bias-agent/app/api/analyze/route.ts`:
- Around line 22-32: Update the error handling in the analyze route’s catch
block to distinguish client-input/validation failures, such as unsupported
interval or insufficient candles, from upstream fetch or analysis failures.
Return HTTP 400 for client errors and retain 502 for upstream failures, using
the existing error information and route flow without changing successful
responses.

In `@kits/smc-bias-agent/components/PriceChart.tsx`:
- Line 32: Remove the unused localIndexOf function definition from the
PriceChart component, leaving the surrounding chart logic and start value
unchanged.

In `@kits/smc-bias-agent/lamatic.config.ts`:
- Around line 1-15: Update the config object exported by lamatic.config.ts to
include the required author, steps, and links metadata, matching the structure
and values used by an existing sibling kit configuration. Set links.github to
reference kits/smc-bias-agent while preserving the current name, slug, type,
description, and tags.

In `@kits/smc-bias-agent/lib/binance.ts`:
- Around line 16-42: Both outbound requests lack cancellation and can hang the
analysis request indefinitely. In kits/smc-bias-agent/lib/binance.ts:16-42,
update fetchCandles to create an AbortController, enforce the shared timeout
pattern, pass its signal to fetch, and clean up the timer; apply the same change
to getBiasNarrative’s fetch in
kits/smc-bias-agent/lib/lamatic-client.ts:101-110, preserving existing response
and error handling.
- Around line 29-41: Validate each row in the Binance response before mapping it
in the surrounding fetch/parser function: require the expected six fields,
verify the timestamp and OHLCV values are present and finite after conversion,
and reject malformed rows with a clear error instead of returning NaN. Remove
the unchecked tuple cast and raw parseFloat flow while preserving the existing
normalized output for valid rows.

In `@kits/smc-bias-agent/lib/lamatic-client.ts`:
- Around line 92-98: Align the Lamatic configuration contract so
getBiasNarrative uses the variables provided by the example or the example
defines the single LAMATIC_FLOW_ENDPOINT contract; update
kits/smc-bias-agent/lib/lamatic-client.ts lines 92-98 and
kits/smc-bias-agent/.env.example lines 1-4 consistently, ensuring the example
enables the Lamatic narrative path instead of falling back silently.

In `@kits/smc-bias-agent/lib/smc.ts`:
- Around line 12-14: Update findOrderBlocks to enforce the impulse-strength
threshold when selecting the opposite-colored origin candle, requiring its
absolute body range to meet IMPULSE_MIN_RANGE_MULT times the relevant average
range before accepting it; otherwise continue searching or reject the candidate.
If this filter is not intended, remove the unused IMPULSE_MIN_RANGE_MULT
constant instead.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: ASSERTIVE

Plan: Pro

Run ID: ea41a1d0-2522-4683-abba-7dd749c7bc38

📥 Commits

Reviewing files that changed from the base of the PR and between 0ada432 and ac50441.

⛔ Files ignored due to path filters (1)
  • kits/smc-bias-agent/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (20)
  • kits/smc-bias-agent/.env.example
  • kits/smc-bias-agent/.gitignore
  • kits/smc-bias-agent/README.md
  • kits/smc-bias-agent/app/api/analyze/route.ts
  • kits/smc-bias-agent/app/globals.css
  • kits/smc-bias-agent/app/layout.tsx
  • kits/smc-bias-agent/app/page.tsx
  • kits/smc-bias-agent/components/BiasCard.tsx
  • kits/smc-bias-agent/components/PriceChart.tsx
  • kits/smc-bias-agent/lamatic.config.ts
  • kits/smc-bias-agent/lib/binance.ts
  • kits/smc-bias-agent/lib/lamatic-client.ts
  • kits/smc-bias-agent/lib/smc.ts
  • kits/smc-bias-agent/lib/types.ts
  • kits/smc-bias-agent/next-env.d.ts
  • kits/smc-bias-agent/next.config.js
  • kits/smc-bias-agent/package.json
  • kits/smc-bias-agent/postcss.config.js
  • kits/smc-bias-agent/tailwind.config.ts
  • kits/smc-bias-agent/tsconfig.json

Comment on lines +1 to +4
LAMATIC_API_KEY=lt-a37857b83dd6f993e9d327b9a9f68bba
LAMATIC_GRAPHQL_URL=https://ayushsorganization263-ayushsproject211.lamatic.dev/graphql
LAMATIC_PROJECT_ID=3bffc6da-08d8-4f1a-af0c-f654bca169e6
LAMATIC_WORKFLOW_ID=8ba7821c-251d-4d58-827b-bb5d627a3d57 No newline at end of file

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🔴 Critical | ⚡ Quick win

Abort, abort — this tape is self-destructing for a reason, and these credentials should too.

These values look like real, issued credentials (API key, project ID, workflow ID, and a personal Lamatic subdomain in the GraphQL URL), not placeholders. Static analysis flags a generic API key here. Committing real secrets into a .env.example template exposes them to anyone who clones the repo.

Rotate this key/workflow immediately and replace all four values with clearly fake placeholders (e.g. LAMATIC_API_KEY=your-lamatic-api-key).

🧰 Tools
🪛 Betterleaks (1.6.1)

[high] 1-1: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🪛 dotenv-linter (4.0.0)

[warning] 4-4: [EndingBlankLine] No blank line at the end of the file

(EndingBlankLine)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@kits/smc-bias-agent/.env.example` around lines 1 - 4, Replace the
credential-like values in the .env.example entries LAMATIC_API_KEY,
LAMATIC_GRAPHQL_URL, LAMATIC_PROJECT_ID, and LAMATIC_WORKFLOW_ID with clearly
fake placeholders, and rotate or revoke the exposed Lamatic credentials
separately.

Source: Linters/SAST tools

Comment on lines +22 to +32
try {
const candles = await fetchCandles(symbol, interval);
const analysis = analyzeSMC(symbol, interval, candles);
const narrative = await getBiasNarrative(analysis);

return NextResponse.json({ analysis, narrative });
} catch (err) {
const message = err instanceof Error ? err.message : "Unexpected error while analyzing the symbol.";
return NextResponse.json({ error: message }, { status: 502 });
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

One-size-fits-all disguise won't fool every checkpoint.

Every thrown error — including client-input problems like an unsupported interval or "not enough candles" — is mapped to 502. That's a Bad-Gateway code reserved for upstream failures; input-validation failures should surface as 400.

🎯 Proposed fix: distinguish client vs upstream errors
   } catch (err) {
     const message = err instanceof Error ? err.message : "Unexpected error while analyzing the symbol.";
-    return NextResponse.json({ error: message }, { status: 502 });
+    const isClientError = message.includes("Unsupported interval") || message.includes("Not enough candles");
+    return NextResponse.json({ error: message }, { status: isClientError ? 400 : 502 });
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
const candles = await fetchCandles(symbol, interval);
const analysis = analyzeSMC(symbol, interval, candles);
const narrative = await getBiasNarrative(analysis);
return NextResponse.json({ analysis, narrative });
} catch (err) {
const message = err instanceof Error ? err.message : "Unexpected error while analyzing the symbol.";
return NextResponse.json({ error: message }, { status: 502 });
}
}
try {
const candles = await fetchCandles(symbol, interval);
const analysis = analyzeSMC(symbol, interval, candles);
const narrative = await getBiasNarrative(analysis);
return NextResponse.json({ analysis, narrative });
} catch (err) {
const message = err instanceof Error ? err.message : "Unexpected error while analyzing the symbol.";
const isClientError = message.includes("Unsupported interval") || message.includes("Not enough candles");
return NextResponse.json({ error: message }, { status: isClientError ? 400 : 502 });
}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@kits/smc-bias-agent/app/api/analyze/route.ts` around lines 22 - 32, Update
the error handling in the analyze route’s catch block to distinguish
client-input/validation failures, such as unsupported interval or insufficient
candles, from upstream fetch or analysis failures. Return HTTP 400 for client
errors and retain 502 for upstream failures, using the existing error
information and route flow without changing successful responses.

const xAt = (localIndex: number) => PAD_LEFT + localIndex * slot + slot / 2;
const yAt = (price: number) => PAD_TOP + (1 - (price - minPrice) / span) * plotH;

const localIndexOf = (globalIndex: number) => globalIndex - start;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Eliminate unused function.

Agent, your mission, should you choose to accept it, is to eliminate this dead code to keep our operation's footprint clean. localIndexOf is defined here but never utilized in the field.

🕶️ Proposed fix
-  const localIndexOf = (globalIndex: number) => globalIndex - start;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const localIndexOf = (globalIndex: number) => globalIndex - start;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@kits/smc-bias-agent/components/PriceChart.tsx` at line 32, Remove the unused
localIndexOf function definition from the PriceChart component, leaving the
surrounding chart logic and start value unchanged.

Comment on lines +1 to +15
// NOTE: field names here are my best inference from the public repo structure
// (every kit is typed via this file's `type` field: "template" | "bundle" | "kit").
// Confirm this against an existing sibling kit's lamatic.config.ts after forking
// and adjust field names if the actual schema differs.

const config = {
name: "SMC Bias Agent",
slug: "smc-bias-agent",
type: "kit" as const,
description:
"Detects Smart Money Concepts structure (order blocks, fair value gaps, break of structure / change of character) on a crypto pair and returns a plain-English directional bias with key levels to watch.",
tags: ["crypto", "trading", "smc", "ict", "technical-analysis"],
};

export default config;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate kit config files and inspect the target plus a sibling example.
git ls-files 'kits/*/lamatic.config.ts' | sed -n '1,80p'

echo '--- target ---'
cat -n kits/smc-bias-agent/lamatic.config.ts

echo '--- sibling list with line counts ---'
for f in $(git ls-files 'kits/*/lamatic.config.ts' | grep -v '^kits/smc-bias-agent/lamatic.config.ts$' | head -n 5); do
  echo "FILE: $f"
  wc -l "$f"
done

Repository: Lamatic/AgentKit

Length of output: 4871


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Read a representative sibling config to compare required fields and schema.
sibling=$(git ls-files 'kits/*/lamatic.config.ts' | grep -v '^kits/smc-bias-agent/lamatic.config.ts$' | head -n 1)
echo "SIBLING=$sibling"
cat -n "$sibling"

Repository: Lamatic/AgentKit

Length of output: 158


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Check for the repo's validation workflow mention of links.github and kit naming.
rg -n "links\.github|kits/<name>|lamatic\.config\.ts|author|steps|links" .github kits -g '!**/node_modules/**' -g '!**/dist/**' -g '!**/build/**'

Repository: Lamatic/AgentKit

Length of output: 50373


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '## kit config files'
git ls-files 'kits/*/lamatic.config.ts' | sort

echo
echo '## target file'
cat -n kits/smc-bias-agent/lamatic.config.ts

echo
echo '## first sibling'
sibling=$(git ls-files 'kits/*/lamatic.config.ts' | grep -v '^kits/smc-bias-agent/lamatic.config.ts$' | sort | head -n 1)
echo "SIBLING: $sibling"
cat -n "$sibling"

echo
echo '## schema references'
rg -n "links\.github|author:|steps:|type:|slug:|tags:" .github kits -g '!**/node_modules/**' -g '!**/dist/**' -g '!**/build/**'

Repository: Lamatic/AgentKit

Length of output: 50372


Restore the required kit metadata.
kits/smc-bias-agent/lamatic.config.ts is missing author, steps, and links; this kit config needs to match the repo’s metadata contract, and links.github should point to kits/smc-bias-agent.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@kits/smc-bias-agent/lamatic.config.ts` around lines 1 - 15, Update the config
object exported by lamatic.config.ts to include the required author, steps, and
links metadata, matching the structure and values used by an existing sibling
kit configuration. Set links.github to reference kits/smc-bias-agent while
preserving the current name, slug, type, description, and tags.

Source: Coding guidelines

Comment on lines +16 to +42
export async function fetchCandles(symbol: string, interval: string, limit = 150): Promise<Candle[]> {
if (!isValidInterval(interval)) {
throw new Error(`Unsupported interval "${interval}". Use one of: ${[...ALLOWED_INTERVALS].join(", ")}`);
}

const url = `${BINANCE_BASE}?symbol=${encodeURIComponent(symbol.toUpperCase())}&interval=${interval}&limit=${limit}`;
const res = await fetch(url, { next: { revalidate: 30 } });

if (!res.ok) {
const body = await res.text().catch(() => "");
throw new Error(`Binance request failed (${res.status}): ${body || res.statusText}`);
}

const raw = (await res.json()) as unknown[];

return raw.map((row) => {
const r = row as [number, string, string, string, string, string, ...unknown[]];
return {
time: Math.floor(r[0] / 1000),
open: parseFloat(r[1]),
high: parseFloat(r[2]),
low: parseFloat(r[3]),
close: parseFloat(r[4]),
volume: parseFloat(r[5]),
};
});
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Two unfused fetches in the same mission — patch both before this op goes live. Both outbound fetch calls run synchronously inside the POST /api/analyze request path with no timeout or AbortController, so either external service stalling can hang the request indefinitely.

  • kits/smc-bias-agent/lib/binance.ts#L16-L42: wrap the Binance fetch call in fetchCandles with an AbortController-based timeout.
  • kits/smc-bias-agent/lib/lamatic-client.ts#L101-L110: wrap the Lamatic flow fetch call in getBiasNarrative with the same timeout pattern.
📍 Affects 2 files
  • kits/smc-bias-agent/lib/binance.ts#L16-L42 (this comment)
  • kits/smc-bias-agent/lib/lamatic-client.ts#L101-L110
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@kits/smc-bias-agent/lib/binance.ts` around lines 16 - 42, Both outbound
requests lack cancellation and can hang the analysis request indefinitely. In
kits/smc-bias-agent/lib/binance.ts:16-42, update fetchCandles to create an
AbortController, enforce the shared timeout pattern, pass its signal to fetch,
and clean up the timer; apply the same change to getBiasNarrative’s fetch in
kits/smc-bias-agent/lib/lamatic-client.ts:101-110, preserving existing response
and error handling.

Comment on lines +29 to +41
const raw = (await res.json()) as unknown[];

return raw.map((row) => {
const r = row as [number, string, string, string, string, string, ...unknown[]];
return {
time: Math.floor(r[0] / 1000),
open: parseFloat(r[1]),
high: parseFloat(r[2]),
low: parseFloat(r[3]),
close: parseFloat(r[4]),
volume: parseFloat(r[5]),
};
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

No safe-house for malformed Binance rows.

The row as [number, string, ...] cast plus raw parseFloat trusts the response shape entirely — an API change or unexpected row (missing element, empty string) silently yields NaN, which then propagates through swing/OB/FVG math without a loud failure.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@kits/smc-bias-agent/lib/binance.ts` around lines 29 - 41, Validate each row
in the Binance response before mapping it in the surrounding fetch/parser
function: require the expected six fields, verify the timestamp and OHLCV values
are present and finite after conversion, and reject malformed rows with a clear
error instead of returning NaN. Remove the unchecked tuple cast and raw
parseFloat flow while preserving the existing normalized output for valid rows.

Comment on lines +92 to +98
export async function getBiasNarrative(analysis: SMCAnalysis): Promise<BiasNarrative> {
const apiKey = process.env.LAMATIC_API_KEY;
const endpoint = process.env.LAMATIC_FLOW_ENDPOINT;

if (!apiKey || !endpoint) {
return { reasoning: localFallbackNarrative(analysis), source: "fallback" };
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

The dead-drop location and the pickup instructions don't match. getBiasNarrative requires LAMATIC_FLOW_ENDPOINT, but .env.example never defines it (it ships LAMATIC_GRAPHQL_URL, LAMATIC_PROJECT_ID, LAMATIC_WORKFLOW_ID instead), so following the example as-is silently disables the Lamatic narrative path.

  • kits/smc-bias-agent/lib/lamatic-client.ts#L92-L98: either read the endpoint from the vars actually shipped in .env.example (build it from LAMATIC_GRAPHQL_URL/LAMATIC_PROJECT_ID/LAMATIC_WORKFLOW_ID) or standardize on a single LAMATIC_FLOW_ENDPOINT contract.
  • kits/smc-bias-agent/.env.example#L1-L4: add LAMATIC_FLOW_ENDPOINT (or rename to match whatever contract lamatic-client.ts settles on) so the example is actually functional out of the box.
📍 Affects 2 files
  • kits/smc-bias-agent/lib/lamatic-client.ts#L92-L98 (this comment)
  • kits/smc-bias-agent/.env.example#L1-L4
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@kits/smc-bias-agent/lib/lamatic-client.ts` around lines 92 - 98, Align the
Lamatic configuration contract so getBiasNarrative uses the variables provided
by the example or the example defines the single LAMATIC_FLOW_ENDPOINT contract;
update kits/smc-bias-agent/lib/lamatic-client.ts lines 92-98 and
kits/smc-bias-agent/.env.example lines 1-4 consistently, ensuring the example
enables the Lamatic narrative path instead of falling back silently.

Comment on lines +12 to +14
const SWING_LOOKBACK = 2;
const IMPULSE_LOOKAHEAD = 4;
const IMPULSE_MIN_RANGE_MULT = 1.5;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Agent, this gadget was packed but never deployed.

IMPULSE_MIN_RANGE_MULT is declared but never used — findOrderBlocks accepts the first opposite-colored candle before a structure event regardless of its range, so the intended impulse-strength filter implied by this constant's name isn't actually enforced.

Either wire it into the origin-candle search (e.g. require Math.abs(origin.close - origin.open) >= IMPULSE_MIN_RANGE_MULT * avgRange) or remove the dead constant if it's not needed.

Also applies to: 67-115

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@kits/smc-bias-agent/lib/smc.ts` around lines 12 - 14, Update findOrderBlocks
to enforce the impulse-strength threshold when selecting the opposite-colored
origin candle, requiring its absolute body range to meet IMPULSE_MIN_RANGE_MULT
times the relevant average range before accepting it; otherwise continue
searching or reject the candidate. If this filter is not intended, remove the
unused IMPULSE_MIN_RANGE_MULT constant instead.

@github-actions

Copy link
Copy Markdown
Contributor

Hi @Ayush441-python! 👋

Before this PR can be reviewed by maintainers, please resolve all comments and requested changes from the CodeRabbit automated review.

Steps to follow:

  1. Read through all CodeRabbit comments carefully
  2. Address each issue raised (or reply explaining why you disagree)
  3. Push your fixes as new commits
  4. Once all issues are resolved, comment here so we can re-review

This helps keep the review process efficient for everyone. Thank you! 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant