# Trading Bots

## Overview

The Risk Protocol Trading Bot is an autonomous arbitrage system that continuously monitors and executes profitable opportunities across Risk Protocol's token ecosystem. The bot operates 24/7, executing complex multi-step transactions involving flashloans, token swaps, and redemptions to capture price inefficiencies between Risk Protocol's 1:1 deposit/redemption mechanism and market prices on decentralized exchanges, including our own.

Key Characteristics of the trading bot:

* **Autonomous Operation**: Runs continuously with configurable check intervals
* **Multi-Strategy**: Implements 6 distinct arbitrage routes
* **Capital Efficient**: Utilizes flashloans to execute arbitrage without upfront capital
* **Performance Optimized**: Sub-2-second cycle times with batched RPC calls and cached data
* **Production Hardened**: Includes retry logic, monitoring, resource management, and failsafes

We plan to open-source it soon. Users may fork the trading bot from our GitHub once we open-source it.

## System Architecture

High-Level Components

```
┌─────────────────────────────────────────────────────────────┐
│                      Trading Bot (Node.js)                  │
│  ┌─────────────┐  ┌──────────────┐  ┌──────────────────┐    │
│  │   Bot.ts    │─▶│ Helper.ts    │─▶│ Strategies.sol   │    │
│  │ (Orchestr.) │  │ (Route Logic)│  │ (Smart Contract) │    │
│  └─────────────┘  └──────────────┘  └──────────────────┘    │
│         │                │                     │            │
│         ▼                ▼                     ▼            │
│  ┌──────────────────────────────────────────────────┐       │
│  │          Shared Data Layer (Cached)              │       │
│  │  • Prices  • Flashloan Data  • Pool State        │       │
│  └──────────────────────────────────────────────────┘       │
└─────────────────────────────────────────────────────────────┘
                          │
        ┌─────────────────┼─────────────────┐
        ▼                 ▼                 ▼
  ┌───────────┐    ┌────────────┐    ┌──────────┐
  │  Ethereum │    │   Price    │    │ BetterSt.│
  │    RPC    │    │    API     │    │  Logging │
  └───────────┘    └────────────┘    └──────────┘
```

## Arbitrage Strategies

The bot implements 6 distinct arbitrage routes or strategies, each exploiting different market inefficiencies. The six trading bot strategies are listed below:

### Route 1: MONZA (Nested Flashloan Arbitrage)

**Strategy**: Exploit price discrepancy when `market(rON) + market(rOFF) < underlying`

**Execution Flow:**

1. Flashloan rON from Wrapper X
2. Nested flashloan rOFF from Wrapper Y
3. Redeem both tokens for the underlying (1:1 ratio)
4. Swap underlying on TRP DEX for rOFF to repay Wrapper Y
5. Swap underlying for rON to repay Wrapper X
6. Retain profit in underlying tokens

**Use Case**: When the aggregate market price of both SMART Tokens trades at a discount to the value of the underlying upon redemption.

***

### Route 2: SUZUKA (Single Token Arbitrage)

**Strategy**: Borrow unwanted token, swap for wanted token

**Execution Flow:**

1. Flashloan unwanted token from wrapper
2. Swap on Balancer for the wanted token
3. Repay the flashloan with the wanted token
4. Profit from price spread

**Use Case**: When the discount on the unwanted token in one of the wrappers is large enough to constitute a profitable arbitrage.

***

### Route 3: MUGELLO (Unwanted Token Disposal)

**Strategy**: Nested flashloans with unwanted token disposal and underlying redemption

**Execution Flow:**

1. Flashloan rON from Wrapper X
2. Nested flashloan rOFF from Wrapper Y
3. Redeem equal amounts for the underlying
4. Use underlying to acquire rOFF on Balancer
5. Repay Wrapper Y with rOFF
6. Repay Wrapper X with the remaining rON
7. Retain profit

**Use Case**: Complex market conditions with asymmetric liquidity

***

### Route 4: SPA (Premium Flashloan Strategy)

**Strategy**: Similar to Route 1 but with a premium payment structure

**Execution Flow:**

1. Flashloan both rON and rOFF from wrappers with premiums
2. Redeem for underlying (1:1)
3. Execute Balancer swaps to acquire repayment tokens
4. Repay both flashloans with premiums
5. Retain profit after covering premium costs

**Use Case**: When the arbitrage opportunity exceeds the flashloan premium costs

***

### Route 5: ASSEN (Aave Deposit-and-Swap)

