npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

saksh-crypto-exchange

v1.0.5

Published

A package for processing crypto exchange orders

Downloads

13

Readme

Saksh Crypto Exchange

A Node.js package designed for processing cryptocurrency exchange orders, including market, limit, and stop orders.

Installation

To install the saksh-crypto-exchange package, use npm:

npm install saksh-crypto-exchange

Usage

Here's a practical example of how to utilize the saksh-crypto-exchange package to process various types of orders.



const SakshWallet = require('saksh-easy-wallet');
const SakshCryptoExchange = require('./lib/SakshCryptoExchange.js');
const mongoose = require('mongoose');

// Initialize the wallet and set the admin
const wallet = new SakshWallet();
wallet.setAdmin('[email protected]');

// Custom fee debit logic
const customFeeDebit = async (wallet, amount, currency) => {
    // Custom fee debit logic
    const feePercentage = 0.01; // 1% fee
    const fee = amount * feePercentage;
    const netAmount = amount - fee;
    console.log(`Debiting fee: ${fee} ${currency}`);
    await wallet.sakshCredit('[email protected]', fee, currency, 'ref123', 'Admin Fee');
    return { netAmount, fee };
};

// Custom get current price logic
const getCurrentPrice = async (baseCurrency, quoteCurrency) => {
    // Implement the logic to get the current price
    // For example, you can fetch the price from an external API
    return 50000; // Example price
};

// Initialize the order processing system with custom fee debit logic and get current price logic
let sakshCryptoExchange;

// Function to fetch and process the most recent 5 pending orders
async function processRecentPendingOrders() {
    try {
        const pendingOrders = await sakshCryptoExchange.getPendingOrders(5);
        for (const order of pendingOrders) {
            await sakshCryptoExchange.processOrder(order);
        }

        console.log('Most recent 5 pending orders processed');
    } catch (error) {
        console.error('Error processing pending orders:', error);
    }
}

// Connect to MongoDB, then start processing orders
async function initialize() {
    // Connect to MongoDB
    try {
        await mongoose.connect('mongodb://localhost:27017/saksh2323Cart', {
            useNewUrlParser: true,
            useUnifiedTopology: true,
        });
        console.log('Database connected');

        // Initialize the order processing system with custom fee debit logic and get current price logic
        sakshCryptoExchange = new SakshCryptoExchange(wallet, customFeeDebit, getCurrentPrice);
        console.log('Order processing initialized');

        // Example usage
        await wallet.sakshCredit('user123', 500, 'USD', 'ref123', 'Salary payment'); // Credited 500 USD. New balance is 500

        console.log(wallet.adminEmail);
        await sakshCryptoExchange.placeMarketOrder('user123', 'BTC', 'USD', 1);
        await sakshCryptoExchange.placeMarketOrder('user124', 'BTC', 'USD', 2);
        await sakshCryptoExchange.placeMarketOrder('user125', 'BTC', 'USD', 1.5);

        const orderHistory = await sakshCryptoExchange.getOrderHistory('user123');
        console.log('Order History for user123:', orderHistory);

        // Process the most recent 5 pending orders
        await processRecentPendingOrders();

        // Close the MongoDB connection
        await mongoose.connection.close();
    } catch (error) {
        console.error('Error connecting to MongoDB:', error);
    }
}

// Run the initialization
initialize();

Here is an example of the package using express js



const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const SakshWallet = require('saksh-easy-wallet');
const SakshCryptoExchange = require('./lib/SakshCryptoExchange.js');

const app = express();
const port = 3000;

// Middleware
app.use(bodyParser.json());

// Initialize the wallet and set the admin
const wallet = new SakshWallet();
wallet.setAdmin('[email protected]');

// Custom fee debit logic
const customFeeDebit = async (wallet, amount, currency) => {
    // Custom fee debit logic
    const feePercentage = 0.01; // 1% fee
    const fee = amount * feePercentage;
    const netAmount = amount - fee;
    console.log(`Debiting fee: ${fee} ${currency}`);
    await wallet.sakshCredit('[email protected]', fee, currency, 'ref123', 'Admin Fee');
    return { netAmount, fee };
};

// Custom get current price logic
const getCurrentPrice = async (baseCurrency, quoteCurrency) => {
    // Implement the logic to get the current price
    // For example, you can fetch the price from an external API
    return 50000; // Example price
};

// Initialize the order processing system with custom fee debit logic and get current price logic
let sakshCryptoExchange;

