Files
AI-Stock-Trader/WebServer/Controllers/Automation.cs
T

145 lines
5.7 KiB
C#

using Controllers.DataBase;
using Entities;
using Newtonsoft.Json;
namespace Controllers.PythonInterop {
public class Automation {
AIModule _aiModule;
DbDriver _dbDriver;
public Automation(AIModule aiModule, DbDriver dbDriver) {
_aiModule = aiModule;
_dbDriver = dbDriver;
}
public void GlobalPredictAI() {
// Start this process on a background thread so its non-blocking
Task thread = new Task(async () => {
// Load the userlist
List<string>? UserList = JsonConvert.DeserializeObject<List<string>>(_dbDriver.Get("Users"));
List<string> VerifiedUserList = UserList != null ? UserList : new List<string>();
// Process each request at the same time for speed improvement
Parallel.ForEach(VerifiedUserList, async (username) => {
string dbPrefix = $"[{username.ToLower()}]:";
// Load the Tracked stocks for each user
List<Stock>? TrackedStocks = JsonConvert.DeserializeObject<List<Stock>>( _dbDriver.Get( dbPrefix + "watched" ) );
List<Stock> VerifiedTrackedStocks = TrackedStocks != null ? TrackedStocks : new List<Stock>();
// Go through each stock
List<Task> threadpool = new List<Task>();
foreach(Stock cur in VerifiedTrackedStocks) {
// Predict the trend on a new thread
Task thread = new Task(() => {
(string, float)Result = _aiModule.PredictAI(cur.Symbol);
// If error log it
if (!string.IsNullOrEmpty(Result.Item1)){
Console.WriteLine(Result.Item1);
}
// Write the score to the users tracked stocks
cur.Score = Result.Item2;
});
thread.Start();
threadpool.Add(thread);
}
// Wait for all the threads to finish
await Task.WhenAll(threadpool);
// Process Stocks -> Buy Sell Hold / Based on the global data from earlier
// Save the new scores to the database for reference from the UI
_dbDriver.Set( dbPrefix + "watched", JsonConvert.SerializeObject( VerifiedTrackedStocks ) );
});
});
thread.Start();
}
public void GlobalTrainAI(){
Task thread = new Task(async () => {
_aiModule.TrainAI();
});
thread.Start();
}
void sellStock(PurchasedStock stock){
string dbPrefix = $"[{userName.ToLower()}]:";
if (Session != null){
// Get sell price
float sellPrice = stock.Quantity * aiModule.GetCurrentPrice( stock.Symbol );
// Try to sell the stock
(bool, string) result = PaymentProcessor.TrySell(PaymentKey, sellPrice);
if (!result.Item1){
resultError = result.Item2;
return;
}
// Remove Stock
Session.TradeHistory.Remove(stock);
dbDriver.Set( dbPrefix + "Stocks", Newtonsoft.Json.JsonConvert.SerializeObject(Session.TradeHistory) );
// Reload the users money
bool moneyLoaded = float.TryParse(dbDriver.Get( dbPrefix + "money" ), out float moneyResult);
Session.Money = moneyLoaded ? moneyResult : 1000;
// Reset the Impodent Key
result = PaymentProcessor.CreatePayment(Session.UserName);
if (!result.Item1){
resultError = "[New payment session failed] : " + result.Item2;
return;
}
PaymentKey = result.Item2;
}
}
void buyStock(string StockSymbol){
if (Session != null){
string dbPrefix = $"[{userName.ToLower()}]:";
// Try Parse the quantitiy input
// Get the max quantity that I can Afford
float QuantityResult = 0;
// Get Stock Price
float stockPrice = aiModule.GetCurrentPrice( StockSymbol );
// Try Pay for the stock
(bool, string) result = PaymentProcessor.TryPayment(PaymentKey, QuantityResult * stockPrice);
if (!result.Item1){
resultError = result.Item2;
return;
}
// Add the stock
Session.TradeHistory.Add( new PurchasedStock(){
Symbol = StockSymbol.ToUpper(),
PurchasePrice = stockPrice,
Quantity = QuantityResult,
} );
dbDriver.Set( dbPrefix + "Stocks", Newtonsoft.Json.JsonConvert.SerializeObject(Session.TradeHistory) );
// Reload the users money
bool moneyLoaded = float.TryParse(dbDriver.Get( dbPrefix + "money" ), out float moneyResult);
Session.Money = moneyLoaded ? moneyResult : 1000;
// Reset the Impodent Key
result = PaymentProcessor.CreatePayment(Session.UserName);
if (!result.Item1){
resultError = "[New payment session failed] : " + result.Item2;
return;
}
PaymentKey = result.Item2;
}
}
}
}