public override void UpdatePredictors() { TickerChangedEventArgs lastTicker = Data.Store.GetLastTicker(pair); double lastPrice = lastTicker.MarketData.PriceLast; double buyPrice = lastTicker.MarketData.OrderTopBuy; double sellPrice = lastTicker.MarketData.OrderTopSell; double change24 = lastTicker.ChangeLast; double mult = GetOPTMultiplier(change24); ruleMeanRev.SetTrigger(mult); TickerChangedEventArgs[] tickers = Data.Store.GetTickerData(pair); if (tickers == null) { throw new Exception("Data store returned NULL tickers for pair " + pair); } predictorExtremes.Update(tickers); predictorMeanRev.Recalculate(tickers); predictorMacd.Recalculate(tickers); Utility.TradeTracker.UpdateOpenPosition(pair, buyPrice); GUI.GUIManager.SetPairSummary(this.pair, tickers, lastTicker.MarketData.Volume24HourBase); }
public static void UpdateTickers() { try { KeyValuePair <CurrencyPair, PoloniexAPI.MarketTools.IMarketData>[] data = ClientManager.client.Markets.GetSummaryAsync().Result.ToArray(); if (data == null) { return; } for (int i = 0; i < data.Length; i++) { TickerChangedEventArgs lastTicker = Data.Store.GetLastTicker(data[i].Key); if (lastTicker == null) { continue; } if (!PoloniexAPI.MarketTools.MarketData.Equal(lastTicker.MarketData, data[i].Value)) { TickerChangedEventArgs tempTicker = new TickerChangedEventArgs(data[i].Key, (PoloniexAPI.MarketTools.MarketData)data[i].Value); tempTicker.Timestamp = Utility.DateTimeHelper.DateTimeToUnixTimestamp(DateTime.Now); Data.Store.AddTickerData(tempTicker); } } } catch (Exception e) { Utility.ErrorLog.ReportError("Error refreshing market data", e); } }
public static void UpdateWalletValue(string currency) { // update the wallet BTC value based on most recent ticker values // doesn't make any API calls, just recalculates based on local data try { if (walletState == null) { UpdateWallet(); } else if (currency == "BTC") { return; } else { IBalance balance; if (walletState.TryGetValue(currency, out balance)) { CurrencyPair cp = new CurrencyPair("BTC", currency); TickerChangedEventArgs lastTicker = Data.Store.GetLastTicker(cp); if (lastTicker != null) { double currValue = lastTicker.MarketData.PriceLast; double currAmount = balance.QuoteOnOrders + balance.QuoteAvailable; balance.BitcoinValue = currAmount * currValue; GUI.GUIManager.UpdateWallet(walletState.ToArray()); } } } } catch (Exception e) { Console.WriteLine(e.Message + "\n" + e.StackTrace); } }
public static void PullTickerHistoryRecent(CurrencyPair pair) { if (!AllowTickerUpdate) { return; } if (tickerData == null) { tickerData = new TSList <TSList <TickerChangedEventArgs> >(); } allowUpdatePairs = new List <CurrencyPair>(); List <PoloniexAPI.MarketTools.ITrade> trades = WebApiCustom.GetTrades(pair); if (trades != null) { TickerChangedEventArgs[] fakeTickers = new TickerChangedEventArgs[trades.Count]; for (int i = 0; i < trades.Count; i++) { MarketData md = new MarketData(trades[i].PricePerCoin); TickerChangedEventArgs ticker = new TickerChangedEventArgs(pair, md); fakeTickers[i] = ticker; } TSList <TickerChangedEventArgs> tickerList = new TSList <TickerChangedEventArgs>(fakeTickers); tickerList.Sort(); tickerData.Add(tickerList); allowUpdatePairs.Add(pair); } }
// File Managment public static void SaveTradeData() { List <TickerChangedEventArgs> allTickers = new List <TickerChangedEventArgs>(); for (int i = 0; i < tickerData.Count; i++) { for (int j = 0; j < tickerData[i].Count; j++) { TickerChangedEventArgs currTicker = tickerData[i][j]; allTickers.Add(currTicker); } } allTickers.Sort(); List <string> lines = new List <string>(); for (int i = 0; i < allTickers.Count; i++) { TickerChangedEventArgs currTicker = allTickers[i]; string currLine = string.Format("{0}:{1}:{2}:{3}", currTicker.CurrencyPair, currTicker.Timestamp, currTicker.MarketData.PriceLast.ToString("F8"), currTicker.MarketData.Volume24HourBase.ToString("F8")); lines.Add(currLine); } CLI.Manager.PrintLog("Saving ticker data to file (" + lines.Count + " tickers)"); Utility.FileManager.SaveFile("data/ticker data", lines.ToArray()); CLI.Manager.PrintLog("Done!"); }
public override void Setup(bool simulate = false) { GUI.GUIManager.AddStrategyScreenPair(this.pair); // ---------------------------------- SetupRules(); // ---------------------------------- // Check file if this has been bought already double openPos = Utility.TradeTracker.GetOpenPosition(pair); LastBuyTime = Utility.TradeTracker.GetOpenPositionBuyTime(pair); openPosition = openPos; TickerChangedEventArgs lastTicker = Data.Store.GetLastTicker(pair); if (lastTicker == null) { throw new Exception("Couldn't build timeframe model for " + pair + " - no tickers available"); } predictorExtremes = new Data.Predictors.PriceExtremes(pair); TickerChangedEventArgs[] tickers = Data.Store.GetTickerData(pair); if (tickers == null) { throw new Exception("Couldn't build predictor history for " + pair + " - no tickers available"); } predictorExtremes.Update(tickers); }
async void Live_OnTickerChanged(object sender, TickerChangedEventArgs ticker) { if (TickerDataTask == null) { Debug.WriteLine("No task set!"); return; } if (IsRunning && !IsReentrant) { // previous task hasn't completed Debug.WriteLine("Ticker Task already running"); return; } try { // we're running it now IsRunning = true; Debug.WriteLine("Ticker Running Task"); await TickerDataTask.Invoke(); Debug.WriteLine("Ticker Task Completed"); } catch (Exception) { Debug.WriteLine("Ticker Task Failed"); } finally { // allow it to run again IsRunning = false; } }
public static void AddTickerData(TickerChangedEventArgs ticker, bool ignoreTimeFilter = false) { if (!AllowTickerUpdate) { return; } if (allowUpdatePairs == null) { return; } if (!allowUpdatePairs.Contains(ticker.CurrencyPair)) { return; } int storeTime; lock (TickerStoreTime) { if (!TickerStoreTime.TryGetValue(ticker.CurrencyPair, out storeTime)) { storeTime = TickerStoreTimeDefault; } } long deleteTime = ticker.Timestamp - storeTime; lock (tickerData) { for (int i = 0; i < tickerData.Count; i++) { if (tickerData[i] == null) { continue; } if (tickerData[i].Count == 0) { continue; } if (tickerData[i][0].CurrencyPair == ticker.CurrencyPair) { while (tickerData[i][0].Timestamp < deleteTime) { tickerData[i].First().Dispose(); tickerData[i].RemoveAt(0); } if (!ignoreTimeFilter && ticker.Timestamp - tickerData[i].Last().Timestamp < 5) { return; } tickerData[i].Add(ticker); Trading.Manager.NotifyTickerUpdate(ticker.CurrencyPair); return; } } TSList <TickerChangedEventArgs> list = new TSList <TickerChangedEventArgs>(); list.Add(ticker); tickerData.Add(list); Trading.Manager.NotifyTickerUpdate(ticker.CurrencyPair); } }
public override void OnTick(TickerChangedEventArgs ticker) { // Ticker data if (ticker.CurrencyPair == Symbol) { topBuyPrice = ticker.MarketData.OrderTopBuy; topSellPrice = ticker.MarketData.OrderTopSell; } }
public static void MapPattern(TickerChangedEventArgs[] tickers, TickerChangedEventArgs prediction) { double[] values = new double[tickers.Length]; for (int i = 0; i < tickers.Length; i++) { values[i] = tickers[i].MarketData.PriceLast; } MapPattern(values, prediction.MarketData.PriceLast); }
public override void OnTick(TickerChangedEventArgs ticker) { // Tticker prices if (ticker.CurrencyPair == Symbol) { //Debug.WriteLine("TOP BUY " + ticker.MarketData.OrderTopBuy); //Debug.WriteLine("TOP SELL " + ticker.MarketData.OrderTopSell); topBuyPrice = ticker.MarketData.OrderTopBuy; topSellPrice = ticker.MarketData.OrderTopSell; currentTickerPrice = ticker.MarketData.PriceLast; } }
public override void OnTick(TickerChangedEventArgs ticker) { // Save ticker variables if (ticker.MarketData.Volume24HourBase > 2000) { topBuyPrice = ticker.MarketData.OrderTopBuy; topSellPrice = ticker.MarketData.OrderTopSell; currentTickerPrice = ticker.MarketData.PriceLast; dailyVolume = ticker.MarketData.Volume24HourBase; perenctChangeTick = ticker.MarketData.PriceChangePercentage; } }
public override void Setup(bool simulate = false) { GUI.GUIManager.AddStrategyScreenPair(this.pair); // ---------------------------------- SetupRules(); // ---------------------------------- // Check file if this has been bought already double openPos = Utility.TradeTracker.GetOpenPosition(pair); LastBuyTime = Utility.TradeTracker.GetOpenPositionBuyTime(pair); openPosition = openPos; TickerChangedEventArgs lastTicker = Data.Store.GetLastTicker(pair); if (lastTicker == null) { throw new Exception("Couldn't build timeframe model for " + pair + " - no tickers available"); } predictorExtremes = new Data.Predictors.PriceExtremes(pair); predictorMACD = new Data.Predictors.MACD(pair, 7200); predictorVolume = new Data.Predictors.Volume(pair, 300, 7200); predictorMeanRev = new Data.Predictors.MeanReversion(pair, 7200); TickerChangedEventArgs[] tickers = Data.Store.GetTickerData(pair); if (tickers == null) { throw new Exception("Couldn't build predictor history for " + pair + " - no tickers available"); } predictorExtremes.Update(tickers); predictorVolume.Recalculate(tickers); predictorMeanRev.Recalculate(tickers); List <TickerChangedEventArgs> tickerList = new List <TickerChangedEventArgs>(); for (int i = 0; i < tickers.Length; i++) { tickerList.Add(tickers[i]); predictorMACD.Recalculate(tickerList.ToArray()); if (i % 100 == 0) { Utility.ThreadManager.ReportAlive("MeanRevADX"); } } }
public override void OnTick(TickerChangedEventArgs ticker) { // Last ticker price if (ticker.CurrencyPair == Symbol) { Debug.WriteLine("TOP BUY " + ticker.MarketData.OrderTopBuy); Debug.WriteLine("TOP SELL " + ticker.MarketData.OrderTopSell); topBuyPrice = ticker.MarketData.OrderTopBuy; topSellPrice = ticker.MarketData.OrderTopSell; } PercentChange(ticker); }
private void Live_OnTickerChanged(object sender, TickerChangedEventArgs ticker) { CurrencyPair symbol = GetSymbolCode(symbol1, symbol2); if (ticker.CurrencyPair == symbol) { TickerTextBlock.Dispatcher.Invoke(new Action(() => { TickerData.Items.Add(ticker.MarketData); TickerData.Items.Refresh(); TickerTextBlock.Text = ticker.MarketData.PriceLast.ToStringNormalized(); currentTickerPrice = ticker.MarketData.PriceLast; })); } }
public override void OnTick(TickerChangedEventArgs ticker) { // Last ticker price if (ticker.CurrencyPair == Symbol) { symbolOk = true; topBuyPrice = ticker.MarketData.OrderTopBuy; topSellPrice = ticker.MarketData.OrderTopSell; tickerPricePercentageChange = ticker.MarketData.PriceChangePercentage; tickerPriceLast = ticker.MarketData.PriceLast; } }
public override void UpdatePredictors() { TickerChangedEventArgs lastTicker = Data.Store.GetLastTicker(pair); double lastPrice = lastTicker.MarketData.PriceLast; double buyPrice = lastTicker.MarketData.OrderTopBuy; double sellPrice = lastTicker.MarketData.OrderTopSell; TickerChangedEventArgs[] tickers = Data.Store.GetTickerData(pair); if (tickers == null) { throw new Exception("Data store returned NULL tickers for pair " + pair); } predictorExtremes.Update(tickers); predictorDX.Recalculate(tickers); Utility.TradeTracker.UpdateOpenPosition(pair, buyPrice); }
public override void OnTick(TickerChangedEventArgs ticker) { // Last ticker price if (ticker.CurrencyPair == Symbol) { symbolOk = true; Debug.WriteLine("TOP BUY " + ticker.MarketData.OrderTopBuy); Debug.WriteLine("TOP SELL " + ticker.MarketData.OrderTopSell); topBuyPrice = ticker.MarketData.OrderTopBuy; topSellPrice = ticker.MarketData.OrderTopSell; tickerPricePercentageChange = ticker.MarketData.PriceChangePercentage; tickerPriceLast = ticker.MarketData.PriceLast; } //PercentChange(ticker); }
private static void AddTicker(TickerChangedEventArgs ticker, List <Trading.TPManager> tpManagers, bool evaluate) { Data.Store.AddTickerData(ticker); if (evaluate) { for (int i = 0; i < tpManagers.Count; i++) { if (ticker.CurrencyPair == tpManagers[i].GetPair()) { PoloniexBot.GUI.GUIManager.SetTradeHistoryEndTime(ticker.Timestamp); tpManagers[i].UpdatePredictors(); tpManagers[i].EvaluateAndTrade(); Trading.Manager.UpdateWalletValue(ticker.CurrencyPair.QuoteCurrency); return; } } } }
public override void UpdatePredictors() { TickerChangedEventArgs lastTicker = Data.Store.GetLastTicker(pair); double lastPrice = lastTicker.MarketData.PriceLast; double buyPrice = lastTicker.MarketData.OrderTopBuy; double sellPrice = lastTicker.MarketData.OrderTopSell; TickerChangedEventArgs[] tickers = Data.Store.GetTickerData(pair); if (tickers == null) { throw new Exception("Data store returned NULL tickers for pair " + pair); } if (tickers.Length > 0) { LastUSDTBTCPrice = tickers.Last().MarketData.PriceLast; } Manager.UpdateWalletValue("USDT", LastUSDTBTCPrice); predictorExtremes.Update(tickers); GUI.GUIManager.UpdateMainSummary(tickers); }
public override void EvaluateTrade() { TickerChangedEventArgs lastTicker = Data.Store.GetLastTicker(pair); double lastPrice = lastTicker.MarketData.PriceLast; double buyPrice = lastTicker.MarketData.OrderTopBuy; double sellPrice = lastTicker.MarketData.OrderTopSell; if (lastPrice == lastTradePrice) { return; } lastTradePrice = lastPrice; double currQuoteAmount = Manager.GetWalletState(pair.QuoteCurrency); double currBaseAmount = Manager.GetWalletState(pair.BaseCurrency); double currQuoteOrdersAmount = Manager.GetWalletStateOrders(pair.QuoteCurrency); double currTradableBaseAmount = currBaseAmount * 0.3; if (currTradableBaseAmount < RuleMinimumBaseAmount.MinimumTradeAmount) { currTradableBaseAmount = currBaseAmount; } double postBaseAmount = currQuoteAmount * buyPrice; double postQuoteAmount = currTradableBaseAmount / sellPrice; double minPrice = 0; double maxPrice = 0; double volumeTrend = 0; double priceDelta = 0; // -------------------------- Data.ResultSet.Variable tempVar; if (predictorExtremes.GetLastResult().variables.TryGetValue("min", out tempVar)) { minPrice = tempVar.value; } if (predictorExtremes.GetLastResult().variables.TryGetValue("max", out tempVar)) { maxPrice = tempVar.value; } if (predictorVolume.GetLastResult().variables.TryGetValue("ratio", out tempVar)) { volumeTrend = tempVar.value; } if (predictorPriceDelta.GetLastResult().variables.TryGetValue("priceDelta", out tempVar)) { priceDelta = tempVar.value; } // ------------------------------------------- // Compile all the rule variables into a dictionary // ------------------------------------------- Dictionary <string, double> ruleVariables = new Dictionary <string, double>(); ruleVariables.Add("lastBuyTimestamp", LastBuyTime); ruleVariables.Add("lastSellTimestamp", LastSellTime); ruleVariables.Add("lastTickerTimestamp", lastTicker.Timestamp); ruleVariables.Add("price", lastPrice); ruleVariables.Add("buyPrice", buyPrice); ruleVariables.Add("sellPrice", sellPrice); ruleVariables.Add("openPrice", openPosition); ruleVariables.Add("quoteAmountOrders", currQuoteOrdersAmount); ruleVariables.Add("quoteAmount", currQuoteAmount); ruleVariables.Add("baseAmount", currBaseAmount); ruleVariables.Add("baseAmountTradable", currTradableBaseAmount); ruleVariables.Add("postQuoteAmount", postQuoteAmount); ruleVariables.Add("postBaseAmount", postBaseAmount); ruleVariables.Add("volumeTrend", volumeTrend); ruleVariables.Add("priceDelta1", priceDelta); ruleVariables.Add("minPrice", minPrice); ruleVariables.Add("maxPrice", maxPrice); ruleVariables.Add("minGUI", lastPrice / minPrice); ruleVariables.Add("maxGUI", maxPrice / lastPrice); // ----------------------- // Update the sell band price rise offset // ----------------------- ((RuleSellBand)ruleSellBand).PriceRiseOffset = predictorExtremes.PriceRiseOffset; // ----------------------- // Recalculate all the rules // ----------------------- try { for (int i = 0; i < allRules.Length; i++) { allRules[i].Recalculate(ruleVariables); } } catch (Exception e) { Console.WriteLine("Error: " + e.Message); return; } // ---------------- // Update GUI // ---------------- GUI.GUIManager.UpdateStrategyScreenPair(this.pair, ruleVariables); Utility.TradeTracker.UpdateStopLoss(pair, ruleStopLoss.currTrigger); // ---------------- // Custom rule logic // ---------------- #region Buy Logic Tree if (ruleMinBase.Result != RuleResult.BlockBuy && ruleMinQuotePost.Result != RuleResult.BlockBuy) { // we have enough of base and will have enough of quote (after trade) to satisfy minimum trade amount (0.0001) // note: this counts the volatility factor, RuleMinimumBaseAmount uses baseAmount * volatility in verification if (ruleForce.Result == RuleResult.Buy) { Buy(sellPrice, postQuoteAmount, true); return; } if (ruleDelayAllTrades.Result != RuleResult.BlockBuySell && ruleDelayBuy.Result != RuleResult.BlockBuy && !RuleBubbleSave.BlockTrade) { // enough time has passed since the last trades were made if (ruleMinQuote.Result == RuleResult.BlockSell) { // if it's blocking sell that means we don't own quote, so go ahead with buying if (ruleVolumeTrend.Result == RuleResult.Buy && rulePriceDelta.Result == RuleResult.Buy) { Buy(sellPrice, postQuoteAmount, true); return; } } } } #endregion #region Sell Logic Tree if (ruleMinQuote.Result != RuleResult.BlockSell && ruleMinBasePost.Result != RuleResult.BlockSell) { // we have enough of quote and will have enough of base (after trade) to satisfy minimum trade amount (0.0001) if (ruleForce.Result == RuleResult.Sell) { Sell(buyPrice, currQuoteAmount, true); return; } if (ruleDelayAllTrades.Result != RuleResult.BlockBuySell) { // enough time has passed since the last trades were made if (ruleStopLoss.Result == RuleResult.Sell) { // price has dropped below stop-loss Sell(buyPrice, currQuoteAmount, true); return; } if (ruleMinSellPriceDump.Result != RuleResult.BlockSell) { // current price is profitable (0.5%) Sell(buyPrice, currQuoteAmount, false); return; } if (ruleMinSellprice.Result != RuleResult.BlockSell) { // current price is profitable (2%) if (ruleSellBand.Result == RuleResult.Sell) { // price is below the sell band Sell(buyPrice, currQuoteAmount, false); return; } } } } #endregion }
public override void EvaluateTrade() { TickerChangedEventArgs lastTicker = Data.Store.GetLastTicker(pair); double lastPrice = lastTicker.MarketData.PriceLast; double buyPrice = lastTicker.MarketData.OrderTopBuy; double sellPrice = lastTicker.MarketData.OrderTopSell; double currQuoteAmount = Manager.GetWalletState(pair.QuoteCurrency); double currBaseAmount = Manager.GetWalletState(pair.BaseCurrency); double currTradableBaseAmount = currBaseAmount * 0.3; // VolatilityScore; double postBaseAmount = currQuoteAmount * buyPrice; double postQuoteAmount = currTradableBaseAmount / sellPrice; double lowerBand = 0; double meanRev = 0; Data.ResultSet.Variable tempVar; if (predictorBollingerBands.GetLastResult().variables.TryGetValue("lowerBand", out tempVar)) { lowerBand = tempVar.value; } if (predictorMeanReverse.GetLastResult().variables.TryGetValue("score", out tempVar)) { meanRev = tempVar.value; } // ------------------------------- // Update the trade history screen // ------------------------------- // todo: update trade history // ------------------------------------------- // Compile all the rule variables into a dictionary // ------------------------------------------- Dictionary <string, double> ruleVariables = new Dictionary <string, double>(); ruleVariables.Add("lastBuyTimestamp", LastBuyTime); ruleVariables.Add("lastSellTimestamp", LastSellTime); ruleVariables.Add("lastTickerTimestamp", lastTicker.Timestamp); ruleVariables.Add("price", lastPrice); ruleVariables.Add("buyPrice", buyPrice); ruleVariables.Add("sellPrice", sellPrice); ruleVariables.Add("openPrice", openPosition); ruleVariables.Add("maxPrice", maximumPrice); ruleVariables.Add("quoteAmount", currQuoteAmount); ruleVariables.Add("baseAmount", currBaseAmount); ruleVariables.Add("baseAmountTradable", currTradableBaseAmount); ruleVariables.Add("postQuoteAmount", postQuoteAmount); ruleVariables.Add("postBaseAmount", postBaseAmount); ruleVariables.Add("bollingerBandLow", lowerBand); ruleVariables.Add("meanRev", meanRev); // ----------------------- // Recalculate global rules // ----------------------- ruleGlobalTrend.Recalculate(ruleVariables, pair); ruleVariables.Add("mRevGlobal", RuleGlobalDrop.GetGlobalTrend()); // ----------------------- // Recalculate all the rules // ----------------------- try { for (int i = 0; i < allRules.Length; i++) { allRules[i].Recalculate(ruleVariables); } } catch (Exception e) { Console.WriteLine("Error: " + e.Message); return; } // ---------------- // Update GUI // ---------------- GUI.GUIManager.UpdateStrategyScreenPair(this.pair, ruleVariables); // ---------------- // Custom rule logic // ---------------- #region Buy Logic Tree if (ruleMinBase.Result != RuleResult.BlockBuy && ruleMinQuotePost.Result != RuleResult.BlockBuy) { // we have enough of base and will have enough of quote (after trade) to satisfy minimum trade amount (0.0001) // note: this counts the volatility factor, RuleMinimumBaseAmount uses baseAmount * volatility in verification if (ruleForce.Result == RuleResult.Buy) { Buy(sellPrice, postQuoteAmount); return; } if (ruleDelayAllTrades.Result != RuleResult.BlockBuySell && ruleDelayBuy.Result != RuleResult.BlockBuy) { // enough time has passed since the last trades were made if (ruleMinQuote.Result == RuleResult.BlockSell) { // if it's blocking sell that means we don't own quote, so go ahead with buying if (ruleGlobalTrend.Result == RuleResult.None) { // global trend isn't dropping if (ruleBollingerBuy.Result == RuleResult.Buy && ruleMeanRev.Result == RuleResult.Buy) { // price is below the low bollinger line Buy(sellPrice, postQuoteAmount); return; } } } } } #endregion #region Sell Logic Tree if (ruleMinQuote.Result != RuleResult.BlockSell && ruleMinBasePost.Result != RuleResult.BlockSell) { // we have enough of quote and will have enough of base (after trade) to satisfy minimum trade amount (0.0001) if (ruleForce.Result == RuleResult.Sell) { Sell(buyPrice, currQuoteAmount); return; } if (ruleDelayAllTrades.Result != RuleResult.BlockBuySell) { // enough time has passed since the last trades were made if (ruleMinSellprice.Result != RuleResult.BlockSell && ruleDump.Result == RuleResult.Sell) { // current price is profitable and pair is in dump mode Sell(buyPrice, currQuoteAmount); return; } if (ruleMinSellprice.Result != RuleResult.BlockSell && ruleSellBand.Result == RuleResult.Sell) { // current price is profitable and is below the sell band Sell(buyPrice, currQuoteAmount); return; } if (ruleStopLoss.Result == RuleResult.Sell) { // the price has dropped 10% since buying // sell to prevent further losses Sell(buyPrice, currQuoteAmount); return; } } } #endregion }
public void Recalculate(long timestamp, double price, double[] values) { // adx, boll, macd, meanRev, priceDelta TickerChangedEventArgs tempTicker = new TickerChangedEventArgs(pair, new PoloniexAPI.MarketTools.MarketData(price)); tempTicker.Timestamp = timestamp; predictorExtremes.Update(new TickerChangedEventArgs[] { tempTicker }); Utility.TradeTracker.UpdateOpenPosition(pair, price); // ------------------------------ double lastPrice = price; double buyPrice = price; double sellPrice = price; double currQuoteAmount = Manager.GetWalletState(pair.QuoteCurrency); double currBaseAmount = Manager.GetWalletState(pair.BaseCurrency); double currTradableBaseAmount = currBaseAmount * 0.3; // VolatilityScore; double postBaseAmount = currQuoteAmount * buyPrice; double postQuoteAmount = currTradableBaseAmount / sellPrice; double adx = values[0]; double boll = values[1]; double macd = values[2]; double meanRev = values[3]; double priceDelta = values[4]; double minPrice = 0; double maxPrice = 0; // -------------------------- Data.ResultSet.Variable tempVar; if (predictorExtremes.GetLastResult().variables.TryGetValue("min", out tempVar)) { minPrice = tempVar.value; } if (predictorExtremes.GetLastResult().variables.TryGetValue("max", out tempVar)) { maxPrice = tempVar.value; } // -------------------------- // ------------------------------------------- // Compile all the rule variables into a dictionary // ------------------------------------------- Dictionary <string, double> ruleVariables = new Dictionary <string, double>(); ruleVariables.Add("lastBuyTimestamp", LastBuyTime); ruleVariables.Add("lastSellTimestamp", LastSellTime); ruleVariables.Add("lastTickerTimestamp", timestamp); ruleVariables.Add("price", lastPrice); ruleVariables.Add("buyPrice", buyPrice); ruleVariables.Add("sellPrice", sellPrice); ruleVariables.Add("openPrice", openPosition); ruleVariables.Add("quoteAmount", currQuoteAmount); ruleVariables.Add("baseAmount", currBaseAmount); ruleVariables.Add("baseAmountTradable", currTradableBaseAmount); ruleVariables.Add("postQuoteAmount", postQuoteAmount); ruleVariables.Add("postBaseAmount", postBaseAmount); ruleVariables.Add("adx", adx); ruleVariables.Add("bandSizeDelta", boll); ruleVariables.Add("macd", macd); ruleVariables.Add("meanRev", meanRev); ruleVariables.Add("priceDelta", priceDelta); ruleVariables.Add("minPrice", minPrice); ruleVariables.Add("maxPrice", maxPrice); ruleVariables.Add("minGUI", lastPrice / minPrice); ruleVariables.Add("maxGUI", maxPrice / lastPrice); // ----------------------- // Recalculate all the rules // ----------------------- try { for (int i = 0; i < allRules.Length; i++) { allRules[i].Recalculate(ruleVariables); } } catch (Exception e) { Console.WriteLine("Error: " + e.Message); return; } // ---------------- // Update GUI // ---------------- GUI.GUIManager.UpdateStrategyScreenPair(this.pair, ruleVariables); // ---------------- // Custom rule logic // ---------------- #region Buy Logic Tree if (ruleMinBase.Result != RuleResult.BlockBuy && ruleMinQuotePost.Result != RuleResult.BlockBuy) { // we have enough of base and will have enough of quote (after trade) to satisfy minimum trade amount (0.0001) // note: this counts the volatility factor, RuleMinimumBaseAmount uses baseAmount * volatility in verification if (ruleDelayAllTrades.Result != RuleResult.BlockBuySell && ruleDelayBuy.Result != RuleResult.BlockBuy) { // enough time has passed since the last trades were made if (ruleMinQuote.Result == RuleResult.BlockSell) { // if it's blocking sell that means we don't own quote, so go ahead with buying if (ruleADX.currentResult == RuleResult.Buy && ruleMeanRev.currentResult == RuleResult.Buy) { // price has stopped falling and is below average Buy(sellPrice, postQuoteAmount, timestamp); return; } } } } #endregion #region Sell Logic Tree if (ruleMinQuote.Result != RuleResult.BlockSell && ruleMinBasePost.Result != RuleResult.BlockSell) { // we have enough of quote and will have enough of base (after trade) to satisfy minimum trade amount (0.0001) if (ruleDelayAllTrades.Result != RuleResult.BlockBuySell) { // enough time has passed since the last trades were made if (ruleMinSellprice.Result != RuleResult.BlockSell) { // current price is profitable if (ruleSellBand.Result == RuleResult.Sell) { // price is below the sell band Sell(buyPrice, currQuoteAmount, timestamp); return; } } if (ruleStopLoss.Result == RuleResult.Sell) { // price has dropped below stop-loss Sell(buyPrice, currQuoteAmount, timestamp); return; } } } #endregion }
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously public virtual void OnTick(TickerChangedEventArgs ticker) { // Override this method on sub classes // Find a way to call this method after each tick change on price(bid or ask) }
// Percentage Change public void PercentChange(TickerChangedEventArgs ticker) { DateTime startdate = new DateTime(2017, 1, 1); DateTime enddate = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, 0); var CandleSeries = Client.PoloniexClient.Markets.GetChartDataAsync(Symbol, MarketSeries, startdate, enddate); var candleSeries = CandleSeries.Result; var index = candleSeries.Count() - 2; //Percent Drop Calc if (ticker.CurrencyPair == Symbol) { double lastClose = candleSeries[index].Close; double percentChange = Math.Round(((ticker.MarketData.PriceLast - lastClose) / ticker.MarketData.PriceLast) * 100, 4); double tickerPercentChange = ticker.MarketData.PriceChangePercentage; // Output IBS to datawindow outputData.Dispatcher.Invoke(new Action(() => { outputData.Strategy1Output.Text += "Percentage Change" + "\n" + percentChange + "\n" + DateTime.Now.ToString() + "\n" + "-------------------" + "\n"; outputData.Strategy1Output.Text += "Ticker Change" + "\n" + tickerPercentChange + "\n" + DateTime.Now.ToString() + "\n" + "-------------------" + "\n"; outputData.Strategy1Output.Text += "Last Close" + "\n" + lastClose + "\n" + candleSeries[index].Time + "\n" + "-------------------" + "\n"; outputData.Strategy1Output.Text += "Last Ticker Price" + "\n" + ticker.MarketData.PriceLast + "\n" + DateTime.Now.ToString() + "\n" + "-------------------" + "\n"; })); //Buy try { if ((bool)Buy) { //if (CandleSeries[index].Close > CandleSeries[index].Open && percentChange <= 1) if (percentChange <= -1) { //double pricePerCoinBuy = await currentPrice.CurrentMarketPrice(Symbol, OrderType.Buy); var volume = quantity.TotalToQuantity(Total, topBuyPrice); Dispatcher.CurrentDispatcher.Invoke(() => { var buyOrder = Task.Run(async() => { await marketOrder.ExecuteMarketOrder(Symbol, OrderType.Buy, volume); }); //var buyOrder = marketOrder.ExecuteMarketOrder(Symbol, OrderType.Buy, volume); buyOrder.Wait(); }); // Output IBS to datawindow string tradeOutputBuy = DateTime.Now + "\n" + "Volume = " + volume + "\n" + OrderType.Buy + "\n" + "% Change = " + percentChange + "\n" + "-------------------" + "\n"; Debug.WriteLine(tradeOutputBuy); outputData.Strategy1Output.Text += tradeOutputBuy; } } if ((bool)Sell) { if (percentChange >= 100) { var quoteBalance = balance.GetBalance(Symbol.QuoteCurrency); var balanceQuote = quoteBalance.Result; if (balanceQuote > minOrderSize) { if (balanceQuote > minOrderSize) { //double pricePerCoinSell = await currentPrice.CurrentMarketPrice(Symbol, OrderType.Sell); var volume = quantity.TotalToQuantity(Total, topSellPrice); Dispatcher.CurrentDispatcher.Invoke(() => { var sellOrder = Task.Run(async() => { await marketOrder.ExecuteMarketOrder(Symbol, OrderType.Sell, volume); }); sellOrder.Wait(); }); // Output IBS to datawindow string tradeOutputSell = DateTime.Now + "\n" + "Volume = " + volume + "\n" + OrderType.Sell + "\n" + "% Change = " + percentChange + "\n" + "-------------------" + "\n"; Debug.WriteLine(tradeOutputSell); outputData.Strategy1Output.Text += tradeOutputSell; } } } } } catch (Exception error) { Console.WriteLine(error.Message); //MessageDialogue.Show("Order Error" + error.Message); } } }
public void TickChanged(object sender, TickerChangedEventArgs ticker) { OnTick(ticker); }
public static bool PullTickerHistory(CurrencyPair pair, long startTimestamp, long endTimestamp) { if (!AllowTickerUpdate) { return(false); } if (tickerData == null) { tickerData = new TSList <TSList <TickerChangedEventArgs> >(); } if (allowUpdatePairs == null) { allowUpdatePairs = new List <CurrencyPair>(); } // pull last trades List <PoloniexAPI.MarketTools.ITrade> trades = new List <ITrade>(); int failedAttempts = 0; while (true) { try { List <PoloniexAPI.MarketTools.ITrade> temp = WebApiCustom.GetTrades(pair, (int)startTimestamp, (int)endTimestamp); trades.AddRange(temp); if (temp.Count < 300) { break; } endTimestamp = Utility.DateTimeHelper.DateTimeToUnixTimestamp(temp.Last().Time); failedAttempts = 0; ThreadManager.ReportAlive("Data.Store"); Thread.Sleep(1500); } catch (Exception e) { // Console.WriteLine(e.Message + "\n" + e.StackTrace); Console.WriteLine(pair + " - ERROR"); failedAttempts++; if (failedAttempts >= 5) { return(false); } Thread.Sleep(4000); } } // convert into fake tickers if (trades.Count == 0) { return(false); } TickerChangedEventArgs[] fakeTickers = new TickerChangedEventArgs[trades.Count]; for (int j = 0; j < trades.Count; j++) { MarketData md = new MarketData(trades[j].PricePerCoin); TickerChangedEventArgs ticker = new TickerChangedEventArgs(pair, md); ticker.Timestamp = DateTimeHelper.DateTimeToUnixTimestamp(trades[j].Time); fakeTickers[j] = ticker; } // dump them into ticker data TSList <TickerChangedEventArgs> tickerList = new TSList <TickerChangedEventArgs>(fakeTickers); tickerList.Sort(); tickerData.Add(tickerList); allowUpdatePairs.Add(pair); return(true); }
public override void EvaluateTrade() { TickerChangedEventArgs lastTicker = Data.Store.GetLastTicker(pair); double lastPrice = lastTicker.MarketData.PriceLast; double buyPrice = lastTicker.MarketData.OrderTopBuy; double sellPrice = lastTicker.MarketData.OrderTopSell; double currQuoteAmount = Manager.GetWalletState(pair.QuoteCurrency); double currBaseAmount = Manager.GetWalletState(pair.BaseCurrency); double currTradableBaseAmount = currBaseAmount * 0.5; // VolatilityScore; if (currTradableBaseAmount < RuleMinimumBaseAmount.MinimumAllowedTradeAmount) { currTradableBaseAmount = currBaseAmount; } double postBaseAmount = currQuoteAmount * buyPrice; double postQuoteAmount = currTradableBaseAmount / sellPrice; double minPrice = 0; double maxPrice = 0; double delta1 = 0; double delta2 = 0; double delta3 = 0; // -------------------------- Data.ResultSet.Variable tempVar; if (predictorExtremes.GetLastResult().variables.TryGetValue("min", out tempVar)) { minPrice = tempVar.value; } if (predictorExtremes.GetLastResult().variables.TryGetValue("max", out tempVar)) { maxPrice = tempVar.value; } if (predictorDX.GetLastResult().variables.TryGetValue("delta1", out tempVar)) { delta1 = tempVar.value; } if (predictorDX.GetLastResult().variables.TryGetValue("delta2", out tempVar)) { delta2 = tempVar.value; } if (predictorDX.GetLastResult().variables.TryGetValue("delta3", out tempVar)) { delta3 = tempVar.value; } // ------------------------------------------- // Compile all the rule variables into a dictionary // ------------------------------------------- Dictionary <string, double> ruleVariables = new Dictionary <string, double>(); ruleVariables.Add("lastBuyTimestamp", LastBuyTime); ruleVariables.Add("lastSellTimestamp", LastSellTime); ruleVariables.Add("lastTickerTimestamp", lastTicker.Timestamp); ruleVariables.Add("price", lastPrice); ruleVariables.Add("buyPrice", buyPrice); ruleVariables.Add("sellPrice", sellPrice); ruleVariables.Add("openPrice", openPosition); ruleVariables.Add("quoteAmount", currQuoteAmount); ruleVariables.Add("baseAmount", currBaseAmount); ruleVariables.Add("baseAmountTradable", currTradableBaseAmount); ruleVariables.Add("postQuoteAmount", postQuoteAmount); ruleVariables.Add("postBaseAmount", postBaseAmount); ruleVariables.Add("priceDelta1", delta1); // ruleVariables.Add("priceDelta2", delta2); // ruleVariables.Add("priceDelta3", delta3); ruleVariables.Add("minPrice", minPrice); ruleVariables.Add("maxPrice", maxPrice); ruleVariables.Add("minGUI", lastPrice / minPrice); ruleVariables.Add("maxGUI", maxPrice / lastPrice); DayOfWeek dof = Utility.DateTimeHelper.UnixTimestampToDateTime(lastTicker.Timestamp).DayOfWeek; if (dof == DayOfWeek.Saturday || dof == DayOfWeek.Sunday) { return; } // ----------------------- // Recalculate all the rules // ----------------------- try { for (int i = 0; i < allRules.Length; i++) { allRules[i].Recalculate(ruleVariables); } } catch (Exception e) { Console.WriteLine("Error: " + e.Message); return; } // ---------------- // Update GUI // ---------------- GUI.GUIManager.UpdateStrategyScreenPair(this.pair, ruleVariables); // ---------------- // Custom rule logic // ---------------- #region Buy Logic Tree if (ruleMinBase.Result != RuleResult.BlockBuy && ruleMinQuotePost.Result != RuleResult.BlockBuy) { // we have enough of base and will have enough of quote (after trade) to satisfy minimum trade amount (0.0001) // note: this counts the volatility factor, RuleMinimumBaseAmount uses baseAmount * volatility in verification if (ruleForce.Result == RuleResult.Buy) { Buy(sellPrice, postQuoteAmount); return; } if (ruleDelayAllTrades.Result != RuleResult.BlockBuySell && ruleDelayBuy.Result != RuleResult.BlockBuy) { // enough time has passed since the last trades were made if (ruleMinQuote.Result == RuleResult.BlockSell) { // if it's blocking sell that means we don't own quote, so go ahead with buying if (rulePriceDelta.currentResult == RuleResult.Buy) { // price is on an upwards trend Buy(sellPrice, postQuoteAmount); return; } } } } #endregion #region Sell Logic Tree if (ruleMinQuote.Result != RuleResult.BlockSell && ruleMinBasePost.Result != RuleResult.BlockSell) { // we have enough of quote and will have enough of base (after trade) to satisfy minimum trade amount (0.0001) if (ruleForce.Result == RuleResult.Sell) { Sell(buyPrice, currQuoteAmount); return; } if (ruleDelayAllTrades.Result != RuleResult.BlockBuySell) { // enough time has passed since the last trades were made if (ruleMinSellprice.Result != RuleResult.BlockSell) { // current price is profitable Sell(buyPrice, currQuoteAmount); return; } /* * * * if (ruleSellBand.Result == RuleResult.Sell) { * // price is below the sell band * * Sell(buyPrice, currQuoteAmount); * SaveTradeData(true, LastSellTime - LastBuyTime); * return; * } * } */ if (ruleStopLoss.Result == RuleResult.Sell) { // price has dropped below stop-loss Sell(buyPrice, currQuoteAmount); return; } } } #endregion }
public override void EvaluateTrade() { TickerChangedEventArgs lastTicker = Data.Store.GetLastTicker(pair); double lastPrice = lastTicker.MarketData.PriceLast; double buyPrice = lastTicker.MarketData.OrderTopBuy; double sellPrice = lastTicker.MarketData.OrderTopSell; double currQuoteAmount = Manager.GetWalletState(pair.QuoteCurrency); double currBaseAmount = Manager.GetWalletState(pair.BaseCurrency); double currQuoteOrdersAmount = Manager.GetWalletStateOrders(pair.QuoteCurrency); double currBaseOrdersAmount = Manager.GetWalletStateOrders(pair.BaseCurrency); double currTradableBaseAmount = currBaseAmount * 0.5; if (currTradableBaseAmount < RuleMinimumBaseAmount.MinimumAllowedTradeAmount) { currTradableBaseAmount = currBaseAmount; } double postBaseAmount = currQuoteAmount * buyPrice; double postQuoteAmount = currTradableBaseAmount / sellPrice; double minPrice = 0; double maxPrice = 0; double delta1 = 0; // -------------------------- Data.ResultSet.Variable tempVar; if (predictorExtremes.GetLastResult().variables.TryGetValue("min", out tempVar)) { minPrice = tempVar.value; } if (predictorExtremes.GetLastResult().variables.TryGetValue("max", out tempVar)) { maxPrice = tempVar.value; } if (predictorDX.GetLastResult().variables.TryGetValue("delta1", out tempVar)) { delta1 = tempVar.value; } // ------------------------------------------- // Compile all the rule variables into a dictionary // ------------------------------------------- Dictionary <string, double> ruleVariables = new Dictionary <string, double>(); ruleVariables.Add("lastBuyTimestamp", LastBuyTime); ruleVariables.Add("lastSellTimestamp", LastSellTime); ruleVariables.Add("lastTickerTimestamp", lastTicker.Timestamp); ruleVariables.Add("price", lastPrice); ruleVariables.Add("buyPrice", buyPrice); ruleVariables.Add("sellPrice", sellPrice); ruleVariables.Add("openPrice", openPosition); ruleVariables.Add("quoteAmount", currQuoteAmount); ruleVariables.Add("baseAmount", currBaseAmount); ruleVariables.Add("quoteAmountOrders", currQuoteOrdersAmount); ruleVariables.Add("baseAmountOrders", currBaseOrdersAmount); ruleVariables.Add("baseAmountTradable", currTradableBaseAmount); ruleVariables.Add("postQuoteAmount", postQuoteAmount); ruleVariables.Add("postBaseAmount", postBaseAmount); ruleVariables.Add("priceDelta1", delta1); ruleVariables.Add("minPrice", minPrice); ruleVariables.Add("maxPrice", maxPrice); ruleVariables.Add("minGUI", lastPrice / minPrice); ruleVariables.Add("maxGUI", maxPrice / lastPrice); // ----------------------- // Recalculate all the rules // ----------------------- try { for (int i = 0; i < allRules.Length; i++) { allRules[i].Recalculate(ruleVariables); } } catch (Exception e) { Console.WriteLine("Error: " + e.Message); return; } // ---------------- // Update GUI // ---------------- GUI.GUIManager.UpdateStrategyScreenPair(this.pair, ruleVariables); // ---------------- // Custom rule logic // ---------------- if (ruleDelayAllTrades.Result != RuleResult.BlockBuySell) { // look at base order amount (phase 2: buying) if (ruleMinBaseOrders.Result != RuleResult.BlockBuy) { // update the buy order if (buyPrice > orderPrice) { // price is higher then my buy price, so move mine to the top Move(orderID, buyPrice + Utility.Constants.OneSatoshi, true); return; } return; } // look at quote amount (phase 3: need to sell) if (ruleMinQuote.Result != RuleResult.BlockSell && ruleMinBasePost.Result != RuleResult.BlockSell) { // we have enough of quote and will have enough of base (after trade) to satisfy minimum trade amount (0.0001) Sell(openPosition * 1.015, currQuoteAmount); return; } // look at base amount (phase 1: need to buy) if (ruleMinBase.Result != RuleResult.BlockBuy && ruleMinQuotePost.Result != RuleResult.BlockBuy) { // we have enough of base and will have enough of quote (after trade) to satisfy minimum trade amount (0.0001) // note: this counts the volatility factor, RuleMinimumBaseAmount uses baseAmount * volatility in verification if (ruleForce.Result == RuleResult.Buy) { Buy(buyPrice + Utility.Constants.OneSatoshi, postQuoteAmount); return; } if (rulePriceDelta.currentResult == RuleResult.Buy) { // price has stopped falling and is below average Buy(buyPrice + Utility.Constants.OneSatoshi, postQuoteAmount); return; } return; } } }
public static TSList <TSList <TickerChangedEventArgs> > LoadTradeData(bool addTickers = true) { CLI.Manager.PrintLog("Clearing trade pairs"); Trading.Manager.ClearAllPairs(); CLI.Manager.PrintLog("Clearing current ticker data"); if (allowUpdatePairs != null) { allowUpdatePairs.Clear(); } if (tickerData == null) { tickerData = new TSList <TSList <TickerChangedEventArgs> >(); } ClearTickerData(); CLI.Manager.PrintLog("Loading ticker data from file"); string[] lines = Utility.FileManager.ReadFile("data/ticker data"); if (lines == null || lines.Length == 0) { throw new Exception("Failed reading file - no lines returned"); } TSList <TSList <TickerChangedEventArgs> > tickerStoreReference; if (addTickers) { tickerStoreReference = tickerData; } else { tickerStoreReference = new TSList <TSList <TickerChangedEventArgs> >(); } for (int i = 0; i < lines.Length; i++) { string[] parts = lines[i].Split(':'); CurrencyPair currPair = CurrencyPair.Parse(parts[0]); long currTimestamp = long.Parse(parts[1]); double currPrice = double.Parse(parts[2]); double volume24Base = double.Parse(parts[3]); TickerChangedEventArgs currTicker = new TickerChangedEventArgs(currPair, new MarketData(currPrice)); currTicker.Timestamp = currTimestamp; currTicker.MarketData.Volume24HourBase = volume24Base; if (allowUpdatePairs == null) { allowUpdatePairs = new List <CurrencyPair>(); } if (!allowUpdatePairs.Contains(currPair)) { allowUpdatePairs.Add(currPair); } // add to list bool added = false; for (int j = 0; j < tickerStoreReference.Count; j++) { if (tickerStoreReference[j][0].CurrencyPair == currPair) { tickerStoreReference[j].Add(currTicker); added = true; break; } } if (!added) { tickerStoreReference.Add(new TSList <TickerChangedEventArgs>()); tickerStoreReference.Last().Add(currTicker); } } CLI.Manager.PrintLog("Loading complete (" + lines.Length + " tickers)"); return(tickerStoreReference); }