// Function to fetch and process the most recent 5 pending orders
async function processRecentPendingOrders() {
    try {
        const pendingOrders = await sakshCryptoExchange.getPendingOrders(5);
        for (const order of pendingOrders) {
            await sakshCryptoExchange.processOrder(order);
        }

        console.log('Most recent 5 pending orders processed');
    } catch (error) {
        console.error('Error processing pending orders:', error);
    }
}

// Connect to MongoDB, then start processing orders
async function initialize() {
    // Connect to MongoDB
    try {
        await mongoose.connect('mongodb://localhost:27017/saksh2323Cart', {
            useNewUrlParser: true,
            useUnifiedTopology: true,
        });
        console.log('Database connected');

        // Initialize the order processing system with custom fee debit logic and get current price logic
        sakshCryptoExchange = new SakshCryptoExchange(wallet, customFeeDebit, getCurrentPrice);
        console.log('Order processing initialized');
    } catch (error) {
        console.error('Error connecting to MongoDB:', error);
    }
}

// Run the initialization
initialize();

// Route to place a market order
app.post('/place-market-order', async (req, res) => {
    const { userId, baseCurrency, quoteCurrency, amount } = req.body;

    if (!userId || !baseCurrency || !quoteCurrency || !amount) {
        return res.status(400).send('Invalid request');
    }

    try {
        await sakshCryptoExchange.placeMarketOrder(userId, baseCurrency, quoteCurrency, amount);
        res.status(200).json({ message: 'Market order placed and processed' });
    } catch (error) {
        res.status(500).json({ error: `Error placing market order: ${error.message}` });
    }
});

// Route to get order history for a specific user
app.get('/order-history/:userId', async (req, res) => {
    const { userId } = req.params;

    try {
        const orderHistory = await sakshCryptoExchange.getOrderHistory(userId);
        res.status(200).json(orderHistory);
    } catch (error) {
        res.status(500).json({ error: `Error fetching order history: ${error.message}` });
    }
});

// Route to process the most recent 5 pending orders
app.post('/process-pending-orders', async (req, res) => {
    try {
        await processRecentPendingOrders();
        res.status(200).json({ message: 'Most recent 5 pending orders processed' });
    } catch (error) {
        res.status(500).json({ error: `Error processing pending orders: ${error.message}` });
    }
});

// Start the server
app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});

Flow Chart

Market Order Processing Flowchart

Textual Representation

  1. Start
  2. Initialize Wallet and Order Queue
  3. Place Market Order
    • Input: userId, baseCurrency, quoteCurrency, amount
  4. Add Market Order to Queue
  5. Process Market Order
    • Retrieve order from queue
  6. Sort Opposite Order Book
    • Sort by price (ascending for buy, descending for sell)
  7. Match Orders
    • While remainingAmount > 0 and oppositeOrderBook is not empty:
      • Find best match
      • If remainingAmount >= bestMatch.amount:
        • Execute full match
        • Update remainingAmount
      • Else:
        • Execute partial match
        • Update bestMatch.amount
        • Set remainingAmount to 0
  8. Calculate Fee (if feeDebitCallback is provided)
    • Call feeDebitCallback
    • Update netAmount and fee
  9. Debit User Wallet
    • Debit totalPrice from user's wallet
  10. Update Order History
    • Add transaction details to order history
  11. Update Order Status
    • Update order status to 'completed'
  12. End

Flowchart Diagram

+-------------------------------+
|           Start               |
+-------------------------------+
              |
              v
+-------------------------------+
| Initialize Wallet and Order   |
| Queue                         |
+-------------------------------+
              |
              v
+-------------------------------+
| Place Market Order            |
| Input: userId, baseCurrency,  |
| quoteCurrency, amount         |
+-------------------------------+
              |
              v
+-------------------------------+
| Add Market Order to Queue     |
+-------------------------------+
              |
              v
+-------------------------------+
| Process Market Order          |
| Retrieve order from queue     |
+-------------------------------+
              |
              v
+-------------------------------+
| Sort Opposite Order Book      |
| Sort by price (asc for buy,   |
| desc for sell)                |
+-------------------------------+
              |
              v
+-------------------------------+
| Match Orders                  |
| While remainingAmount > 0 and |
| oppositeOrderBook is not empty|
|   Find best match             |
|   If remainingAmount >=       |
|   bestMatch.amount            |
|     Execute full match        |
|     Update remainingAmount    |
|   Else                        |
|     Execute partial match     |
|     Update bestMatch.amount   |
|     Set remainingAmount to 0  |
+-------------------------------+
              |
              v
+-------------------------------+
| Calculate Fee (if             |
| feeDebitCallback is provided) |
| Call feeDebitCallback         |
| Update netAmount and fee      |
+-------------------------------+
              |
              v
