{"id":48872278,"url":"https://github.com/dahsameer/nepse-api-helper","last_synced_at":"2026-04-15T22:39:57.112Z","repository":{"id":57687672,"uuid":"482434018","full_name":"dahsameer/nepse-api-helper","owner":"dahsameer","description":"a wrapper to use nepse api easily since they set up weird restrictions","archived":false,"fork":false,"pushed_at":"2026-03-21T12:05:22.000Z","size":109,"stargazers_count":9,"open_issues_count":0,"forks_count":2,"subscribers_count":2,"default_branch":"main","last_synced_at":"2026-04-15T22:39:33.970Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"unlicense","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dahsameer.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2022-04-17T05:18:44.000Z","updated_at":"2026-03-21T12:05:26.000Z","dependencies_parsed_at":"2025-10-19T15:08:27.579Z","dependency_job_id":"473ef8bd-d690-42ff-bc76-af7863ba4823","html_url":"https://github.com/dahsameer/nepse-api-helper","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/dahsameer/nepse-api-helper","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dahsameer%2Fnepse-api-helper","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dahsameer%2Fnepse-api-helper/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dahsameer%2Fnepse-api-helper/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dahsameer%2Fnepse-api-helper/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dahsameer","download_url":"https://codeload.github.com/dahsameer/nepse-api-helper/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dahsameer%2Fnepse-api-helper/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31863499,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-15T15:24:51.572Z","status":"ssl_error","status_checked_at":"2026-04-15T15:24:39.138Z","response_time":63,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-04-15T22:39:56.536Z","updated_at":"2026-04-15T22:39:57.101Z","avatar_url":"https://github.com/dahsameer.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\n# nepse-api-helper\n\n\u003e **A modern TypeScript library for seamless, robust access to the Nepal Stock Exchange (NEPSE) API.**\n\n---\n\n## Why use nepse-api-helper?\n\n- **Handles NEPSE's complex token logic and restrictions for you**\n- **Automatic caching and retry logic** for reliability and speed\n- **Pluggable logging** for full observability\n- **TypeScript-first**: strict types, generics, and DX\n- **WASM fallback**: always works, even if NEPSE changes their obfuscation\n- **Easy to test and extend**\n\n---\n\n[![npm version](https://img.shields.io/npm/v/nepse-api-helper.svg)](https://www.npmjs.com/package/nepse-api-helper)\n[![License: MIT](https://img.shields.io/badge/License-The%20Unlicense-yellow.svg)](https://opensource.org/license/unlicense)\n\nA TypeScript/JavaScript library that simplifies interaction with the NEPSE (Nepal Stock Exchange) API by handling authentication, token management, and API requests.\n\n\u003e **Educational Purpose Only**: This library is created for educational purposes to understand API interactions and is not affiliated with or endorsed by NEPSE.\n\n## Features\n\n- **Automatic Token Management**: Handles token generation and caching automatically\n- **Dual Implementation**: Choose between WebAssembly or pure TypeScript implementations\n- **Built-in Caching**: Reduces API calls with intelligent caching mechanisms\n- **TypeScript Support**: Fully typed for better developer experience\n- **Cross-Platform**: Works in Node.js and modern browsers (CORS restrictions may apply)\n- **Pluggable Logging**: Inject your own logger for full control\n- **Easy to Use**: Simple, intuitive API\n\n---\n\n## Installation\n\n```bash\nnpm install nepse-api-helper\n```\n\nOr with yarn:\n\n```bash\nyarn add nepse-api-helper\n```\n\nOr with pnpm:\n\n```bash\npnpm install nepse-api-helper\n```\n\n## Quick Start (Minimal Example)\n\n```typescript\nimport { nepseClient } from \"nepse-api-helper\";\n\n// Initialize the client (required before any API calls)\nawait nepseClient.initialize();\n\nconst securities = await nepseClient.getSecurities();\nconsole.log(securities[0]);\n```\n\n## Quick Start (Advanced Example with Logger)\n\n```typescript\nimport { nepseClient } from \"nepse-api-helper\";\n\nconst logger = {\n  info: (msg, ...args) =\u003e console.log(\"INFO:\", msg, ...args),\n  warn: (msg, ...args) =\u003e console.warn(\"WARN:\", msg, ...args),\n  error: (msg, ...args) =\u003e console.error(\"ERROR:\", msg, ...args),\n};\n\nawait nepseClient.initialize({ logger });\n\nconst marketStatus = await nepseClient.getMarketStatus();\nlogger.info(`Market is ${marketStatus.isOpen ? \"open\" : \"closed\"}`);\n\nconst detail = await nepseClient.getSecurityDetail(\"NIFRA\");\nlogger.info(\"NIFRA detail:\", detail);\n```\n\n---\n\n\n## How it Works (Architecture)\n\n**Flow:**\n\n1. `initialize()` loads WASM or TypeScript fallback for NEPSE's token logic\n2. API calls use a short-lived token, auto-refreshed and cached\n3. All requests use custom headers (`Salter \u003ctoken\u003e`) and retry logic\n4. Security briefs and details are cached for performance\n5. All errors are thrown as `NepseError` with codes for easy handling\n6. Logging is pluggable: inject your own logger for full control\n\n**Diagram:**\n\n```\nUser code\n  |\n  v\nnepseClient.initialize() --+--\u003e WASM/TS loader\n                  |\nAPI call (getSecurities) --+--\u003e token logic --\u003e fetchWithRetry --\u003e caching --\u003e logger\n```\n\n---\n\n## Initialization Options\n\nThe library supports two initialization modes and pluggable logging:\n\n### 1. WebAssembly Mode (Default)\n\nUses the latest deobfuscation logic from NEPSE's WASM module. **Recommended for production use** to ensure compatibility with the latest NEPSE API.\n\n```typescript\nawait nepseClient.initialize(); // Uses WASM by default\n\n// Or explicitly:\nawait nepseClient.initialize({ useWasm: true });\n\n// With a custom logger:\nawait nepseClient.initialize({ useWasm: true, logger });\n```\n\n**Pros:**\n\n- Always up-to-date with latest NEPSE logic\n- Most reliable for production\n\n**Cons:**\n\n- Requires WebAssembly support in runtime\n- Slightly slower initialization\n\n### 2. Pure TypeScript Mode\n\nUses a hardcoded TypeScript implementation of the deobfuscation logic.\n\n```typescript\nawait nepseClient.initialize({ useWasm: false });\n```\n\n**Pros:**\n\n- Works in all JavaScript environments\n- Faster initialization\n- No external dependencies\n\n**Cons:**\n\n- May become outdated if NEPSE changes their logic\n- Requires manual updates\n\n\n---\n\n## API Reference \u0026 Types\n\n- [Full TypeScript types](./lib/types.ts)\n- [Error codes](./lib/errors.ts)\n- [Constants](./lib/constants.ts)\n\n---\n\n### Client Methods\n\n#### `initialize(options?)`\n\nInitializes the client. **Must be called before any other operations.**\n\n```typescript\nawait nepseClient.initialize({\n  useWasm: true, // Optional: Use WebAssembly (default: true)\n});\n```\n\n#### `getSecurities()`\n\nFetches all securities (both active and inactive).\n\n```typescript\nconst securities = await nepseClient.getSecurities();\n// Returns: SecurityBrief[]\n```\n\n#### `getSecurityDetail(symbol)`\n\nGets detailed information about a specific security.\n\n```typescript\nconst security = await nepseClient.getSecurityDetail(\"NIFRA\");\n// Returns: SecurityDetail\n```\n\n#### `getMarketStatus()`\n\nChecks if the market is currently open.\n\n```typescript\nconst status = await nepseClient.getMarketStatus();\n// Returns: MarketStatus\nconsole.log(status.isOpen); // true or false\n```\n\n#### `getToken()`\n\nRetrieves the current authentication token. Useful for making custom API calls.\n\n```typescript\nconst token = await nepseClient.getToken();\n// Returns: string (JWT token)\n```\n\n### Making Custom API Calls\n\nFor endpoints not covered by the library, you can use the token to make custom requests. Note: the library now exports an Axios instance (`nepseAxios`) and `createHeaders` accepts an optional token and options object.\n\n```typescript\nimport { nepseClient, createHeaders, nepseAxios, BASE_URL } from \"nepse-api-helper\";\n\n// Initialize and get token\nawait nepseClient.initialize();\nconst token = await nepseClient.getToken();\n\n// Make custom API call using Axios\nconst response = await nepseAxios.get(`${BASE_URL}/api/nots/securityDailyTradeStat/58`, {\n  headers: createHeaders(token)\n});\n\nconst data = response.data;\n```\n\n### Utility Functions\n\n#### `createHeaders(token?, options?)`\n\nCreates headers object for NEPSE API requests. `token` is optional. If you need to omit the Authorization header (e.g. when loading the WASM blob or requesting the prove object), pass `{ omitAuthorization: true }` as the second argument.\n\n```typescript\n// With Authorization\nconst headersWithAuth = createHeaders(token);\n\n// Without Authorization\nconst headersWithoutAuth = createHeaders(undefined, { omitAuthorization: true });\n```\n\nNote: when making POST/PUT requests use Axios' `data` option for request bodies (not `body`), and read results from `response.data`.\n\n## TypeScript Types\n\nThe library exports TypeScript types for better development experience:\n\n```typescript\nimport type {\n  SecurityBrief,\n  SecurityDetail,\n  MarketStatus,\n  NepseExports,\n} from \"nepse-api-helper\";\n```\n\n\n---\n\nThe library throws descriptive errors with error codes and supports pluggable logging:\n\n```typescript\ntry {\n  await nepseClient.getSecurities();\n} catch (error) {\n  if (error.code === \"NOT_INITIALIZED\") {\n    // Your logger will also receive this error\n    console.error(\"Client not initialized. Call initialize() first.\");\n  } else if (error.code === \"WASM_FETCH_ERROR\") {\n    console.error(\"Failed to load WASM module\");\n  } else {\n    console.error(\"Unknown error:\", error.message);\n  }\n}\n\n// To capture logs, provide a logger when initializing:\nawait nepseClient.initialize({ logger });\n```\n\n## Common Issues\n\n### SSL Certificate Error\n\nIf you encounter SSL certificate errors in Node.js:\n\n```bash\n# Linux/Mac\nexport NODE_TLS_REJECT_UNAUTHORIZED='0'\n\n# Windows (PowerShell)\n$env:NODE_TLS_REJECT_UNAUTHORIZED='0'\n\n# Windows (CMD)\nset NODE_TLS_REJECT_UNAUTHORIZED=0\n```\n\nOr in your code:\n\n```javascript\nprocess.env.NODE_TLS_REJECT_UNAUTHORIZED = \"0\";\n```\n\n\u003e **Warning**: Disabling SSL verification should only be done in development/testing environments.\n\n### WASM Not Supported\n\nIf your environment doesn't support WebAssembly:\n\n```typescript\n// Use pure TypeScript implementation\nawait nepseClient.initialize({ useWasm: false });\n```\n\n\n---\n\n### Check if Market is Open\n\n```typescript\nimport { nepseClient } from \"nepse-api-helper\";\n\nawait nepseClient.initialize();\n\nconst status = await nepseClient.getMarketStatus();\n\nif (status.isOpen) {\n  console.log(\"Market is open!\");\n} else {\n  console.log(\"Market is closed\");\n}\n```\n\n### Get Top Securities\n\n```typescript\nimport { nepseClient } from \"nepse-api-helper\";\n\nawait nepseClient.initialize();\n\nconst securities = await nepseClient.getSecurities();\nconst activeSecurities = securities.filter((s) =\u003e s.activeStatus === \"A\");\n\nconsole.log(`Found ${activeSecurities.length} active securities`);\n```\n\n### Fetch Security Details\n\n```typescript\nimport { nepseClient } from \"nepse-api-helper\";\n\nawait nepseClient.initialize({ logger });\n\nconst symbols = [\"NIFRA\", \"NICL\", \"NABIL\"];\n\nfor (const symbol of symbols) {\n  try {\n    const detail = await nepseClient.getSecurityDetail(symbol);\n    console.log(`${symbol}: ${detail.name}`);\n    console.log(`  LTP: ${detail.lastTradePrice}`);\n  } catch (error) {\n    console.error(`Failed to fetch ${symbol}:`, error.message);\n  }\n}\n```\n\n\n---\n\nRun the test suite:\n\n```bash\npnpm test\n```\n\n\n---\n\nContributions are welcome! This is my first npm package, so I appreciate:\n\n- Bug reports\n- Feature suggestions\n- Documentation improvements\n- Pull requests\n\nPlease feel free to open an issue or submit a PR.\n\n### Development Setup\n\n```bash\n# Clone the repository\ngit clone https://github.com/dahsameer/nepse-api-helper\n\n# Install dependencies\ncd nepse-api-helper\npnpm install\n\n# Run tests\npnpm test\n\n# Build\npnpm run build\n```\n\n\n---\n\nThe Unlicense\n\n\n---\n\nThis library is provided \"as is\" without warranty of any kind. It is created for educational purposes only. The author is not responsible for any misuse or any consequences of using this library. Always ensure you comply with NEPSE's terms of service and applicable regulations.\n\n\n---\n\n## FAQ / Troubleshooting\n\n**Q: Why do I get SSL errors?**\nA: NEPSE's API uses a certificate that may not be trusted by Node.js. See \"SSL Certificate Error\" above for how to disable verification in dev.\n\n**Q: How do I mock API calls for tests?**\nA: Use a custom logger and mock `fetch` or `getAccessToken` in your tests. See `test/unit.spec.ts` for examples.\n\n**Q: How do I use my own logger?**\nA: Pass `{ logger }` to `initialize`. See the advanced example above.\n\n**Q: How do I use the TypeScript fallback?**\nA: Pass `{ useWasm: false }` to `initialize`.\n\n**Q: How do I get the raw token for custom requests?**\nA: Use `await nepseClient.getToken()` and pass it to `createHeaders(token)`.\n\n**Q: How do I get the latest types?**\nA: Import from `nepse-api-helper` or see [lib/types.ts](./lib/types.ts).\n\n---\n\n## Customization \u0026 Extensibility\n\n- **Logger:** Inject any logger (console, winston, pino, etc.)\n- **Fetch:** Mock or override fetch for tests\n- **Caching:** Extend or replace cache logic in `lib/cache.ts`\n- **Error Handling:** Catch `NepseError` and use error codes for robust handling\n- **WASM/TS:** Use fallback logic for environments without WASM\n\n---\n\n**Working as of:** October 19, 2025\n\nSince this library depends on NEPSE's API structure, it may break if NEPSE makes significant changes to their API. Please report any issues on the [GitHub issues page](https://github.com/dahsameer/nepse-api-helper/issues).\n\n---\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdahsameer%2Fnepse-api-helper","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdahsameer%2Fnepse-api-helper","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdahsameer%2Fnepse-api-helper/lists"}