Z-Trading is a comprehensive algorithmic trading framework designed for High Frequency Trading (HFT) and multi-venue execution. Built on top of the powerful Zorro Trading Platform, it combines the speed and efficiency of compiled C algorithms with the flexibility of Python for data analysis, risk management, and visualization.
The framework provides asynchronous low-latency operations perfect for ultra-fast Market Making (MM) and Market Taking (MT) strategies. With over 361 pre-built algorithms and support for 25+ brokers and exchanges (including traditional markets like Interactive Brokers, OANDA, FXCM, and crypto exchanges like Binance, Bitfinex, Bittrex, Deribit, Kraken), Z-Trading enables traders to develop, backtest, and deploy robust quantitative strategies across multiple asset classes including forex, stocks, indices, commodities, bonds, cryptocurrencies, and derivatives.
Powered by the Zorro trading engine featuring:
- Ultra-low latency (~750ns in HFT mode)
- 300+ technical indicators and time series analysis functions
- World's fastest optimizer (25 seconds for 12 parameters)
- World's fastest tick-level backtester (0.3 seconds for 10 years)
- Machine learning integration (Torch, Keras, TensorFlow, MxNet)
- Support for 25+ brokers and exchanges
Includes 326 C strategies and 35 Python utilities covering:
- Trend Following: ALMA, EMA, HMA, Laguerre, and more
- Mean Reversion: Counter-trend and oscillator-based systems
- Machine Learning: Neural networks and pattern recognition (Alice series)
- Currency Strength: G12 multi-currency correlation system
- Market Making: High-frequency FX market making strategies
- Options Trading: Greeks calculation and volatility strategies
- Portfolio Management: MVO, OptimalF, and correlation-based allocation
- Economic Data: COT reports and fundamental analysis
- ⚡ High Frequency Trading - Ultra-low-latency C-based execution engine (~750ns latency)
- 💹 Multi-Venue Support - 25+ brokers and exchanges including:
- Traditional Markets: Interactive Brokers, OANDA, FXCM, Alpaca, Dukascopy, IG, Rithmic, TradeStation, Tradier
- Crypto Exchanges: Binance, Bitfinex, Bittrex, Deribit, Kraken, Coinigy
- Platform Connections: MetaTrader 4/5, IBKR TWS
- 📊 361+ Algorithms - Pre-built trading strategies and indicators
- 🐍 Python Bridge - Seamless integration between C and Python engines
- 🤖 Machine Learning - Torch, Keras, TensorFlow, MxNet integration
- 📈 Live Dashboards - Real-time monitoring via Google Sheets
- 🗄️ MySQL Database - Store and analyze historical trading data
- 💰 Risk Management - Advanced position sizing and portfolio optimization
- 🌍 Multi-Asset Support - Trade forex, stocks, indices, commodities, bonds, cryptocurrencies, and derivatives (options, futures)
- 🔄 Backtesting Engine - Test strategies with historical data
- ⚙️ Low-Latency Operations - Async execution for maximum speed
- 📉 Statistical Analysis - Volatility, correlation, and performance analytics
- 🤖 AI Integration - Compatible with Keras and PyTorch models
- 📊 Trade Profiling - Detailed performance metrics and visualization
- 🔐 Secure Configuration - Environment-based credentials management
- Open source interface for all API, REST, and FIX connections
- User-written custom plugins available
- AlphaVantage - Market data API
- CryptoCompare - Cryptocurrency data
- IEX - Exchange data feed
- DTN IQFeed - Professional real-time data
- Stooq - Historical market data
- Alpaca - Commission-free trading
- Dukascopy - Swiss forex bank
- Finvasia - Indian broker
- FXCM - Forex and CFD trading
- IG - Multi-asset broker
- Interactive Brokers - Professional trading platform
- Oanda - Forex and CFD broker
- Rithmic - Professional futures trading
- TDA/Schwab - US stocks and options
- TradeStation - Advanced trading platform
- Tradier - Brokerage API
- IBKR TWS - Interactive Brokers Trader Workstation
- MT4 - MetaTrader 4 platform
- MT5 - MetaTrader 5 platform
- Binance - World's largest crypto exchange
- Bitfinex - Advanced crypto trading
- Bittrex - US crypto exchange
- Coinigy - Multi-exchange platform
- Deribit - Crypto options and futures
- Kraken - Established crypto exchange
- Time Frames: From 1 millisecond to 1 week
- Multi-Connection: Simultaneous connection to multiple brokers and data feeds
- Account Management: Account/asset lists with symbol mapping and individual parameters
- Options/Combos: Full support for complex strategies
- Greeks Calculation: IV, Delta, Gamma, Theta, Vega, and all Greeks
- Multi-Leg Strategies: Advanced options combinations
- NFA/FIFO Compliance: Regulatory compliance built-in
- Virtual Hedging: For concurrent opposite positions
- Automated Training: Background training and optimizing while live trading
- Phantom Trades: Skip drawdown periods ("Equity Curve Trading")
- Special HFT Mode: Optimized for high frequency trading backtests
- Ultra-Low Latency: ~750ns execution latency
- World's Fastest Optimizer: 25 seconds for 12 parameters*
- World's Fastest Backtester: 0.3 seconds for 10 years at tick level*
- Standard: Time-based bars
- Range Bars: Price-range based
- Renko: Trend-following brick charts
- Point-and-Figure: Classic charting
- User-Defined: Custom bar types
- Ascent: Hill climbing optimization
- Brute Force: Exhaustive parameter search
- Genetic: Evolutionary algorithms
- User-Defined: Custom optimization methods
- Precise Broker Simulation: Fees, leverage, swaps, slippage modeling
- Oversampling & Detrending: On price, signal, or trade level
- Individual Optimization: Per portfolio component
- Capital Allocation: MVO (Mean-Variance Optimization) or OptimalF algorithms
- Walk Forward Analysis: Rolling and anchored methods
*Performance benchmarks may vary based on hardware and strategy complexity
- Zorro Trading Platform (version 1.68.62 or higher)
- Python 3.6+ with pip or poetry
- MySQL Server (optional, for database features)
- OANDA Account (for live trading)
- Google Cloud Service Account (for Sheets integration)
# Clone the repository
git clone https://github.com/alexcolls/z-trading.git
cd z-trading
# Install Python dependencies with Poetry (recommended)
poetry install
# Or with pip
pip install oandapyV20 pandas pygsheets gspread oauth2client sqlalchemy pymysql
# Configure environment variables
cp .env.sample .env
# Edit .env with your API credentials- Install Zorro: Extract the
engine/contents to your Zorro installation directory - Copy Algorithms: Place C scripts from
algos/into Zorro'sStrategy/folder - Configure APIs: Edit
Zorro.iniwith your broker credentials - Verify Installation: Run
engine/Zorro.exeand load a test strategy
Create a .env.sample file in the root directory:
# OANDA API Credentials
OANDA_TOKEN=your_oanda_api_token
OANDA_ACCOUNT_ID=your_account_id
# Google Sheets API
GOOGLE_SERVICE_ACCOUNT_FILE=path/to/service_account.json
GOOGLE_SHEET_NAME=TradingDashboard
# MySQL Database
MYSQL_HOST=localhost
MYSQL_USER=your_username
MYSQL_PASSWORD=your_password
MYSQL_DATABASE=trading_db
# Risk Management
HARD_STOP_PERCENT=2.0
INITIAL_BALANCE=10000- Create a Google Cloud Project and enable Google Sheets API
- Download service account JSON credentials
- Place credentials as
algos/GS_main.jsonandalgos/GS_trader1.json - Share your Google Sheet with the service account email
-- Create databases for statistics and correlations
CREATE DATABASE OandaEurope_Statistics;
CREATE DATABASE OandaEurope_Correlations;
-- Import schema (example)
USE OandaEurope_Statistics;
CREATE TABLE AvgVolatilities (
Symbol VARCHAR(20) PRIMARY KEY,
-- Add your columns for different timeframes
);// Example: Simple trend trading strategy
#include <profile.c>
function run()
{
vars Price = series(price());
vars Trend = series(LowPass(Price, 500));
Stop = 4*ATR(100);
if(valley(Trend))
enterLong();
else if(peak(Trend))
enterShort();
StartDate = 2020;
EndDate = 2024;
asset("EUR/USD");
set(LOGFILE);
}Run via Zorro GUI:
- Open
Zorro.exe - Select your script from the dropdown
- Choose Trade/Test/Train mode
- Click "Run"
# Start the trader dashboard
poetry run python algos/TraderDashboard.py
# Or directly with Python
python algos/TraderDashboard.pyThe dashboard will prompt for:
- OANDA API Token
- Account ID
- Google Sheet name
- Update frequency (seconds)
# Run the risk manager
poetry run python algos/RiskManager.pyThis calculates:
- Maximum position sizes per instrument
- Portfolio correlation adjustments
- Volatility-based sizing
- Exposure levels and warnings
from algos.OandaLib import Oanda_Prices, Oanda_Candles, GSapi
# Get real-time prices for all symbols
prices = Oanda_Prices(account_id, {'instruments': 'EUR_USD,GBP_USD'})
# Fetch historical candles
candles = Oanda_Candles('EUR_USD', {
'granularity': 'H1',
'count': 500
})
# Update Google Sheets
gs = GSapi('OandaEurope', 'Dashboard')
gs.update_value('A1', 'Hello Trading!')- Zorro Trading Platform - C-based trading engine and backtesting framework
- C Language - High-performance algorithm development
- Python 3.6+ - Data analysis, dashboards, and utilities
- OANDA v20 API - Market data and order execution
- Google Sheets API - Real-time dashboards and monitoring
- MySQL / SQLAlchemy - Data storage and retrieval
- Pandas - Time series analysis and data manipulation
- PyGsheets / Gspread - Google Sheets integration
z-trading/
├── algos/ # Trading algorithms and utilities (361 files)
│ ├── c/ # C trading strategies (326 files)
│ │ ├── Alice*.c # Alice strategy variations
│ │ ├── Allocation*.c # Portfolio allocation strategies
│ │ ├── BB*.c # Bollinger Band strategies
│ │ ├── Benchmark.c # Performance benchmarking
│ │ ├── BTCUSD*.c # Bitcoin trading strategies
│ │ ├── Deribittest.c # Deribit exchange testing
│ │ ├── CryptoFac*.c # Crypto factor strategies
│ │ └── ... # 320+ more strategies
│ ├── *.py # Python utilities (35 files)
│ │ ├── OandaLib.py # OANDA API wrapper
│ │ ├── TraderDashboard.py # Live trading monitor
│ │ ├── RiskManager.py # Position sizing & risk
│ │ ├── Correlations.py # Correlation analysis
│ │ ├── Volatility.py # Volatility calculations
│ │ └── GoogleService.py # Google Sheets integration
│ └── *.json # Service account credentials
│
├── engine/ # Zorro trading platform
│ ├── Zorro.exe # Main trading application
│ ├── Zview.exe # Chart viewer
│ ├── ZOptimizer.exe # Strategy optimizer
│ ├── *.dll # Required libraries
│ ├── include/ # C header files
│ │ ├── trading.h # Core trading functions
│ │ ├── functions.h # Math and indicators
│ │ ├── zorro.h # Platform API
│ │ └── ... # Additional headers
│ └── Plugin/ # Broker API plugins
│
├── .env.sample # Environment configuration template
├── LICENSE # Apache License 2.0
└── README.md # This file
Real-time trading dashboard that monitors:
- Account balance and NAV
- Open positions and P&L
- Margin usage and available capital
- Position sizing recommendations
- Updates Google Sheets automatically
Advanced risk management system featuring:
- Volatility-based position sizing
- Correlation-adjusted exposure limits
- Maximum position calculations per instrument
- Portfolio-level risk monitoring
- Integration with Google Sheets for live updates
Python wrapper for OANDA API providing:
- Real-time pricing for 120+ instruments
- Historical candlestick data
- Spread analysis
- Position management
- Google Sheets data export
Over 326 compiled C strategies including:
- Trend following (Alice series)
- Mean reversion
- Breakout systems
- Statistical arbitrage
- Machine learning integrations
- Custom indicators (Ehlers, Accelerator, etc.)
Major Pairs: EUR/USD, GBP/USD, USD/JPY, AUD/USD, NZD/USD, USD/CAD, USD/CHF
Cross Pairs: EUR/GBP, EUR/JPY, GBP/JPY, AUD/JPY, EUR/AUD, GBP/AUD, and more
Exotic Pairs: USD/CNH, USD/MXN, USD/TRY, USD/ZAR, USD/THB, USD/INR, etc.
- US: SPX500, NAS100, US30, US2000
- Europe: EU50, DE30, FR40, UK100, NL25
- Asia-Pacific: JP225, HK33, CN50, AU200, IN50, SG30, TWIX
- Energy: WTICO (Crude Oil), BCO (Brent), NATGAS (Natural Gas)
- Metals: XAU (Gold), XAG (Silver), XPT (Platinum), XPD (Palladium), XCU (Copper)
- Agriculture: CORN, WHEAT, SOYBN (Soybeans), SUGAR
- Major Cryptos: BTC/USD, ETH/USD, LTC/USD, XRP/USD, BCH/USD
- Crypto Derivatives: Bitcoin futures and options (via Deribit, Bitmex)
- Exchange Support: Binance, Bitfinex, Bittrex, Coinigy, Deribit, Kraken
- Trading Pairs: BTC/USDT, ETH/BTC, and 100+ crypto pairs
- US Treasuries: USB02Y, USB05Y, USB10Y, USB30Y
- European Bonds: DE10YB (German Bund), UK10YB (UK Gilt)
XAU/AUD, XAU/CAD, XAU/CHF, XAU/EUR, XAU/GBP, XAU/JPY, XAU/XAG, and more
Run historical simulations with the Zorro engine:
function run()
{
StartDate = 20200101; // YYYYMMDD format
EndDate = 20241231;
BarPeriod = 60; // 1-hour bars
// Your strategy logic here
set(LOGFILE | PLOTNOW);
}function run()
{
NumYears = 4;
NumWFOCycles = 10;
// Strategy parameters
var Period = optimize(20, 10, 100, 10);
set(WFO);
}# Train a model with historical data
from algos.DataFromC import load_zorro_data
import tensorflow as tf
# Load data exported from Zorro
df = load_zorro_data('EUR_USD.csv')
# Build and train your model
model = tf.keras.Sequential([...])
model.fit(X_train, y_train)
# Export predictions back to Zorro
model.predict(X_test).to_csv('predictions.csv')Run multiple strategies simultaneously with portfolio-level risk management:
// Portfolio manager script
function run()
{
// Allocate capital across strategies
Lots = PortfolioLots("Strategy1", 0.3);
Lots = PortfolioLots("Strategy2", 0.4);
Lots = PortfolioLots("Strategy3", 0.3);
}The integrated Google Sheets dashboards provide:
- Account Overview: Balance, NAV, P&L, margin usage
- Position Monitor: Live positions with entry price, current P&L, and size
- Risk Metrics: Exposure by instrument, correlation matrix, VAR calculations
- Performance Stats: Win rate, Sharpe ratio, max drawdown, profit factor
- Market Data: Real-time prices, spreads, volatility measures
Access your dashboard at your configured Google Sheet URL.
IMPORTANT: PLEASE READ CAREFULLY
Trading financial instruments involves substantial risk and may not be suitable for all investors. The high degree of leverage can work against you as well as for you. Before deciding to trade, you should carefully consider your investment objectives, level of experience, and risk appetite.
- 📉 Loss of Capital: You may lose some or all of your initial investment
- 💸 Leverage Risk: Leveraged trading can magnify both gains and losses
- 📊 Market Risk: Market volatility can result in rapid losses
- ⚙️ Technical Risk: Software bugs or system failures may impact trading
- 🌐 Liquidity Risk: Some instruments may have limited liquidity
- This software is provided for educational and research purposes only
- Past performance is not indicative of future results
- The authors and contributors are not liable for any trading losses
- Always conduct your own research and consult financial advisors
- Use at your own risk in live trading environments
- Comply with all applicable laws and regulations in your jurisdiction
By using this software, you acknowledge that you understand these risks and accept full responsibility for your trading decisions.
Contributions are welcome! Whether you want to:
- 🐛 Report bugs or issues
- 💡 Suggest new features or strategies
- 📝 Improve documentation
- 🔧 Submit code improvements
- 📊 Share trading strategies
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingStrategy) - Commit your changes (
git commit -m '✨ Add new momentum strategy') - Push to the branch (
git push origin feature/AmazingStrategy) - Open a Pull Request
- Follow C99 standards for algorithm development
- Use PEP 8 style guide for Python code
- Test strategies thoroughly in simulation before live trading
- Document your code with clear comments
- Never commit API keys or credentials
Copyright 2022 quantium
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
For the full license text, see LICENSE.
Built with:
- Zorro Trading Platform - Professional algorithmic trading software
- OANDA - Forex and CFD trading API
- Python - Data analysis and automation
- Pandas - Time series analysis
- Google Sheets API - Real-time dashboards
- MySQL - Database management
Special thanks to the algorithmic trading community for inspiration and support.
- Twitter: @fxmozart_sol
- Issues: GitHub Issues
- Discussions: GitHub Discussions
For collaboration opportunities, reach out via Twitter!
If this project helped you with your algorithmic trading journey, please consider:
- ⭐ Starring the repository
- 🐛 Reporting bugs and issues
- 💡 Suggesting new features
- 🤝 Contributing strategies
- 📢 Sharing with the trading community
- 💬 Joining discussions
Made with 💹 and ⚡ for Algorithmic Trading
Trade smarter, faster, and more efficiently
© 2022 Z-Trading | Apache License 2.0