The NIJA Trading Bot now includes a comprehensive trade ledger system that records every BUY/SELL transaction in a persistent SQLite database. This system provides:
trade_ledgerRecords every individual BUY/SELL transaction:
id: Unique transaction IDtimestamp: Transaction timestampuser_id: User identifier (default: ‘master’)symbol: Trading pair (e.g., ‘BTC-USD’)side: ‘BUY’ or ‘SELL’action: ‘OPEN’ or ‘CLOSE’price: Execution pricequantity: Asset quantitysize_usd: Position size in USDfee: Transaction feeorder_id: Broker order IDposition_id: Unique position identifiernotes: Additional notesopen_positionsTracks currently open positions:
position_id: Unique position identifieruser_id: User identifiersymbol: Trading pairside: ‘LONG’ or ‘SHORT’entry_price: Entry pricequantity: Position quantitysize_usd: Position size in USDstop_loss: Stop loss pricetake_profit_1/2/3: Take profit levelsentry_fee: Entry transaction feeentry_time: Position open timestampstatus: Position statuscompleted_tradesHistorical completed trades with P&L:
position_id: Unique position identifieruser_id: User identifiersymbol: Trading pairside: ‘LONG’ or ‘SHORT’entry_price: Entry priceexit_price: Exit pricequantity: Position quantitysize_usd: Position size in USDentry_fee: Entry transaction feeexit_fee: Exit transaction feetotal_fees: Combined feesgross_profit: Profit before feesnet_profit: Profit after feesprofit_pct: Profit percentageentry_time: Entry timestampexit_time: Exit timestampduration_seconds: Trade durationexit_reason: Reason for exitAll endpoints are available at http://localhost:5001/api/
GET /api/positions/open
Query Parameters:
user_id (optional): Filter by user IDsymbol (optional): Filter by trading symbolResponse:
{
"positions": [
{
"position_id": "BTC-USD_1705858800",
"symbol": "BTC-USD",
"side": "LONG",
"entry_price": 50000.0,
"quantity": 0.002,
"size_usd": 100.0,
"stop_loss": 49000.0,
"take_profit_1": 51000.0,
"entry_time": "2026-01-21T10:00:00",
"user_id": "master"
}
],
"count": 1,
"timestamp": "2026-01-21T16:30:00"
}
GET /api/trades/history
Query Parameters:
user_id (optional): Filter by user IDsymbol (optional): Filter by trading symbollimit (optional): Max results (default: 100)offset (optional): Pagination offsetResponse:
{
"trades": [
{
"position_id": "ETH-USD_1705858700",
"symbol": "ETH-USD",
"side": "LONG",
"entry_price": 3000.0,
"exit_price": 3100.0,
"size_usd": 100.0,
"net_profit": 2.79,
"profit_pct": 2.79,
"duration_seconds": 1800,
"exit_reason": "Take profit",
"exit_time": "2026-01-21T10:30:00"
}
],
"count": 1,
"statistics": {
"total_trades": 10,
"total_pnl": 45.67,
"win_rate": 70.0,
"winners": 7,
"losers": 3
},
"timestamp": "2026-01-21T16:30:00"
}
GET /api/trades/ledger
Query Parameters:
user_id (optional): Filter by user IDsymbol (optional): Filter by trading symbollimit (optional): Max results (default: 100)Response:
{
"transactions": [
{
"id": 1,
"timestamp": "2026-01-21T10:00:00",
"symbol": "BTC-USD",
"side": "BUY",
"action": "OPEN",
"price": 50000.0,
"quantity": 0.002,
"size_usd": 100.0,
"fee": 0.6,
"user_id": "master"
}
],
"count": 1
}
GET /api/trades/statistics
Query Parameters:
user_id (optional): Filter by user IDResponse:
{
"statistics": {
"total_trades": 10,
"total_pnl": 45.67,
"avg_pnl": 4.567,
"winners": 7,
"losers": 3,
"best_trade": 15.23,
"worst_trade": -8.45,
"total_fees": 12.00,
"open_positions": 2,
"win_rate": 70.0
},
"user_id": "master",
"timestamp": "2026-01-21T16:30:00"
}
GET /api/trades/export
Query Parameters:
format: ‘csv’ or ‘pdf’ (CSV only currently supported)table: ‘trade_ledger’, ‘open_positions’, or ‘completed_trades’user_id (optional): Filter by user IDResponse: Downloads a CSV file with the requested data.
Example:
curl "http://localhost:5001/api/trades/export?format=csv&table=completed_trades" -o trades.csv
Access the trade ledger dashboard at:
http://localhost:5000/trades
The trade ledger is automatically integrated into the execution engine:
from bot.execution_engine import ExecutionEngine
from bot.broker_manager import BrokerManager
# Initialize
broker = BrokerManager()
engine = ExecutionEngine(broker_client=broker, user_id='master')
# Execute a trade - automatically recorded in database
position = engine.execute_entry(
symbol='BTC-USD',
side='long',
position_size=100.0,
entry_price=50000.0,
stop_loss=49000.0,
take_profit_levels={'tp1': 51000.0, 'tp2': 52000.0, 'tp3': 53000.0}
)
# Close position - automatically recorded
engine.execute_exit(
symbol='BTC-USD',
exit_price=51000.0,
size_pct=1.0,
reason='Take profit hit'
)
By default, the database is stored at:
./data/trade_ledger.db
You can specify a different location:
from bot.trade_ledger_db import get_trade_ledger_db
db = get_trade_ledger_db('/custom/path/trade_ledger.db')
from bot.trade_ledger_db import get_trade_ledger_db
# Get database instance
db = get_trade_ledger_db()
# Get open positions
positions = db.get_open_positions(user_id='master')
for pos in positions:
print(f"{pos['symbol']}: ${pos['size_usd']:.2f} @ ${pos['entry_price']:.2f}")
# Get trade history
trades = db.get_trade_history(limit=10)
for trade in trades:
print(f"{trade['symbol']}: ${trade['net_profit']:.2f} ({trade['profit_pct']:.2f}%)")
# Get statistics
stats = db.get_statistics()
print(f"Win Rate: {stats['win_rate']:.1f}%")
print(f"Total P&L: ${stats['total_pnl']:.2f}")
# Export to CSV
csv_data = db.export_to_csv('completed_trades')
with open('trades_export.csv', 'w') as f:
f.write(csv_data)
.gitignore: data/trade_ledger.db# Create backup
cp data/trade_ledger.db data/trade_ledger_backup_$(date +%Y%m%d).db
# Or use SQLite backup command
sqlite3 data/trade_ledger.db ".backup data/trade_ledger_backup.db"
from bot.trade_ledger_db import get_trade_ledger_db
db = get_trade_ledger_db()
# Get database statistics
stats = db.get_statistics()
print(f"Total trades: {stats['total_trades']}")
# Note: Database is automatically optimized with indexes
# No manual maintenance required
If you get “database is locked” errors:
If trades aren’t appearing:
python bot/user_dashboard_api.pyFor issues or questions:
./logs/Last Updated: January 21, 2026 Version: 1.0 Author: NIJA Trading Systems