public MovingAverage(ref TickerClient tickerClient, string ProductName, int timeInterValInMin = 3, int smaSlices = 40, int serverDownloadAmount = 10, bool updateDb = true, bool clearDataOnDispose = true) { //var a = tickerClient.CurrentPrice; clearSharedExDataOnDispose = clearDataOnDispose; UpdateJasonDB = updateDb; AmountOfDataToDownload = serverDownloadAmount; //Logger.WriteLog("Starting moving avg calculations"); isBusyCalculatingSMA = false; Product = ProductName; isBusyUpdatingMA = false; //ForceRedownloadData = false; if (SharedRawExchangeData == null) { SharedRawExchangeData = new List <CandleData>(); } TIME_INTERVAL = timeInterValInMin; SMA_UPDATE_INTERVAL_SEC = TIME_INTERVAL * 60; //time interval in seconds SLICES = smaSlices; TickerPriceClient = tickerClient; Init(timeInterValInMin); //Task.Run(() => Init(timeInterValInMin)).Wait(); }
public MyOrderBook(CBAuthenticationContainer authContainer, string product, ref TickerClient inputTickerClient) : base(authContainer) { isUpdatingOrderList = false; isBusyCancelAndReorder = false; BusyWithWithCancelReorder = false; OrderRetriedCount = 0; OrderStartingPrice = 0; AvoidExFees = true; //avoid fees by default ProductName = product; _auth = authContainer; orderList = new OrderList(_auth); MyChaseOrderList = new List <MyOrder>(); lastTickTIme = DateTime.UtcNow; PriceTicker = inputTickerClient; //new TickerClient(product); //no need to create two different ticker, use one global ticker PriceTicker.PriceUpdated += PriceUpdateEventHandler; PriceTicker.TickerConnectedEvent += TickerConnectedEventHandler; PriceTicker.TickerDisconnectedEvent += TickerDisconnectedEventHandler; fillsClient = new FillsClient(_auth, this); fillsClient.FillUpdated += OrderFilledEventHandler; }
public MainWindow() { InitializeComponent(); var instanceContext = new InstanceContext(new ClientCallBack(time_block, clock_image)); Closing += new CancelEventHandler(ClosingEvent); proxy = new TickerClient(instanceContext); }
public Simulator2(ref TickerClient ticker, string productName, int CommonInterval = 30, int LargeSmaLen = 50, int SmallSmaLen = 12, int BasePriceSma = 10, bool downloadLatestData = false) { COMMON_INTERVAL = CommonInterval; LARGE_SMA_LEN = LargeSmaLen; SMALL_SMA_LEN = SmallSmaLen; BASE_SMA_LEN = BasePriceSma; BasePrices_MA = new MovingAverage(ref ticker, productName, COMMON_INTERVAL, BASE_SMA_LEN, 10, downloadLatestData, false); //BigSma_MA = new MovingAverage(ref ticker, productName, COMMON_INTERVAL, LARGE_SMA_LEN, 10, downloadLatestData, false); //SmallSma_MA = new MovingAverage(ref ticker, productName, COMMON_INTERVAL, SMALL_SMA_LEN, 10, downloadLatestData, false); var smaDtPoints_BasePrice = getSmaWithDataPts(BasePrices_MA, BASE_SMA_LEN); //var t = smaDtPoints_BasePrice.Select(d=>d.SmaValue) var SmaDtPoints_Big = getSmaWithDataPts(smaDtPoints_BasePrice, LARGE_SMA_LEN); var SmaDtPoints_Small = getSmaWithDataPts(smaDtPoints_BasePrice, SMALL_SMA_LEN); var maxdate = DateTime.Now; if (SmaDtPoints_Big.First().Time > SmaDtPoints_Small.First().Time) { maxdate = SmaDtPoints_Big.First().Time; } else { maxdate = SmaDtPoints_Small.First().Time; } if (maxdate < smaDtPoints_BasePrice.First().Time) { maxdate = smaDtPoints_BasePrice.First().Time; } var firstCommonDate = maxdate; //SmaDtPoints_Big.First().Time; ActualPriceList = BasePrices_MA.SmaDataPts_Candle.Where(c => c.Time >= firstCommonDate).Select(d => new SmaData { ActualPrice = d.Close, SmaValue = (double)d.Close, Time = d.Time }).ToList(); Price = smaDtPoints_BasePrice.Where(d => d.Time >= firstCommonDate).ToList(); BigSma = SmaDtPoints_Big.Where(d => d.Time >= firstCommonDate).ToList(); SmallSma = SmaDtPoints_Small.Where(d => d.Time >= firstCommonDate).ToList(); }
public void Initialize(string username, string server) { var concurrencyService = new ConcurrencyService(); context = NetMQContext.Create(); var tickerClient = new TickerClient(context, server); var netMQHeartBeatClient = NetMQHeartBeatClient.CreateInstance(context, server); HeartBeatClient = new HeartBeatClient(); var tickerFactory = new TickerFactory(); TickerRepository = new TickerRepository(tickerClient, tickerFactory); }
public ContextValues(ref MyOrderBook orderBook, ref TickerClient inputTicker) { MyOrderBook = orderBook; CurrentTicker = inputTicker; UserStartedTrading = false; TradeActionList = new List <string>(); //ForceSold = false; BuySellAmount = 0.01m;//default //CurrentLargeSmaTimeInterval = 3; //default //CurrentLargeSmaSlices = 60; //default CurrentAction = "NOT_SET"; //CurrentSmallSmaTimeInterval = 3; //default //CurrentSmallSmaSlices = 55; //default PriceBuffer = 0.05m; //default CurrentRealtimePrice = 0; CurrentBufferedPrice = 0; //CurrentLargeSmaPrice = 0; BuyOrderFilled = false; SellOrderFilled = false; WaitingSellFill = false; WaitingBuyFill = false; WaitingBuyOrSell = false; WaitTimeAfterBigSmaCrossInMin = 5; //buy sell every time interval MaxBuy = 5; MaxSell = 5; StartAutoTrading = false; //AutoTradingStoppedEvent?.Invoke(this, EventArgs.Empty); LastLargeSmaCrossTime = DateTime.UtcNow.ToLocalTime(); //LastSmallSmaCrossTime = DateTime.UtcNow.ToLocalTime(); }
public static void ManualSimulate2() { int lastCommonInterval = 0; int lastBigSma = 0; int lastSmallSma = 0; Simulator2 S = null; var ProductName = "LTC-USD"; TickerClient Ticker = new TickerClient(ProductName); //wait for ticker to get ready Thread.Sleep(2 * 1000); try { Console.WriteLine("Enter simulation start date:"); var inDt = Console.ReadLine(); DateTime dt; DateTime.TryParse(inDt, out dt); Console.WriteLine("Enter Common time interval in minutes"); var inputCommonInterval = Convert.ToInt16(Console.ReadLine()); Console.WriteLine("Enter base price sma len: "); var basePriceSma = Convert.ToInt16(Console.ReadLine()); Console.WriteLine("Enter big sma length"); var inputBigSmaLen = Convert.ToInt16(Console.ReadLine()); Console.WriteLine("Enter small sma length"); var inputSmallSmaLen = Convert.ToInt16(Console.ReadLine()); //Console.WriteLine("Enter signal len: "); //var inputSmaLen = Convert.ToInt16(Console.ReadLine()); if (S == null) { S = new Simulator2(ref Ticker, ProductName, inputCommonInterval, inputBigSmaLen, inputSmallSmaLen, basePriceSma, true); S.GraphWindow = _GraphingWindow; } else { if (!(lastCommonInterval == inputCommonInterval && lastBigSma == inputBigSmaLen && lastSmallSma == inputSmallSmaLen)) { S.Dispose(); S = null; S = new Simulator2(ref Ticker, ProductName, inputCommonInterval, inputBigSmaLen, inputSmallSmaLen, basePriceSma); S.GraphWindow = _GraphingWindow; } } S.Calculate(dt, DateTime.Now, true, true); lastCommonInterval = inputCommonInterval; lastBigSma = inputBigSmaLen; lastSmallSma = inputSmallSmaLen; } catch (Exception ex) { Console.WriteLine("invalid input / error in calc: " + ex.Message); } }
private static List <ResultData> RunSim_ThreadSafe(ref TickerClient inputTicker, DateTime startDt, DateTime endDt, int inputSimCount) { int lastCommonInterval = 0; int lastBigSma = 0; int lastSmallSma = 0; Simulator2 S = null; TickerClient Ticker = inputTicker; DateTime autoStartDate = startDt; DateTime autoEndDate = endDt; List <ResultData> resultList = new List <ResultData>(); int simCount = inputSimCount; //Parallel.For(0, simCount, i => for (int i = 0; i < simCount; i++) { IntervalData interval = null; interval = getIntervalData(); try { if (S == null) { S = new Simulator2(ref Ticker, ProductName, interval.interval, interval.bigSmaLen, interval.smallSmaLen, interval.basePriceSmaLen, true); S.GraphWindow = _GraphingWindow; } else { if (!(lastCommonInterval == interval.interval && lastBigSma == interval.bigSmaLen && lastSmallSma == interval.smallSmaLen)) { S.Dispose(); S = null; S = new Simulator2(ref Ticker, ProductName, interval.interval, interval.bigSmaLen, interval.smallSmaLen, interval.basePriceSmaLen); S.GraphWindow = _GraphingWindow; } } var plResult = S.Calculate(autoStartDate, autoEndDate, false, true); resultList.Add(new ResultData { Pl = plResult, intervals = interval }); lastCommonInterval = interval.interval; lastBigSma = interval.bigSmaLen; lastSmallSma = interval.smallSmaLen; } catch (Exception ex) { Console.WriteLine("invalid input / error in calc"); } } return(resultList); }
public static void AutoSimulate2() { _TriedIntervalList.Clear(); TickerClient Ticker = new TickerClient(ProductName); //wait for ticker to get ready Thread.Sleep(2 * 1000); DateTime dtStart = DateTime.MinValue; while (dtStart == DateTime.MinValue) { Console.WriteLine("Enter simulation start date:"); var inDt = Console.ReadLine(); DateTime.TryParse(inDt, out dtStart); } DateTime autoStartDate = dtStart;// new DateTime(2017, 10, 1); //DateTime autoEndDate = new DateTime(2018, 2, 13);//DateTime.Now; DateTime dtEnd = DateTime.MinValue; while (dtEnd == DateTime.MinValue) { Console.WriteLine("Enter simulation end date, enter n to use todays date:"); var inDt = Console.ReadLine(); if (inDt == "n") { dtEnd = DateTime.Now; break; } DateTime.TryParse(inDt, out dtEnd); } DateTime autoEndDate = dtEnd; //DateTime.Now; List <ResultData> allCombinedResultList = new List <ResultData>(); var startTime = DateTime.Now; int simCount = 0; int Each_Sim_Count = 50;//50; while (simCount == 0) { Console.WriteLine("Enter number of simulation count, " + Each_Sim_Count + " minimun"); simCount = Convert.ToInt32(Console.ReadLine()); } List <Task> allSimTasks = new List <Task>(); var eachBatchCount = 1000; var lastBatchCompletionTime = DateTime.Now; Int32 SLEEP_TIME_SEC = 30 * 1000; for (int batch = eachBatchCount; batch < simCount + eachBatchCount; batch += eachBatchCount) { Console.WriteLine("starting batch: " + (batch - eachBatchCount) + " - " + batch); if (batch > eachBatchCount) { Thread.Sleep(SLEEP_TIME_SEC); } var threadCount = Math.Ceiling((eachBatchCount / (double)Each_Sim_Count)); for (int i = 0; i < threadCount; i++) { var curTask = Task.Factory.StartNew(() => { var returnedResult = RunSim_ThreadSafe(ref Ticker, autoStartDate, autoEndDate, Each_Sim_Count); allCombinedResultList.AddRange(returnedResult); }); allSimTasks.Add(curTask); } Task.WaitAll(allSimTasks.ToArray()); if (batch >= eachBatchCount) { var timeTakenLastBatch = (DateTime.Now - lastBatchCompletionTime).TotalMinutes; Console.WriteLine("Time taken to complete last batch (min): " + timeTakenLastBatch); var expectedCompletionTime = (timeTakenLastBatch + ((SLEEP_TIME_SEC / 1000) / 60)) * ((simCount - batch) / eachBatchCount); Console.WriteLine("Expected completion time: " + expectedCompletionTime + " min, " + DateTime.Now.AddMinutes(expectedCompletionTime)); lastBatchCompletionTime = DateTime.Now; } } Console.WriteLine("\nTop 5 profit results\n"); IntervalData bestValues = null; for (int i = 0; i < 5; i++) { var best = allCombinedResultList.Where(d => d.Pl == allCombinedResultList.Max(a => a.Pl)).First(); if (bestValues == null) { bestValues = best.intervals; } var resMsg = "best result: " + i + "\n" + "PL: " + best.Pl + "\n" + "Interval: " + best.intervals.interval + "\n" + "Base price sma: " + best.intervals.basePriceSmaLen + "\n" + "big sma: " + best.intervals.bigSmaLen + "\n" + "small sma: " + best.intervals.smallSmaLen + "\n"; Logger.WriteLog("\n" + resMsg); allCombinedResultList.Remove(best); } var S = new Simulator2(ref Ticker, ProductName, bestValues.interval, bestValues.bigSmaLen, bestValues.smallSmaLen, bestValues.basePriceSmaLen, false); S.GraphWindow = _GraphingWindow; S.Calculate(autoStartDate, autoEndDate, true, true); //Console.WriteLine("\nTop 5 loss results\n"); //for (int i = 0; i < 5; i++) //{ // var best = allCombinedResultList.Where(d => d.Pl == allCombinedResultList.Min(a => a.Pl)).First(); // var resMsg = "best result: " + i + "\n" // + "PL: " + best.Pl + "\n" // + "Interval: " + best.intervals.interval + "\n" // + "Base price sma: " + best.intervals.basePriceSmaLen + "\n" // + "big sma: " + best.intervals.bigSmaLen + "\n" // + "small sma: " + best.intervals.smallSmaLen + "\n"; // Logger.WriteLog("\n" + resMsg); // allCombinedResultList.Remove(best); //} Console.WriteLine("time taken for " + allSimTasks.Count() * Each_Sim_Count + " iterations (min): " + (DateTime.Now - startTime).TotalMinutes); //Console.ReadLine(); }
private void InitManager(string ProductName, IntervalValues intervalValues) { //try to get ticker first //Logger.WriteLog("Init Manager Thread ID: " + Thread.CurrentThread.ManagedThreadId.ToString()); try { Logger.WriteLog("Initializing ticker"); ProductTickerClient = new TickerClient(ProductName); } catch (Exception ex) { Logger.WriteLog("Manager cant initialize ticker"); return; } ProductTickerClient.PriceUpdated += ProductTickerClient_UpdateHandler; AvoidExchangeFees = true; ProductTickerClient.TickerConnectedEvent += TickerConnectedHandler; ProductTickerClient.TickerDisconnectedEvent += TickerDisconnectedHandler; MyAuth = new CBAuthenticationContainer(MyKey, MyPassphrase, MySecret); MyProductOrderBook = new MyOrderBook(MyAuth, ProductName, ref ProductTickerClient); MyProductOrderBook.OrderUpdateEvent += FillUpdateEventHandler; CurContextValues = new ContextValues(ref MyProductOrderBook, ref ProductTickerClient); CurContextValues.ProductName = ProductName; CurContextValues.Auth = MyAuth; CurContextValues.AutoTradingStartEvent += autoTradeStartEventHandler; CurContextValues.AutoTradingStopEvent += autoTradeStopEventHandler; ////update ui with initial prices ProductTickerClient_UpdateHandler(this, new TickerMessage(ProductTickerClient.CurrentPrice)); CurrentDisplaySmaTimeInterval = intervalValues.LargeIntervalInMin; CurrentDisplaySmaSlices = intervalValues.LargeSmaSlices; //default large sma slice value //SmaSmall = new MovingAverage(ref ProductTickerClient, ProductName, CurContextValues.CurrentSmallSmaTimeInterval, CurContextValues.CurrentSmallSmaSlices); //SmaSmall.MovingAverageUpdated += SmaSmallChangedEventHandler; Logger.WriteLog(string.Format("{0} manager started", ProductName)); //currentTradeStrategy = new TradeStrategyA(ref CurContextValues); //currentTradeStrategy = new TradeStrategyB(ref CurContextValues); //currentTradeStrategy = new TradeStrategyC(ref CurContextValues); //currentTradeStrategy = new TradeStrategyB(ref CurContextValues); //currentTradeStrategy = new TradeStrategyD(ref CurContextValues); if (intervalValues == null) { intervalValues = new IntervalValues(30, 15, 5);//IntervalValues(5, 3, 1); } //currentTradeStrategy = new TradeStrategyE(ref CurContextValues, intervalValues); CreateUpdateStrategyInstance(intervalValues, true).Wait(); currentTradeStrategy.CurrentActionChangedEvent += CUrrentActionChangeEventHandler; //save the interval values for later use //CurContextValues.CurrentIntervalValues = intervalValues; SetCurrentIntervalValues(intervalValues); DisplaySma = new MovingAverage(ref ProductTickerClient, ProductName, CurrentDisplaySmaTimeInterval, CurrentDisplaySmaSlices); DisplaySma.MovingAverageUpdatedEvent += DisplaySmaChangedEventHandler; UpdateDisplaySmaParameters(CurrentDisplaySmaTimeInterval, CurrentDisplaySmaSlices); UpdateBuySellAmount(0.01m); //default //UpdateBuySellBuffer(0.03m); //default try { UpdateFunds(); } catch (Exception) { Logger.WriteLog("Error getting available funds details, please check your gdax credentials"); } AppSettings.MajorSettingsChangEvent += MajorSettingsChangedEventHandler; //writeCurrentStrategySmaValues(); //ShowGraph(gra); }