+-------------------------------+
| Debit User Wallet             |
| Debit totalPrice from user's  |
| wallet                        |
+-------------------------------+
              |
              v
+-------------------------------+
| Update Order History          |
| Add transaction details to    |
| order history                 |
+-------------------------------+
              |
              v
+-------------------------------+
| Update Order Status           |
| Update order status to        |
| 'completed'                   |
+-------------------------------+
              |
              v
+-------------------------------+
|             End               |
+-------------------------------+

Limit order

Limit Order Processing Flowchart

Textual Representation

  1. Start
  2. Initialize Wallet and Order Queue
  3. Place Limit Order
    • Input: userId, baseCurrency, quoteCurrency, amount, price
  4. Add Limit Order to Queue
  5. Process Limit Order
    • Retrieve order from queue
  6. Add Order to Order Book
    • If orderType is 'buy':
      • Add to buy order book
      • Sort buy order book by price (ascending)
    • Else:
      • Add to sell order book
      • Sort sell order book by price (descending)
  7. Update Order Book
    • Log order added to order book
  8. End

Flowchart Diagram

+-------------------------------+
|           Start               |
+-------------------------------+
              |
              v
+-------------------------------+
| Initialize Wallet and Order   |
| Queue                         |
+-------------------------------+
              |
              v
+-------------------------------+
| Place Limit Order             |
| Input: userId, baseCurrency,  |
| quoteCurrency, amount, price  |
+-------------------------------+
              |
              v
+-------------------------------+
| Add Limit Order to Queue      |
+-------------------------------+
              |
              v
+-------------------------------+
| Process Limit Order           |
| Retrieve order from queue     |
+-------------------------------+
              |
              v
+-------------------------------+
| Add Order to Order Book       |
| If orderType is 'buy'         |
|   Add to buy order book       |
|   Sort buy order book by      |
|   price (ascending)           |
| Else                          |
|   Add to sell order book      |
|   Sort sell order book by     |
|   price (descending)          |
+-------------------------------+
              |
              v
+-------------------------------+
| Update Order Book             |
| Log order added to order book |
+-------------------------------+
              |
              v
+-------------------------------+
|             End               |
+-------------------------------+

Stop Order Processing Flowchart

Textual Representation

  1. Start
  2. Initialize Wallet and Order Queue
  3. Place Stop Order
    • Input: userId, baseCurrency, quoteCurrency, amount, stopPrice
  4. Add Stop Order to Queue
  5. Process Stop Order
    • Retrieve order from queue
  6. Add Order to Order Book
    • If orderType is 'buy':
      • Add to buy order book
      • Sort buy order book by stop price (ascending)
    • Else:
      • Add to sell order book
      • Sort sell order book by stop price (descending)
  7. Update Order Book
    • Log order added to order book
  8. End

Flowchart Diagram

+-------------------------------+
|           Start               |
+-------------------------------+
              |
              v
+-------------------------------+
| Initialize Wallet and Order   |
| Queue                         |
+-------------------------------+
              |
              v
+-------------------------------+
| Place Stop Order              |
| Input: userId, baseCurrency,  |
| quoteCurrency, amount,        |
| stopPrice                     |
+-------------------------------+
              |
              v
+-------------------------------+
| Add Stop Order to Queue       |
+-------------------------------+
              |
              v
+-------------------------------+
| Process Stop Order            |
| Retrieve order from queue     |
+-------------------------------+
              |
              v
+-------------------------------+
| Add Order to Order Book       |
| If orderType is 'buy'         |
|   Add to buy order book       |
|   Sort buy order book by      |
|   stop price (ascending)      |
| Else                          |
|   Add to sell order book      |
|   Sort sell order book by     |
|   stop price (descending)     |
+-------------------------------+
              |
              v
+-------------------------------+
| Update Order Book             |
| Log order added to order book |
+-------------------------------+
              |
              v
+-------------------------------+
|             End               |
+-------------------------------+

API

OrderProcessing

Constructor

new OrderProcessing(wallet, orderQueue)
  • wallet: An instance of SakshWallet.
  • orderQueue: An instance of Queue from the Bull library.

Methods

  • processOrder(job): Processes an order job from the queue.
  • processMarketOrder(orderType, amount, userId, baseCurrency, quoteCurrency, orderId): Processes a market order.
  • processLimitOrder(orderType, amount, userId, baseCurrency, quoteCurrency, price, orderId): Processes a limit order.
  • processStopOrder(orderType, amount, userId, baseCurrency, quoteCurrency, stopPrice, orderId): Processes a stop order.

Contributing

Contributions are welcome! If you have suggestions or improvements, please open an issue or submit a pull request on GitHub.

License

This project is licensed under the ISC License.