1.0.5 • Published 6 months ago

saksh-crypto-exchange v1.0.5

Weekly downloads
-
License
MIT
Repository
github
Last release
6 months ago

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('admin@example.com');

// 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('admin@example.com', 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('admin@example.com');

// 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('admin@example.com', 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.

1.0.5

6 months ago

1.0.4

6 months ago

1.0.3

6 months ago

1.0.2

6 months ago

1.0.1

6 months ago

1.0.0

6 months ago