feat: implement complete automation system with real trading connection

This commit is contained in:
mindesbunister
2025-07-18 20:02:45 +02:00
parent 74b0087f17
commit 892c2c845f
18 changed files with 1930 additions and 16 deletions

Binary file not shown.

View File

@@ -0,0 +1,150 @@
-- CreateTable
CREATE TABLE "automation_sessions" (
"id" TEXT NOT NULL PRIMARY KEY,
"userId" TEXT NOT NULL,
"status" TEXT NOT NULL DEFAULT 'ACTIVE',
"mode" TEXT NOT NULL DEFAULT 'SIMULATION',
"symbol" TEXT NOT NULL,
"timeframe" TEXT NOT NULL,
"totalTrades" INTEGER NOT NULL DEFAULT 0,
"successfulTrades" INTEGER NOT NULL DEFAULT 0,
"failedTrades" INTEGER NOT NULL DEFAULT 0,
"totalPnL" REAL NOT NULL DEFAULT 0,
"totalPnLPercent" REAL NOT NULL DEFAULT 0,
"winRate" REAL NOT NULL DEFAULT 0,
"avgRiskReward" REAL NOT NULL DEFAULT 0,
"maxDrawdown" REAL NOT NULL DEFAULT 0,
"startBalance" REAL,
"currentBalance" REAL,
"settings" JSONB,
"lastAnalysis" DATETIME,
"lastTrade" DATETIME,
"nextScheduled" DATETIME,
"errorCount" INTEGER NOT NULL DEFAULT 0,
"lastError" TEXT,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL,
CONSTRAINT "automation_sessions_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
-- CreateTable
CREATE TABLE "ai_learning_data" (
"id" TEXT NOT NULL PRIMARY KEY,
"userId" TEXT NOT NULL,
"sessionId" TEXT,
"tradeId" TEXT,
"analysisData" JSONB NOT NULL,
"marketConditions" JSONB NOT NULL,
"outcome" TEXT,
"actualPrice" REAL,
"predictedPrice" REAL,
"confidenceScore" REAL,
"accuracyScore" REAL,
"timeframe" TEXT NOT NULL,
"symbol" TEXT NOT NULL,
"screenshot" TEXT,
"feedbackData" JSONB,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL,
CONSTRAINT "ai_learning_data_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
-- RedefineTables
PRAGMA defer_foreign_keys=ON;
PRAGMA foreign_keys=OFF;
CREATE TABLE "new_trades" (
"id" TEXT NOT NULL PRIMARY KEY,
"userId" TEXT NOT NULL,
"symbol" TEXT NOT NULL,
"side" TEXT NOT NULL,
"amount" REAL NOT NULL,
"price" REAL NOT NULL,
"status" TEXT NOT NULL DEFAULT 'PENDING',
"driftTxId" TEXT,
"profit" REAL,
"fees" REAL,
"screenshotUrl" TEXT,
"aiAnalysis" TEXT,
"isAutomated" BOOLEAN NOT NULL DEFAULT false,
"entryPrice" REAL,
"exitPrice" REAL,
"stopLoss" REAL,
"takeProfit" REAL,
"leverage" REAL,
"timeframe" TEXT,
"tradingMode" TEXT,
"confidence" REAL,
"marketSentiment" TEXT,
"outcome" TEXT,
"pnlPercent" REAL,
"actualRR" REAL,
"executionTime" DATETIME,
"learningData" JSONB,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL,
"executedAt" DATETIME,
"closedAt" DATETIME,
CONSTRAINT "trades_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO "new_trades" ("aiAnalysis", "amount", "closedAt", "createdAt", "driftTxId", "executedAt", "fees", "id", "price", "profit", "screenshotUrl", "side", "status", "symbol", "updatedAt", "userId") SELECT "aiAnalysis", "amount", "closedAt", "createdAt", "driftTxId", "executedAt", "fees", "id", "price", "profit", "screenshotUrl", "side", "status", "symbol", "updatedAt", "userId" FROM "trades";
DROP TABLE "trades";
ALTER TABLE "new_trades" RENAME TO "trades";
CREATE TABLE "new_trading_journals" (
"id" TEXT NOT NULL PRIMARY KEY,
"userId" TEXT NOT NULL,
"date" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"screenshotUrl" TEXT NOT NULL,
"aiAnalysis" TEXT NOT NULL,
"marketSentiment" TEXT,
"keyLevels" JSONB,
"recommendation" TEXT NOT NULL,
"confidence" REAL NOT NULL,
"notes" TEXT,
"isAutomated" BOOLEAN NOT NULL DEFAULT false,
"symbol" TEXT,
"timeframe" TEXT,
"tradingMode" TEXT,
"tradeId" TEXT,
"outcome" TEXT,
"actualPrice" REAL,
"priceAtAnalysis" REAL,
"accuracyScore" REAL,
"executionDelay" INTEGER,
"marketCondition" TEXT,
"sessionId" TEXT,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL,
CONSTRAINT "trading_journals_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO "new_trading_journals" ("aiAnalysis", "confidence", "createdAt", "date", "id", "keyLevels", "marketSentiment", "notes", "recommendation", "screenshotUrl", "updatedAt", "userId") SELECT "aiAnalysis", "confidence", "createdAt", "date", "id", "keyLevels", "marketSentiment", "notes", "recommendation", "screenshotUrl", "updatedAt", "userId" FROM "trading_journals";
DROP TABLE "trading_journals";
ALTER TABLE "new_trading_journals" RENAME TO "trading_journals";
CREATE TABLE "new_user_settings" (
"id" TEXT NOT NULL PRIMARY KEY,
"userId" TEXT NOT NULL,
"autoTrading" BOOLEAN NOT NULL DEFAULT false,
"tradingAmount" REAL NOT NULL DEFAULT 100,
"riskPercentage" REAL NOT NULL DEFAULT 2,
"maxDailyTrades" INTEGER NOT NULL DEFAULT 5,
"enableNotifications" BOOLEAN NOT NULL DEFAULT true,
"automationMode" TEXT NOT NULL DEFAULT 'SIMULATION',
"autoTimeframe" TEXT NOT NULL DEFAULT '1h',
"autoSymbol" TEXT NOT NULL DEFAULT 'SOLUSD',
"autoTradingEnabled" BOOLEAN NOT NULL DEFAULT false,
"autoAnalysisEnabled" BOOLEAN NOT NULL DEFAULT false,
"maxLeverage" REAL NOT NULL DEFAULT 3.0,
"stopLossPercent" REAL NOT NULL DEFAULT 2.0,
"takeProfitPercent" REAL NOT NULL DEFAULT 6.0,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL,
CONSTRAINT "user_settings_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO "new_user_settings" ("autoTrading", "createdAt", "enableNotifications", "id", "maxDailyTrades", "riskPercentage", "tradingAmount", "updatedAt", "userId") SELECT "autoTrading", "createdAt", "enableNotifications", "id", "maxDailyTrades", "riskPercentage", "tradingAmount", "updatedAt", "userId" FROM "user_settings";
DROP TABLE "user_settings";
ALTER TABLE "new_user_settings" RENAME TO "user_settings";
CREATE UNIQUE INDEX "user_settings_userId_key" ON "user_settings"("userId");
PRAGMA foreign_keys=ON;
PRAGMA defer_foreign_keys=OFF;
-- CreateIndex
CREATE UNIQUE INDEX "automation_sessions_userId_symbol_timeframe_key" ON "automation_sessions"("userId", "symbol", "timeframe");

BIN
prisma/prisma/dev.db Normal file

Binary file not shown.

View File

@@ -8,15 +8,17 @@ datasource db {
}
model User {
id String @id @default(cuid())
email String @unique
name String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
apiKeys ApiKey[]
trades Trade[]
journals TradingJournal[]
settings UserSettings?
id String @id @default(cuid())
email String @unique
name String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
apiKeys ApiKey[]
trades Trade[]
journals TradingJournal[]
settings UserSettings?
automationSessions AutomationSession[]
aiLearningData AILearningData[]
@@map("users")
}
@@ -44,6 +46,15 @@ model UserSettings {
riskPercentage Float @default(2)
maxDailyTrades Int @default(5)
enableNotifications Boolean @default(true)
// Automation settings
automationMode String @default("SIMULATION") // SIMULATION, LIVE
autoTimeframe String @default("1h")
autoSymbol String @default("SOLUSD")
autoTradingEnabled Boolean @default(false)
autoAnalysisEnabled Boolean @default(false)
maxLeverage Float @default(3.0)
stopLossPercent Float @default(2.0)
takeProfitPercent Float @default(6.0)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@ -64,6 +75,23 @@ model Trade {
fees Float?
screenshotUrl String?
aiAnalysis String?
// Automation fields
isAutomated Boolean @default(false)
entryPrice Float?
exitPrice Float?
stopLoss Float?
takeProfit Float?
leverage Float?
timeframe String?
tradingMode String? // SIMULATION, LIVE
confidence Float?
marketSentiment String?
// Learning fields
outcome String? // WIN, LOSS, BREAKEVEN
pnlPercent Float?
actualRR Float? // Actual risk/reward ratio
executionTime DateTime?
learningData Json? // Store additional learning data
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
executedAt DateTime?
@@ -84,6 +112,20 @@ model TradingJournal {
recommendation String
confidence Float
notes String?
// Automation fields
isAutomated Boolean @default(false)
symbol String?
timeframe String?
tradingMode String? // SIMULATION, LIVE
tradeId String? // Link to actual trade if executed
outcome String? // WIN, LOSS, BREAKEVEN, PENDING
actualPrice Float? // Actual price when trade was executed
priceAtAnalysis Float? // Price at time of analysis
// Learning fields
accuracyScore Float? // How accurate the prediction was
executionDelay Int? // Minutes between analysis and execution
marketCondition String? // TRENDING, RANGING, VOLATILE
sessionId String? // Link to automation session
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@ -112,3 +154,57 @@ model SystemLog {
@@map("system_logs")
}
model AutomationSession {
id String @id @default(cuid())
userId String
status String @default("ACTIVE") // ACTIVE, PAUSED, STOPPED
mode String @default("SIMULATION") // SIMULATION, LIVE
symbol String
timeframe String
totalTrades Int @default(0)
successfulTrades Int @default(0)
failedTrades Int @default(0)
totalPnL Float @default(0)
totalPnLPercent Float @default(0)
winRate Float @default(0)
avgRiskReward Float @default(0)
maxDrawdown Float @default(0)
startBalance Float?
currentBalance Float?
settings Json? // Store automation settings
lastAnalysis DateTime?
lastTrade DateTime?
nextScheduled DateTime?
errorCount Int @default(0)
lastError String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([userId, symbol, timeframe])
@@map("automation_sessions")
}
model AILearningData {
id String @id @default(cuid())
userId String
sessionId String?
tradeId String?
analysisData Json // Store the AI analysis
marketConditions Json // Store market conditions at time of analysis
outcome String? // WIN, LOSS, BREAKEVEN
actualPrice Float?
predictedPrice Float?
confidenceScore Float?
accuracyScore Float? // Calculated after outcome is known
timeframe String
symbol String
screenshot String? // Link to screenshot used for analysis
feedbackData Json? // Store feedback for learning
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@map("ai_learning_data")
}

View File

@@ -0,0 +1,210 @@
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
model User {
id String @id @default(cuid())
email String @unique
name String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
apiKeys ApiKey[]
trades Trade[]
journals TradingJournal[]
settings UserSettings?
automationSessions AutomationSession[]
aiLearningData AILearningData[]
@@map("users")
}
model ApiKey {
id String @id @default(cuid())
userId String
provider String
keyName String
encryptedKey String
isActive Boolean @default(true)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([userId, provider, keyName])
@@map("api_keys")
}
model UserSettings {
id String @id @default(cuid())
userId String @unique
autoTrading Boolean @default(false)
tradingAmount Float @default(100)
riskPercentage Float @default(2)
maxDailyTrades Int @default(5)
enableNotifications Boolean @default(true)
// Automation settings
automationMode String @default("SIMULATION") // SIMULATION, LIVE
autoTimeframe String @default("1h")
autoSymbol String @default("SOLUSD")
autoTradingEnabled Boolean @default(false)
autoAnalysisEnabled Boolean @default(false)
maxLeverage Float @default(3.0)
stopLossPercent Float @default(2.0)
takeProfitPercent Float @default(6.0)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@map("user_settings")
}
model Trade {
id String @id @default(cuid())
userId String
symbol String
side String
amount Float
price Float
status String @default("PENDING")
driftTxId String?
profit Float?
fees Float?
screenshotUrl String?
aiAnalysis String?
// Automation fields
isAutomated Boolean @default(false)
entryPrice Float?
exitPrice Float?
stopLoss Float?
takeProfit Float?
leverage Float?
timeframe String?
tradingMode String? // SIMULATION, LIVE
confidence Float?
marketSentiment String?
// Learning fields
outcome String? // WIN, LOSS, BREAKEVEN
pnlPercent Float?
actualRR Float? // Actual risk/reward ratio
executionTime DateTime?
learningData Json? // Store additional learning data
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
executedAt DateTime?
closedAt DateTime?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@map("trades")
}
model TradingJournal {
id String @id @default(cuid())
userId String
date DateTime @default(now())
screenshotUrl String
aiAnalysis String
marketSentiment String?
keyLevels Json?
recommendation String
confidence Float
notes String?
// Automation fields
isAutomated Boolean @default(false)
symbol String?
timeframe String?
tradingMode String? // SIMULATION, LIVE
tradeId String? // Link to actual trade if executed
outcome String? // WIN, LOSS, BREAKEVEN, PENDING
actualPrice Float? // Actual price when trade was executed
priceAtAnalysis Float? // Price at time of analysis
// Learning fields
accuracyScore Float? // How accurate the prediction was
executionDelay Int? // Minutes between analysis and execution
marketCondition String? // TRENDING, RANGING, VOLATILE
sessionId String? // Link to automation session
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@map("trading_journals")
}
model Screenshot {
id String @id @default(cuid())
url String
filename String
fileSize Int
mimeType String
metadata Json?
createdAt DateTime @default(now())
@@map("screenshots")
}
model SystemLog {
id String @id @default(cuid())
level String
message String
metadata Json?
createdAt DateTime @default(now())
@@map("system_logs")
}
model AutomationSession {
id String @id @default(cuid())
userId String
status String @default("ACTIVE") // ACTIVE, PAUSED, STOPPED
mode String @default("SIMULATION") // SIMULATION, LIVE
symbol String
timeframe String
totalTrades Int @default(0)
successfulTrades Int @default(0)
failedTrades Int @default(0)
totalPnL Float @default(0)
totalPnLPercent Float @default(0)
winRate Float @default(0)
avgRiskReward Float @default(0)
maxDrawdown Float @default(0)
startBalance Float?
currentBalance Float?
settings Json? // Store automation settings
lastAnalysis DateTime?
lastTrade DateTime?
nextScheduled DateTime?
errorCount Int @default(0)
lastError String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([userId, symbol, timeframe])
@@map("automation_sessions")
}
model AILearningData {
id String @id @default(cuid())
userId String
sessionId String?
tradeId String?
analysisData Json // Store the AI analysis
marketConditions Json // Store market conditions at time of analysis
outcome String? // WIN, LOSS, BREAKEVEN
actualPrice Float?
predictedPrice Float?
confidenceScore Float?
accuracyScore Float? // Calculated after outcome is known
timeframe String
symbol String
screenshot String? // Link to screenshot used for analysis
feedbackData Json? // Store feedback for learning
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@map("ai_learning_data")
}