public BittrexTradeManager(ITradingStrategy strat, INotificationManager notificationManager, Action <string> log) { _api = new BittrexApi(Constants.IsDryRunning); _strategy = strat; _log = log; _notification = notificationManager; }
public static async Task <List <BackTestResult> > BackTestShowTrades(ITradingStrategy strategy, BacktestOptions backtestOptions, IDataStoreBacktest dataStore) { var runner = new BackTestRunner(); var results = await runner.RunSingleStrategy(strategy, backtestOptions, dataStore); return(results); }
public static async void BackTestConsole(ITradingStrategy strategy, BacktestOptions backtestOptions, IDataStoreBacktest dataStore) { List <BackTestResult> results = await BackTest(strategy, backtestOptions, dataStore); if (results.Count > 0) { Console.WriteLine(results .OrderByDescending(x => x.SuccessRate) .ToList() .ToStringTable(new[] { "Market", "# Trades", "# Profitable", "Success Rate", "BTC Profit", "Profit %", "Avg. Duration", "Period" }, (x) => x.Market, (x) => x.AmountOfTrades, (x) => x.AmountOfProfitableTrades, (x) => $"{x.SuccessRate:0.00}%", (x) => $"{x.TotalProfit:0.00000000}", (x) => $"{x.TotalProfitPercentage:0.00}%", (x) => $"{(x.AverageDuration):0.00} hours", (x) => $"{x.DataPeriod} days")); } else { ConsoleUtility.WriteColoredLine("\tNo backtests results found...", ConsoleColor.Red); } ConsoleUtility.WriteSeparator(); }
public static async Task <JArray> BackTestJson(ITradingStrategy strategy, BacktestOptions backtestOptions, IDataStoreBacktest dataStore) { List <BackTestResult> results = await BackTest(strategy, backtestOptions, dataStore); JArray jArrayResult = new JArray(); if (results.Count > 0) { foreach (var result in results) { JObject currentResult = new JObject(); currentResult["Market"] = result.Market; currentResult["Strategy"] = strategy.Name; currentResult["AmountOfTrades"] = result.AmountOfTrades; currentResult["AmountOfProfitableTrades"] = result.AmountOfProfitableTrades; currentResult["SuccessRate"] = result.SuccessRate; currentResult["TotalProfit"] = result.TotalProfit; currentResult["TotalProfitPercentage"] = result.TotalProfitPercentage; currentResult["AverageDuration"] = result.AverageDuration; currentResult["DataPeriod"] = result.DataPeriod; jArrayResult.Add(currentResult); } } return(jArrayResult); }
public TradingStrategyPredicator( double initialCapital, double currentCapital, ITradingStrategy strategy, IDictionary <ParameterAttribute, object> strategyParameters, ITradingDataProvider provider, StockBlockRelationshipManager relationshipManager, int positionFrozenDays, IEnumerable <Position> activePositions, ILogger logger) { if (strategy == null || provider == null) { throw new ArgumentNullException(); } _strategy = strategy; _strategyParameterValues = strategyParameters; _provider = provider; _equityManager = new EquityManager(new SimpleCapitalManager(initialCapital, currentCapital), positionFrozenDays); _unprocessedActivePositions = activePositions.ToList(); _context = new StandardEvaluationContext(_provider, _equityManager, logger, null, null, relationshipManager); }
private static void BackTest(ITradingStrategy strategy) { var runner = new BackTestRunner(); var results = runner.RunSingleStrategy(strategy, CoinsToBacktest, StakeAmount); Console.WriteLine(); Console.WriteLine($"\t=============== BACKTESTING REPORT {strategy.Name.ToUpper()} ==============="); Console.WriteLine(); WriteColoredLine($"\tNote: Profit is based on trading with 0.1 BTC each trade.", ConsoleColor.Cyan); Console.WriteLine(); // Prints the results for each coin for this strategy. if (results.Count > 0) { Console.WriteLine(results .OrderByDescending(x => x.SuccessRate) .ToList() .ToStringTable <BackTestResult>(new string[] { "Market", "# Trades", "# Profitable", "Success Rate", "BTC Profit", "Profit %", "Avg. Duration", "Period" }, (x) => x.Market, (x) => x.AmountOfTrades, (x) => x.AmountOfProfitableTrades, (x) => $"{x.SuccessRate:0.00}%", (x) => $"{x.TotalProfit:0.00000000}", (x) => $"{x.TotalProfitPercentage:0.00}%", (x) => $"{(x.AverageDuration):0.00} hours", (x) => $"{x.DataPeriod} days")); } else { WriteColoredLine("\tNo backtests results found...", ConsoleColor.Red); } WriteSeparator(); }
public static async Task <JArray> BackTestShowTradesJson(ITradingStrategy strategy, BacktestOptions backtestOptions, IDataStoreBacktest dataStore) { var results = await BackTestShowTrades(strategy, backtestOptions, dataStore); JArray jArrayResult = new JArray(); var trades = new List <BackTestTradeResult>(); foreach (var result in results) { trades.AddRange(result.Trades); } foreach (var trade in trades) { JObject currentResult = new JObject(); currentResult["Strategy"] = strategy.Name; currentResult["Market"] = trade.Market; currentResult["OpenRate"] = trade.OpenRate; currentResult["CloseRate"] = trade.CloseRate; currentResult["Profit"] = trade.Profit; currentResult["ProfitPercentage"] = trade.ProfitPercentage; currentResult["Duration"] = trade.Duration; currentResult["StartDate"] = trade.StartDate; currentResult["EndDate"] = trade.EndDate; jArrayResult.Add(currentResult); } return(jArrayResult); }
public static async Task <List <BackTestResult> > BackTest(ITradingStrategy strategy, BacktestOptions backtestOptions, IDataStoreBacktest dataStore, string baseCurrency, bool saveSignals, decimal startingWallet, decimal tradeAmount) { var runner = new BackTestRunner(); var results = await runner.RunSingleStrategy(strategy, backtestOptions, dataStore, baseCurrency, saveSignals, startingWallet, tradeAmount); return(results); }
public GdaxApi(string apiKey, string apiSecret, string apiPassPhrase, string slackWebhook, ILogger logger, ITradingStrategy tradingStrategy) { _apiKey = apiKey; _apiSecret = apiSecret; _apiPassPhrase = apiPassPhrase; SlackWebhook = slackWebhook; Logger = logger; TradingStrategy = tradingStrategy ?? new TradingStrategy { MinutesOfAccountHistoryOrderForPurchaseDecision = 60, MinutesOfAccountHistoryOrderForSellDecision = 60, MinutesOfPublicHistoryOrderForPurchaseDecision = 30, MinutesOfPublicHistoryOrderForSellDecision = 30, MinimumReservePercentageAfterInitInTargetCurrency = 0.1m, MinimumReservePercentageAfterInitInExchangeCurrency = 0.1m, OrderCapPercentageAfterInit = 0.6m, OrderCapPercentageOnInit = 0.25m, AutoDecisionExecution = true, MarketChangeSensitivityRatio = 0.01m, PriceCorrectionFrequencyInHours = 24, TradingValueBleedRatio = 0.1m }; Rest = new Rest("https://api.gdax.com", new RestConfig { OperationMode = RestMode.HTTPRestClient, UseRestConvertForCollectionSerialization = false }, logger); }
public GenericTradeManager(IExchangeApi api, ITradingStrategy strat, INotificationManager notificationManager, Action <string> log) { _api = api; _strategy = strat; _log = log; _notification = notificationManager; }
public TradingContext(IExchangeCode exchange, string symbol, ITradingStrategy strategy, IEnumerable <ICandle> candles) { _exchange = exchange; _symbol = symbol; _strategy = strategy; _candles = candles; }
public async Task <TradingContext> Build(ExchangeCode exchangeCode, string symbol) { ITradingStrategy strategy = null; IEnumerable <ICandle> candles = null; return(await WithConnection(async (connection, transaction) => { Strategy strategyInfo = await _strategyManager.Get(exchangeCode, symbol, connection); if (!strategyInfo.IsEnabled) { return null; } Type type = Type.GetType(strategyInfo.TypeName, true, true); strategy = (ITradingStrategy)Activator.CreateInstance(type); // TODO: Add Strategy preset support //strategy.Preset = strategyInfo.Preset; candles = await _candlesManager.GetLastCandles(exchangeCode, symbol, strategy.OptimalTimeframe.Code, strategy.MinNumberOfCandles, connection, transaction); TradingContext context = new TradingContext(exchangeCode, symbol, strategy, candles); return context; })); }
public TradingStrategyEvaluator( int numberOfAccounts, int accountId, ICapitalManager capitalManager, ITradingStrategy strategy, IDictionary <ParameterAttribute, object> strategyParameters, ITradingDataProvider provider, StockBlockRelationshipManager relationshipManager, TradingSettings settings, ILogger logger, StreamWriter dumpDataWriter) { if (numberOfAccounts <= 0 || accountId < 0 || accountId >= numberOfAccounts) { throw new ArgumentOutOfRangeException(); } if (strategy == null || provider == null || settings == null) { throw new ArgumentNullException(); } _numberOfAccounts = numberOfAccounts; _accountId = accountId; _strategy = strategy; _strategyParameterValues = strategyParameters; _provider = provider; _settings = settings; _equityManager = new EquityManager(capitalManager, _settings.PositionFrozenDays); _context = new StandardEvaluationContext(_provider, _equityManager, logger, settings, dumpDataWriter, relationshipManager); _tradingTracker = new TradingTracker(capitalManager.InitialCapital); }
public LiveTradeManager(IExchangeApi api, ITradingStrategy strategy, INotificationManager notificationManager, ILogger logger, TradeOptions settings, IDataStore dataStore) { _api = api; _strategy = strategy; _logger = logger; _notification = notificationManager; _dataStore = dataStore; _settings = settings; if (_api == null) { throw new ArgumentException("Invalid exchange provided..."); } if (_strategy == null) { throw new ArgumentException("Invalid strategy provided..."); } if (_dataStore == null) { throw new ArgumentException("Invalid data store provided..."); } if (_settings == null) { throw new ArgumentException("Invalid settings provided..."); } if (_logger == null) { throw new ArgumentException("Invalid logger provided..."); } }
public NotifyOnlyTradeManager(IExchangeApi api, ITradingStrategy strategy, INotificationManager notificationManager, string buyMessage, string sellMessage, ILogger logger, TradeOptions settings) { _api = api; _strategy = strategy; _logger = logger; _notification = notificationManager; _buyMessage = buyMessage; _sellMessage = sellMessage; _settings = settings; }
/// <summary> /// Shows the strategy form for live trading. /// Not entirely finished /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnStrategy_Click(object sender, EventArgs e) { using (var f = new BackTestingForm()) { if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK) { _strategy = f.TradingStrategy; } } }
public List <BackTestResult> RunSingleStrategy(ITradingStrategy strategy, List <string> coinsToTest, decimal stakeAmount) { var results = new List <BackTestResult>(); // Go through our coinpairs and backtest them. foreach (var pair in coinsToTest) { var candleProvider = new JsonCandleProvider("data"); // This creates a list of buy signals. var candles = candleProvider.GetCandles(pair); var trend = strategy.Prepare(candles); var backTestResult = new BackTestResult { Market = pair }; for (int i = 0; i < trend.Count; i++) { if (trend[i] == TradeAdvice.Buy) { // Calculate win/lose forwards from buy point for (int j = i; j < trend.Count; j++) { // Sell as soon as the strategy tells us to.. if (trend[j] == TradeAdvice.Sell) { // We ignore fees for now. Goal of the backtester is to compare strategy efficiency. var currentProfitPercentage = ((candles[j].Close - candles[i].Close) / candles[i].Close) * 100; var quantity = stakeAmount / candles[i].Close; // We always trade with 0.1 BTC. var currentProfit = (candles[j].Close - candles[i].Close) * quantity; backTestResult.Trades.Add(new BackTestTradeResult { Quatity = quantity, OpenRate = candles[i].Close, CloseRate = candles[j].Close, ProfitPercentage = currentProfitPercentage, Profit = currentProfit, Duration = j - i, StartDate = candles[i].Timestamp, EndDate = candles[j].Timestamp }); break; } } } } results.Add(backTestResult); } return(results); }
private void BackTestingForm_FormClosing(object sender, FormClosingEventArgs e) { if (this.DialogResult == System.Windows.Forms.DialogResult.OK) { CreateTradingStrategy(); } else { _tradingStrategy = null; } }
public static async Task <JArray> BackTestJson(ITradingStrategy strategy, BacktestOptions backtestOptions, IDataStoreBacktest dataStore, string baseCurrency, bool saveSignals, decimal startingWallet, decimal tradeAmount) { var results = await BackTest(strategy, backtestOptions, dataStore, baseCurrency, saveSignals, startingWallet, tradeAmount); var jArrayResult = new JArray(); if (results.Count > 0) { var resultsSummary = new BackTestStrategyResult(); resultsSummary.Results = results; resultsSummary.Strategy = strategy.Name; resultsSummary.ConcurrentTrades = results.First().ConcurrentTrades; resultsSummary.Wallet = results.First().Wallet; resultsSummary.LowWallet = results.First().LowWallet; var endWallet = Math.Round(resultsSummary.Wallet, 3); var walletRealPercentage = Math.Round(((resultsSummary.Wallet - startingWallet) / startingWallet) * 100, 3); var lowWallet = Math.Round(resultsSummary.LowWallet, 3); var currentResult1 = new JObject(); currentResult1["Strategy"] = resultsSummary.Strategy; currentResult1["ConcurrentTrades"] = resultsSummary.ConcurrentTrades; currentResult1["Wallet"] = endWallet + " " + baseCurrency + " (" + walletRealPercentage + "%)"; currentResult1["LowWallet"] = lowWallet; currentResult1["AmountOfTrades"] = resultsSummary.AmountOfTrades; currentResult1["AmountOfProfitableTrades"] = resultsSummary.AmountOfProfitableTrades; currentResult1["SuccessRate"] = resultsSummary.SuccessRate; currentResult1["TotalProfit"] = resultsSummary.TotalProfit; currentResult1["TotalProfitPercentage"] = resultsSummary.TotalProfitPercentage; currentResult1["AverageDuration"] = resultsSummary.AverageDuration; currentResult1["DataPeriod"] = resultsSummary.DataPeriod; currentResult1["BaseCurrency"] = baseCurrency; jArrayResult.Add(currentResult1); foreach (var result in results) { var currentResult = new JObject(); currentResult["Market"] = result.Market; currentResult["Strategy"] = strategy.Name; currentResult["AmountOfTrades"] = result.AmountOfTrades; currentResult["AmountOfProfitableTrades"] = result.AmountOfProfitableTrades; currentResult["SuccessRate"] = result.SuccessRate; currentResult["TotalProfit"] = result.TotalProfit; currentResult["TotalProfitPercentage"] = result.TotalProfitPercentage; currentResult["AverageDuration"] = result.AverageDuration; currentResult["DataPeriod"] = result.DataPeriod; jArrayResult.Add(currentResult); } } return(jArrayResult); }
protected override async Task RunInternalAsync(CancellationToken token) { WriteToHeartBeatLog(); if (!BaseData.CurrentPriceStorage.IsAddedOrUpdated) { WriteToWorkerLog($"{Country} doesn't have updated current price storage."); return; } IReadOnlyList <IMemberStock> memberStocks = await DatabaseOperations.GetMemberStocksAsync().ConfigureAwait(false); if (memberStocks == null || memberStocks.Count == 0) { return; } List <Task> tasks = new List <Task>(); foreach (IMemberStock memberStock in memberStocks) { if (!memberStock.IsNotify) { continue; } ITradingStrategy strategy = _buySellStrategyProvider.GetBuyStrategy(memberStock, BaseData, TestStatus); if (strategy == null) { continue; } Task t = strategy.ExecuteAsync(token); tasks.Add(t); } if (tasks.Count == 0) { return; } try { // TODO :timeout ? await Task.WhenAll(tasks.ToArray()).ConfigureAwait(false); } catch { // TODO: log? } }
public async Task <IActionResult> StrategyTesting(StrategyTestingModel model) { IEnumerable <Candle> candles = await _candleProcessor.GetLast(model.ExchangeCode, model.Symbol, model.IntervalCode, 1500); Strategy strategyInfo = await _strategyProcessor.Get(model.StrategyId); Type type = Type.GetType(strategyInfo.TypeName, true, true); ITradingStrategy strategy = (ITradingStrategy)Activator.CreateInstance(type); ITradingAdviceCode res = strategy.Forecast(candles); return(View()); }
public void TurnAlgoOn() { try { this.tradingStrategy = TradingStrategyFactory.GetTradingStrategy("RideTheMacd"); if (this.tradingApi == null) { this.tradingApi = TradingApiFactory.GetTradingApi(""); } this.simulationStrategy = TradingStrategyFactory.GetTradingStrategy("Simulation"); this.simulationApi = TradingApiFactory.GetTradingApi(""); this.IsAlgoOn = true; } catch (Exception ex) { AddError(ex, "TurnAlgoOn"); } }
public static async void BackTestShowTradesConsole(ITradingStrategy strategy, BacktestOptions backtestOptions, IDataStoreBacktest dataStore) { var results = await BackTestShowTrades(strategy, backtestOptions, dataStore); Console.WriteLine(); Console.WriteLine($"\t=============== BACKTESTING REPORT {strategy.Name.ToUpper()} ==============="); Console.WriteLine(); ConsoleUtility.WriteColoredLine($"\tNote: Profit is based on trading with 0.1 BTC each trade.", ConsoleColor.Cyan); Console.WriteLine(); // Prints the results for each coin for this strategy. if (results.Count > 0) { var trades = new List <BackTestTradeResult>(); foreach (var result in results) { trades.AddRange(result.Trades); } Console.WriteLine(trades .OrderBy(x => x.StartDate) .ToList() .ToStringTable(new[] { "Market", "Open", "Close", "BTC Profit", "Profit %", "Duration", "Startdate", "Enddate" }, (x) => x.Market, (x) => $"{x.OpenRate:0.00000000}", (x) => $"{x.CloseRate:0.00000000}", (x) => $"{x.Profit:0.00000000}", (x) => $"{x.ProfitPercentage:0.00}%", (x) => $"{(x.Duration):0.00} hours", (x) => $"{x.StartDate:dd-MM-yyyy hh:mm}", (x) => $"{x.EndDate:dd-MM-yyyy hh:mm}")); } else { ConsoleUtility.WriteColoredLine("\tNo backtests results found...", ConsoleColor.Red); } ConsoleUtility.WriteSeparator(); }
private void CreateTradingStrategy() { var strategySettings = GetSettings(); strategySettings.MinAmountItem1ToKeep = numMinAmountBTC.Value; strategySettings.MinAmountItem2ToKeep = numMinAmountMoney.Value; strategySettings.MaxAmountMoneyPerBuyOrder = numMaxAmountMoneyPerBuyOrder.Value; strategySettings.MaxNbBTCPerSellOrder = numMaxNbBTCPerSellOrder.Value; //Back testing strategySettings.InitialItem1Balance = numBalBTCTest.Value; strategySettings.InitialItem2Balance = numBalUSDTest.Value; strategySettings.Pair = chartSelector.SelectedPair; strategySettings.BuyFee = numBuyFee.Value; strategySettings.SellFee = numSellFee.Value; //strategy specific settings (_settingsCtrl as Interfaces.IStrategySettingsControl).FillSettings(strategySettings); var item = cbbStrategy.GetSelectedValue <StrategyCbbItem>(); _tradingStrategy = (ITradingStrategy)Activator.CreateInstance(item.StrategyType, strategySettings); }
/// <summary> /// Creates a new trade in our system and opens a buy order. /// </summary> /// <returns></returns> private async Task CreateNewTrade(TradeSignal signal, ITradingStrategy strategy) { decimal currentQuoteBalance = 9999; if (!Global.Configuration.TradeOptions.PaperTrade) { // Get our Bitcoin balance from the exchange var exchangeQuoteBalance = await Global.ExchangeApi.GetBalance(signal.QuoteCurrency); // Check trading mode currentQuoteBalance = exchangeQuoteBalance.Available; } // Do we even have enough funds to invest? (only for SetAside; if you choose Reinvest we push a %) if (Global.Configuration.TradeOptions.ProfitStrategy == ProfitType.SetAside && currentQuoteBalance < Global.Configuration.TradeOptions.AmountToInvestPerTrader) { Global.Logger.Warning("Insufficient funds ({Available}) to perform a {MarketName} trade. Skipping this trade.", currentQuoteBalance, signal.MarketName); return; } var trade = await CreateBuyOrder(signal, strategy); // We found a trade and have set it all up! if (trade != null) { // Save the order. await Global.DataStore.SaveTradeAsync(trade); //money area unavailable from wallet immediately await Global.DataStore.SaveWalletTransactionAsync(new WalletTransaction() { Amount = -(trade.OpenRate *trade.Quantity), Date = trade.OpenDate }); // Send a notification that we found something suitable await SendNotification($"Saved a BUY ORDER for: {this.TradeToString(trade)}"); } }
/// <summary> /// Creates a new trade in our system and opens a buy order. /// </summary> /// <returns></returns> private async Task CreateNewTrade(TradeSignal signal, ITradingStrategy strategy) { decimal currentQuoteBalance = 9999; if (!Global.Configuration.TradeOptions.PaperTrade) { // Get our Bitcoin balance from the exchange var exchangeQuoteBalance = await Global.ExchangeApi.GetBalance(signal.QuoteCurrency); // Check trading mode currentQuoteBalance = exchangeQuoteBalance.Available; } // Do we even have enough funds to invest? (only for SetAside; if you choose Reinvest we push a %) if (Global.Configuration.TradeOptions.ProfitStrategy == ProfitType.SetAside && currentQuoteBalance < Global.Configuration.TradeOptions.AmountToInvestPerTrader) { Global.Logger.Warning("Insufficient funds ({Available}) to perform a {MarketName} trade. Skipping this trade.", currentQuoteBalance, signal.MarketName); return; } await CreateBuyOrder(signal, strategy); }
private async Task <CoinTrader> RunHistoryData(ITradingStrategy strategy) { FakeBittrexApi fakeBittrexApi = new FakeBittrexApi(null); fakeBittrexApi.IsInTestMode = true; fakeBittrexApi.Candles = _candles; var coinTrader = new CoinTrader(fakeBittrexApi) { IsInTestMode = true }; _fakeBittrexApi.IsInTestMode = true; coinTrader.Initialize(new TraderState { Market = _market }); coinTrader.Strategy = strategy; await fakeBittrexApi.SendMarketUpdates(_market); Console.WriteLine($"Profit: {coinTrader.TraderState.Budget.Profit}%"); return(coinTrader); }
private async Task <CoinTrader> RunHistoryData(ITradingStrategy strategy) { FakeBittrexApi fakeBittrexApi = new FakeBittrexApi(_apiKey, _apiSecret) { IsInTestMode = true, Candles = _candles }; var coinTrader = new CoinTrader(fakeBittrexApi) { IsInTestMode = true }; _fakeBittrexApi.IsInTestMode = true; coinTrader.Candles = _hourlyCandles; coinTrader.Initialize(new TraderState { Market = _market }); coinTrader.Strategy = strategy; await fakeBittrexApi.SendMarketUpdates(_market); return(coinTrader); }
private void CreateTradingStrategy() { var strategySettings = GetSettings(); strategySettings.MinAmountItem1ToKeep = numMinAmountBTC.Value; strategySettings.MinAmountItem2ToKeep = numMinAmountMoney.Value; strategySettings.MaxAmountMoneyPerBuyOrder = numMaxAmountMoneyPerBuyOrder.Value; strategySettings.MaxNbBTCPerSellOrder = numMaxNbBTCPerSellOrder.Value; //Back testing strategySettings.InitialItem1Balance = numBalBTCTest.Value; strategySettings.InitialItem2Balance = numBalUSDTest.Value; strategySettings.Pair = chartSelector.SelectedPair; strategySettings.BuyFee = numBuyFee.Value; strategySettings.SellFee = numSellFee.Value; //strategy specific settings (_settingsCtrl as Interfaces.IStrategySettingsControl).FillSettings(strategySettings); var item = cbbStrategy.GetSelectedValue<StrategyCbbItem>(); _tradingStrategy = (ITradingStrategy)Activator.CreateInstance(item.StrategyType, strategySettings); }
public ForexStrategyTrader(ITradingStrategy tradingStrategy, IMarketEventsLogger marketEventsLogger) { this.tradingStrategy = tradingStrategy ?? throw new ArgumentNullException(nameof(tradingStrategy)); this.marketEventsLogger = marketEventsLogger ?? throw new ArgumentNullException(nameof(marketEventsLogger)); }
public NotificationManager(IExchangeApi api, ITradingStrategy strategy, Action <string> log) { _api = api; _strategy = strategy; _log = log; }