using System; using sharp.trading.bittrex; using sharp.extensions; using sharp.trading; using System.Collections.Generic; using sharp.json; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.IO; using System.Linq; using System.Threading; using System.Text; using System.Diagnostics; using System.Collections; using System.CodeDom; using sharp.trading.cache; using sharp.json.network; using sharp.tradebot.rpc; using System.Net.WebSockets; using TradeBot; using System.Net.Sockets; /** * tradebot.exe [ --test ] --servicedaemon [ --port ] * --newbot [ --dll ] --class * --unload * --load * **/ namespace sharp.tradebot { class TradeBotApplication { public static int jsonPort = 33555; public static void Main(string[] args) { ArgumentReader ar = new ArgumentReader(args); while (ar.MoveNext()) { switch (ar.Current) { case "--test": TradingEnvironment.DataDirectory = "sharp.trading.data"; jsonPort = 33554; break; case "--servicedaemon": ServiceDaemon.Run(ar.Reminder()); return; case "--shutdown": ShutDown(); return; case "--register": callDaemon("register", ar.NextFollowing(3)); return; case "--unregister": callDaemon("unregister", ar.NextFollowing(1)); return; case "--load": callDaemon("load", ar.NextFollowing(1)); return; case "--unload": callDaemon("unload", ar.NextFollowing(1)); return; case "--reload": callDaemon("reload", ar.NextFollowing(1)); return; } } } private static void ShutDown(){ callDaemon("shutdown",new string[0]); } private static bool callDaemon(string command,string[] arguments){ RPCRequest request = new RPCRequest(); request.Command = command; request.Arguments = arguments; JSONTcpClient client = new JSONTcpClient(jsonPort); client.Send(JSON.From(request)); JSON jresponse = client.Receive(); RPCResponse response = jresponse.To(); Console.WriteLine("callDaemon: Daemon Message: {0}",response.Message); request = new RPCRequest(); request.Arguments = new string[0]; request.Command = "disconnect"; client.Send(JSON.From(request)); return response.Success; } //TradeBotApplication app = new TradeBotApplication(); //app.Initialize(args); //app.Prepare(); //try //{ // IEnumerator ae = app.Arguments.ToArray().GetEnumerator(); // while (ae.MoveNext()) // { // switch (ae.Current.ToString()) // { // case "-test": // app.Arguments.Remove(ae.Current.ToString()); // jsonPort = 33554; // break; // case "-servicedaemon": // app.Mode = AppMode.SERVICEDAEMON; // app.Arguments.Remove(ae.Current.ToString()); // break; // } // } //} catch (Exception e){ // Console.WriteLine("Exception while handling command line arguments. {0}",e.ToString()); // app.LockFile.Unlock(); // return; //} //app.Start(); //app.Shutdown(); //public enum AppMode { // DEFAULT, SERVICEDAEMON //} //public LockFile LockFile { get; private set; } //public AppMode Mode { get; set; } = AppMode.DEFAULT; //List tradingBots = new List(); //List Arguments = new List(); //public TradeBotApplication() //{ // this.LockFile = new LockFile(getLockFileName()); //} //public string getLockFileName(){ // return Path.Combine(TradingBotEnvironment.BaseDataDirectory, "tradebot.lock"); //} //private void Initialize(string[] arguments) //{ // this.Arguments.AddRange(arguments); // if (TradingEnvironment.DefaultConnection == null) // { // TradingEnvironment.DefaultConnection = new BittrexConnector(); // } // DirectoryExtensions.EnsureDirectoryExists(TradingBotEnvironment.BaseDataDirectory); // LockFile.Lock(); //} //private void Prepare(){ // if (!LockFile.IsLocked){ // LockFile.Lock(); // } // bool shouldSave = false; // if (!Directory.Exists(Path.Combine(TradingBotEnvironment.BaseDataDirectory,"sys"))){ // Directory.CreateDirectory(Path.Combine(TradingBotEnvironment.BaseDataDirectory, "sys")); // } // if (File.Exists(Path.Combine(TradingBotEnvironment.BaseDataDirectory,"sys","connector.json"))){ // JSON connector = JSON.ReadFrom(Path.Combine(TradingBotEnvironment.BaseDataDirectory,"sys","connector.json")); // if (connector["class"] != null){ // Type t = Type.GetType(connector["class"].String); // TradingConnection c = (TradingConnection)Activator.CreateInstance(t, connector["arguments"].To()); // TradingEnvironment.DefaultConnection = c; // } // } else { // TradingEnvironment.DefaultConnection = new BittrexConnector(); // shouldSave = true; // } // if (File.Exists(Path.Combine(TradingBotEnvironment.BaseDataDirectory,"sys","bots.json"))){ // JSON bots = JSON.ReadFrom(Path.Combine(TradingBotEnvironment.BaseDataDirectory, "sys", "bots.json")); // foreach (JSON bot in bots){ // Type t = Type.GetType(bot["class"].String); // TradingBot tbot = (TradingBot)Activator.CreateInstance(t, new object[] { new Guid(bot["uuid"].String) } ); // AddTradingBot(tbot); // } // } else { // shouldSave = true; // } // if (shouldSave){ // Save(); // } //} //public void Save() //{ // if (!LockFile.IsLocked){ // throw new Exception("Cannot save, file lock not locked"); // } // JSONObject connector = new JSONObject(); // if (TradingEnvironment.DefaultConnection == null) // { // connector["class"] = null; // connector["arguments"] = new JSONArray(); // } // else // { // connector["class"] = TradingEnvironment.DefaultConnection.GetType().AssemblyQualifiedName; // connector["arguments"] = JSON.From(TradingEnvironment.DefaultConnection.getConstructorArguments()); // } // connector.WriteTo(Path.Combine(TradingBotEnvironment.BaseDataDirectory, "sys", "connector.json"),true); // JSONArray bots = new JSONArray(); // foreach (TradingBot bot in TradingBots) // { // JSONObject o = new JSONObject(); // o["class"] = bot.GetType().AssemblyQualifiedName; // o["uuid"] = bot.UID.ToString(); // bots.Add(o); // } // bots.WriteTo(Path.Combine(TradingBotEnvironment.BaseDataDirectory, "sys", "bots.json"),true); //} //private void Shutdown() //{ // if (LockFile.IsLocked){ // LockFile.Unlock(); // } //} //public void Start(){ // switch (Mode){ // case AppMode.SERVICEDAEMON: // ServiceDaemon(); // break; // default: // Run(); // break; // } //} //public void ServiceDaemon(){ // ServiceManager.Default.GetHashCode(); // while (true){ // Thread.Sleep(1000); // if (File.Exists(Path.Combine(TradingEnvironment.DataDirectory, "daemon.shutdown"))){ // File.Delete(Path.Combine(TradingEnvironment.DataDirectory, "daemon.shutdown")); // break; // } // } // ServiceManager.Default.Shutdown(); //} //public void Run() //{ // foreach (TradingBot bot in tradingBots) // { // RunBot(bot); // } //} //public void Run(string[] uids) //{ // foreach (TradingBot bot in tradingBots) // { // if (uids.Contains(bot.UID.ToString())){ // RunBot(bot); // } // } //} //private void RunBot(TradingBot bot) //{ // Console.WriteLine("Running Bot: {0}", bot.ToString()); // try { // bot.Prepare(); // bot.Trade(); // bot.Finish(); // } catch (Exception e){ // Console.WriteLine("Bot threw exception: {0}",e.ToString()); // bot.Unlock(); // } //} //public TradingBot[] TradingBots { // get { return tradingBots.ToArray(); } //} //public void AddTradingBot(TradingBot bot){ // this.tradingBots.Add(bot); //} //public void RemoveTradingBot(TradingBot bot){ // this.tradingBots.Remove(bot); //} public Double ConvertValue(string valueSymbol,double volume,string targetSymbol){ if (valueSymbol.Equals(targetSymbol)){ return volume; } Market primMarket; Market secMarket; try { primMarket = TradingEnvironment.DefaultConnection.openMarket(valueSymbol, targetSymbol); return primMarket.getOrderBook().getVolumePrice(volume).Item2; } catch (Exception e){ Console.WriteLine("Direct conversion from {0} to {1} is not available",valueSymbol,targetSymbol); } try { primMarket = TradingEnvironment.DefaultConnection.openMarket(valueSymbol, "BTC"); secMarket = TradingEnvironment.DefaultConnection.openMarket("BTC", targetSymbol); return secMarket.getOrderBook().getVolumePrice(primMarket.getOrderBook().getVolumePrice(volume).Item2).Item2; } catch (Exception e){ Console.WriteLine("Conversion of {0} to {1} via BTC not available.",valueSymbol,targetSymbol); } return 0; } public void DumpBalances(string targetSymbol) { TradingConnection c = TradingEnvironment.DefaultConnection; double targetBalance = 0; foreach (trading.Balance balance in c.getBalances()) { if (balance.CurrentBalance > 0) { double targetValue = ConvertValue(balance.Currency, balance.CurrentBalance, targetSymbol); Console.WriteLine("Balance: {0,12:#####0.000000} {1,4} => {2,12:#####0.000000} {3}", balance.CurrentBalance, balance.Currency, targetValue, targetSymbol); targetBalance += targetValue; } } Console.WriteLine(); Console.WriteLine("Current {1} Value: {0,12:#####0.00} {1}", targetBalance, targetSymbol); Console.WriteLine(); } } }