@@ -51,33 +51,24 @@
|
|||||||
|
|
||||||
## 📖 Introduction
|
## 📖 Introduction
|
||||||
|
|
||||||
### What is QuantDinger?
|
**QuantDinger** is a local-first, privacy-first, self-hosted quantitative trading platform. It runs on your own infrastructure, providing multi-user accounts backed by PostgreSQL while keeping full control of your strategies, trading data, and API keys.
|
||||||
|
|
||||||
QuantDinger is a **local-first, privacy-first, self-hosted quantitative trading infrastructure**. It runs on your own machine/server, providing **multi-user accounts backed by PostgreSQL** while keeping full control of your strategies, trading data, and API keys.
|
### Why QuantDinger?
|
||||||
|
|
||||||
### Why Local-First?
|
| Feature | QuantDinger | Cloud SaaS |
|
||||||
|
|---------|-------------|------------|
|
||||||
|
| Data Ownership | ✅ Local storage | ❌ Vendor-controlled |
|
||||||
|
| Strategy Privacy | ✅ Never leaves your server | ❌ Uploaded to cloud |
|
||||||
|
| Subscription Fees | ✅ None | ❌ Monthly charges |
|
||||||
|
| Customization | ✅ Full source access | ❌ Limited |
|
||||||
|
|
||||||
Unlike SaaS platforms that lock your data and strategies in the cloud, QuantDinger runs locally. Your strategies, trading logs, API keys, and analysis results stay on your machine. No vendor lock-in, no subscription fees, no data exfiltration.
|
### Core Capabilities
|
||||||
|
|
||||||
### Who is this for?
|
- **🐍 Python-Native Strategies** — Write indicators in standard Python with AI assistance
|
||||||
|
- **🤖 AI Multi-Agent Research** — LLM-powered analysis with web scraping and market intelligence
|
||||||
QuantDinger is built for traders, researchers, and engineers who:
|
- **📊 Visual Backtesting** — TradingView-like charting with strategy visualization
|
||||||
- Value data sovereignty and privacy
|
- **⚡ Live Trading** — Direct API execution for 10+ crypto exchanges, IBKR, and MT5
|
||||||
- Want transparent, auditable trading infrastructure
|
- **🔒 Self-Hosted** — Your data stays on your infrastructure
|
||||||
- Prefer engineering over marketing
|
|
||||||
- Need a complete workflow: data, analysis, backtesting, and execution
|
|
||||||
|
|
||||||
### Core Features
|
|
||||||
|
|
||||||
QuantDinger includes a built-in **LLM-based multi-agent research system** that gathers financial intelligence from the web, combines it with local market data, and generates analysis reports. This integrates with strategy development, backtesting, and live trading workflows.
|
|
||||||
|
|
||||||
### Core Value
|
|
||||||
|
|
||||||
- **🔓 Apache 2.0 Open Source (Code)**: Permissive and commercial-friendly. You can fork and modify the codebase under Apache 2.0, while preserving required notices.
|
|
||||||
- **🐍 Python-Native & Visual**: Write indicators in standard Python (easier than PineScript) with AI assistance. Visualize signals directly on charts—a "Local TradingView" experience.
|
|
||||||
- **🤖 AI-Loop Optimization**: It doesn't just run strategies; AI analyzes backtest results to suggest parameter tuning (Stop-Loss/TP/MACD settings), forming a closed optimization loop.
|
|
||||||
- **🌍 Universal Market Access**: One unified system for Crypto (Live), US/CN Stocks, Forex, and Futures (Data/Notify).
|
|
||||||
- **⚡ Docker & Clean Arch**: 4-line command deployment. Modern Tech Stack (Vue + Python) with a clean, separation-of-concerns architecture.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -85,315 +76,163 @@ QuantDinger includes a built-in **LLM-based multi-agent research system** that g
|
|||||||
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
<a href="https://youtu.be/HPTVpqL7knM">
|
<a href="https://youtu.be/HPTVpqL7knM">
|
||||||
<img src="docs/screenshots/video_demo.png" alt="QuantDinger Project Introduction Video" width="100%" style="border-radius: 10px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); max-width: 800px;">
|
<img src="docs/screenshots/video_demo.png" alt="QuantDinger Demo" width="100%" style="border-radius: 10px; max-width: 800px;">
|
||||||
</a>
|
</a>
|
||||||
<p><strong>Click the video above to watch the QuantDinger project introduction</strong></p>
|
<p><strong>Click to watch the project introduction</strong></p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 📚 Documentation
|
## 📸 Screenshots
|
||||||
|
|
||||||
### Guides
|
|
||||||
- [Python Strategy Development Guide](docs/STRATEGY_DEV_GUIDE.md)
|
|
||||||
- [Interactive Brokers (IBKR) Trading Guide](docs/IBKR_TRADING_GUIDE_EN.md) 🆕
|
|
||||||
- [MetaTrader 5 (MT5) Trading Guide](docs/MT5_TRADING_GUIDE_EN.md) 🆕
|
|
||||||
|
|
||||||
### Notification Configuration
|
|
||||||
- [Telegram Notification Setup](docs/NOTIFICATION_TELEGRAM_CONFIG_EN.md)
|
|
||||||
- [Email (SMTP) Notification Setup](docs/NOTIFICATION_EMAIL_CONFIG_EN.md)
|
|
||||||
- [SMS (Twilio) Notification Setup](docs/NOTIFICATION_SMS_CONFIG_EN.md)
|
|
||||||
|
|
||||||
## 📸 Visual Tour
|
|
||||||
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
<h3>🗺️ System Architecture Overview</h3>
|
<img src="docs/screenshots/tuopu.png" alt="System Architecture" width="100%" style="max-width: 800px;">
|
||||||
<p>A comprehensive view of QuantDinger's AI-powered research, backtesting, and automated trading capabilities.</p>
|
<p><em>System Architecture Overview</em></p>
|
||||||
<img src="docs/screenshots/tuopu.png" alt="QuantDinger System Topology" width="100%" style="border-radius: 10px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); max-width: 800px;">
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<br/>
|
<table align="center">
|
||||||
|
|
||||||
<div align="center">
|
|
||||||
<h3>📊 Professional Quant Dashboard</h3>
|
|
||||||
<p>Real-time monitoring of market dynamics, assets, and strategy status.</p>
|
|
||||||
<img src="docs/screenshots/dashboard.png" alt="QuantDinger Dashboard" width="100%" style="border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);">
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<br/>
|
|
||||||
|
|
||||||
<table align="center" width="100%">
|
|
||||||
<tr>
|
<tr>
|
||||||
<td width="50%" align="center" valign="top">
|
<td align="center"><img src="docs/screenshots/dashboard.png" alt="Dashboard"><br/><em>Dashboard</em></td>
|
||||||
<h3>🤖 AI Deep Research</h3>
|
|
||||||
<p>Multi-agent collaboration for market sentiment & technical analysis.</p>
|
|
||||||
<img src="docs/screenshots/ai_analysis1.png" alt="AI Market Analysis" style="border-radius: 6px;">
|
|
||||||
</td>
|
|
||||||
<td width="50%" align="center" valign="top">
|
|
||||||
<h3>💬 Smart Trading Assistant</h3>
|
|
||||||
<p>Natural language interface for instant market insights.</p>
|
|
||||||
<img src="docs/screenshots/trading_assistant.png" alt="Trading Assistant" style="border-radius: 6px;">
|
|
||||||
</td>
|
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<td width="50%" align="center" valign="top">
|
<td align="center"><img src="docs/screenshots/ai_analysis1.png" alt="AI Analysis"><br/><em>AI Multi-Agent Analysis</em></td>
|
||||||
<h3>📈 Interactive Indicator Analysis</h3>
|
|
||||||
<p>Rich library of technical indicators with drag-and-drop analysis.</p>
|
|
||||||
<img src="docs/screenshots/indicator_analysis.png" alt="Indicator Analysis" style="border-radius: 6px;">
|
|
||||||
</td>
|
|
||||||
<td width="50%" align="center" valign="top">
|
|
||||||
<h3>🐍 Python Strategy Gen</h3>
|
|
||||||
<p>Built-in editor with AI-assisted strategy coding.</p>
|
|
||||||
<img src="docs/screenshots/indicator_creat_python_code.png" alt="Code Generation" style="border-radius: 6px;">
|
|
||||||
</td>
|
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<td colspan="2" align="center" valign="top">
|
<td align="center"><img src="docs/screenshots/indicator_analysis.png" alt="Indicator Analysis"><br/><em>Indicator Analysis</em></td>
|
||||||
<h3>📊 Portfolio Monitor</h3>
|
|
||||||
<p>Track positions, set alerts, and receive AI-powered analysis via Email/Telegram.</p>
|
|
||||||
<img src="docs/screenshots/portfolio.jpg" alt="Portfolio Monitor" style="border-radius: 6px; max-width: 90%;">
|
|
||||||
</td>
|
|
||||||
</tr>
|
</tr>
|
||||||
</table>
|
</table>
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 🔌 Supported Exchanges & Brokers
|
||||||
|
|
||||||
|
### Cryptocurrency (Direct API Trading)
|
||||||
|
|
||||||
|
| Exchange | Spot | Futures | Features |
|
||||||
|
|:--------:|:----:|:-------:|:---------|
|
||||||
|
| **Binance** | ✅ | ✅ | Margin, COIN-M, USDⓈ-M |
|
||||||
|
| **OKX** | ✅ | ✅ | Options, Copy Trading |
|
||||||
|
| **Bitget** | ✅ | ✅ | Copy Trading |
|
||||||
|
| **Bybit** | ✅ | ✅ | Linear, Inverse |
|
||||||
|
| **KuCoin** | ✅ | ✅ | — |
|
||||||
|
| **Gate.io** | ✅ | ✅ | — |
|
||||||
|
| **Kraken** | ✅ | ✅ | — |
|
||||||
|
| **Coinbase** | ✅ | — | Spot Only |
|
||||||
|
| **Bitfinex** | ✅ | ✅ | Derivatives |
|
||||||
|
| **Deepcoin** | ✅ | ✅ | — |
|
||||||
|
|
||||||
|
### Traditional Brokers
|
||||||
|
|
||||||
|
| Broker | Markets | Platform |
|
||||||
|
|:------:|:--------|:---------|
|
||||||
|
| **Interactive Brokers** | US/HK Stocks, Options | TWS / IB Gateway |
|
||||||
|
| **MetaTrader 5** | Forex, CFDs | MT5 Terminal |
|
||||||
|
|
||||||
|
### Market Data Sources
|
||||||
|
|
||||||
|
| Market | Sources |
|
||||||
|
|--------|---------|
|
||||||
|
| Crypto | 100+ exchanges via CCXT |
|
||||||
|
| US Stocks | Yahoo Finance, Finnhub, Tiingo |
|
||||||
|
| CN/HK Stocks | AkShare, East Money |
|
||||||
|
| Forex | Finnhub, OANDA |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## ✨ Key Features
|
## ✨ Key Features
|
||||||
|
|
||||||
### 1. Visual Python Strategy Workbench
|
### 1. Visual Python Strategy Workbench
|
||||||
*Better than PineScript, Smarter than SaaS.*
|
|
||||||
|
|
||||||
- **Python Native**: Write indicators and strategies in Python. Leverage the entire Python ecosystem (Pandas, Numpy, TA-Lib) instead of proprietary languages like PineScript.
|
Write strategies in Python with full ecosystem access (Pandas, NumPy, TA-Lib). AI assists with code generation, and signals visualize directly on interactive charts.
|
||||||
- **"Mini-TradingView" Experience**: Run your Python indicators directly on the built-in K-line charts. Visually debug buy/sell signals on historical data.
|
|
||||||
- **AI-Assisted Coding**: Let the built-in AI write the complex logic for you. From idea to code in seconds.
|
|
||||||
|
|
||||||
### 2. Complete Trading Lifecycle
|
### 2. Complete Trading Lifecycle
|
||||||
*From Indicator to Execution, Seamlessly.*
|
|
||||||
|
|
||||||
1. **Indicator**: Define your market entry/exit signals.
|
```
|
||||||
2. **Strategy Config**: Attach risk management rules (Position sizing, Stop-Loss, Take-Profit).
|
Indicator → Strategy Config → Backtest → AI Optimization → Live Execution
|
||||||
3. **Backtest & AI Optimization**: Run backtests, view rich performance metrics, and **let AI analyze the result to suggest improvements** (e.g., "Adjust MACD threshold to X").
|
|
||||||
4. **Execution Mode**:
|
|
||||||
- **Live Trading**:
|
|
||||||
- **Cryptocurrency**: Direct API execution for 10+ exchanges (Binance, OKX, Bitget, Bybit, etc.)
|
|
||||||
- **US/HK Stocks**: Via Interactive Brokers (IBKR) 🆕
|
|
||||||
- **Forex**: Via MetaTrader 5 (MT5) 🆕
|
|
||||||
- **Signal Notification**: For markets without live trading support (A-shares/Futures), send signals via Telegram, Discord, Email, SMS, or Webhook.
|
|
||||||
|
|
||||||
### 3. AI Multi-Agent Research
|
|
||||||
*Your 24/7 AI Investment Committee.*
|
|
||||||
|
|
||||||
The system employs a multi-agent team to act as a secondary filter for your strategies:
|
|
||||||
|
|
||||||
- **Research Agents**: Scrape web news and macro events (Google/Bing).
|
|
||||||
- **Analysis Agents**: Analyze technical indicators and capital flows.
|
|
||||||
- **Strategic Integration**: The AI judgment can serve as a "Market Filter"—only allowing your strategy to trade when the AI sentiment aligns (e.g., "Don't buy if AI Risk Analyst flags high macro danger").
|
|
||||||
|
|
||||||
### 4. Universal Data Engine
|
|
||||||
|
|
||||||
QuantDinger provides a unified data interface across multiple markets:
|
|
||||||
|
|
||||||
- **Cryptocurrency**: Direct API connections for trading (10+ exchanges) and CCXT integration for market data (100+ sources)
|
|
||||||
- **Stocks**: Yahoo Finance, Finnhub, Tiingo (US stocks), and AkShare (CN/HK stocks)
|
|
||||||
- **Futures/Forex**: OANDA and major futures data sources
|
|
||||||
- **Proxy Support**: Built-in proxy configuration for restricted network environments
|
|
||||||
|
|
||||||
### 5. Memory-Augmented Agents (Local RAG + Reflection Loop)
|
|
||||||
|
|
||||||
QuantDinger’s agents don’t start from scratch every time. The backend includes a **local memory store** and an optional **reflection/verification loop**:
|
|
||||||
|
|
||||||
- **What it is**: RAG-style experience retrieval injected into agent prompts (NOT model fine-tuning).
|
|
||||||
- **Where it lives**: PostgreSQL database (shared with main data) or local files under `backend_api_python/data/memory/` (privacy-first).
|
|
||||||
|
|
||||||
```mermaid
|
|
||||||
flowchart TB
|
|
||||||
%% ===== 🌐 Entry Layer =====
|
|
||||||
subgraph Entry["🌐 API Entry"]
|
|
||||||
A["📡 POST /api/analysis/multi"]
|
|
||||||
A2["🔄 POST /api/analysis/reflect"]
|
|
||||||
end
|
|
||||||
|
|
||||||
%% ===== ⚙️ Service Layer =====
|
|
||||||
subgraph Service["⚙️ Service Orchestration"]
|
|
||||||
B[AnalysisService]
|
|
||||||
C[AgentCoordinator]
|
|
||||||
D["📊 Build Context<br/>price · kline · news · indicators"]
|
|
||||||
end
|
|
||||||
|
|
||||||
%% ===== 🤖 Multi-Agent Workflow =====
|
|
||||||
subgraph Agents["🤖 Multi-Agent Workflow"]
|
|
||||||
|
|
||||||
subgraph P1["📈 Phase 1 · Analysis (Parallel)"]
|
|
||||||
E1["🔍 MarketAnalyst<br/><i>Technical</i>"]
|
|
||||||
E2["📑 FundamentalAnalyst<br/><i>Fundamentals</i>"]
|
|
||||||
E3["📰 NewsAnalyst<br/><i>News & Events</i>"]
|
|
||||||
E4["💭 SentimentAnalyst<br/><i>Market Mood</i>"]
|
|
||||||
E5["⚠️ RiskAnalyst<br/><i>Risk Assessment</i>"]
|
|
||||||
end
|
|
||||||
|
|
||||||
subgraph P2["🎯 Phase 2 · Debate (Parallel)"]
|
|
||||||
F1["🐂 BullResearcher<br/><i>Bullish Case</i>"]
|
|
||||||
F2["🐻 BearResearcher<br/><i>Bearish Case</i>"]
|
|
||||||
end
|
|
||||||
|
|
||||||
subgraph P3["💹 Phase 3 · Decision"]
|
|
||||||
G["🎰 TraderAgent<br/><i>Final Verdict → BUY / SELL / HOLD</i>"]
|
|
||||||
end
|
|
||||||
|
|
||||||
end
|
|
||||||
|
|
||||||
%% ===== 🧠 Memory Layer =====
|
|
||||||
subgraph Memory["🧠 PostgreSQL Memory Store"]
|
|
||||||
M1[("market_analyst")]
|
|
||||||
M2[("fundamental")]
|
|
||||||
M3[("news_analyst")]
|
|
||||||
M4[("sentiment")]
|
|
||||||
M5[("risk_analyst")]
|
|
||||||
M6[("bull_researcher")]
|
|
||||||
M7[("bear_researcher")]
|
|
||||||
M8[("trader_agent")]
|
|
||||||
end
|
|
||||||
|
|
||||||
%% ===== 🔄 Reflection Loop =====
|
|
||||||
subgraph Reflect["🔄 Reflection Loop (Optional)"]
|
|
||||||
R[ReflectionService]
|
|
||||||
RR[("reflection_records.db")]
|
|
||||||
W["⏰ ReflectionWorker"]
|
|
||||||
end
|
|
||||||
|
|
||||||
%% ===== Main Flow =====
|
|
||||||
A --> B --> C --> D
|
|
||||||
D --> P1 --> P2 --> P3
|
|
||||||
|
|
||||||
%% ===== Memory Read/Write =====
|
|
||||||
E1 <-.-> M1
|
|
||||||
E2 <-.-> M2
|
|
||||||
E3 <-.-> M3
|
|
||||||
E4 <-.-> M4
|
|
||||||
E5 <-.-> M5
|
|
||||||
F1 <-.-> M6
|
|
||||||
F2 <-.-> M7
|
|
||||||
G <-.-> M8
|
|
||||||
|
|
||||||
%% ===== Reflection Flow =====
|
|
||||||
C --> R --> RR
|
|
||||||
W --> RR
|
|
||||||
W -.->|"verify + learn"| M8
|
|
||||||
A2 -.->|"manual review"| M8
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**Retrieval ranking (simplified)**:
|
### 3. AI Multi-Agent Research
|
||||||
|
|
||||||
\[
|
A team of specialized agents analyzes markets:
|
||||||
score = w_{sim}\cdot sim + w_{recency}\cdot recency + w_{returns}\cdot returns\_score
|
- **Research Agents** — Web scraping for news and events
|
||||||
\]
|
- **Analysis Agents** — Technical indicators and capital flows
|
||||||
|
- **Risk Assessment** — Market filter based on AI sentiment
|
||||||
|
|
||||||
Config lives in `.env` (see `backend_api_python/env.example`): `ENABLE_AGENT_MEMORY`, `AGENT_MEMORY_TOP_K`, `AGENT_MEMORY_ENABLE_VECTOR`, `AGENT_MEMORY_HALF_LIFE_DAYS`, and `ENABLE_REFLECTION_WORKER`.
|
### 4. Multi-LLM Support
|
||||||
|
|
||||||
### 6. Strategy Runtime
|
| Provider | Models |
|
||||||
|
|----------|--------|
|
||||||
|
| OpenRouter | 100+ models |
|
||||||
|
| OpenAI | GPT-4o, GPT-4o-mini |
|
||||||
|
| Google | Gemini 1.5 Flash/Pro |
|
||||||
|
| DeepSeek | DeepSeek Chat |
|
||||||
|
| xAI | Grok Beta |
|
||||||
|
|
||||||
- **Thread-Based Executor**: Independent thread pool for strategy execution
|
### 5. Enterprise Features
|
||||||
- **Auto-Restore**: Resumes running strategies after system restarts
|
|
||||||
- **Order Queue**: Background worker for order execution
|
|
||||||
|
|
||||||
### 7. Multi-LLM Provider Support
|
- **Multi-User Support** — PostgreSQL-backed accounts with role-based permissions
|
||||||
|
- **OAuth Integration** — Google and GitHub login
|
||||||
QuantDinger supports multiple AI providers with auto-detection:
|
- **Security** — Cloudflare Turnstile, rate limiting, email verification
|
||||||
|
|
||||||
| Provider | Features |
|
|
||||||
|----------|----------|
|
|
||||||
| **OpenRouter** | Multi-model gateway (default), 100+ models |
|
|
||||||
| **OpenAI** | GPT-4o, GPT-4o-mini |
|
|
||||||
| **Google Gemini** | Gemini 1.5 Flash/Pro |
|
|
||||||
| **DeepSeek** | DeepSeek Chat (cost-effective) |
|
|
||||||
| **xAI Grok** | Grok Beta |
|
|
||||||
|
|
||||||
Simply configure your preferred provider's API key in `.env`. The system auto-detects available providers.
|
|
||||||
|
|
||||||
### 8. User Management & Security
|
|
||||||
|
|
||||||
- **Multi-User Support**: PostgreSQL-backed user accounts with role-based permissions
|
|
||||||
- **OAuth Login**: Google and GitHub OAuth integration
|
|
||||||
- **Email Verification**: Registration and password reset via email codes
|
|
||||||
- **Security Features**: Cloudflare Turnstile captcha, IP/account rate limiting
|
|
||||||
- **Demo Mode**: Read-only mode for public demonstrations
|
|
||||||
|
|
||||||
### 9. Tech Stack
|
|
||||||
|
|
||||||
- **Backend**: Python (Flask) + PostgreSQL + Redis (optional)
|
|
||||||
- **Frontend**: Vue 2 + Ant Design Vue + KlineCharts/ECharts
|
|
||||||
- **Deployment**: Docker Compose (with PostgreSQL)
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🔌 Supported Exchanges & Brokers
|
## 🚀 Quick Start
|
||||||
|
|
||||||
QuantDinger supports multiple execution methods for different market types:
|
### Docker Deployment (Recommended)
|
||||||
|
|
||||||
### Cryptocurrency Exchanges (Direct API)
|
```bash
|
||||||
|
# Clone and configure
|
||||||
|
git clone https://github.com/brokermr810/QuantDinger.git
|
||||||
|
cd QuantDinger
|
||||||
|
cp backend_api_python/env.example backend_api_python/.env
|
||||||
|
|
||||||
| Exchange | Markets |
|
# Start services
|
||||||
|:--------:|:---------|
|
docker-compose up -d --build
|
||||||
| Binance | Spot, Futures, Margin |
|
```
|
||||||
| OKX | Spot, Perpetual, Options |
|
|
||||||
| Bitget | Spot, Futures, Copy Trading |
|
|
||||||
| Bybit | Spot, Linear Futures |
|
|
||||||
| Coinbase Exchange | Spot |
|
|
||||||
| Kraken | Spot, Futures |
|
|
||||||
| KuCoin | Spot, Futures |
|
|
||||||
| Gate.io | Spot, Futures |
|
|
||||||
| Bitfinex | Spot, Derivatives |
|
|
||||||
|
|
||||||
### Traditional Brokers
|
**Access:**
|
||||||
|
- Frontend: http://localhost:8888
|
||||||
|
- API: http://localhost:5000
|
||||||
|
- Default login: `quantdinger` / `123456`
|
||||||
|
|
||||||
| Broker | Markets | Platform |
|
### Docker Commands
|
||||||
|:------:|:--------|:---------|
|
|
||||||
| **Interactive Brokers (IBKR)** | US Stocks, HK Stocks | TWS / IB Gateway 🆕 |
|
|
||||||
| **MetaTrader 5 (MT5)** | Forex | MT5 Terminal 🆕 |
|
|
||||||
|
|
||||||
### Market Data (via CCXT)
|
```bash
|
||||||
|
docker-compose ps # Status
|
||||||
|
docker-compose logs -f # Logs
|
||||||
|
docker-compose down # Stop
|
||||||
|
docker-compose up -d --build # Rebuild
|
||||||
|
```
|
||||||
|
|
||||||
Bybit, Gate.io, Kraken, KuCoin, HTX, and 100+ other exchanges for market data.
|
### Local Development
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Backend
|
||||||
|
cd backend_api_python
|
||||||
|
pip install -r requirements.txt
|
||||||
|
cp env.example .env
|
||||||
|
python run.py
|
||||||
|
|
||||||
|
# Frontend
|
||||||
|
cd quantdinger_vue
|
||||||
|
npm install && npm run serve
|
||||||
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Multi-Language Support
|
## 📚 Documentation
|
||||||
|
|
||||||
QuantDinger is built for a global audience with comprehensive internationalization:
|
- [Python Strategy Development Guide](docs/STRATEGY_DEV_GUIDE.md)
|
||||||
|
- [Interactive Brokers (IBKR) Trading Guide](docs/IBKR_TRADING_GUIDE_EN.md)
|
||||||
<p>
|
- [MetaTrader 5 (MT5) Trading Guide](docs/MT5_TRADING_GUIDE_EN.md)
|
||||||
<img src="https://img.shields.io/badge/🇺🇸_English-Supported-2563EB?style=flat-square" alt="English" />
|
- [Telegram Notification Setup](docs/NOTIFICATION_TELEGRAM_CONFIG_EN.md)
|
||||||
<img src="https://img.shields.io/badge/🇨🇳_简体中文-Supported-2563EB?style=flat-square" alt="Simplified Chinese" />
|
- [Email Notification Setup](docs/NOTIFICATION_EMAIL_CONFIG_EN.md)
|
||||||
<img src="https://img.shields.io/badge/🇹🇼_繁體中文-Supported-2563EB?style=flat-square" alt="Traditional Chinese" />
|
|
||||||
<img src="https://img.shields.io/badge/🇯🇵_日本語-Supported-2563EB?style=flat-square" alt="Japanese" />
|
|
||||||
<img src="https://img.shields.io/badge/🇰🇷_한국어-Supported-2563EB?style=flat-square" alt="Korean" />
|
|
||||||
<img src="https://img.shields.io/badge/🇩🇪_Deutsch-Supported-2563EB?style=flat-square" alt="German" />
|
|
||||||
<img src="https://img.shields.io/badge/🇫🇷_Français-Supported-2563EB?style=flat-square" alt="French" />
|
|
||||||
<img src="https://img.shields.io/badge/🇹🇭_ไทย-Supported-2563EB?style=flat-square" alt="Thai" />
|
|
||||||
<img src="https://img.shields.io/badge/🇻🇳_Tiếng_Việt-Supported-2563EB?style=flat-square" alt="Vietnamese" />
|
|
||||||
<img src="https://img.shields.io/badge/🇸🇦_العربية-Supported-2563EB?style=flat-square" alt="Arabic" />
|
|
||||||
</p>
|
|
||||||
|
|
||||||
All UI elements, error messages, and documentation are fully translated. Language is auto-detected based on browser settings or can be manually switched in the app.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Supported Markets
|
## 🏗️ Architecture
|
||||||
|
|
||||||
| Market Type | Data Sources | Trading |
|
```
|
||||||
|-------------|--------------|---------|
|
|
||||||
| **Cryptocurrency** | Binance, OKX, Bitget, + 100 exchanges | ✅ Full support |
|
|
||||||
| **US Stocks** | Yahoo Finance, Finnhub, Tiingo | ✅ Via IBKR 🆕 |
|
|
||||||
| **HK Stocks** | AkShare, East Money | ✅ Via IBKR 🆕 |
|
|
||||||
| **CN Stocks (A-shares)** | AkShare, East Money | ⚡ Data only |
|
|
||||||
| **Forex** | Finnhub, OANDA | ✅ Via MT5 🆕 |
|
|
||||||
| **Futures** | Exchange APIs, AkShare | ⚡ Data only |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Architecture (Current Repo)
|
|
||||||
|
|
||||||
```text
|
|
||||||
┌─────────────────────────────┐
|
┌─────────────────────────────┐
|
||||||
│ quantdinger_vue │
|
│ quantdinger_vue │
|
||||||
│ (Vue 2 + Ant Design Vue) │
|
│ (Vue 2 + Ant Design Vue) │
|
||||||
@@ -402,446 +241,49 @@ All UI elements, error messages, and documentation are fully translated. Languag
|
|||||||
▼
|
▼
|
||||||
┌─────────────────────────────┐
|
┌─────────────────────────────┐
|
||||||
│ backend_api_python │
|
│ backend_api_python │
|
||||||
│ (Flask + strategy runtime) │
|
│ (Flask + Strategy Runtime) │
|
||||||
└──────────────┬──────────────┘
|
└──────────────┬──────────────┘
|
||||||
│
|
│
|
||||||
├─ PostgreSQL (multi-user support)
|
┌──────────┼──────────┐
|
||||||
├─ Redis (optional cache)
|
▼ ▼ ▼
|
||||||
└─ Data providers / LLMs / Exchanges
|
PostgreSQL Redis Exchanges
|
||||||
|
(opt) & LLMs
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Repository Layout
|
## 🌍 Multi-Language Support
|
||||||
|
|
||||||
```text
|
<p>
|
||||||
.
|
<img src="https://img.shields.io/badge/🇺🇸_English-Supported-2563EB?style=flat-square" alt="English" />
|
||||||
├─ backend_api_python/ # Flask API + AI + backtest + strategy runtime
|
<img src="https://img.shields.io/badge/🇨🇳_简体中文-Supported-2563EB?style=flat-square" alt="Chinese" />
|
||||||
│ ├─ app/
|
<img src="https://img.shields.io/badge/🇹🇼_繁體中文-Supported-2563EB?style=flat-square" alt="Traditional Chinese" />
|
||||||
│ ├─ env.example # Copy to .env for local config
|
<img src="https://img.shields.io/badge/🇯🇵_日本語-Supported-2563EB?style=flat-square" alt="Japanese" />
|
||||||
│ ├─ requirements.txt
|
<img src="https://img.shields.io/badge/🇰🇷_한국어-Supported-2563EB?style=flat-square" alt="Korean" />
|
||||||
│ └─ run.py # Entrypoint
|
<img src="https://img.shields.io/badge/🇩🇪_Deutsch-Supported-2563EB?style=flat-square" alt="German" />
|
||||||
└─ quantdinger_vue/ # Vue 2 UI (dev server proxies /api -> backend)
|
<img src="https://img.shields.io/badge/🇫🇷_Français-Supported-2563EB?style=flat-square" alt="French" />
|
||||||
```
|
</p>
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Quick Start
|
## 📜 License
|
||||||
|
|
||||||
### Option 1: Docker Deployment (Recommended)
|
Licensed under **Apache License 2.0**. See [LICENSE](LICENSE).
|
||||||
|
|
||||||
The fastest way to get QuantDinger running with PostgreSQL database and multi-user support.
|
**Trademark Notice:** Apache 2.0 does not grant trademark rights. QuantDinger branding (name/logo) is protected. See [TRADEMARKS.md](TRADEMARKS.md) for usage guidelines.
|
||||||
|
|
||||||
#### 1. Configure Environment
|
|
||||||
|
|
||||||
Create a `.env` file in project root:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Database Configuration
|
|
||||||
POSTGRES_USER=quantdinger
|
|
||||||
POSTGRES_PASSWORD=your_secure_password
|
|
||||||
POSTGRES_DB=quantdinger
|
|
||||||
|
|
||||||
# Admin Account (created on first startup)
|
|
||||||
ADMIN_USER=quantdinger
|
|
||||||
ADMIN_PASSWORD=123456
|
|
||||||
|
|
||||||
# Optional: AI Features
|
|
||||||
OPENROUTER_API_KEY=your_api_key
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 2. Start Services
|
|
||||||
|
|
||||||
**Linux / macOS**
|
|
||||||
```bash
|
|
||||||
git clone https://github.com/brokermr810/QuantDinger.git && \
|
|
||||||
cd QuantDinger && \
|
|
||||||
cp backend_api_python/env.example backend_api_python/.env && \
|
|
||||||
docker-compose up -d --build
|
|
||||||
```
|
|
||||||
|
|
||||||
**Windows (PowerShell)**
|
|
||||||
```powershell
|
|
||||||
git clone https://github.com/brokermr810/QuantDinger.git
|
|
||||||
cd QuantDinger
|
|
||||||
Copy-Item backend_api_python\env.example -Destination backend_api_python\.env
|
|
||||||
docker-compose up -d --build
|
|
||||||
```
|
|
||||||
|
|
||||||
This will automatically:
|
|
||||||
- Start PostgreSQL database (port 5432)
|
|
||||||
- Initialize database schema
|
|
||||||
- Start backend API (port 5000)
|
|
||||||
- Start frontend (port 8888)
|
|
||||||
- Create admin user from `ADMIN_USER`/`ADMIN_PASSWORD` in `.env`
|
|
||||||
|
|
||||||
#### 3. Access the Application
|
|
||||||
|
|
||||||
- **Frontend UI**: http://localhost:8888
|
|
||||||
- **Backend API**: http://localhost:5000
|
|
||||||
- **Default Account**: Uses `ADMIN_USER` / `ADMIN_PASSWORD` from `.env` (default: `quantdinger` / `123456`, please change for production)
|
|
||||||
|
|
||||||
> **Note**: For production, edit `backend_api_python/.env` to set strong passwords, add `OPENROUTER_API_KEY` for AI features, then restart with `docker-compose restart backend`.
|
|
||||||
|
|
||||||
#### Docker Commands Reference
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# View running status
|
|
||||||
docker-compose ps
|
|
||||||
|
|
||||||
# View logs
|
|
||||||
docker-compose logs -f
|
|
||||||
|
|
||||||
# View backend logs only
|
|
||||||
docker-compose logs -f backend
|
|
||||||
|
|
||||||
# View frontend logs only
|
|
||||||
docker-compose logs -f frontend
|
|
||||||
|
|
||||||
# Stop services
|
|
||||||
docker-compose down
|
|
||||||
|
|
||||||
# Stop and remove volumes (WARNING: deletes database!)
|
|
||||||
docker-compose down -v
|
|
||||||
|
|
||||||
# Restart services
|
|
||||||
docker-compose restart
|
|
||||||
|
|
||||||
# Rebuild and restart
|
|
||||||
docker-compose up -d --build
|
|
||||||
|
|
||||||
# Enter backend container
|
|
||||||
docker exec -it quantdinger-backend /bin/bash
|
|
||||||
|
|
||||||
# Enter frontend container
|
|
||||||
docker exec -it quantdinger-frontend /bin/sh
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Docker Architecture
|
|
||||||
|
|
||||||
```
|
|
||||||
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
|
||||||
│ Frontend │ │ Backend │ │ PostgreSQL │
|
|
||||||
│ (Nginx) │────▶│ (Python) │────▶│ Database │
|
|
||||||
│ Port: 8888 │ │ Port: 5000 │ │ Port: 5432 │
|
|
||||||
└─────────────────┘ └─────────────────┘ └─────────────────┘
|
|
||||||
│ │ │
|
|
||||||
└───────────────────────┴───────────────────────┘
|
|
||||||
Docker Network
|
|
||||||
```
|
|
||||||
|
|
||||||
- **Frontend**: Vue.js app served by Nginx, proxies API requests to backend
|
|
||||||
- **Backend**: Python Flask API service with multi-user authentication
|
|
||||||
- **PostgreSQL**: Database for user data, strategies, and trading records
|
|
||||||
|
|
||||||
#### Data Persistence
|
|
||||||
|
|
||||||
The following data is persisted across container restarts:
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
volumes:
|
|
||||||
postgres_data: # PostgreSQL database
|
|
||||||
- ./backend_api_python/logs:/app/logs # Logs
|
|
||||||
- ./backend_api_python/data:/app/data # Data directory
|
|
||||||
- ./backend_api_python/.env:/app/.env # Configuration
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Customization
|
|
||||||
|
|
||||||
**Change ports** - Edit `docker-compose.yml`:
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
services:
|
|
||||||
frontend:
|
|
||||||
ports:
|
|
||||||
- "8080:80" # Change to port 8080
|
|
||||||
|
|
||||||
backend:
|
|
||||||
ports:
|
|
||||||
- "5001:5000" # Change to port 5001
|
|
||||||
```
|
|
||||||
|
|
||||||
**Configure HTTPS** - Use a reverse proxy (like Caddy/Nginx):
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Using Caddy (automatic HTTPS)
|
|
||||||
caddy reverse-proxy --from yourdomain.com --to localhost:80
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Production Recommendations
|
|
||||||
|
|
||||||
**Security:**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Generate strong SECRET_KEY
|
|
||||||
openssl rand -hex 32
|
|
||||||
|
|
||||||
# Set secure admin password
|
|
||||||
ADMIN_PASSWORD=your-very-secure-password
|
|
||||||
```
|
|
||||||
|
|
||||||
**Resource limits** - Add to `docker-compose.yml`:
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
services:
|
|
||||||
backend:
|
|
||||||
deploy:
|
|
||||||
resources:
|
|
||||||
limits:
|
|
||||||
cpus: '2'
|
|
||||||
memory: 2G
|
|
||||||
reservations:
|
|
||||||
cpus: '0.5'
|
|
||||||
memory: 512M
|
|
||||||
```
|
|
||||||
|
|
||||||
**Log management:**
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
services:
|
|
||||||
backend:
|
|
||||||
logging:
|
|
||||||
driver: "json-file"
|
|
||||||
options:
|
|
||||||
max-size: "100m"
|
|
||||||
max-file: "3"
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Docker Troubleshooting
|
|
||||||
|
|
||||||
**Frontend can't connect to backend:**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker-compose logs backend
|
|
||||||
curl http://localhost:5000/api/health
|
|
||||||
```
|
|
||||||
|
|
||||||
**Database connection issues:**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Check PostgreSQL container status
|
|
||||||
docker-compose logs postgres
|
|
||||||
|
|
||||||
# Verify PostgreSQL is ready
|
|
||||||
docker exec quantdinger-db pg_isready -U quantdinger
|
|
||||||
|
|
||||||
# Connect to database manually
|
|
||||||
docker exec -it quantdinger-db psql -U quantdinger -d quantdinger
|
|
||||||
```
|
|
||||||
|
|
||||||
**Build failures:**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Clear Docker cache and rebuild
|
|
||||||
docker-compose build --no-cache
|
|
||||||
```
|
|
||||||
|
|
||||||
**Out of memory:**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Check memory usage
|
|
||||||
docker stats
|
|
||||||
|
|
||||||
# Add swap space (Linux)
|
|
||||||
sudo fallocate -l 2G /swapfile
|
|
||||||
sudo chmod 600 /swapfile
|
|
||||||
sudo mkswap /swapfile
|
|
||||||
sudo swapon /swapfile
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Updating
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Pull latest code
|
|
||||||
git pull
|
|
||||||
|
|
||||||
# Rebuild and restart
|
|
||||||
docker-compose up -d --build
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Backup
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Backup PostgreSQL database
|
|
||||||
docker exec quantdinger-db pg_dump -U quantdinger quantdinger > backup/quantdinger_$(date +%Y%m%d).sql
|
|
||||||
|
|
||||||
# Backup configuration
|
|
||||||
cp backend_api_python/.env backup/.env_$(date +%Y%m%d)
|
|
||||||
|
|
||||||
# Restore database (if needed)
|
|
||||||
cat backup/quantdinger_YYYYMMDD.sql | docker exec -i quantdinger-db psql -U quantdinger quantdinger
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Option 2: Local Development
|
|
||||||
|
|
||||||
**Prerequisites**
|
|
||||||
|
|
||||||
- Python 3.10+ recommended
|
|
||||||
- Node.js 16+ recommended
|
|
||||||
- PostgreSQL 14+ installed and running
|
|
||||||
|
|
||||||
#### 1. Setup PostgreSQL
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Create database and user
|
|
||||||
sudo -u postgres psql
|
|
||||||
CREATE DATABASE quantdinger;
|
|
||||||
CREATE USER quantdinger WITH ENCRYPTED PASSWORD 'your_password';
|
|
||||||
GRANT ALL PRIVILEGES ON DATABASE quantdinger TO quantdinger;
|
|
||||||
\q
|
|
||||||
|
|
||||||
# Initialize schema
|
|
||||||
psql -U quantdinger -d quantdinger -f backend_api_python/migrations/init.sql
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 2. Start the backend (Flask API)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd backend_api_python
|
|
||||||
pip install -r requirements.txt
|
|
||||||
cp env.example .env # Windows: copy env.example .env
|
|
||||||
```
|
|
||||||
|
|
||||||
Edit `.env` and set:
|
|
||||||
```bash
|
|
||||||
DATABASE_URL=postgresql://quantdinger:your_password@localhost:5432/quantdinger
|
|
||||||
SECRET_KEY=your-secret-key
|
|
||||||
ADMIN_USER=quantdinger
|
|
||||||
ADMIN_PASSWORD=123456
|
|
||||||
```
|
|
||||||
|
|
||||||
Then start:
|
|
||||||
```bash
|
|
||||||
python run.py
|
|
||||||
```
|
|
||||||
|
|
||||||
Backend will be available at `http://localhost:5000`.
|
|
||||||
|
|
||||||
#### 2. Start the frontend (Vue UI)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd quantdinger_vue
|
|
||||||
npm install
|
|
||||||
npm run serve
|
|
||||||
```
|
|
||||||
|
|
||||||
Frontend dev server runs at `http://localhost:8000` and proxies `/api/*` to `http://localhost:5000` (see `quantdinger_vue/vue.config.js`).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Configuration (.env)
|
|
||||||
|
|
||||||
Use `backend_api_python/env.example` as a template. Common settings include:
|
|
||||||
|
|
||||||
- **Auth**: `SECRET_KEY`, `ADMIN_USER`, `ADMIN_PASSWORD`
|
|
||||||
- **Server**: `PYTHON_API_HOST`, `PYTHON_API_PORT`, `PYTHON_API_DEBUG`
|
|
||||||
- **Database**: `DATABASE_URL` (PostgreSQL connection string)
|
|
||||||
- **AI / LLM**: `LLM_PROVIDER` (openrouter/openai/google/deepseek/grok), provider-specific API keys
|
|
||||||
- **OAuth**: `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`
|
|
||||||
- **Security**: `TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY`, `ENABLE_REGISTRATION`
|
|
||||||
- **Web search**: `SEARCH_PROVIDER`, `SEARCH_GOOGLE_*`, `SEARCH_BING_API_KEY`
|
|
||||||
- **Order Execution**: `ORDER_MODE` (maker/market), `MAKER_WAIT_SEC`, `MAKER_OFFSET_BPS`
|
|
||||||
- **Proxy (optional)**: `PROXY_PORT` or `PROXY_URL`
|
|
||||||
- **Workers**: `ENABLE_PENDING_ORDER_WORKER`, `ENABLE_PORTFOLIO_MONITOR`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### API
|
|
||||||
|
|
||||||
The backend provides REST endpoints for login, market data, indicators, backtesting, strategies, and AI analysis.
|
|
||||||
|
|
||||||
- Health: `GET /health` (also supports `GET /api/health` for deployment probes)
|
|
||||||
- Auth (frontend-compatible): `POST /api/user/login`, `POST /api/user/logout`, `GET /api/user/info`
|
|
||||||
|
|
||||||
For the full route list, see `backend_api_python/app/routes/`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### License
|
|
||||||
|
|
||||||
Licensed under the **Apache License 2.0**. See `LICENSE`.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🤝 Community & Support
|
## 🤝 Community & Support
|
||||||
|
|
||||||
- **Contributing**: [Contributing Guide](CONTRIBUTING.md) · [Contributors](CONTRIBUTORS.md)
|
|
||||||
- **Telegram**: [QuantDinger Group](https://t.me/quantdinger)
|
- **Telegram**: [QuantDinger Group](https://t.me/quantdinger)
|
||||||
- **Discord**: [Join Server](https://discord.gg/vwJ8zxFh9Q)
|
- **Discord**: [Join Server](https://discord.gg/vwJ8zxFh9Q)
|
||||||
- **📺 Video Demo**: [Project Introduction](https://youtu.be/HPTVpqL7knM)
|
|
||||||
- **YouTube**: [@quantdinger](https://youtube.com/@quantdinger)
|
|
||||||
- **Email**: [brokermr810@gmail.com](mailto:brokermr810@gmail.com)
|
|
||||||
- **GitHub Issues**: [Report bugs / Request features](https://github.com/brokermr810/QuantDinger/issues)
|
- **GitHub Issues**: [Report bugs / Request features](https://github.com/brokermr810/QuantDinger/issues)
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 💼 Commercial License & Sponsorship
|
|
||||||
|
|
||||||
QuantDinger is licensed under **Apache License 2.0** (code). However, **Apache 2.0 does NOT grant trademark rights**. Our branding assets (name/logo) are protected as trademarks and are governed separately from the code license:
|
|
||||||
|
|
||||||
- **Copyright/Attribution**: You must keep required copyright and license notices (including any NOTICE/attribution in the repo and in the UI where applicable).
|
|
||||||
- **Trademarks (Name/Logo/Branding)**: Without permission, you may not modify QuantDinger branding (name/logo/UI brand), or use it to imply endorsement or misrepresent origin. If you redistribute a modified version, you should remove QuantDinger branding and rebrand unless you have a commercial license.
|
|
||||||
|
|
||||||
If you need to keep/modify QuantDinger branding in a redistribution (including UI branding and logo usage), please contact us for a **commercial license**.
|
|
||||||
|
|
||||||
See: `TRADEMARKS.md`
|
|
||||||
|
|
||||||
### What you get with a Commercial License
|
|
||||||
|
|
||||||
- **Commercial authorization** to modify branding/copyright display as agreed
|
|
||||||
- **Operations support**: deployment, upgrades, incident support, and maintenance guidance
|
|
||||||
- **Consulting services**: architecture review, performance tuning, strategy workflow consulting
|
|
||||||
- **Sponsorship options**: become a project sponsor and we can **display your logo/ad** (README/website/in-app placement as agreed)
|
|
||||||
|
|
||||||
### Contact
|
|
||||||
|
|
||||||
- **Telegram**: `https://t.me/worldinbroker`
|
|
||||||
- **Email**: [brokermr810@gmail.com](mailto:brokermr810@gmail.com)
|
- **Email**: [brokermr810@gmail.com](mailto:brokermr810@gmail.com)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 💼 Trusted Exchange Partners (Affiliate Links)
|
## 💝 Support the Project
|
||||||
|
|
||||||
By using our partner links, you support QuantDinger's development while enjoying the same trading experience.
|
|
||||||
|
|
||||||
<div align="center">
|
|
||||||
<table>
|
|
||||||
<tr>
|
|
||||||
<td align="center" width="33.33%">
|
|
||||||
<a href="https://www.bmwweb.ac/referral/earn-together/refer2earn-usdc/claim?hl=zh-CN&ref=GRO_28502_9OSOJ" target="_blank">
|
|
||||||
<img src="https://img.shields.io/badge/Binance-Exchange-F0B90B?style=for-the-badge&logo=binance&logoColor=white" alt="Binance" />
|
|
||||||
</a>
|
|
||||||
<br/><br/>
|
|
||||||
<strong>World's Largest Crypto Exchange</strong><br/>
|
|
||||||
<small>Spot • Futures • Margin Trading</small>
|
|
||||||
</td>
|
|
||||||
<td align="center" width="33.33%">
|
|
||||||
<a href="https://www.bjwebptyiou.com/join/14449926" target="_blank">
|
|
||||||
<img src="https://img.shields.io/badge/OKX-Exchange-000000?style=for-the-badge&logo=okx&logoColor=white" alt="OKX" />
|
|
||||||
</a>
|
|
||||||
<br/><br/>
|
|
||||||
<strong>Leading Derivatives Platform</strong><br/>
|
|
||||||
<small>Spot • Perpetual • Options</small>
|
|
||||||
</td>
|
|
||||||
<td align="center" width="33.33%">
|
|
||||||
<a href="https://share.glassgs.com/u/H8XZGS71" target="_blank">
|
|
||||||
<img src="https://img.shields.io/badge/Bitget-Exchange-1F2937?style=for-the-badge&logo=bitget&logoColor=white" alt="Bitget" />
|
|
||||||
</a>
|
|
||||||
<br/><br/>
|
|
||||||
<strong>Innovative Copy Trading</strong><br/>
|
|
||||||
<small>Spot • Futures • Social Trading</small>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 💝 Direct Support (Donations)
|
|
||||||
|
|
||||||
Your contributions help us maintain and improve QuantDinger.
|
|
||||||
|
|
||||||
**Crypto Donations (ERC-20 / BEP-20 / Polygon / Arbitrum)**
|
**Crypto Donations (ERC-20 / BEP-20 / Polygon / Arbitrum)**
|
||||||
|
|
||||||
@@ -856,47 +298,19 @@ Your contributions help us maintain and improve QuantDinger.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 🎓 Supporting Partners
|
## 🎓 Supporting Partners
|
||||||
|
|
||||||
We are proud to be supported by academic institutions and organizations advancing quantitative finance education and research.
|
|
||||||
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
<table>
|
|
||||||
<tr>
|
|
||||||
<td align="center" width="50%">
|
|
||||||
<a href="https://beinvolved.indiana.edu/organization/quantfiniu" target="_blank">
|
<a href="https://beinvolved.indiana.edu/organization/quantfiniu" target="_blank">
|
||||||
<img src="docs/screenshots/qfs_logo.png" alt="Indiana University Quantitative Finance Society" width="280" style="border-radius: 8px;">
|
<img src="docs/screenshots/qfs_logo.png" alt="QFS" width="200">
|
||||||
</a>
|
</a>
|
||||||
<br/><br/>
|
<br/>
|
||||||
<strong>Quantitative Finance Society (QFS)</strong><br/>
|
<strong>Quantitative Finance Society</strong><br/>
|
||||||
<small>Indiana University Bloomington</small><br/>
|
<small>Indiana University Bloomington</small>
|
||||||
<small>Fostering the next generation of quantitative finance professionals</small>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
> 💡 **Interested in becoming a supporting partner?** We welcome collaborations with universities, research institutions, and organizations. Contact us at [brokermr810@gmail.com](mailto:brokermr810@gmail.com) or via [Telegram](https://t.me/worldinbroker).
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Acknowledgements
|
## 🙏 Acknowledgements
|
||||||
|
|
||||||
QuantDinger stands on the shoulders of great open-source projects:
|
Built with [Flask](https://flask.palletsprojects.com/) · [Vue.js](https://vuejs.org/) · [CCXT](https://github.com/ccxt/ccxt) · [Pandas](https://pandas.pydata.org/) · [KlineCharts](https://github.com/klinecharts/KLineChart) · [Ant Design Vue](https://antdv.com/)
|
||||||
|
|
||||||
| Project | Description | Link |
|
|
||||||
|---------|-------------|------|
|
|
||||||
| **Flask** | Lightweight WSGI web framework | [flask.palletsprojects.com](https://flask.palletsprojects.com/) |
|
|
||||||
| **flask-cors** | Cross-Origin Resource Sharing extension | [GitHub](https://github.com/corydolphin/flask-cors) |
|
|
||||||
| **Pandas** | Data analysis and manipulation library | [pandas.pydata.org](https://pandas.pydata.org/) |
|
|
||||||
| **CCXT** | Cryptocurrency exchange trading library | [github.com/ccxt/ccxt](https://github.com/ccxt/ccxt) |
|
|
||||||
| **yfinance** | Yahoo Finance market data downloader | [github.com/ranaroussi/yfinance](https://github.com/ranaroussi/yfinance) |
|
|
||||||
| **akshare** | China financial data interface | [github.com/akfamily/akshare](https://github.com/akfamily/akshare) |
|
|
||||||
| **requests** | HTTP library for Python | [requests.readthedocs.io](https://requests.readthedocs.io/) |
|
|
||||||
| **Vue.js** | Progressive JavaScript framework | [vuejs.org](https://vuejs.org/) |
|
|
||||||
| **Ant Design Vue** | Enterprise-class UI components | [antdv.com](https://antdv.com/) |
|
|
||||||
| **KlineCharts** | Lightweight financial charting library | [github.com/klinecharts/KLineChart](https://github.com/klinecharts/KLineChart) |
|
|
||||||
| **Lightweight Charts** | TradingView charting library | [github.com/nicepkg/lightweight-charts](https://github.com/nicepkg/lightweight-charts) |
|
|
||||||
| **ECharts** | Apache data visualization library | [echarts.apache.org](https://echarts.apache.org/) |
|
|
||||||
|
|
||||||
Thanks to all maintainers and contributors across these ecosystems! ❤️
|
|
||||||
|
|||||||
+1
-37
@@ -381,6 +381,7 @@ QuantDinger 支持多种市场类型的执行方式:
|
|||||||
| KuCoin | 现货, 合约 |
|
| KuCoin | 现货, 合约 |
|
||||||
| Gate.io | 现货, 合约 |
|
| Gate.io | 现货, 合约 |
|
||||||
| Bitfinex | 现货, 衍生品 |
|
| Bitfinex | 现货, 衍生品 |
|
||||||
|
| Deepcoin | 现货, 永续 |
|
||||||
|
|
||||||
### 传统券商
|
### 传统券商
|
||||||
|
|
||||||
@@ -613,43 +614,6 @@ QuantDinger 的代码使用 **Apache License 2.0** 授权。但需要注意:**
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 💼 值得信赖的交易所合作伙伴(联盟链接)
|
|
||||||
|
|
||||||
使用我们的合作伙伴链接,在享受相同交易体验的同时支持 QuantDinger 的发展。
|
|
||||||
|
|
||||||
<div align="center">
|
|
||||||
<table>
|
|
||||||
<tr>
|
|
||||||
<td align="center" width="33.33%">
|
|
||||||
<a href="https://www.bmwweb.ac/referral/earn-together/refer2earn-usdc/claim?hl=zh-CN&ref=GRO_28502_9OSOJ" target="_blank">
|
|
||||||
<img src="https://img.shields.io/badge/Binance-Exchange-F0B90B?style=for-the-badge&logo=binance&logoColor=white" alt="Binance" />
|
|
||||||
</a>
|
|
||||||
<br/><br/>
|
|
||||||
<strong>全球最大的加密货币交易所</strong><br/>
|
|
||||||
<small>现货 • 期货 • 杠杆交易</small>
|
|
||||||
</td>
|
|
||||||
<td align="center" width="33.33%">
|
|
||||||
<a href="https://www.bjwebptyiou.com/join/14449926" target="_blank">
|
|
||||||
<img src="https://img.shields.io/badge/OKX-Exchange-000000?style=for-the-badge&logo=okx&logoColor=white" alt="OKX" />
|
|
||||||
</a>
|
|
||||||
<br/><br/>
|
|
||||||
<strong>领先的衍生品平台</strong><br/>
|
|
||||||
<small>现货 • 永续合约 • 期权</small>
|
|
||||||
</td>
|
|
||||||
<td align="center" width="33.33%">
|
|
||||||
<a href="https://share.glassgs.com/u/H8XZGS71" target="_blank">
|
|
||||||
<img src="https://img.shields.io/badge/Bitget-Exchange-1F2937?style=for-the-badge&logo=bitget&logoColor=white" alt="Bitget" />
|
|
||||||
</a>
|
|
||||||
<br/><br/>
|
|
||||||
<strong>创新的跟单交易</strong><br/>
|
|
||||||
<small>现货 • 期货 • 社交交易</small>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 💝 直接支持(捐赠)
|
### 💝 直接支持(捐赠)
|
||||||
|
|
||||||
你的贡献帮助我们维护和改进 QuantDinger。
|
你的贡献帮助我们维护和改进 QuantDinger。
|
||||||
|
|||||||
+1
-37
@@ -351,6 +351,7 @@ QuantDingerは複数の市場タイプに対して複数の実行方法をサポ
|
|||||||
| KuCoin | 現物, 先物 |
|
| KuCoin | 現物, 先物 |
|
||||||
| Gate.io | 現物, 先物 |
|
| Gate.io | 現物, 先物 |
|
||||||
| Bitfinex | 現物, デリバティブ |
|
| Bitfinex | 現物, デリバティブ |
|
||||||
|
| Deepcoin | 現物, 無期限 |
|
||||||
|
|
||||||
### 伝統的なブローカー
|
### 伝統的なブローカー
|
||||||
|
|
||||||
@@ -569,43 +570,6 @@ QuantDinger のコードは **Apache License 2.0** で提供されています
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 💼 取引所パートナー(アフィリエイトリンク)
|
|
||||||
|
|
||||||
パートナーリンクを使用することで、同じ取引体験を楽しみながら QuantDinger の開発を支援できます。
|
|
||||||
|
|
||||||
<div align="center">
|
|
||||||
<table>
|
|
||||||
<tr>
|
|
||||||
<td align="center" width="33.33%">
|
|
||||||
<a href="https://www.bmwweb.ac/referral/earn-together/refer2earn-usdc/claim?hl=zh-CN&ref=GRO_28502_9OSOJ" target="_blank">
|
|
||||||
<img src="https://img.shields.io/badge/Binance-Exchange-F0B90B?style=for-the-badge&logo=binance&logoColor=white" alt="Binance" />
|
|
||||||
</a>
|
|
||||||
<br/><br/>
|
|
||||||
<strong>世界最大の暗号通貨取引所</strong><br/>
|
|
||||||
<small>現物 • 先物 • マージン取引</small>
|
|
||||||
</td>
|
|
||||||
<td align="center" width="33.33%">
|
|
||||||
<a href="https://www.bjwebptyiou.com/join/14449926" target="_blank">
|
|
||||||
<img src="https://img.shields.io/badge/OKX-Exchange-000000?style=for-the-badge&logo=okx&logoColor=white" alt="OKX" />
|
|
||||||
</a>
|
|
||||||
<br/><br/>
|
|
||||||
<strong>主要なデリバティブプラットフォーム</strong><br/>
|
|
||||||
<small>現物 • パーペチュアル • オプション</small>
|
|
||||||
</td>
|
|
||||||
<td align="center" width="33.33%">
|
|
||||||
<a href="https://share.glassgs.com/u/H8XZGS71" target="_blank">
|
|
||||||
<img src="https://img.shields.io/badge/Bitget-Exchange-1F2937?style=for-the-badge&logo=bitget&logoColor=white" alt="Bitget" />
|
|
||||||
</a>
|
|
||||||
<br/><br/>
|
|
||||||
<strong>革新的なコピートレード</strong><br/>
|
|
||||||
<small>現物 • 先物 • ソーシャルトレード</small>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 💝 直接サポート(寄付)
|
### 💝 直接サポート(寄付)
|
||||||
|
|
||||||
あなたのご支援は QuantDinger の維持・改善に役立ちます。
|
あなたのご支援は QuantDinger の維持・改善に役立ちます。
|
||||||
|
|||||||
+1
-37
@@ -351,6 +351,7 @@ QuantDinger는 다양한 시장 유형에 대해 여러 실행 방법을 지원
|
|||||||
| KuCoin | 현물, 선물 |
|
| KuCoin | 현물, 선물 |
|
||||||
| Gate.io | 현물, 선물 |
|
| Gate.io | 현물, 선물 |
|
||||||
| Bitfinex | 현물, 파생상품 |
|
| Bitfinex | 현물, 파생상품 |
|
||||||
|
| Deepcoin | 현물, 무기한 |
|
||||||
|
|
||||||
### 전통적인 브로커
|
### 전통적인 브로커
|
||||||
|
|
||||||
@@ -582,43 +583,6 @@ QuantDinger의 코드는 **Apache License 2.0**으로 제공됩니다. 다만 **
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 💼 거래소 파트너(어필리에이트 링크)
|
|
||||||
|
|
||||||
파트너 링크를 사용하면 동일한 거래 경험을 즐기면서 QuantDinger의 개발을 지원할 수 있습니다.
|
|
||||||
|
|
||||||
<div align="center">
|
|
||||||
<table>
|
|
||||||
<tr>
|
|
||||||
<td align="center" width="33.33%">
|
|
||||||
<a href="https://www.bmwweb.ac/referral/earn-together/refer2earn-usdc/claim?hl=zh-CN&ref=GRO_28502_9OSOJ" target="_blank">
|
|
||||||
<img src="https://img.shields.io/badge/Binance-Exchange-F0B90B?style=for-the-badge&logo=binance&logoColor=white" alt="Binance" />
|
|
||||||
</a>
|
|
||||||
<br/><br/>
|
|
||||||
<strong>세계 최대 암호화폐 거래소</strong><br/>
|
|
||||||
<small>현물 • 선물 • 마진 거래</small>
|
|
||||||
</td>
|
|
||||||
<td align="center" width="33.33%">
|
|
||||||
<a href="https://www.bjwebptyiou.com/join/14449926" target="_blank">
|
|
||||||
<img src="https://img.shields.io/badge/OKX-Exchange-000000?style=for-the-badge&logo=okx&logoColor=white" alt="OKX" />
|
|
||||||
</a>
|
|
||||||
<br/><br/>
|
|
||||||
<strong>주요 파생상품 플랫폼</strong><br/>
|
|
||||||
<small>현물 • 영구 선물 • 옵션</small>
|
|
||||||
</td>
|
|
||||||
<td align="center" width="33.33%">
|
|
||||||
<a href="https://share.glassgs.com/u/H8XZGS71" target="_blank">
|
|
||||||
<img src="https://img.shields.io/badge/Bitget-Exchange-1F2937?style=for-the-badge&logo=bitget&logoColor=white" alt="Bitget" />
|
|
||||||
</a>
|
|
||||||
<br/><br/>
|
|
||||||
<strong>혁신적인 복사 거래</strong><br/>
|
|
||||||
<small>현물 • 선물 • 소셜 거래</small>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 💝 직접 지원(기부)
|
### 💝 직접 지원(기부)
|
||||||
|
|
||||||
귀하의 기여는 QuantDinger의 유지 및 개선에 도움이 됩니다.
|
귀하의 기여는 QuantDinger의 유지 및 개선에 도움이 됩니다.
|
||||||
|
|||||||
+1
-37
@@ -351,6 +351,7 @@ QuantDinger 支持多種市場類型的執行方式:
|
|||||||
| KuCoin | 現貨, 合約 |
|
| KuCoin | 現貨, 合約 |
|
||||||
| Gate.io | 現貨, 合約 |
|
| Gate.io | 現貨, 合約 |
|
||||||
| Bitfinex | 現貨, 衍生品 |
|
| Bitfinex | 現貨, 衍生品 |
|
||||||
|
| Deepcoin | 現貨, 永續 |
|
||||||
|
|
||||||
### 傳統券商
|
### 傳統券商
|
||||||
|
|
||||||
@@ -583,43 +584,6 @@ QuantDinger 的代碼使用 **Apache License 2.0** 授權。但請注意:**Apa
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 💼 值得信賴的交易所合作夥伴(聯盟鏈接)
|
|
||||||
|
|
||||||
使用我們的合作夥伴鏈接,在享受相同交易體驗的同時支持 QuantDinger 的發展。
|
|
||||||
|
|
||||||
<div align="center">
|
|
||||||
<table>
|
|
||||||
<tr>
|
|
||||||
<td align="center" width="33.33%">
|
|
||||||
<a href="https://www.bmwweb.ac/referral/earn-together/refer2earn-usdc/claim?hl=zh-CN&ref=GRO_28502_9OSOJ" target="_blank">
|
|
||||||
<img src="https://img.shields.io/badge/Binance-Exchange-F0B90B?style=for-the-badge&logo=binance&logoColor=white" alt="Binance" />
|
|
||||||
</a>
|
|
||||||
<br/><br/>
|
|
||||||
<strong>全球最大的加密貨幣交易所</strong><br/>
|
|
||||||
<small>現貨 • 期貨 • 槓桿交易</small>
|
|
||||||
</td>
|
|
||||||
<td align="center" width="33.33%">
|
|
||||||
<a href="https://www.bjwebptyiou.com/join/14449926" target="_blank">
|
|
||||||
<img src="https://img.shields.io/badge/OKX-Exchange-000000?style=for-the-badge&logo=okx&logoColor=white" alt="OKX" />
|
|
||||||
</a>
|
|
||||||
<br/><br/>
|
|
||||||
<strong>領先的衍生品平台</strong><br/>
|
|
||||||
<small>現貨 • 永續合約 • 期權</small>
|
|
||||||
</td>
|
|
||||||
<td align="center" width="33.33%">
|
|
||||||
<a href="https://share.glassgs.com/u/H8XZGS71" target="_blank">
|
|
||||||
<img src="https://img.shields.io/badge/Bitget-Exchange-1F2937?style=for-the-badge&logo=bitget&logoColor=white" alt="Bitget" />
|
|
||||||
</a>
|
|
||||||
<br/><br/>
|
|
||||||
<strong>創新的跟單交易</strong><br/>
|
|
||||||
<small>現貨 • 期貨 • 社交交易</small>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 💝 直接支持(捐贈)
|
### 💝 直接支持(捐贈)
|
||||||
|
|
||||||
你的貢獻幫助我們維護和改進 QuantDinger。
|
你的貢獻幫助我們維護和改進 QuantDinger。
|
||||||
|
|||||||
@@ -0,0 +1,640 @@
|
|||||||
|
"""
|
||||||
|
Deepcoin (direct REST) client for spot / perpetual swap orders.
|
||||||
|
|
||||||
|
Based on official Deepcoin Python SDK example.
|
||||||
|
API Base URL: https://api.deepcoin.com
|
||||||
|
|
||||||
|
Signing:
|
||||||
|
- DC-ACCESS-SIGN = base64(hmac_sha256(secret, timestamp + method + uri + body))
|
||||||
|
- For GET: message = timestamp + method + uri (with query params)
|
||||||
|
- For POST: message = timestamp + method + uri + json_body
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import datetime
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
from decimal import Decimal, ROUND_DOWN
|
||||||
|
from typing import Any, Dict, Optional, Tuple
|
||||||
|
from urllib.parse import urlencode
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from app.services.live_trading.base import BaseRestClient, LiveOrderResult, LiveTradingError
|
||||||
|
from app.services.live_trading.symbols import to_deepcoin_symbol
|
||||||
|
|
||||||
|
|
||||||
|
class DeepcoinClient(BaseRestClient):
|
||||||
|
"""
|
||||||
|
Deepcoin REST client for spot and perpetual swap trading.
|
||||||
|
|
||||||
|
Based on official Deepcoin Python SDK.
|
||||||
|
Supports both spot and swap (perpetual futures) markets.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
api_key: str,
|
||||||
|
secret_key: str,
|
||||||
|
passphrase: str = "",
|
||||||
|
base_url: str = "https://api.deepcoin.com",
|
||||||
|
timeout_sec: float = 15.0,
|
||||||
|
market_type: str = "swap", # "swap" (perpetual) or "spot"
|
||||||
|
):
|
||||||
|
super().__init__(base_url=base_url, timeout_sec=timeout_sec)
|
||||||
|
self.api_key = (api_key or "").strip()
|
||||||
|
self.secret_key = (secret_key or "").strip()
|
||||||
|
self.passphrase = (passphrase or "").strip()
|
||||||
|
self.market_type = (market_type or "swap").strip().lower()
|
||||||
|
if self.market_type not in ("swap", "spot"):
|
||||||
|
self.market_type = "swap"
|
||||||
|
|
||||||
|
if not self.api_key or not self.secret_key:
|
||||||
|
raise LiveTradingError("Missing Deepcoin api_key/secret_key")
|
||||||
|
|
||||||
|
# Best-effort cache for instrument metadata (qty step, min qty, etc.)
|
||||||
|
# Key: f"{market_type}:{symbol}" -> (fetched_at_ts, info_dict)
|
||||||
|
self._inst_cache: Dict[str, Tuple[float, Dict[str, Any]]] = {}
|
||||||
|
self._inst_cache_ttl_sec = 300.0
|
||||||
|
|
||||||
|
# Best-effort cache for leverage settings
|
||||||
|
self._lev_cache: Dict[str, Tuple[float, bool]] = {}
|
||||||
|
self._lev_cache_ttl_sec = 60.0
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _to_dec(x: Any) -> Decimal:
|
||||||
|
try:
|
||||||
|
return Decimal(str(x))
|
||||||
|
except Exception:
|
||||||
|
return Decimal("0")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _dec_str(d: Decimal) -> str:
|
||||||
|
try:
|
||||||
|
return format(d, "f")
|
||||||
|
except Exception:
|
||||||
|
return str(d)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _floor_to_step(value: Decimal, step: Decimal) -> Decimal:
|
||||||
|
if step is None:
|
||||||
|
return value
|
||||||
|
if value <= 0:
|
||||||
|
return Decimal("0")
|
||||||
|
try:
|
||||||
|
st = Decimal(step)
|
||||||
|
except Exception:
|
||||||
|
st = Decimal("0")
|
||||||
|
if st <= 0:
|
||||||
|
return value
|
||||||
|
try:
|
||||||
|
n = (value / st).to_integral_value(rounding=ROUND_DOWN)
|
||||||
|
return n * st
|
||||||
|
except Exception:
|
||||||
|
return Decimal("0")
|
||||||
|
|
||||||
|
def _get_iso_time(self) -> str:
|
||||||
|
"""
|
||||||
|
Generate ISO 8601 timestamp for Deepcoin API.
|
||||||
|
Format: 2024-07-29T11:12:00.123Z
|
||||||
|
"""
|
||||||
|
ticks = time.time()
|
||||||
|
localdate = datetime.datetime.utcfromtimestamp(ticks)
|
||||||
|
iso_time = localdate.isoformat()
|
||||||
|
# Ensure milliseconds and Z suffix
|
||||||
|
iso_time_change = iso_time[:23] + "Z"
|
||||||
|
return iso_time_change
|
||||||
|
|
||||||
|
def _build_uri_with_params(self, uri: str, params: Optional[Dict[str, Any]], method: str) -> str:
|
||||||
|
"""
|
||||||
|
Build URI with query parameters for GET requests.
|
||||||
|
For POST requests, return URI as-is.
|
||||||
|
"""
|
||||||
|
if method.upper() == "GET" and params and params != {}:
|
||||||
|
query_parts = []
|
||||||
|
for key, value in params.items():
|
||||||
|
query_parts.append(f"{key}={value}")
|
||||||
|
query_string = "&".join(query_parts)
|
||||||
|
return f"{uri}?{query_string}"
|
||||||
|
return uri
|
||||||
|
|
||||||
|
def _sign(self, iso_time: str, method: str, uri: str, data: Optional[Dict[str, Any]] = None) -> str:
|
||||||
|
"""
|
||||||
|
Generate HMAC-SHA256 signature for request authentication.
|
||||||
|
|
||||||
|
For POST: message = timestamp + method + uri + json_body
|
||||||
|
For GET: message = timestamp + method + uri (with query params)
|
||||||
|
"""
|
||||||
|
method_upper = method.upper()
|
||||||
|
if method_upper == "POST" and data:
|
||||||
|
# Convert dict to JSON string with double quotes
|
||||||
|
data_str = json.dumps(data, separators=(',', ':'))
|
||||||
|
message = f"{iso_time}{method_upper}{uri}{data_str}"
|
||||||
|
else:
|
||||||
|
message = f"{iso_time}{method_upper}{uri}"
|
||||||
|
|
||||||
|
message_bytes = message.encode('utf-8')
|
||||||
|
key_bytes = self.secret_key.encode('utf-8')
|
||||||
|
sign = base64.b64encode(
|
||||||
|
hmac.new(key=key_bytes, msg=message_bytes, digestmod=hashlib.sha256).digest()
|
||||||
|
).decode('utf-8')
|
||||||
|
return sign
|
||||||
|
|
||||||
|
def _headers(self, iso_time: str, sign: str) -> Dict[str, str]:
|
||||||
|
"""
|
||||||
|
Build authenticated request headers.
|
||||||
|
"""
|
||||||
|
headers = {
|
||||||
|
"DC-ACCESS-KEY": self.api_key,
|
||||||
|
"DC-ACCESS-SIGN": sign,
|
||||||
|
"DC-ACCESS-TIMESTAMP": iso_time,
|
||||||
|
"DC-ACCESS-PASSPHRASE": self.passphrase,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
}
|
||||||
|
return headers
|
||||||
|
|
||||||
|
def _public_request(self, method: str, uri: str, *, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Make public (unauthenticated) API request.
|
||||||
|
"""
|
||||||
|
full_uri = self._build_uri_with_params(uri, params, method)
|
||||||
|
url = f"{self.base_url}{full_uri}"
|
||||||
|
|
||||||
|
try:
|
||||||
|
if method.upper() == "GET":
|
||||||
|
resp = requests.get(url=url, timeout=self.timeout_sec)
|
||||||
|
else:
|
||||||
|
resp = requests.post(url=url, json=params, timeout=self.timeout_sec)
|
||||||
|
|
||||||
|
if resp.status_code >= 400:
|
||||||
|
raise LiveTradingError(f"Deepcoin HTTP {resp.status_code}: {resp.text[:500]}")
|
||||||
|
|
||||||
|
data = resp.json()
|
||||||
|
if isinstance(data, dict):
|
||||||
|
code = data.get("code") or data.get("retCode")
|
||||||
|
if code not in (0, "0", None, "", "00000"):
|
||||||
|
raise LiveTradingError(f"Deepcoin error: {data}")
|
||||||
|
return data if isinstance(data, dict) else {"raw": data}
|
||||||
|
except requests.RequestException as e:
|
||||||
|
raise LiveTradingError(f"Deepcoin request failed: {str(e)}")
|
||||||
|
|
||||||
|
def _signed_request(
|
||||||
|
self,
|
||||||
|
method: str,
|
||||||
|
uri: str,
|
||||||
|
*,
|
||||||
|
params: Optional[Dict[str, Any]] = None,
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Make authenticated API request following Deepcoin signing spec.
|
||||||
|
|
||||||
|
For GET requests: params are appended to URI as query string
|
||||||
|
For POST requests: params are sent as JSON body
|
||||||
|
"""
|
||||||
|
iso_time = self._get_iso_time()
|
||||||
|
method_upper = method.upper()
|
||||||
|
|
||||||
|
# Build full URI (with query params for GET)
|
||||||
|
full_uri = self._build_uri_with_params(uri, params, method)
|
||||||
|
|
||||||
|
# Generate signature
|
||||||
|
if method_upper == "POST":
|
||||||
|
sign = self._sign(iso_time, method_upper, uri, params)
|
||||||
|
else:
|
||||||
|
sign = self._sign(iso_time, method_upper, full_uri, None)
|
||||||
|
|
||||||
|
headers = self._headers(iso_time, sign)
|
||||||
|
url = f"{self.base_url}{full_uri}"
|
||||||
|
|
||||||
|
try:
|
||||||
|
if method_upper == "POST":
|
||||||
|
body_str = json.dumps(params, separators=(',', ':')) if params else ""
|
||||||
|
resp = requests.post(url=url, headers=headers, data=body_str, timeout=self.timeout_sec)
|
||||||
|
else:
|
||||||
|
resp = requests.get(url=url, headers=headers, timeout=self.timeout_sec)
|
||||||
|
|
||||||
|
if resp.status_code >= 400:
|
||||||
|
raise LiveTradingError(f"Deepcoin HTTP {resp.status_code}: {resp.text[:500]}")
|
||||||
|
|
||||||
|
data = resp.json()
|
||||||
|
if isinstance(data, dict):
|
||||||
|
code = data.get("code") or data.get("retCode")
|
||||||
|
if code not in (0, "0", None, "", "00000"):
|
||||||
|
raise LiveTradingError(f"Deepcoin error: {data}")
|
||||||
|
return data if isinstance(data, dict) else {"raw": data}
|
||||||
|
except requests.RequestException as e:
|
||||||
|
raise LiveTradingError(f"Deepcoin request failed: {str(e)}")
|
||||||
|
|
||||||
|
def ping(self) -> bool:
|
||||||
|
"""
|
||||||
|
Test API connectivity using public endpoint.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# Try public endpoint to check connectivity
|
||||||
|
url = f"{self.base_url}/deepcoin/market/time"
|
||||||
|
resp = requests.get(url=url, timeout=self.timeout_sec)
|
||||||
|
return resp.status_code == 200
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def get_balance(self) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Get account balance.
|
||||||
|
|
||||||
|
Endpoint: GET /deepcoin/account/balances
|
||||||
|
"""
|
||||||
|
params = {"instType": "SWAP" if self.market_type == "swap" else "SPOT"}
|
||||||
|
return self._signed_request("GET", "/deepcoin/account/balances", params=params)
|
||||||
|
|
||||||
|
def get_positions(self, *, symbol: str = "") -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Get open positions.
|
||||||
|
|
||||||
|
Endpoint: GET /deepcoin/account/positions
|
||||||
|
"""
|
||||||
|
params: Dict[str, Any] = {"instType": "SWAP" if self.market_type == "swap" else "SPOT"}
|
||||||
|
if symbol:
|
||||||
|
params["instId"] = to_deepcoin_symbol(symbol)
|
||||||
|
return self._signed_request("GET", "/deepcoin/account/positions", params=params)
|
||||||
|
|
||||||
|
def set_leverage(self, *, symbol: str, leverage: float, mgn_mode: str = "cross") -> bool:
|
||||||
|
"""
|
||||||
|
Set leverage for a trading pair.
|
||||||
|
|
||||||
|
Endpoint: POST /deepcoin/account/set-leverage
|
||||||
|
"""
|
||||||
|
sym = to_deepcoin_symbol(symbol)
|
||||||
|
if not sym:
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
lv = int(float(leverage or 1.0))
|
||||||
|
except Exception:
|
||||||
|
lv = 1
|
||||||
|
if lv < 1:
|
||||||
|
lv = 1
|
||||||
|
|
||||||
|
mm = str(mgn_mode or "cross").strip().lower()
|
||||||
|
if mm not in ("cross", "isolated"):
|
||||||
|
mm = "cross"
|
||||||
|
|
||||||
|
# Check cache
|
||||||
|
cache_key = f"{sym}:{mm}:{lv}"
|
||||||
|
now = time.time()
|
||||||
|
cached = self._lev_cache.get(cache_key)
|
||||||
|
if cached:
|
||||||
|
ts, ok = cached
|
||||||
|
if ok and (now - float(ts or 0.0)) <= float(self._lev_cache_ttl_sec or 60.0):
|
||||||
|
return True
|
||||||
|
|
||||||
|
params = {
|
||||||
|
"instId": sym,
|
||||||
|
"lever": str(lv),
|
||||||
|
"mgnMode": mm,
|
||||||
|
"mrgPosition": "merge",
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
self._signed_request("POST", "/deepcoin/account/set-leverage", params=params)
|
||||||
|
self._lev_cache[cache_key] = (now, True)
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def get_instrument_info(self, *, symbol: str) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Get instrument metadata (min qty, qty step, etc.).
|
||||||
|
|
||||||
|
Endpoint: GET /deepcoin/market/instruments
|
||||||
|
"""
|
||||||
|
sym = to_deepcoin_symbol(symbol)
|
||||||
|
if not sym:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
key = f"{self.market_type}:{sym}"
|
||||||
|
now = time.time()
|
||||||
|
cached = self._inst_cache.get(key)
|
||||||
|
if cached:
|
||||||
|
ts, obj = cached
|
||||||
|
if obj and (now - float(ts or 0.0)) <= float(self._inst_cache_ttl_sec or 300.0):
|
||||||
|
return obj
|
||||||
|
|
||||||
|
inst_type = "SWAP" if self.market_type == "swap" else "SPOT"
|
||||||
|
params = {"instType": inst_type, "instId": sym}
|
||||||
|
|
||||||
|
try:
|
||||||
|
raw = self._public_request("GET", "/deepcoin/market/instruments", params=params)
|
||||||
|
data = (raw.get("data") or []) if isinstance(raw, dict) else []
|
||||||
|
first: Dict[str, Any] = data[0] if isinstance(data, list) and data else {}
|
||||||
|
if isinstance(first, dict) and first:
|
||||||
|
self._inst_cache[key] = (now, first)
|
||||||
|
return first if isinstance(first, dict) else {}
|
||||||
|
except Exception:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def _normalize_qty(self, *, symbol: str, qty: float) -> Decimal:
|
||||||
|
"""
|
||||||
|
Normalize order quantity to exchange requirements.
|
||||||
|
"""
|
||||||
|
q = self._to_dec(qty)
|
||||||
|
if q <= 0:
|
||||||
|
return Decimal("0")
|
||||||
|
|
||||||
|
sym = to_deepcoin_symbol(symbol)
|
||||||
|
try:
|
||||||
|
info = self.get_instrument_info(symbol=sym) or {}
|
||||||
|
except Exception:
|
||||||
|
info = {}
|
||||||
|
|
||||||
|
# Extract lot size filter
|
||||||
|
step = self._to_dec(info.get("lotSz") or info.get("qtyStep") or "0")
|
||||||
|
mn = self._to_dec(info.get("minSz") or info.get("minOrderQty") or "0")
|
||||||
|
|
||||||
|
if step > 0:
|
||||||
|
q = self._floor_to_step(q, step)
|
||||||
|
if mn > 0 and q < mn:
|
||||||
|
return Decimal("0")
|
||||||
|
return q
|
||||||
|
|
||||||
|
def place_market_order(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
symbol: str,
|
||||||
|
side: str,
|
||||||
|
qty: float,
|
||||||
|
reduce_only: bool = False,
|
||||||
|
pos_side: str = "",
|
||||||
|
client_order_id: Optional[str] = None,
|
||||||
|
) -> LiveOrderResult:
|
||||||
|
"""
|
||||||
|
Place a market order.
|
||||||
|
|
||||||
|
Endpoint: POST /deepcoin/trade/order
|
||||||
|
|
||||||
|
Args:
|
||||||
|
symbol: Trading pair (e.g., "BTC/USDT:USDT" or "BTCUSDT")
|
||||||
|
side: "buy" or "sell"
|
||||||
|
qty: Order quantity in base currency
|
||||||
|
reduce_only: If True, only reduce position (for futures)
|
||||||
|
pos_side: Position side for hedge mode ("long" or "short")
|
||||||
|
client_order_id: Optional client order ID
|
||||||
|
"""
|
||||||
|
sym = to_deepcoin_symbol(symbol)
|
||||||
|
sd = (side or "").strip().lower()
|
||||||
|
if sd not in ("buy", "sell"):
|
||||||
|
raise LiveTradingError(f"Invalid side: {side}")
|
||||||
|
|
||||||
|
q_req = float(qty or 0.0)
|
||||||
|
q_dec = self._normalize_qty(symbol=symbol, qty=q_req)
|
||||||
|
if float(q_dec or 0) <= 0:
|
||||||
|
raise LiveTradingError(f"Invalid qty (below step/min): requested={q_req}")
|
||||||
|
|
||||||
|
params: Dict[str, Any] = {
|
||||||
|
"instId": sym,
|
||||||
|
"tdMode": "cash" if self.market_type == "spot" else "cross",
|
||||||
|
"side": sd,
|
||||||
|
"ordType": "market",
|
||||||
|
"sz": self._dec_str(q_dec),
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.market_type != "spot":
|
||||||
|
ps = (pos_side or "").strip().lower()
|
||||||
|
if ps in ("long", "short", "net"):
|
||||||
|
params["posSide"] = ps
|
||||||
|
if reduce_only:
|
||||||
|
params["reduceOnly"] = True
|
||||||
|
|
||||||
|
if client_order_id:
|
||||||
|
params["clOrdId"] = str(client_order_id)
|
||||||
|
|
||||||
|
raw = self._signed_request("POST", "/deepcoin/trade/order", params=params)
|
||||||
|
data = (raw.get("data") or []) if isinstance(raw, dict) else []
|
||||||
|
first: Dict[str, Any] = data[0] if isinstance(data, list) and data else {}
|
||||||
|
oid = str(first.get("ordId") or first.get("orderId") or first.get("clOrdId") or "")
|
||||||
|
|
||||||
|
return LiveOrderResult(
|
||||||
|
exchange_id="deepcoin",
|
||||||
|
exchange_order_id=oid,
|
||||||
|
filled=0.0,
|
||||||
|
avg_price=0.0,
|
||||||
|
raw=raw,
|
||||||
|
)
|
||||||
|
|
||||||
|
def place_limit_order(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
symbol: str,
|
||||||
|
side: str,
|
||||||
|
qty: float,
|
||||||
|
price: float,
|
||||||
|
reduce_only: bool = False,
|
||||||
|
pos_side: str = "",
|
||||||
|
client_order_id: Optional[str] = None,
|
||||||
|
) -> LiveOrderResult:
|
||||||
|
"""
|
||||||
|
Place a limit order.
|
||||||
|
|
||||||
|
Endpoint: POST /deepcoin/trade/order
|
||||||
|
"""
|
||||||
|
sym = to_deepcoin_symbol(symbol)
|
||||||
|
sd = (side or "").strip().lower()
|
||||||
|
if sd not in ("buy", "sell"):
|
||||||
|
raise LiveTradingError(f"Invalid side: {side}")
|
||||||
|
|
||||||
|
q_req = float(qty or 0.0)
|
||||||
|
px = float(price or 0.0)
|
||||||
|
if q_req <= 0 or px <= 0:
|
||||||
|
raise LiveTradingError("Invalid qty/price")
|
||||||
|
|
||||||
|
q_dec = self._normalize_qty(symbol=symbol, qty=q_req)
|
||||||
|
if float(q_dec or 0) <= 0:
|
||||||
|
raise LiveTradingError(f"Invalid qty (below step/min): requested={q_req}")
|
||||||
|
|
||||||
|
params: Dict[str, Any] = {
|
||||||
|
"instId": sym,
|
||||||
|
"tdMode": "cash" if self.market_type == "spot" else "cross",
|
||||||
|
"side": sd,
|
||||||
|
"ordType": "limit",
|
||||||
|
"sz": self._dec_str(q_dec),
|
||||||
|
"px": str(px),
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.market_type != "spot":
|
||||||
|
ps = (pos_side or "").strip().lower()
|
||||||
|
if ps in ("long", "short", "net"):
|
||||||
|
params["posSide"] = ps
|
||||||
|
if reduce_only:
|
||||||
|
params["reduceOnly"] = True
|
||||||
|
|
||||||
|
if client_order_id:
|
||||||
|
params["clOrdId"] = str(client_order_id)
|
||||||
|
|
||||||
|
raw = self._signed_request("POST", "/deepcoin/trade/order", params=params)
|
||||||
|
data = (raw.get("data") or []) if isinstance(raw, dict) else []
|
||||||
|
first: Dict[str, Any] = data[0] if isinstance(data, list) and data else {}
|
||||||
|
oid = str(first.get("ordId") or first.get("orderId") or first.get("clOrdId") or "")
|
||||||
|
|
||||||
|
return LiveOrderResult(
|
||||||
|
exchange_id="deepcoin",
|
||||||
|
exchange_order_id=oid,
|
||||||
|
filled=0.0,
|
||||||
|
avg_price=0.0,
|
||||||
|
raw=raw,
|
||||||
|
)
|
||||||
|
|
||||||
|
def cancel_order(self, *, symbol: str, order_id: str = "", client_order_id: str = "") -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Cancel an order.
|
||||||
|
|
||||||
|
Endpoint: POST /deepcoin/trade/cancel-order
|
||||||
|
"""
|
||||||
|
sym = to_deepcoin_symbol(symbol)
|
||||||
|
params: Dict[str, Any] = {"instId": sym}
|
||||||
|
|
||||||
|
if order_id:
|
||||||
|
params["ordId"] = str(order_id)
|
||||||
|
elif client_order_id:
|
||||||
|
params["clOrdId"] = str(client_order_id)
|
||||||
|
else:
|
||||||
|
raise LiveTradingError("Deepcoin cancel_order requires order_id or client_order_id")
|
||||||
|
|
||||||
|
return self._signed_request("POST", "/deepcoin/trade/cancel-order", params=params)
|
||||||
|
|
||||||
|
def get_order(self, *, symbol: str, order_id: str = "", client_order_id: str = "") -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Get order details.
|
||||||
|
|
||||||
|
Endpoint: GET /deepcoin/trade/order
|
||||||
|
"""
|
||||||
|
sym = to_deepcoin_symbol(symbol)
|
||||||
|
params: Dict[str, Any] = {"instId": sym}
|
||||||
|
|
||||||
|
if order_id:
|
||||||
|
params["ordId"] = str(order_id)
|
||||||
|
elif client_order_id:
|
||||||
|
params["clOrdId"] = str(client_order_id)
|
||||||
|
else:
|
||||||
|
raise LiveTradingError("Deepcoin get_order requires order_id or client_order_id")
|
||||||
|
|
||||||
|
resp = self._signed_request("GET", "/deepcoin/trade/order", params=params)
|
||||||
|
data = (resp.get("data") or []) if isinstance(resp, dict) else []
|
||||||
|
first: Dict[str, Any] = data[0] if isinstance(data, list) and data else {}
|
||||||
|
return first
|
||||||
|
|
||||||
|
def get_open_orders(self, *, symbol: str = "") -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Get open orders.
|
||||||
|
|
||||||
|
Endpoint: GET /deepcoin/trade/orders-pending
|
||||||
|
"""
|
||||||
|
params: Dict[str, Any] = {"instType": "SWAP" if self.market_type == "swap" else "SPOT"}
|
||||||
|
if symbol:
|
||||||
|
params["instId"] = to_deepcoin_symbol(symbol)
|
||||||
|
return self._signed_request("GET", "/deepcoin/trade/orders-pending", params=params)
|
||||||
|
|
||||||
|
def get_order_history(self, *, symbol: str = "", limit: int = 100) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Get order history.
|
||||||
|
|
||||||
|
Endpoint: GET /deepcoin/trade/orders-history
|
||||||
|
"""
|
||||||
|
params: Dict[str, Any] = {
|
||||||
|
"instType": "SWAP" if self.market_type == "swap" else "SPOT",
|
||||||
|
"limit": str(limit),
|
||||||
|
}
|
||||||
|
if symbol:
|
||||||
|
params["instId"] = to_deepcoin_symbol(symbol)
|
||||||
|
return self._signed_request("GET", "/deepcoin/trade/orders-history", params=params)
|
||||||
|
|
||||||
|
def wait_for_fill(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
symbol: str,
|
||||||
|
order_id: str = "",
|
||||||
|
client_order_id: str = "",
|
||||||
|
max_wait_sec: float = 3.0,
|
||||||
|
poll_interval_sec: float = 0.5,
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Poll order status until filled or timeout.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
{
|
||||||
|
"filled": float,
|
||||||
|
"avg_price": float,
|
||||||
|
"fee": float,
|
||||||
|
"fee_ccy": str,
|
||||||
|
"status": str,
|
||||||
|
"order": {...}
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
end_ts = time.time() + float(max_wait_sec or 0.0)
|
||||||
|
last: Dict[str, Any] = {}
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
last = self.get_order(
|
||||||
|
symbol=symbol,
|
||||||
|
order_id=str(order_id or ""),
|
||||||
|
client_order_id=str(client_order_id or ""),
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
last = last or {}
|
||||||
|
|
||||||
|
status = str(last.get("state") or last.get("status") or last.get("orderStatus") or "")
|
||||||
|
|
||||||
|
try:
|
||||||
|
filled = float(last.get("accFillSz") or last.get("fillSz") or last.get("cumExecQty") or 0.0)
|
||||||
|
except Exception:
|
||||||
|
filled = 0.0
|
||||||
|
|
||||||
|
try:
|
||||||
|
avg_price = float(last.get("avgPx") or last.get("fillPx") or last.get("avgPrice") or 0.0)
|
||||||
|
except Exception:
|
||||||
|
avg_price = 0.0
|
||||||
|
|
||||||
|
# Extract fee
|
||||||
|
fee = 0.0
|
||||||
|
fee_ccy = ""
|
||||||
|
try:
|
||||||
|
fee = abs(float(last.get("fee") or last.get("cumExecFee") or 0.0))
|
||||||
|
fee_ccy = str(last.get("feeCcy") or "")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if filled > 0 and avg_price > 0:
|
||||||
|
return {
|
||||||
|
"filled": filled,
|
||||||
|
"avg_price": avg_price,
|
||||||
|
"fee": fee,
|
||||||
|
"fee_ccy": fee_ccy,
|
||||||
|
"status": status,
|
||||||
|
"order": last,
|
||||||
|
}
|
||||||
|
|
||||||
|
if status.lower() in ("filled", "cancelled", "canceled", "rejected"):
|
||||||
|
return {
|
||||||
|
"filled": filled,
|
||||||
|
"avg_price": avg_price,
|
||||||
|
"fee": fee,
|
||||||
|
"fee_ccy": fee_ccy,
|
||||||
|
"status": status,
|
||||||
|
"order": last,
|
||||||
|
}
|
||||||
|
|
||||||
|
if time.time() >= end_ts:
|
||||||
|
return {
|
||||||
|
"filled": filled,
|
||||||
|
"avg_price": avg_price,
|
||||||
|
"fee": fee,
|
||||||
|
"fee_ccy": fee_ccy,
|
||||||
|
"status": status,
|
||||||
|
"order": last,
|
||||||
|
}
|
||||||
|
|
||||||
|
time.sleep(float(poll_interval_sec or 0.5))
|
||||||
@@ -24,6 +24,7 @@ from app.services.live_trading.kraken_futures import KrakenFuturesClient
|
|||||||
from app.services.live_trading.kucoin import KucoinSpotClient, KucoinFuturesClient
|
from app.services.live_trading.kucoin import KucoinSpotClient, KucoinFuturesClient
|
||||||
from app.services.live_trading.gate import GateSpotClient, GateUsdtFuturesClient
|
from app.services.live_trading.gate import GateSpotClient, GateUsdtFuturesClient
|
||||||
from app.services.live_trading.bitfinex import BitfinexClient, BitfinexDerivativesClient
|
from app.services.live_trading.bitfinex import BitfinexClient, BitfinexDerivativesClient
|
||||||
|
from app.services.live_trading.deepcoin import DeepcoinClient
|
||||||
|
|
||||||
# Lazy import IBKR to avoid ImportError if ib_insync not installed
|
# Lazy import IBKR to avoid ImportError if ib_insync not installed
|
||||||
IBKRClient = None
|
IBKRClient = None
|
||||||
@@ -114,6 +115,16 @@ def create_client(exchange_config: Dict[str, Any], *, market_type: str = "swap")
|
|||||||
return BitfinexClient(api_key=api_key, secret_key=secret_key, base_url=base_url)
|
return BitfinexClient(api_key=api_key, secret_key=secret_key, base_url=base_url)
|
||||||
return BitfinexDerivativesClient(api_key=api_key, secret_key=secret_key, base_url=base_url)
|
return BitfinexDerivativesClient(api_key=api_key, secret_key=secret_key, base_url=base_url)
|
||||||
|
|
||||||
|
if exchange_id == "deepcoin":
|
||||||
|
base_url = _get(exchange_config, "base_url", "baseUrl") or "https://api.deepcoin.com"
|
||||||
|
return DeepcoinClient(
|
||||||
|
api_key=api_key,
|
||||||
|
secret_key=secret_key,
|
||||||
|
passphrase=passphrase,
|
||||||
|
base_url=base_url,
|
||||||
|
market_type=mt,
|
||||||
|
)
|
||||||
|
|
||||||
# Traditional brokers (IBKR for US/HK stocks only)
|
# Traditional brokers (IBKR for US/HK stocks only)
|
||||||
if exchange_id == "ibkr":
|
if exchange_id == "ibkr":
|
||||||
# Note: Market category validation should be done at the caller level
|
# Note: Market category validation should be done at the caller level
|
||||||
|
|||||||
@@ -185,3 +185,38 @@ def to_bitfinex_perp_symbol(symbol: str) -> str:
|
|||||||
return f"t{base}F0:{q}F0"
|
return f"t{base}F0:{q}F0"
|
||||||
|
|
||||||
|
|
||||||
|
def to_deepcoin_symbol(symbol: str) -> str:
|
||||||
|
"""
|
||||||
|
Deepcoin symbol format: typically BASE-QUOTE for spot, BASE-QUOTE-SWAP for perpetual.
|
||||||
|
Examples:
|
||||||
|
- Spot: BTC-USDT
|
||||||
|
- Perpetual: BTC-USDT-SWAP
|
||||||
|
|
||||||
|
If symbol already contains '-', return as-is (already in Deepcoin format).
|
||||||
|
"""
|
||||||
|
s = (symbol or "").strip()
|
||||||
|
if not s:
|
||||||
|
return s
|
||||||
|
|
||||||
|
# Already in Deepcoin format
|
||||||
|
if "-" in s:
|
||||||
|
return s.upper()
|
||||||
|
|
||||||
|
base, quote = _split_base_quote(symbol)
|
||||||
|
if not base or not quote:
|
||||||
|
# Best effort: remove slashes and colons
|
||||||
|
return s.replace("/", "-").replace(":", "-").upper()
|
||||||
|
|
||||||
|
# Return BASE-QUOTE format (caller adds -SWAP if needed for futures)
|
||||||
|
return f"{base}-{quote}"
|
||||||
|
|
||||||
|
|
||||||
|
def to_deepcoin_swap_symbol(symbol: str) -> str:
|
||||||
|
"""
|
||||||
|
Deepcoin perpetual swap symbol format: BASE-QUOTE-SWAP, e.g. BTC-USDT-SWAP.
|
||||||
|
"""
|
||||||
|
base_symbol = to_deepcoin_symbol(symbol)
|
||||||
|
if base_symbol.endswith("-SWAP"):
|
||||||
|
return base_symbol
|
||||||
|
return f"{base_symbol}-SWAP"
|
||||||
|
|
||||||
|
|||||||
@@ -282,6 +282,7 @@ class StrategyService:
|
|||||||
from app.services.live_trading.kucoin import KucoinFuturesClient
|
from app.services.live_trading.kucoin import KucoinFuturesClient
|
||||||
from app.services.live_trading.gate import GateSpotClient, GateUsdtFuturesClient
|
from app.services.live_trading.gate import GateSpotClient, GateUsdtFuturesClient
|
||||||
from app.services.live_trading.bitfinex import BitfinexClient, BitfinexDerivativesClient
|
from app.services.live_trading.bitfinex import BitfinexClient, BitfinexDerivativesClient
|
||||||
|
from app.services.live_trading.deepcoin import DeepcoinClient
|
||||||
|
|
||||||
resolved = resolve_exchange_config(exchange_config or {})
|
resolved = resolve_exchange_config(exchange_config or {})
|
||||||
safe_cfg = safe_exchange_config_for_log(resolved)
|
safe_cfg = safe_exchange_config_for_log(resolved)
|
||||||
@@ -350,6 +351,8 @@ class StrategyService:
|
|||||||
priv_data = client.get_wallets()
|
priv_data = client.get_wallets()
|
||||||
elif isinstance(client, BitfinexDerivativesClient):
|
elif isinstance(client, BitfinexDerivativesClient):
|
||||||
priv_data = client.get_wallets()
|
priv_data = client.get_wallets()
|
||||||
|
elif isinstance(client, DeepcoinClient):
|
||||||
|
priv_data = client.get_balance()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
msg = str(e)
|
msg = str(e)
|
||||||
# Add actionable hints for the most common Binance auth error.
|
# Add actionable hints for the most common Binance auth error.
|
||||||
|
|||||||
@@ -1233,7 +1233,8 @@ const locale = {
|
|||||||
'ftxus': 'إف تي إكس الولايات المتحدة',
|
'ftxus': 'إف تي إكس الولايات المتحدة',
|
||||||
'binanceus': 'بينانس الولايات المتحدة',
|
'binanceus': 'بينانس الولايات المتحدة',
|
||||||
'binancecoinm': 'عملة بينانس-M',
|
'binancecoinm': 'عملة بينانس-M',
|
||||||
'binanceusdm': 'Binance USDⓈ-M'
|
'binanceusdm': 'Binance USDⓈ-M',
|
||||||
|
'deepcoin': 'ديبكوين'
|
||||||
},
|
},
|
||||||
'ai-trading-assistant.title': 'مساعد التداول بالذكاء الاصطناعي',
|
'ai-trading-assistant.title': 'مساعد التداول بالذكاء الاصطناعي',
|
||||||
'ai-trading-assistant.strategyList': 'قائمة الإستراتيجية',
|
'ai-trading-assistant.strategyList': 'قائمة الإستراتيجية',
|
||||||
|
|||||||
@@ -1283,7 +1283,8 @@ const locale = {
|
|||||||
'ftxus': 'FTX USA',
|
'ftxus': 'FTX USA',
|
||||||
'binanceus': 'Binance USA',
|
'binanceus': 'Binance USA',
|
||||||
'binancecoinm': 'Binance COIN-M',
|
'binancecoinm': 'Binance COIN-M',
|
||||||
'binanceusdm': 'Binance USDⓈ-M'
|
'binanceusdm': 'Binance USDⓈ-M',
|
||||||
|
'deepcoin': 'Deepcoin'
|
||||||
},
|
},
|
||||||
'ai-trading-assistant.title': 'KI-Handelsassistent',
|
'ai-trading-assistant.title': 'KI-Handelsassistent',
|
||||||
'ai-trading-assistant.strategyList': 'Strategieliste',
|
'ai-trading-assistant.strategyList': 'Strategieliste',
|
||||||
|
|||||||
@@ -1664,7 +1664,8 @@ const locale = {
|
|||||||
'binanceus': 'Binance US',
|
'binanceus': 'Binance US',
|
||||||
'binancecoinm': 'Binance COIN-M',
|
'binancecoinm': 'Binance COIN-M',
|
||||||
'binanceusdm': 'Binance USDⓈ-M',
|
'binanceusdm': 'Binance USDⓈ-M',
|
||||||
'ibkr': 'Interactive Brokers (IBKR)'
|
'ibkr': 'Interactive Brokers (IBKR)',
|
||||||
|
'deepcoin': 'Deepcoin'
|
||||||
},
|
},
|
||||||
'ai-trading-assistant.title': 'AI Trading Assistant',
|
'ai-trading-assistant.title': 'AI Trading Assistant',
|
||||||
'ai-trading-assistant.strategyList': 'Strategy List',
|
'ai-trading-assistant.strategyList': 'Strategy List',
|
||||||
|
|||||||
@@ -1234,7 +1234,8 @@ const locale = {
|
|||||||
'ftxus': 'FTX États-Unis',
|
'ftxus': 'FTX États-Unis',
|
||||||
'binanceus': 'Binance États-Unis',
|
'binanceus': 'Binance États-Unis',
|
||||||
'binancecoinm': 'Binance COIN-M',
|
'binancecoinm': 'Binance COIN-M',
|
||||||
'binanceusdm': 'Binance USDⓈ-M'
|
'binanceusdm': 'Binance USDⓈ-M',
|
||||||
|
'deepcoin': 'Deepcoin'
|
||||||
},
|
},
|
||||||
'ai-trading-assistant.title': 'Assistant de trading IA',
|
'ai-trading-assistant.title': 'Assistant de trading IA',
|
||||||
'ai-trading-assistant.strategyList': 'Liste de stratégies',
|
'ai-trading-assistant.strategyList': 'Liste de stratégies',
|
||||||
|
|||||||
@@ -1238,7 +1238,8 @@ const locale = {
|
|||||||
'ftxus': 'FTX米国',
|
'ftxus': 'FTX米国',
|
||||||
'binanceus': 'バイナンスUS',
|
'binanceus': 'バイナンスUS',
|
||||||
'binancecoinm': 'バイナンス COIN-M',
|
'binancecoinm': 'バイナンス COIN-M',
|
||||||
'binanceusdm': 'バイナンスUSDⓈ-M'
|
'binanceusdm': 'バイナンスUSDⓈ-M',
|
||||||
|
'deepcoin': 'ディープコイン'
|
||||||
},
|
},
|
||||||
'ai-trading-assistant.title': 'AI取引アシスタント',
|
'ai-trading-assistant.title': 'AI取引アシスタント',
|
||||||
'ai-trading-assistant.strategyList': '戦略一覧',
|
'ai-trading-assistant.strategyList': '戦略一覧',
|
||||||
|
|||||||
@@ -1238,7 +1238,8 @@ const locale = {
|
|||||||
'ftxus': 'FTX 미국',
|
'ftxus': 'FTX 미국',
|
||||||
'binanceus': '바이낸스 미국',
|
'binanceus': '바이낸스 미국',
|
||||||
'binancecoinm': '바이낸스 코인-M',
|
'binancecoinm': '바이낸스 코인-M',
|
||||||
'binanceusdm': '바이낸스 USDⓈ-M'
|
'binanceusdm': '바이낸스 USDⓈ-M',
|
||||||
|
'deepcoin': '딥코인'
|
||||||
},
|
},
|
||||||
'ai-trading-assistant.title': 'AI 트레이딩 도우미',
|
'ai-trading-assistant.title': 'AI 트레이딩 도우미',
|
||||||
'ai-trading-assistant.strategyList': '전략 목록',
|
'ai-trading-assistant.strategyList': '전략 목록',
|
||||||
|
|||||||
@@ -1235,7 +1235,8 @@ const locale = {
|
|||||||
'ftxus': 'FTX สหรัฐอเมริกา',
|
'ftxus': 'FTX สหรัฐอเมริกา',
|
||||||
'binanceus': 'Binance สหรัฐอเมริกา',
|
'binanceus': 'Binance สหรัฐอเมริกา',
|
||||||
'binancecoinm': 'Binance COIN-M',
|
'binancecoinm': 'Binance COIN-M',
|
||||||
'binanceusdm': 'Binance USDⓈ-M'
|
'binanceusdm': 'Binance USDⓈ-M',
|
||||||
|
'deepcoin': 'ดีพคอยน์'
|
||||||
},
|
},
|
||||||
'ai-trading-assistant.title': 'ผู้ช่วยการซื้อขาย AI',
|
'ai-trading-assistant.title': 'ผู้ช่วยการซื้อขาย AI',
|
||||||
'ai-trading-assistant.strategyList': 'รายการกลยุทธ์',
|
'ai-trading-assistant.strategyList': 'รายการกลยุทธ์',
|
||||||
|
|||||||
@@ -2376,7 +2376,9 @@ const locale = {
|
|||||||
|
|
||||||
'binancecoinm': 'Binance COIN-M',
|
'binancecoinm': 'Binance COIN-M',
|
||||||
|
|
||||||
'binanceusdm': 'Binance USDⓈ-M'
|
'binanceusdm': 'Binance USDⓈ-M',
|
||||||
|
|
||||||
|
'deepcoin': 'Deepcoin'
|
||||||
|
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
@@ -1559,7 +1559,8 @@ const locale = {
|
|||||||
'binanceus': 'Binance US',
|
'binanceus': 'Binance US',
|
||||||
'binancecoinm': 'Binance COIN-M',
|
'binancecoinm': 'Binance COIN-M',
|
||||||
'binanceusdm': 'Binance USDⓈ-M',
|
'binanceusdm': 'Binance USDⓈ-M',
|
||||||
'ibkr': '盈透证券 (IBKR)'
|
'ibkr': '盈透证券 (IBKR)',
|
||||||
|
'deepcoin': 'Deepcoin'
|
||||||
},
|
},
|
||||||
'ai-trading-assistant.title': 'AI交易助手',
|
'ai-trading-assistant.title': 'AI交易助手',
|
||||||
'ai-trading-assistant.strategyList': '策略列表',
|
'ai-trading-assistant.strategyList': '策略列表',
|
||||||
|
|||||||
@@ -1421,7 +1421,8 @@ const locale = {
|
|||||||
'ftxus': 'FTX US',
|
'ftxus': 'FTX US',
|
||||||
'binanceus': 'Binance US',
|
'binanceus': 'Binance US',
|
||||||
'binancecoinm': 'Binance COIN-M',
|
'binancecoinm': 'Binance COIN-M',
|
||||||
'binanceusdm': 'Binance USDⓈ-M'
|
'binanceusdm': 'Binance USDⓈ-M',
|
||||||
|
'deepcoin': 'Deepcoin'
|
||||||
},
|
},
|
||||||
'ai-trading-assistant.title': 'AI交易助手',
|
'ai-trading-assistant.title': 'AI交易助手',
|
||||||
'ai-trading-assistant.strategyList': '策略列表',
|
'ai-trading-assistant.strategyList': '策略列表',
|
||||||
|
|||||||
@@ -1255,7 +1255,8 @@ const EXCHANGE_OPTIONS = [
|
|||||||
{ value: 'kraken', labelKey: 'kraken' },
|
{ value: 'kraken', labelKey: 'kraken' },
|
||||||
{ value: 'kucoin', labelKey: 'kucoin' },
|
{ value: 'kucoin', labelKey: 'kucoin' },
|
||||||
{ value: 'gate', labelKey: 'gate' },
|
{ value: 'gate', labelKey: 'gate' },
|
||||||
{ value: 'bitfinex', labelKey: 'bitfinex' }
|
{ value: 'bitfinex', labelKey: 'bitfinex' },
|
||||||
|
{ value: 'deepcoin', labelKey: 'deepcoin' }
|
||||||
]
|
]
|
||||||
|
|
||||||
// Traditional broker options (US/HK stocks) - extensible for future brokers
|
// Traditional broker options (US/HK stocks) - extensible for future brokers
|
||||||
@@ -1289,7 +1290,7 @@ export default {
|
|||||||
},
|
},
|
||||||
needsPassphrase () {
|
needsPassphrase () {
|
||||||
// Exchanges that require passphrase
|
// Exchanges that require passphrase
|
||||||
return ['okx', 'okex', 'coinbaseexchange', 'kucoin', 'bitget'].includes(this.currentExchangeId)
|
return ['okx', 'okex', 'coinbaseexchange', 'kucoin', 'bitget', 'deepcoin'].includes(this.currentExchangeId)
|
||||||
},
|
},
|
||||||
// Check if current market uses IBKR (US Stock / HK Stock)
|
// Check if current market uses IBKR (US Stock / HK Stock)
|
||||||
isIBKRMarket () {
|
isIBKRMarket () {
|
||||||
|
|||||||
Reference in New Issue
Block a user