**Strategy**: Arbitrage TRP 1:1 deposit rate vs Balancer market rates

**Execution Flow:**

1. Flashloan underlying from Aave V3 (0.09% premium)
2. Deposit underlying to Risk Protocol → receive rON + rOFF (1:1 ratio)
3. Swap rON to the underlying on Balancer
4. Swap rOFF to the underlying on Balancer
5. Repay Aave flashloan with premium
6. Retain profit from swap rates exceeding deposit cost

**Use Case**: When the market is buying risk tokens below 1:1 underlying value

***

### Route 6: PHILLIP ISLAND (Aave Buy-and-Redeem)

**Strategy**: Arbitrage Balancer market rates vs TRP 1:1 redemption rate

**Execution Flow:**

1. Flashloan underlying from Aave V3 (0.09% premium)
2. Calculate optimal spending for equal rON and rOFF quantities
3. Buy rON from Balancer using the calculated amount
4. Buy rOFF from Balancer using the calculated amount
5. Redeem equal amounts of rON + rOFF for underlying (1:1)
6. Repay Aave flashloan with premium
7. Retain profit from the redemption value exceeding the purchase cost

**Use Case**: When the market is selling risk tokens above 1:1 underlying value

***

#### Bot Runtime

| Property               | Value           |
| ---------------------- | --------------- |
| **Runtime**            | Node.js v18+    |
| **Language**           | TypeScript 5.7+ |
| **Blockchain Library** | ethers.js v6    |

#### Dependencies

**Protocol Integrations**:

* `@trp/core` - Risk Protocol core contracts (SmartToken, WrappedSmartToken)
* `@trp/esp` - Elastic Supply Pool (Balancer-based)

**External Protocols:**

* Aave V3 Pool (Routes 5 & 6)

#### Performance Metrics

| Metric              | Value                           |
| ------------------- | ------------------------------- |
| **Cycle Time**      | 1.5-3.0 seconds (optimized)     |
| **Data Fetch**      | \~300-500ms (batched API calls) |
| **Route Execution** | \~1.2-2.5s (parallel execution) |
| **Memory Usage**    | < 200MB steady state            |
| **RPC Batch Size**  | 100 calls per batch             |

#### Deployment

Prerequisites

**Smart Contract Deployment:**

1. Deploy Strategy contract using Hardhat UUPS proxy
2. Configure contract with token addresses and pool addresses
3. Set Aave pool address for Routes 5 & 6 (optional)
4. Verify the contract on the block explorer

**Bot Deployment:**

1. Configure environment variables (RPC, private key, contract addresses)
2. Fund the bot wallet with ETH for gas
3. Set API URL for price data endpoint

#### Bot Output Example

```
🚀 TRP Arbitrage Bot Starting...
✅ Connected to Ethereum Mainnet
✅ Loaded 6 arbitrage routes: 1,2,3,4,5,6
✅ Strategy contract: 0xABC123...
✅ Monitoring every 15 seconds

[2024-01-15 10:30:45] 🔍 Scanning routes...
[2024-01-15 10:30:46] Route 1: Complex Route: No arbitrage opportunity
[2024-01-15 10:30:47] Route 2: Simple Route: Profitable arbitrage route
[2024-01-15 10:30:48] 💰 Executed Route 2: Profit = 0.025 ETH ($45.50)
[2024-01-15 10:30:49] Route 3: Third Route: No arbitrage opportunity
[2024-01-15 10:30:50] Route 4: Fourth Route: No arbitrage opportunity
[2024-01-15 10:30:51] Route 5: Route 5: No arbitrage opportunity  
[2024-01-15 10:30:52] Route 6: Route 6: Huge arbitrage opportunity found! Profit ratio: 15%
[2024-01-15 10:30:53] 💰 Executed Route 6: Profit = 0.150 ETH ($273.00)
[2024-01-15 10:30:54] ✅ Cycle complete. Next check in 15 seconds...
```

The Trading Bot provides a powerful, automated solution for capitalizing on arbitrage opportunities in the TRP ecosystem. By following this guide and implementing proper risk management practices, users can operate the bot safely and profitably.

Remember to always:

* Test thoroughly before production use
* Monitor operations closely
* Keep configurations updated
* Maintain proper security practices
* Stay informed about protocol updates
* **USE AT YOUR OWN RISK**

Happy Arbitraging! 🚀


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.riskprotocol.io/protocol-design-and-specifications/trading-bots.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
