# Binance P2P Automation System

## Overview
Automated system for processing Binance P2P orders. Automatically pays buyers using Bridge API and marks orders as paid on Binance.

## Features
- ✅ Automatic order monitoring (cron job)
- ✅ Automatic payment processing via Bridge API
- ✅ Automatic order marking as paid on Binance
- ✅ Payment details validation
- ✅ Manual review for incomplete orders
- ✅ Low balance notifications
- ✅ Admin dashboard for order management
- ✅ Error logging and notifications

## Installation

### 1. Database Setup
```bash
# Import database schema
mysql -u your_user -p your_database < database/binance_p2p_orders.sql
```

### 2. Configuration
Edit `includes/config.php`:
- Update database credentials
- Set your Bridge API key
- Set your subdomain URL

### 3. Configure Settings
1. Go to admin panel: `https://your-subdomain.com/admin/settings.php`
2. Enter Binance API credentials
3. Enter Bridge customer ID and external account ID
4. Configure automation settings

### 4. Setup Cron Jobs

#### Order Monitor (runs every 30 seconds)
```bash
*/30 * * * * /usr/bin/php /path/to/website/binance/api/order-monitor.php >> /var/log/binance-order-monitor.log 2>&1
```

#### WebSocket Chat Handler (runs every minute)
```bash
* * * * * /usr/bin/php /path/to/website/binance/api/websocket-chat.php >> /var/log/binance-chat.log 2>&1
```

## File Structure

```
binance/
├── includes/
│   ├── config.php              # Database and API configuration
│   ├── binance-api.php         # Binance P2P API wrapper
│   ├── bridge-api.php          # Bridge API wrapper
│   ├── binance-settings.php    # Settings management
│   └── functions.php           # Helper functions
├── api/
│   ├── order-monitor.php       # Main cron job - monitors orders
│   ├── process-payment.php     # Payment processing logic
│   └── websocket-chat.php      # Chat message sender
├── admin/
│   ├── orders.php              # Orders list page
│   ├── order-details.php      # Order details page
│   ├── settings.php            # Configuration page
│   └── notifications.php      # Notifications page
└── database/
    └── binance_p2p_orders.sql  # Database schema
```

## How It Works

### Order Flow
1. **Order Monitor** checks Binance API every 30 seconds for new orders
2. **Payment Processor** validates payment details
3. If valid → Process payment via Bridge API
4. If invalid → Mark for manual review
5. **Mark as Paid** on Binance (even if payment fails - as per requirement)
6. **Send Chat Message** to buyer confirming payment
7. **Update Database** with all details

### Payment Processing
- Validates payment details based on currency (USD/EUR/MXN)
- Creates Bridge transfer from your configured account
- Waits for confirmation (5 seconds default)
- Marks order as paid on Binance
- Sends confirmation message

### Error Handling
- If Bridge payment fails → Order still marked as paid, error logged
- If Binance API fails → Error logged, order status updated
- All errors stored in database for review

## Admin Interface

### Orders Page (`admin/orders.php`)
- View all orders with filters
- Search by order number, buyer
- Filter by status
- View statistics

### Order Details (`admin/order-details.php`)
- Full order information
- Payment details
- Bridge transfer details
- Error messages
- Raw Binance data

### Settings (`admin/settings.php`)
- Configure Binance API credentials
- Configure Bridge account
- Enable/disable auto payment
- Set low balance threshold

### Notifications (`admin/notifications.php`)
- View system notifications
- Low balance alerts
- Payment failures
- API errors

## Payment Details Required

### USD (ACH)
- `routing_number` - 9 digits
- `account_number` - Account number
- `account_type` - "checking" or "savings"

### EUR (SEPA)
- `iban` - IBAN number
- `bank_country` - 3-letter country code (e.g., "DEU", "FRA")

### MXN (SPEI)
- `clabe` - 18-digit CLABE

## Balance Monitoring

The system checks your account balance and sends notifications when it falls below the threshold (default: 100 USDC).

**Note:** You need to implement the actual balance check in `checkAccountBalance()` function based on your system.

## Security

- Store API keys securely (not in version control)
- Use environment variables or encrypted config
- Implement proper admin authentication
- Validate all inputs
- Log all operations

## Troubleshooting

### Orders not processing
1. Check cron job is running
2. Check Binance API credentials
3. Check Bridge account configuration
4. Check error logs

### Payment failures
1. Check Bridge account has sufficient balance
2. Verify payment details are complete
3. Check Bridge API logs
4. Review order in admin panel

### WebSocket not working
- WebSocket implementation requires additional setup
- Consider using a message queue system
- Or implement a proper WebSocket client library

## Support

For issues or questions, check:
- Error logs in `/var/log/binance-*.log`
- Database `binance_p2p_notifications` table
- Admin panel for order status

