Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Python cache
__pycache__/
*.pyc
*.pyo
*.pyd

# Configuration files (that may contain sensitive data)
config.py

# Log files
*.log
arbitrage_bot.log

# Virtual environment directories
venv/
.venv/
env/
.env/
ENV/
.ENV/

# IDE and editor specific files
.vscode/
.idea/
*.sublime-project
*.sublime-workspace

# OS specific files
.DS_Store
Thumbs.db
137 changes: 134 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,136 @@
# webapp-community
# Backpack Exchange Arbitrage Bot

![Frame 227](https://user-images.githubusercontent.com/26004658/133513974-4c90764b-1e71-49c5-ba00-9fbc7c2c73fc.png)
## Project Description

A webApp containing information about the network, protocol and more
This project is an arbitrage bot designed for the Backpack Exchange. It aims to identify and capitalize on arbitrage opportunities, primarily focusing on triangular arbitrage. The bot includes functionalities for market data retrieval, order execution, real-time data streaming via WebSockets, and comprehensive logging.

## Features

* **Triangular Arbitrage Logic:** Identifies 3-step arbitrage opportunities (e.g., A -> B -> C -> A).
* **Market Data Retrieval:** Fetches public market data including assets, market details, tickers, order books, and k-lines.
* **Authenticated Account Management:** Retrieves account balances, futures positions, and historical data (fills, deposits, withdrawals).
* **Order Execution & Management:** Supports placing various order types (Limit, Market, etc.) and managing open orders (querying, canceling).
* **WebSocket Integration:** Connects to Backpack Exchange WebSockets for real-time data streams (public and private channels like depth, ticker, account updates).
* **Logging:** Comprehensive logging of operations, API calls, errors, and arbitrage opportunities to both console and a rotating log file (`arbitrage_bot.log`).
* **Configuration Management:** External configuration for API keys and other settings via `config.py`.
* **Unit Tests:** Includes a suite of unit tests for core components.

## Installation and Setup

### 1. Clone the Repository

```bash
git clone <repository_url> # Replace <repository_url> with the actual URL of this repository
cd backpack-exchange-arbitrage-bot # Or your chosen directory name
```

### 2. Install Dependencies

Ensure you have Python 3.8+ installed. Then, install the required packages:

```bash
pip install -r requirements.txt
```
This will install libraries such as `requests`, `websockets`, and `pynacl`.

### 3. Configure the Bot

Configuration is managed through a `config.py` file. A template is provided as `config.py.example`.

1. **Create `config.py`:**
Copy the example configuration file:
```bash
cp config.py.example config.py
```

2. **Edit `config.py`:**
Open `config.py` with a text editor and fill in your Backpack Exchange API keys and any other desired settings.

**`config.py` Template and Explanation:**

```python
# Backpack Exchange API Configuration

# Replace with your actual API Public Key
API_PUBLIC_KEY = "YOUR_BACKPACK_API_PUBLIC_KEY"

# Replace with your actual API Private Key (base64 encoded)
# This key is provided by Backpack Exchange and should be kept extremely secure.
API_PRIVATE_KEY = "YOUR_BACKPACK_API_PRIVATE_KEY_BASE64_ENCODED"

# Default request window size in milliseconds for authenticated REST API calls
# This is the duration for which a signed request is valid.
DEFAULT_WINDOW_MS = 5000

# Backpack REST API Base URL
API_BASE_URL = "https://api.backpack.exchange/"

# Backpack WebSocket Base URL
WS_BASE_URL = "wss://ws.backpack.exchange/"

# Default trading fee percentage (e.g., 0.1% = 0.001)
# This is a placeholder for arbitrage calculations.
# Actual fees can vary and ideally should be fetched from the API if possible or adjusted based on your fee tier.
DEFAULT_TRADING_FEE_PERCENTAGE = 0.001
```

**Security Warning: API Keys**
* Your `API_PUBLIC_KEY` and `API_PRIVATE_KEY` are sensitive credentials.
* **NEVER commit your actual `config.py` file with real API keys to any version control system (like Git).** The `.gitignore` file in this repository is set up to ignore `config.py` for this reason.
* Store your API keys securely. If you suspect your keys have been compromised, regenerate them immediately on the Backpack Exchange.
* The private key provided by Backpack Exchange is typically already base64 encoded. Do not try to base64 encode it again.

## Running the Bot

The main script for the bot is `arbitrage_bot.py`.

```bash
python arbitrage_bot.py
```

**Understanding `main()` in `arbitrage_bot.py`:**

The `main()` function in `arbitrage_bot.py` is structured to demonstrate various functionalities of the bot. It includes sections for:
* Testing Public API Endpoints (fetching assets, markets, tickers, etc.).
* Arbitrage Detection Logic (parsing market data and finding triangular arbitrage).
* Testing Authenticated Account Management Endpoints (fetching balances, positions, history - requires valid API keys).
* Testing Authenticated Order Endpoints (placing/canceling orders - requires valid API keys and is **commented out by default** to prevent accidental trades).
* Testing WebSocket Integration (connecting to public and private streams - requires valid API keys for private streams and is **commented out by default** as it's an async operation).

**To test specific functionalities:**
* **Public API calls and Arbitrage Detection:** These usually run by default.
* **Authenticated REST API calls (Account Info, Order Management):**
* Ensure your `config.py` is correctly set up with your API keys.
* In `arbitrage_bot.py`, navigate to the corresponding section in `main()` (e.g., "Testing Authenticated Order Endpoints", "Testing Account Management Endpoints").
* Carefully uncomment the example function calls you wish to test. **Be extremely cautious when uncommenting order execution examples, as they can perform real trades.**
* **WebSocket Tests:**
* Ensure `config.py` is set up for private streams.
* The WebSocket examples are within an async function `websocket_example_main()` inside `main()`.
* To run these, you'll need to uncomment the lines at the very end of `arbitrage_bot.py` related to `asyncio.run(websocket_example_main())`. It's often better to run WebSocket tests via `python websocket_client.py` which has its own async test runner.

**Logging:**

* The bot uses Python's `logging` module.
* Logs are output to both the console and a rotating file named `arbitrage_bot.log`.
* The log file is created in the same directory where `arbitrage_bot.py` is run.
* Log format: `%(asctime)s - %(levelname)s - %(module)s - %(funcName)s - %(message)s`.

## Running Unit Tests

Unit tests are located in the `tests/` directory. To run them:

```bash
python -m unittest discover tests
```
This command will automatically discover and run all tests within the `tests` package.

## Disclaimer

**Use this arbitrage bot at your own risk.**

* Trading cryptocurrencies involves significant financial risk, including the risk of losing a substantial amount of your capital. Arbitrage is not risk-free.
* The authors or contributors of this project are not responsible for any financial losses or other damages you may incur as a result of using this software.
* This software is provided "as is" without any warranties, express or implied.
* **It is highly recommended to thoroughly test this bot with placeholder API keys, on a testnet (if available from Backpack Exchange for API testing), or with very small, non-critical amounts of funds before committing significant capital.**
* Ensure you understand the code and the risks involved before running this bot. Market conditions, API behavior, and software bugs can all lead to unexpected outcomes.
```
Loading