Skip to content

KasarLabs/grid-bot-extended

Repository files navigation

Grid Bot Extended

A Perpetual Futures Trading Bot for X10 Exchange (Extended) - Showcase for ask-starknet

⚠️ CRITICAL WARNINGS ⚠️

🚨 USE AT YOUR OWN RISK 🚨

This software is provided as-is, without any guarantees or warranty. By using this software, you accept all risks associated with automated trading.

  • NO PROFIT GUARANTEE: This bot does NOT guarantee profits. You can and likely will lose money.
  • EDUCATIONAL PURPOSE: This is a showcase/demonstration project, not production-ready trading software.
  • NOT A REAL GRID BOT: This is NOT a traditional grid bot because perpetual futures platforms like Extended don't allow you to own actual tokens - you only have positions. This is better described as a perpetual futures trading bot with grid-like behavior.
  • HIGH RISK: Trading perpetual futures with leverage involves substantial risk of loss.
  • NO FINANCIAL ADVICE: This software does not provide financial advice. Do your own research.
  • TEST FIRST: Always test with small amounts you can afford to lose.

⚠️ Important Limitations

  • Works with perpetual positions, not spot trading
  • You don't own the underlying assets
  • Leverage amplifies both gains and losses
  • Market volatility can lead to rapid losses
  • The bot may not perform as expected in all market conditions

πŸ“– About

Grid Bot Extended is a perpetual futures trading bot built for the X10 Exchange (Extended) on Starknet. It implements a grid-like trading strategy on perpetual futures markets.

This project is a showcase of what can be built using ask-starknet, an AI-powered toolkit for Starknet development.

What is a "Grid Bot" on Perpetuals?

Traditional grid bots work by:

  1. Buying assets at lower prices
  2. Selling assets at higher prices
  3. Profiting from market oscillations

However, on perpetual futures platforms like Extended:

  • You don't own actual tokens
  • You only hold leveraged positions (long/short)
  • The bot creates a grid of orders to open/close positions

How It Works

The bot creates a neutral grid strategy designed to profit from small market variations:

  1. Grid Setup: Divides a price range into multiple levels (grid)
  2. Order Placement: Places buy and sell orders at each grid level
  3. Position Management: Opens long positions when price falls, short positions when price rises
  4. Profit Target: Aims to capture small profits from price oscillations within the grid

Strategy Modes:

  • Neutral: Mixed long/short positions to profit from volatility in both directions
  • Long: Bias towards long positions (bullish)
  • Short: Bias towards short positions (bearish)

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    Grid Bot Extended                     β”‚
β”‚                                                          β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚  β”‚   API      │─────▢│  Grid Bot    │─────▢│ X10     β”‚ β”‚
β”‚  β”‚  Server    β”‚      β”‚   Manager    β”‚      β”‚Exchange β”‚ β”‚
β”‚  β”‚  (Express) β”‚      β”‚              β”‚      β”‚  API    β”‚ β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚        β”‚                     β”‚                          β”‚
β”‚        β”‚              β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”                  β”‚
β”‚        β”‚              β”‚ Starknet    β”‚                  β”‚
β”‚        β”‚              β”‚ Integration β”‚                  β”‚
β”‚        β”‚              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                  β”‚
β”‚        β”‚                                                β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                 β”‚
β”‚  β”‚Auth &      β”‚      β”‚  AI Provider β”‚                 β”‚
β”‚  β”‚Rate Limit  β”‚      β”‚  (Optional)  β”‚                 β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸš€ Getting Started

Prerequisites

  • Node.js 18+
  • npm or pnpm
  • X10 Exchange account with API access
  • Starknet wallet with private key
  • API secret for server authentication

Installation

  1. Clone the repository

    git clone https://github.com/KasarLabs/grid-bot-extended.git
    cd grid-bot-extended
  2. Install dependencies

    npm install
    # or
    pnpm install
  3. Configure environment variables

    cp .env.example .env
  4. Edit .env file with your configuration:

    # Required
    PORT=5050
    API_SECRET=your_secure_random_secret_here
    EXTENDED_API_URL=https://api.x10.exchange
    EXTENDED_API_KEY=your_x10_api_key
    EXTENDED_PRIVATE_KEY=your_starknet_private_key
    STARKNET_RPC_URL=https://starknet-mainnet.public.blastapi.io
    
    # Optional
    NODE_ENV=development
    CORS_ORIGIN=*

    Security Tip: Generate a strong API_SECRET using:

    openssl rand -hex 32
  5. Build the project

    npm run build
  6. Start the server

    npm start

    The server will start on http://localhost:5050


πŸ“‘ API Documentation

Authentication

All /api/* endpoints require authentication using the X-API-Secret header:

X-API-Secret: your_api_secret_from_env

Rate Limiting:

  • General endpoints: 100 requests per 15 minutes
  • Authentication attempts: 5 failed attempts per 15 minutes (brute force protection)
  • Trade history: 20 requests per minute

Endpoints

1. Health Check

No authentication required

GET /health

Response:

{
  "success": true,
  "message": "Service is healthy",
  "data": {
    "status": "ok",
    "uptime": 123.456,
    "timestamp": "2025-11-17T12:00:00.000Z"
  }
}

2. Start Grid Bot

Requires authentication

POST /api/start-grid-bot
Content-Type: application/json
X-API-Secret: your_api_secret

Request Body:

{
  "gridBotTokens": [
    {
      "symbol": "EUR-USD",
      "priceRange": {
        "upperPrice": 1.163,
        "lowerPrice": 1.161
      },
      "gridSpacing": {
        "levelsMax": 4
      },
      "investment": 1.5,
      "leverage": 10,
      "strategy": "neutral"
    }
  ]
}

Configuration Fields:

Field Type Required Description
symbol string βœ… Trading pair (e.g., "EUR-USD", "BTC-USD", "ETH-USD")
priceRange.upperPrice number βœ… Upper bound of the grid (must be > lowerPrice)
priceRange.lowerPrice number βœ… Lower bound of the grid (must be > 0)
gridSpacing.levelsMax number βœ… Number of grid levels (1-1000)
investment number βœ… Investment amount per grid level in USD
leverage number βœ… Leverage multiplier (e.g., 10 = 10x leverage)
strategy string βœ… Trading strategy: "neutral"

Strategy Types:

  • neutral: Balanced approach - profits from price oscillations in both directions
  • long: Bullish bias - more long positions, expects price to rise overall (not implemented for now)
  • short: Bearish bias - more short positions, expects price to fall overall (not implemented for now)

Response (Success):

{
  "success": true,
  "message": "Grid bot manager started successfully with 1 bot(s)"
}

Response (Error):

{
  "success": false,
  "message": "Invalid grid bot configuration",
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Upper price must be greater than lower price",
    "details": {}
  }
}

3. Stop Grid Bot

Requires authentication

POST /api/stop-grid-bot
Content-Type: application/json
X-API-Secret: your_api_secret

Request Body:

{}

Response:

{
  "success": true,
  "message": "Grid bot stopped successfully"
}

4. Get Trade History

Requires authentication

GET /api/trade-history
X-API-Secret: your_api_secret

Response:

{
  "success": true,
  "message": "Trade history retrieved successfully",
  "data": {
    "trades": [],
    "totalTrades": 0,
    "totalProfit": 0
  }
}

Notes:

  • Results are cached for 60 seconds for performance
  • Rate limited to 20 requests per minute

πŸ§ͺ Testing with Postman

A Postman collection is included: postman_collection.json

Import Steps:

  1. Open Postman
  2. Click Import
  3. Select postman_collection.json
  4. Update the API_SECRET variable to match your .env file

Collection Variables:

  • BASE_URL: http://localhost:5050
  • API_SECRET: Your API secret from .env

πŸ“Š Example Use Cases

Example 1: Single Token Grid Bot (EUR-USD)

{
  "gridBotTokens": [
    {
      "symbol": "EUR-USD",
      "priceRange": {
        "upperPrice": 1.163,
        "lowerPrice": 1.161
      },
      "gridSpacing": {
        "levelsMax": 4
      },
      "investment": 1.5,
      "leverage": 10,
      "strategy": "neutral"
    }
  ]
}

What this does:

  • Creates 4 grid levels between $1.161 and $1.163
  • Invests $1.50 per level with 10x leverage
  • Uses neutral strategy for balanced trading

Example 2: Multiple Token Grid Bots

{
  "gridBotTokens": [
    {
      "symbol": "BTC-USD",
      "priceRange": {
        "upperPrice": 50000,
        "lowerPrice": 45000
      },
      "gridSpacing": {
        "levelsMax": 10
      },
      "investment": 100,
      "leverage": 5,
      "strategy": "long"
    },
    {
      "symbol": "ETH-USD",
      "priceRange": {
        "upperPrice": 3000,
        "lowerPrice": 2500
      },
      "gridSpacing": {
        "levelsMax": 8
      },
      "investment": 50,
      "leverage": 3,
      "strategy": "neutral"
    }
  ]
}

What this does:

  • Runs 2 bots simultaneously
  • BTC bot: 10 levels, $100/level, 5x leverage, long bias
  • ETH bot: 8 levels, $50/level, 3x leverage, neutral

πŸ”’ Security Features

  • API Authentication: Required for all trading endpoints
  • Rate Limiting: Prevents brute force and DDoS attacks
  • Brute Force Protection: Progressive lockout after failed auth attempts
  • CORS: Configurable origin restrictions
  • Helmet: Security headers enabled
  • Input Validation: Zod schema validation for all requests

πŸ› οΈ Development

Project Structure

grid-bot-extended/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ config/          # Configuration loaders
β”‚   β”œβ”€β”€ manager/         # Grid bot manager logic
β”‚   β”œβ”€β”€ middleware/      # Auth & rate limiting
β”‚   β”œβ”€β”€ server/          # Express server
β”‚   β”œβ”€β”€ types/           # TypeScript types
β”‚   └── index.ts         # Entry point
β”œβ”€β”€ postman_collection.json
β”œβ”€β”€ .env.example
β”œβ”€β”€ package.json
└── README.md

Available Scripts

npm run build       # Build TypeScript to JavaScript
npm start           # Start production server
npm run dev         # Development mode with watch
npm run format      # Format code with Prettier

🀝 Contributing

This is a showcase project. Contributions are welcome but please understand:

  • This is NOT production-ready
  • Use at your own risk
  • No warranty or guarantees

πŸ“œ License

ISC


πŸ”— Links


βš–οΈ Disclaimer

THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

THE AUTHORS AND KASAR LABS ARE NOT RESPONSIBLE FOR ANY LOSSES, DAMAGES, OR OTHER LIABILITIES THAT MAY RESULT FROM USING THIS SOFTWARE.

TRADING CRYPTOCURRENCIES AND PERPETUAL FUTURES INVOLVES SIGNIFICANT RISK. ONLY TRADE WITH MONEY YOU CAN AFFORD TO LOSE.


Made with ❀️ by KasarLabs

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors