A Telegram bot for placing limit orders on Opinion.trade prediction markets. The bot provides an intuitive interface for market making strategies with secure credential management, invite-based access control, and automatic order synchronization.
Our documentation: https://bidask-bot.gitbook.io/docs/
- Invite-Based Access: Registration requires a valid invite code (10-character alphanumeric)
- Encrypted Storage: All sensitive data (wallet address, private key, API key) is encrypted using AES-GCM encryption
- Async SQLite Database: User credentials are stored locally in an encrypted SQLite database using
aiosqlitefor non-blocking operations - Zero Trust: Your private keys never leave your server in unencrypted form
- Atomic Invite Usage: Invites are used atomically at the end of registration to prevent conflicts
- Data Validation:
- Wallet address, private key, and API key must be unique
- Input trimming (removes leading/trailing whitespace)
- Important notes during registration about matching wallet, private key, and API key
- Connection Testing: API connection is tested at the end of registration using
get_my_ordersbefore saving user data - Error Handling: User-friendly error messages with error codes and timestamps for support reference
- Invite Generation: Admin command
/get_invitesgenerates and displays 10 unused invite codes - Automatic Creation: System automatically creates new invites if fewer than 10 are available
- Statistics: View total, used, and unused invite counts
- One-Time Use: Each invite can only be used once
- Unique Codes: 10-character alphanumeric codes with uniqueness validation
- User Deletion: Admin command
/delete_userallows removing users from the database - Complete Removal: Deletes user, all their orders, and clears associated invites
- Re-registration Support: Deleted users can register again with a new invite code
- Interactive Flow: Step-by-step process for placing limit orders
- Market Analysis: View market information including:
- Best bid/ask prices for YES and NO tokens
- Spread and liquidity metrics
- Top 5 bids and asks with price visualization in cents
- Smart Validation: Automatic balance checks and price validation
- Categorical Markets: Support for multi-outcome markets with submarket selection
- Reposition Threshold: Configurable threshold (in cents) for when orders should be repositioned
- Error Handling: Clear error messages when API calls fail
- Order List: View all your orders with pagination (
/orderscommand) - Order Search: Search orders by order ID, market ID, market title, token name, or side
- Order Cancellation: Cancel orders directly from the bot interface with detailed error messages
- Price Offset in Cents: Set order prices relative to best bid using intuitive cent-based offsets
- Direction Selection: Choose BUY (below current price) or SELL (above current price, can be used to sell shares)
- Order Confirmation: Review all settings before placing orders
- Order Status Tracking: View order status (pending, finished, canceled)
- Bot-Only Orders: Only orders created through the bot can be managed; manually placed orders are not displayed
- Execution Notifications: Automatic notifications when orders are executed with execution details
- Background Task: Automatically synchronizes orders every 60 seconds
- Order Status Monitoring: Checks order status via API before processing
- Automatically updates database when orders are filled or cancelled externally
- Sends notifications for filled orders with order details (price, market link)
- Silently updates cancelled orders without notifications
- Price Tracking: Monitors market price changes and maintains constant offset from current price
- Smart Updates: Only moves orders when price change exceeds configurable threshold (default 0.5 cents)
- Batch Operations: Efficiently cancels and places orders in batches per user
- User Notifications: Sends notifications about:
- Price changes (before repositioning)
- Order updates (after successful repositioning)
- Order filled (when order is executed)
- Placement errors (with detailed error messages)
- Non-blocking: All operations are asynchronous and don't block the bot's event loop
- Safety Checks: Only places new orders after successfully canceling old ones
- Separate Log Files: Different log files for different modules:
logs/bot.log- Main bot operations (INFO level and above)logs/sync_orders.log- Order synchronization operations
- Dual-Level Logging:
- File logs: INFO+ with detailed format including
filename:linenofor debugging - Console logs: WARNING+ with simplified format for important messages only
- File logs: INFO+ with detailed format including
- Detailed Logging: Comprehensive logging with user IDs, market IDs, and execution times
- Performance Monitoring: Logs start time, end time, and duration for each user's processing
- Error Tracking: Full traceback logging for debugging
- User Support: Command
/supportallows users to contact the administrator - Message Forwarding: Support messages (text or photo with caption) are forwarded to the admin
- User Information: Admin receives user ID, username, and name with each support message
- No Registration Required: Support command is available to all users (no registration needed)
- Confirmation: Users receive confirmation when their message is sent
- Multi-Language Help: Command
/helpprovides comprehensive instructions in three languages:- π¬π§ English (default)
- π·πΊ Russian
- π¨π³ Chinese
- Interactive Language Selection: Inline buttons for easy language switching
- Complete Guide: Includes registration instructions, order placement workflow, order management, and support information
- Anti-Spam Protection: Built-in middleware to prevent message spam
- Async Architecture: Fully asynchronous codebase using
aiosqliteandasyncio - Non-blocking I/O: All database and API operations are non-blocking
- Modular Design: Clean separation of concerns with routers and modules
- Registration Check: Commands verify user registration before execution
- Python 3.13+
- Telegram Bot Token (from @BotFather)
- Opinion Labs API Key (obtain from the form)
- BNB Chain RPC URL
- Wallet address and private key for Opinion.trade
- Admin Telegram ID (for invite management)
- Clone the repository:
git clone <repository-url>
cd trade_bot- Install dependencies:
pip install -r requirements.txt- Create a
.envfile in the project root:
BOT_TOKEN=your_telegram_bot_token
MASTER_KEY=your_32_byte_hex_encryption_key
RPC_URL=your_bnb_chain_rpc_url
ADMIN_TELEGRAM_ID=your_telegram_user_id
PROXY=host:port:username:password # Optional- Generate a master key for encryption:
import secrets
print(secrets.token_hex(32))- Run the bot:
cd bot
python main.py- Start the bot with
/start - Enter your invite code (10-character alphanumeric code)
- Enter your Balance spot address from your Opinion.trade profile
β οΈ Important: Must be the wallet address for which the API key was obtained
- Enter your private key
β οΈ Important: Must correspond to the wallet address from step 3
- Enter your Opinion Labs API key
β οΈ Important: Must be the API key obtained for the wallet from step 3
All data is encrypted and stored securely. The bot validates:
- Uniqueness of wallet address, private key, and API key
- API connection at the end of registration (using
get_my_orders) - If connection test fails, registration is aborted and you'll need to restart with
/start
The invite code is validated and used atomically at the end of registration only if all checks pass.
- Use
/get_invitesto get 10 unused invite codes - The system automatically creates new invites if needed
- View statistics: total, used, and unused invite counts
- Share invite codes with users who need access
- Use
/make_marketto start the order placement flow - Enter a market URL from Opinion.trade (e.g.,
https://app.opinion.trade/detail?topicId=155) - For categorical markets, select a submarket
- Review market information (spread, liquidity, best bids/asks)
- Enter the farming amount in USDT
- Select side (YES or NO)
- View top 5 bids and asks
- Set price offset in cents relative to best bid
- Choose direction (BUY or SELL)
- Set reposition threshold (minimum price change in cents to trigger repositioning, default 0.5)
- Confirm and place the order
- Use
/ordersto view all your orders - Browse orders with pagination (10 orders per page)
- Use the search function to find specific orders
- Cancel orders by entering the order ID (order list remains visible for easy copying)
- View order details: status (pending/finished/canceled), price, amount, market, creation date
π¬ Notifications: When an order is executed, the bot automatically sends you a notification with execution details (price, market link, etc.).
- Use
/helpto view comprehensive bot instructions - Select your preferred language (English, Russian, or Chinese) using inline buttons
- The help includes:
- Bot purpose and functionality
- Registration instructions with important notes
- Step-by-step order placement guide with examples
- Order management information
- Support contact information
- Use
/supportto contact the administrator - Enter your question or describe the issue
- You can send text or a photo with a caption
- Your message will be forwarded to the administrator with your user information (ID, username, name)
- You'll receive a confirmation when your message is sent
bot/
βββ main.py # Main bot entry point, background tasks, admin commands
βββ config.py # Configuration and settings management
βββ database.py # Async database operations (aiosqlite)
βββ aes.py # AES-GCM encryption utilities
βββ client_factory.py # Opinion SDK client creation and proxy setup
βββ spam_protection.py # Anti-spam middleware
βββ logger_config.py # Logging configuration and setup
βββ help_text.py # Multi-language help text (English, Russian, Chinese)
βββ start_router.py # User registration flow (/start command)
βββ market_router.py # Market order placement flow (/make_market command)
βββ orders_dialog.py # Order management dialog (/orders command)
βββ sync_orders.py # Automatic order synchronization background task
βββ opinion_api_wrapper.py # Opinion API wrapper functions (async)
βββ invites.py # Invite management functions
βββ users.db # SQLite database (created automatically)
The bot uses a modular router-based architecture:
- Routers: Separate routers for different features (
start_router,market_router) - Async Database: All database operations use
aiosqlitefor non-blocking I/O - Background Tasks: Order synchronization runs as an independent async task
- Dialogs: Complex multi-step interactions use
aiogram-dialogfor better UX - Middleware: Global anti-spam protection for all messages and callbacks
- API Wrapper: Centralized async wrapper for Opinion API calls
- AES-GCM Encryption: Industry-standard encryption for sensitive data
- Local Storage: All data stored locally on your server
- No Third-Party Sharing: Your credentials are never shared with third parties
- Encrypted Database: SQLite database contains only encrypted data
- Async Operations: Non-blocking I/O prevents performance issues
- Invite System: Access control through invite codes
The bot supports the following environment variables:
BOT_TOKEN: Telegram bot token (required)MASTER_KEY: 32-byte hex key for encryption (required)RPC_URL: BNB Chain RPC endpoint (required)ADMIN_TELEGRAM_ID: Telegram user ID for admin commands (required for invite management)PROXY: Proxy configuration in formathost:port:username:password(optional)
/start- Register and set up your account (requires invite code)/make_market- Start placing a limit order/orders- View, search, and manage your orders/help- View comprehensive bot instructions (available in English, Russian, and Chinese)/support- Contact administrator with questions or issues (supports text and photos)
/get_db- Export user database (admin only)/get_invites- Get 10 unused invite codes with statistics (admin only)/delete_user- Delete a user from the database (admin only)
The bot automatically synchronizes your orders every 60 seconds:
-
Status Check: For each pending order, checks status via API
- If order is finished: updates database to 'finished', sends notification with order details (price, market link)
- If order is canceled: updates database to 'canceled', skips processing silently (no notification)
- If status check fails: continues with normal processing (graceful degradation)
-
Price Monitoring: Monitors market prices and maintains a constant offset (in ticks) between the current market price and your order's target price
-
Smart Updates: Only moves orders when the price change exceeds the reposition threshold (default 0.5 cents)
-
Batch Operations: Efficiently cancels and places orders in batches per user
-
Notifications: You'll receive notifications when:
- Market price changes and orders need to be moved (before repositioning)
- Orders are successfully updated with new prices (after repositioning)
- Orders are filled (with order details and market link)
- Placement errors occur (with detailed error messages)
- Efficiency: Skips repositioning when change < threshold (saves API calls and gas fees)
- Reliability: Only places new orders after successfully canceling old ones
- Safety: Validates all operations via API response codes (errno == 0)
- User Awareness: Detailed notifications for all important events
- Performance: Logs execution time for each user's processing
aiogram==3.23.0- Telegram Bot API frameworkaiogram-dialog==2.4.0- Dialog system for complex interactionsaiosqlite==0.22.0- Async SQLite driver for non-blocking database operationsopinion-clob-sdk==0.4.3- Opinion.trade SDK for market interactionscryptography==46.0.3- AES-GCM encryptionpydantic==2.12.5- Settings managementpydantic-settings==2.12.0- Environment variable settingspython-dotenv==1.2.1- Environment variable loading
- All database operations use
aiosqlitefor true async I/O - API calls are wrapped in
asyncio.to_thread()to prevent blocking - Background tasks run independently without blocking the main event loop
- Opinion API wrapper provides async interface for synchronous SDK
- Retrieves all users from the database
- For each user:
- Gets active orders from the database
- For each order:
- Status Check: Checks order status via API
- If filled: updates DB, sends notification, skips processing
- If cancelled: updates DB, skips processing
- Fetches current market price (best_bid for BUY, best_ask for SELL)
- Calculates new target price using saved
offset_ticks - Calculates price change in cents
- If price change β₯
reposition_threshold_cents, adds to cancellation/placement lists - Sends price change notification (only if order will be repositioned)
- Status Check: Checks order status via API
- Cancels old orders in batch (validates via errno == 0)
- Places new orders in batch (only if all old orders were cancelled)
- Updates database with new order parameters (only for successful placements)
- Sends order update notification (for successful placements)
- Sends error notification (for failed placements)
- Invites are stored in
invitestable with fields: id, invite (unique), telegram_id, created_at, used_at - Invite codes are 10-character alphanumeric strings
- Invites are validated before registration and used atomically at the end
- Admin can generate invites via
/get_invitescommand - System automatically creates new invites if needed
- users: Encrypted user credentials (wallet, private key, API key)
telegram_id(PRIMARY KEY): User's Telegram ID- All sensitive data encrypted with AES-GCM
- Unique constraints on wallet address, private key, and API key
- orders: Order information (order_id, market_id, prices, amounts, status, etc.)
- Status values:
pending,finished,canceled(aligned with API terminology) - Default status:
pending - Migration function updates old statuses automatically
- Status values:
- invites: Invite codes and usage tracking
This bot is provided as-is for educational and personal use. Always ensure you understand the risks involved in trading on prediction markets. The developers are not responsible for any financial losses.
For issues, questions, or contributions, please open an issue on GitHub.