Skip to content

jt-lab-com/jt-lib

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

170 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

JT Lib

JT Lib is a comprehensive TypeScript library for creating algorithmic trading strategies. It is the core component of the JT Trader platform, providing a powerful and intuitive API for market data access, technical indicators, order management, and strategy execution.

Part of JT Trader - This library is designed to work seamlessly with the JT Trader trading platform and is installed together with it.

πŸ“‹ Table of Contents

πŸš€ Key Features

  • Trading Operations - Buying, selling, placing orders with automatic contract conversion
  • Market Data - Real-time and historical market data access with candle buffering
  • Technical Indicators - Built-in collection of popular technical indicators (RSI, SMA, ATR, etc.)
  • Event System - Event-driven architecture with triggers for automated strategy execution
  • Order Management - Complete order lifecycle management with OrdersBasket
  • Strategy Framework - Robust BaseScript framework for strategy development
  • Reporting System - Comprehensive reporting with charts, tables, and real-time monitoring
  • Multi-Symbol Trading - Support for trading multiple symbols simultaneously
  • Error Handling - Comprehensive error handling and logging system
  • TypeScript Support - Full TypeScript support with type definitions

πŸ“‹ Requirements

  • Node.js v18.x
  • TypeScript 4.x+
  • JT Trader platform

πŸ›  Installation

JT Lib is installed together with the JT Trader platform. See installation instructions:

πŸš€ Quick Start

DCA (Dollar Cost Averaging) Strategy Example

Here's a complete DCA strategy example using JT Lib:

class Script extends BaseScript {
  static definedArgs = [
    { key: 'symbols', defaultValue: 'BTC/USDT:USDT' },
    { key: 'sizeUsd', defaultValue: 100 },
    { key: 'intervalHours', defaultValue: 168 }, // 1 week
  ];

  dcaBasket: OrdersBasket;
  sizeUsd = getArgNumber('sizeUsd', 100);
  intervalHours = getArgNumber('intervalHours', 168);

  async onInit() {
    // Create basket for trading
    this.dcaBasket = new OrdersBasket({
      symbol: this.symbols[0],
    });
    await this.dcaBasket.init();

    // Register purchase trigger
    globals.triggers.registerTimeHandler('dcaPurchase', this.buyDCA, this);
    
    // Start regular purchases
    globals.triggers.addTaskByTime({
      name: 'dcaPurchase',
      triggerTime: currentTime() + 60 * 1000, // In 1 minute
      interval: this.intervalHours * 60 * 60 * 1000, // Repeat every intervalHours hours
      canReStore: true,
    });
  }

  // Purchase function
  buyDCA = async () => {
    const amount = this.dcaBasket.getContractsAmount(this.sizeUsd);
    await this.dcaBasket.buyMarket(amount);
    log('DCA purchase executed', `amount: ${amount}, price: ${this.dcaBasket.close()}`);
  };
}

RSI Trading Strategy Example

class Script extends BaseScript {
  private rsi: RelativeStrengthIndex;
  private sma: SimpleMovingAverageIndicator;
  private basket: OrdersBasket;
  private isPositionOpened = false;

  async onInit() {
    // Create OrdersBasket for trading
    this.basket = new OrdersBasket({
      symbol: this.symbols[0],
    });
    await this.basket.init();

    // Create indicators
    this.rsi = await globals.indicators.rsi(this.symbols[0], '1h', 14);
    this.sma = await globals.indicators.sma(this.symbols[0], '1h', 20);
  }

  async onTick() {
    if (this.isPositionOpened) return;

    const currentPrice = this.basket.close();
    const rsiValue = this.rsi.getValue();
    const smaValue = this.sma.getValue();

    // Buy signal: RSI oversold + price above SMA
    if (rsiValue < 30 && currentPrice > smaValue) {
      const amount = this.basket.getContractsAmount(100);
      const stopLoss = currentPrice * 0.95; // 5% stop loss
      const takeProfit = currentPrice * 1.1; // 10% take profit
      
      await this.basket.buyMarket(amount, takeProfit, stopLoss);
      this.isPositionOpened = true;
      log('Strategy', 'Buy signal executed', { 
        rsiValue, smaValue, price: currentPrice, stopLoss, takeProfit 
      });
    }

    // Sell signal: RSI overbought + price below SMA
    if (rsiValue > 70 && currentPrice < smaValue) {
      const amount = this.basket.getContractsAmount(100);
      const stopLoss = currentPrice * 1.05; // 5% stop loss
      const takeProfit = currentPrice * 0.9; // 10% take profit
      
      await this.basket.sellMarket(amount, takeProfit, stopLoss);
      this.isPositionOpened = true;
      log('Strategy', 'Sell signal executed', { 
        rsiValue, smaValue, price: currentPrice, stopLoss, takeProfit 
      });
    }
  }

  async onOrderChange(order: Order) {
    if (order.status === 'closed' && order.reduceOnly) {
      // Only reset position flag when closing order is executed
      this.isPositionOpened = false;
      log('Strategy', 'Position closed', { orderId: order.id, side: order.side });
    }
  }
}

Multi-Currency Trading Bots

Multi-currency bot architecture:

// Main script - coordinator
class Script extends BaseScript {
  baskets: Record<string, OrdersBasket> = {};
  
  async onInit() {
    // Creates OrdersBasket for each symbol
    for (const symbol of this.symbols) {
      this.baskets[symbol] = new OrdersBasket({ symbol });
      await this.baskets[symbol].init();
    }
  }
}

// Each OrdersBasket manages its own strategy
class GridBasket extends OrdersBasket {
  // Trading logic for specific symbol
  async onTick() { /* strategy */ }
  async onOrderChange() { /* order handling */ }
}

Principle: Script creates OrdersBasket for each symbol β†’ each basket works independently β†’ centralized management through Script.

πŸ“– Details: Script Development Best Practices

πŸ“š Core Architecture

BaseScript - Strategy Framework

  • Lifecycle Management - onInit(), onTick(), onOrderChange(), onStop()
  • Parameter System - static definedArgs for strategy configuration
  • Global Services - Automatic initialization of all JT Lib services
  • Multi-Symbol Support - Trade multiple symbols simultaneously

OrdersBasket - Trading Operations

  • Order Management - Market, limit, stop-loss, take-profit orders
  • Contract Conversion - Automatic USD to contracts conversion
  • Position Management - Long/short position tracking
  • Hedge Mode - Support for bidirectional trading
  • Trigger Orders - Local and exchange-based stop orders

Event System & Triggers

  • EventEmitter - Reactive programming with typed events
  • Time Triggers - Scheduled task execution
  • Price Triggers - Action execution on price levels
  • Order Triggers - Action execution on order status changes
  • Automatic Restoration - Triggers persist after strategy restart

Market Data & Indicators

  • CandlesBuffer - Efficient historical data management
  • Technical Indicators - RSI, SMA, ATR, and more
  • Real-time Data - Live price feeds and order book
  • Multi-timeframe - Support for different timeframes

Reporting System

  • Widgets - Cards, tables, charts, text blocks
  • Real-time Updates - Live strategy monitoring
  • Data Export - Results in various formats
  • Interactive Controls - Action buttons for strategy management

πŸ“– Documentation

Main Documentation

JT Lib Specific Documentation

Quick Links

πŸ”§ Configuration

JT Lib configuration is handled through JT Trader platform. No separate configuration is required.

Strategy Parameters:

class Script extends BaseScript {
  static definedArgs = [
    { key: 'symbols', defaultValue: 'BTC/USDT:USDT' },
    { key: 'sizeUsd', defaultValue: 100 },
    { key: 'leverage', defaultValue: 1 },
    { key: 'hedgeMode', defaultValue: false },
  ];

  async onInit() {
    // Parameters are automatically available through getArg* functions
    const symbols = getArgString('symbols');
    const sizeUsd = getArgNumber('sizeUsd', 100);
    const leverage = getArgNumber('leverage', 1);
    const hedgeMode = getArgBoolean('hedgeMode', false);
  }
}

πŸ§ͺ Testing

JT Lib strategies can be tested using the JT Trader tester:

  1. Create New Scenario in JT Trader
  2. Select Strategy and configure parameters
  3. Set Test Period and initial balance
  4. Run Test and analyze results
  5. View Report with detailed statistics

πŸ“„ License

  • 🟒 Free for personal, educational, and open-source use (AGPLv3)

🀝 Support

πŸ”— Related Projects

πŸ“ˆ Examples

Available example strategies in the codebase:

  • GridBot Example - Multi-coin grid trading strategy with automatic position management and profit taking
  • RSI Bot Example - RSI momentum strategy that buys when oversold (<30) and sells when overbought (>70)
  • Gainers-Losers Example - Market scanner that finds symbols with significant daily price movements (β‰₯30%)
  • Indicators Example - Technical indicators demonstration with SMA and ATR on real-time charts
  • Trading API Example - Interactive trading interface with callback buttons for all exchange operations

All examples are ready to run and demonstrate different aspects of JT Lib functionality.

πŸ—οΈ Architecture Overview

JT Lib follows a modular architecture with clear separation of concerns:

  • BaseScript - Strategy coordination and lifecycle management
  • OrdersBasket - Trading operations for individual symbols
  • Event System - Reactive programming with typed events
  • Trigger System - Automated task execution
  • Reporting System - Real-time monitoring and analytics
  • Storage System - Persistent state management

JT Lab - Professional tools for algorithmic trading

About

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors