All files / services TradingEngine.js

0% Statements 0/89
0% Branches 0/15
0% Functions 0/16
0% Lines 0/89

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222                                                                                                                                                                                                                                                                                                                                                                                                                                                           
const { ethers } = require('ethers');
const logger = require('../utils/logger');
const redis = require('../config/redis');
const EventEmitter = require('events');
 
class TradingEngine extends EventEmitter {
  constructor() {
    super();
    this.providers = {};
    this.contracts = {};
    this.isRunning = false;
    this.strategies = new Map();
  }
 
  async initialize() {
    try {
      logger.info('Initializing Trading Engine...');
 
      // Setup blockchain providers
      await this.setupProviders();
      
      // Load smart contracts
      await this.loadContracts();
      
      // Initialize strategies
      await this.initializeStrategies();
      
      // Start monitoring
      this.startMonitoring();
      
      this.isRunning = true;
      logger.info('Trading Engine initialized successfully');
      
      this.emit('initialized');
    } catch (error) {
      logger.error('Failed to initialize Trading Engine:', error);
      throw error;
    }
  }
 
  async setupProviders() {
    const chains = {
      ethereum: process.env.ETHEREUM_RPC_URL,
      bsc: process.env.BSC_RPC_URL,
      polygon: process.env.POLYGON_RPC_URL,
      arbitrum: process.env.ARBITRUM_RPC_URL
    };
 
    for (const [chain, rpcUrl] of Object.entries(chains)) {
      if (rpcUrl) {
        this.providers[chain] = new ethers.providers.JsonRpcProvider(rpcUrl);
        logger.info(`Provider setup for ${chain}`);
      }
    }
  }
 
  async loadContracts() {
    // Load contract ABIs and addresses
    const TradingVaultABI = require('../contracts/TradingVault.json');
    const FlashArbitrageABI = require('../contracts/FlashArbitrage.json');
    const MEVBotABI = require('../contracts/MEVBot.json');
 
    const wallet = new ethers.Wallet(
      process.env.BOT_PRIVATE_KEY,
      this.providers.ethereum
    );
 
    this.contracts.tradingVault = new ethers.Contract(
      process.env.TRADING_VAULT_ADDRESS,
      TradingVaultABI,
      wallet
    );
 
    this.contracts.flashArbitrage = new ethers.Contract(
      process.env.FLASH_ARBITRAGE_ADDRESS,
      FlashArbitrageABI,
      wallet
    );
 
    this.contracts.mevBot = new ethers.Contract(
      process.env.MEV_BOT_ADDRESS,
      MEVBotABI,
      wallet
    );
 
    logger.info('Contracts loaded successfully');
  }
 
  async initializeStrategies() {
    const ArbitrageStrategy = require('../strategies/ArbitrageStrategy');
    const FlashLoanStrategy = require('../strategies/FlashLoanStrategy');
    const MEVStrategy = require('../strategies/MEVStrategy');
    const AutoTradingStrategy = require('../strategies/AutoTradingStrategy');
 
    this.strategies.set('arbitrage', new ArbitrageStrategy(this));
    this.strategies.set('flashloan', new FlashLoanStrategy(this));
    this.strategies.set('mev', new MEVStrategy(this));
    this.strategies.set('autotrading', new AutoTradingStrategy(this));
 
    logger.info(`Initialized ${this.strategies.size} trading strategies`);
  }
 
  startMonitoring() {
    // Monitor for arbitrage opportunities
    setInterval(() => {
      if (this.isRunning) {
        this.strategies.get('arbitrage')?.scan();
      }
    }, 5000); // Every 5 seconds
 
    // Monitor for flash loan opportunities
    setInterval(() => {
      if (this.isRunning) {
        this.strategies.get('flashloan')?.scan();
      }
    }, 10000); // Every 10 seconds
 
    // Monitor for MEV opportunities
    setInterval(() => {
      if (this.isRunning) {
        this.strategies.get('mev')?.scan();
      }
    }, 2000); // Every 2 seconds (faster for MEV)
 
    // Monitor auto-trading signals
    setInterval(() => {
      if (this.isRunning) {
        this.strategies.get('autotrading')?.analyze();
      }
    }, 60000); // Every minute
 
    logger.info('Started monitoring for trading opportunities');
  }
 
  async executeTrade(userId, strategyType, params) {
    try {
      const strategy = this.strategies.get(strategyType);
      if (!strategy) {
        throw new Error(`Strategy ${strategyType} not found`);
      }
 
      logger.info(`Executing ${strategyType} trade for user ${userId}`);
      
      const result = await strategy.execute(userId, params);
      
      // Store result in Redis for quick access
      await redis.set(
        `trade:${result.transactionHash}`,
        JSON.stringify(result),
        { EX: 3600 } // Expire after 1 hour
      );
 
      this.emit('tradeExecuted', { userId, strategyType, result });
      
      return result;
    } catch (error) {
      logger.error(`Failed to execute trade: ${error.message}`);
      throw error;
    }
  }
 
  async getPortfolioValue(userId) {
    try {
      // Get user's portfolio from contract
      const portfolio = await this.contracts.tradingVault.getPortfolio(userId);
      
      return {
        totalDeposited: ethers.utils.formatEther(portfolio.totalDeposited),
        currentValue: ethers.utils.formatEther(portfolio.currentValue),
        totalProfits: ethers.utils.formatEther(portfolio.totalProfits),
        totalFeesPaid: ethers.utils.formatEther(portfolio.totalFeesPaid)
      };
    } catch (error) {
      logger.error(`Failed to get portfolio value: ${error.message}`);
      throw error;
    }
  }
 
  async getGasPrice(chain = 'ethereum') {
    try {
      const provider = this.providers[chain];
      const gasPrice = await provider.getGasPrice();
      return ethers.utils.formatUnits(gasPrice, 'gwei');
    } catch (error) {
      logger.error(`Failed to get gas price: ${error.message}`);
      return null;
    }
  }
 
  async estimateProfit(strategyType, params) {
    try {
      const strategy = this.strategies.get(strategyType);
      if (!strategy) {
        throw new Error(`Strategy ${strategyType} not found`);
      }
 
      return await strategy.estimateProfit(params);
    } catch (error) {
      logger.error(`Failed to estimate profit: ${error.message}`);
      throw error;
    }
  }
 
  stop() {
    this.isRunning = false;
    logger.info('Trading Engine stopped');
    this.emit('stopped');
  }
 
  getStatus() {
    return {
      isRunning: this.isRunning,
      connectedChains: Object.keys(this.providers),
      activeStrategies: Array.from(this.strategies.keys()),
      contractsLoaded: Object.keys(this.contracts).length
    };
  }
}
 
module.exports = TradingEngine;