private void addStatistics(List <ClientTradeSummary> tradeStatistics_, ISheet tab_, HSSFWorkbook wb_) { HSSFCellStyle leftColStyle = CellStyle.headingStyle(wb_); HSSFCellStyle contentStyle = CellStyle.contentStyle(wb_); foreach (ClientTradeSummary summary in tradeStatistics_) { IRow row = tab_.CreateRow(currentLine++); ICell[] cells = new ICell[columeNb]; cells[0] = row.CreateCell(0, CellType.String); cells[0].SetCellValue(summary.getAccountId()); cells[0].CellStyle = leftColStyle; cells[1] = row.CreateCell(1, CellType.String); cells[1].SetCellValue(summary.getAbbrName()); cells[1].CellStyle = leftColStyle; cells[2] = row.CreateCell(2, CellType.Numeric); cells[2].SetCellValue((double)MathUtil.round(summary.getTotalTurnover(), 2)); cells[2].CellStyle = leftColStyle; cells[3] = row.CreateCell(3, CellType.Numeric); cells[3].SetCellValue((double)MathUtil.round(summary.getFillRate(), 4)); cells[3].CellStyle = leftColStyle; cells[4] = row.CreateCell(4, CellType.Numeric); cells[4].SetCellValue((double)MathUtil.round(summary.getCancelRate(), 4)); cells[4].CellStyle = leftColStyle; int firstPosition = FIRST_NUMERIC_COLUME; int offset = 0; int algoNb = 0; foreach (OrderAlgo algo in sortedAlgos) { StrategyStatistics algoStrategy = summary.getByAlgo(algo); offset = columeEachAlgo * algoNb + firstPosition; cells[offset + 0] = row.CreateCell(offset + 0, CellType.Numeric); cells[offset + 0].SetCellValue((double)MathUtil.round(algoStrategy.getOrderCount(), 2)); cells[offset + 0].CellStyle = contentStyle; cells[offset + 1] = row.CreateCell(offset + 1, CellType.Numeric); cells[offset + 1].SetCellValue((double)MathUtil.round(algoStrategy.getSliceCount(), 2)); cells[offset + 1].CellStyle = contentStyle; cells[offset + 2] = row.CreateCell(offset + 2, CellType.Numeric); cells[offset + 2].SetCellValue((double)MathUtil.round(algoStrategy.getSlipage(), 2)); cells[offset + 2].CellStyle = contentStyle; cells[offset + 3] = row.CreateCell(offset + 3, CellType.Numeric); cells[offset + 3].SetCellValue((double)MathUtil.round(algoStrategy.getTurnover(), 2)); cells[offset + 3].CellStyle = contentStyle; algoNb++; } } }
/// <summary> /// Adds new 'Order Details' information in 'Execution Details' object for Strategy Instance /// </summary> /// <param name="message"></param> private void StrategyMessageArrived(string message) { //_currentDispatcher.Invoke(DispatcherPriority.Background, (Action)(() => _strategyInstance.InstanceSummary.Add(message))); StrategyStatistics statistics = new StrategyStatistics(_strategyKey, DateTime.Now, message); _currentDispatcher.Invoke(DispatcherPriority.Background, (Action)(() => EventSystem.Publish <StrategyStatistics>(statistics))); }
private void _LogStats() { while (Trading) { var waitTime = LastStatTime.AddMinutes(15) - DateTime.Now; if (waitTime.TotalMilliseconds > 0) { Thread.Sleep(waitTime); } StrategyStatistics.Snapshot(MarketTerminal.GetBalanceFiat(), MarketTerminal.GetBalanceSecurity(), MarketTerminal.GetLastPrice(), GetCoinbaseBTCPrice()); Log.Write($"USD: {StrategyStatistics.Snapshots.Last().Fiat.ToString("N5")} | Asset: {StrategyStatistics.Snapshots.Last().Security}", 1); Log.Write($"Period PL: {StrategyStatistics.Snapshots.Last().PL.ToString("N5")} | Cumulative PL: {StrategyStatistics.Snapshots.Last().CumulativePL.ToString("N5")}", 1); LastStatTime = DateTime.Now; } }
public void PlotStrategyTradepoints(application.Strategy.StrategyMeta meta, bool showEstimation, EstimateTradePointFunc estimateFunc) { int idx; ShowMessage(""); EstimateOptions estOption = new EstimateOptions(); databases.tmpDS.tradeEstimateDataTable tbl = new databases.tmpDS.tradeEstimateDataTable(); application.StrategyStatistics statistics = new StrategyStatistics(); //TradePointInfo[] tradePoints = DataAccess.Libs.GetTradePointWithEstimationDetail(myData.myDataParam, myData.DataStockCode, meta.Code, estOption, out tbl, out statistics); /// Estimate trade points and set tradepoint's [isValid] property to mark whether a tradepoint is valid or not. for (idx = 0; idx < tradePoints.Length; idx++) { tradePoints[idx].isValid = !tbl[idx].ignored; } for (idx = tradePoints.Length - 1; idx > 0; idx--) { if (tradePoints[idx].isValid) { break; } } TradePointInfo tpiTradePointInfo = (TradePointInfo)tradePoints[idx]; BusinessInfo biLastTrade = tpiTradePointInfo.BusinessInfo; BusinessInfo biLastPoint = tradePoints[tradePoints.Length - 1].BusinessInfo; double price = myData.Close[myData.Close.Count - 1]; double risk = (biLastPoint.Short_Resistance - price) / (price - biLastPoint.Short_Support); //string sResult = "Close price=" + price+ // "Target="+biLastTrade.Short_Target+ // "Resistance=" + biLastPoint.Short_Resistance + // " Support=" + biLastPoint.Short_Support + // " Risk return=" +risk+ // " Winning Percentage:"+ String.Format("{0:P2}",statistics.dWinningPercentagePerTrade)+ // " Max %Win Per Trade:" + String.Format("{0:P2}",statistics.dMaxWinningPercentage)+ // " Max %Lose Per Trade" + String.Format("{0:P2}", statistics.dMaxLosingPercentage)+ // " Average %Win Per Trade" + String.Format("{0:P2}", statistics.dAverageWinningPercentage)+ // " Average %Lose Per Trade" + String.Format("{0:P2}", statistics.dAverageLosingPercentage); ; PlotStrategyTradepoints(application.Strategy.StrategyLibs.ToTradePoints(tradePoints), pricePanel); //MessageBox.Show(sResult); //Show form Tools.Forms.TradeStatistics formStatistic = new Tools.Forms.TradeStatistics(); formStatistic.AddStatisticInfo("Close price", price); formStatistic.AddStatisticInfo("Target", biLastTrade.Short_Target); formStatistic.AddStatisticInfo("Resistance", biLastPoint.Short_Resistance); formStatistic.AddStatisticInfo("Support", biLastPoint.Short_Support); formStatistic.AddStatisticInfo("Risk return", risk); formStatistic.AddStatisticInfo("Winning Percentage", String.Format("{0:P2}", statistics.dWinningPercentagePerTrade)); formStatistic.AddStatisticInfo("Max %Win Per Trade", String.Format("{0:P2}", statistics.dMaxWinningPercentage)); formStatistic.AddStatisticInfo("Max %Lose Per Trade", String.Format("{0:P2}", statistics.dMaxLosingPercentage)); formStatistic.AddStatisticInfo("Average %Win Per Trade", String.Format("{0:P2}", statistics.dAverageWinningPercentage)); formStatistic.AddStatisticInfo("Average %Lose Per Trade", String.Format("{0:P2}", statistics.dAverageLosingPercentage)); formStatistic.Show(this.DockPanel, DockState.DockRightAutoHide); //Call estimation handler if any. if (showEstimation && estimateFunc != null) { estimateFunc(this, meta.Code, estOption, tbl); } }
/// <summary> /// </summary> /// <param name="currentBar">Current bar of the simulation</param> public override void OnBarUpdate(int currentBar) { base.OnBarUpdate(currentBar); // Give the indicators some time to warm up. if (currentBar < 50) { return; } _stdDev = UtilityMethods.StdDev(Data.Close, currentBar, 10); string foundStrategyName = ""; double buyDirection = 0.0; if (ShouldBuy(currentBar)) { if (ShouldBuyLong(currentBar)) { buyDirection = Order.OrderType.Long; foundStrategyName = "BullDmiStrategy"; } //else if (ShouldBuyShort(currentBar)) //{ // buyDirection = Order.OrderType.Short; // foundStrategyName = "BearDmiStrategy"; //} } if (buyDirection != 0.0) { CalculateTargets(buyDirection, currentBar); int sizeOfOrder = CalculateOrderSize(buyDirection, currentBar); if (sizeOfOrder > 0) { List <Indicator> dependentIndicators = GetDependentIndicators(); Order placedOrder = EnterOrder(foundStrategyName, currentBar, buyDirection, sizeOfOrder, dependentIndicators, GetBuyConditions(), GetSellConditions()); if (placedOrder != null) { // Get things like win/loss percent up to the point this order was started. StrategyStatistics orderStats = Simulator.Orders.GetStrategyStatistics(placedOrder.StrategyName, placedOrder.Type, placedOrder.Ticker.TickerAndExchange, currentBar, Simulator.Config.MaxLookBackBars); AddExtraOrderInfo(placedOrder, currentBar); //if (orderStats.WinPercent >= Simulator.Config.GavalasPercentForBuy && orderStats.Gain > Simulator.Config.GavalasGainForBuy) if (_riskRatio >= Simulator.Config.ChannelMinRiskRatio && _expectedGainPercent >= Simulator.Config.ChannelMinExpectedGain) { Bars[currentBar] = new OrderSuggestion( orderStats.WinPercent, orderStats.Gain, foundStrategyName, buyDirection, sizeOfOrder, dependentIndicators, new List <StrategyStatistics>() { orderStats }, GetBuyConditions(), GetSellConditions(), placedOrder.ExtraInfo); } } } } }
/// <summary> /// Sees which strategies were found on this far and places orders for all /// the combos of those strategies. The value of this strategy is the best /// strategy that was found on this bar based on the success of the history /// of that strategy. /// </summary> /// <param name="currentBar">Current bar of the simulation</param> protected override void OnBarUpdate(int currentBar) { base.OnBarUpdate(currentBar); double highestWinPercent = 0.0; string highestName = "None"; double highestOrderType = Order.OrderType.Long; StrategyStatistics highestStats = null; List <BuyCondition> highestBuyConditions = null; List <SellCondition> highestSellConditions = null; // Bull and bear strategies can't combo with each other but we still want // to compare them side by side to find our what combo is the best. // So append all the bear combos to the combo list so they can be evaluated too. //List<List<Strategy>> combos = GetComboList(currentBar, Data.HigherTimeframeTrend[currentBar]); List <List <Strategy> > combos = GetComboList(currentBar, Order.OrderType.Long); combos.AddRange(GetComboList(currentBar, Order.OrderType.Short)); // Place orders for all the combos. List <StrategyStatistics> stats = new List <StrategyStatistics>(); for (int i = 0; i < combos.Count; i++) { List <Strategy> comboList = combos[i]; // Ignore combos greater than a max amount. if (comboList.Count > _maxComboSize || comboList.Count < _minComboSize) { continue; } List <string> dependentIndicators = new List <string>(); string comboName = ""; for (int j = 0; j < comboList.Count; j++) { comboName += comboList[j].ToString(); comboName += "-"; // Keep track of the dependent indicators for this strategy. dependentIndicators.AddRange(comboList[j].GetDependentIndicatorNames()); } // Trim off the last '-' if (comboList.Count > 0) { comboName = comboName.TrimEnd('-'); } List <BuyCondition> buyConditions = GetBuyConditions(); List <SellCondition> sellConditions = GetSellConditions(comboList); // Now that the name of the strategy is found, enter the order. Order placedOrder = EnterOrder(_namePrefix + comboName, currentBar, comboList[0].OrderType, _sizeOfOrder, dependentIndicators, buyConditions, sellConditions); if (placedOrder != null) { // Get things like win/loss percent up to the point this order was started. StrategyStatistics orderStats = Simulator.Orders.GetStrategyStatistics(placedOrder.StrategyName, placedOrder.Type, placedOrder.Ticker.TickerAndExchange, currentBar, Simulator.Config.MaxLookBackBars); stats.Add(orderStats); // For each combo we want to find out the winning % and the gain // for it and save those values for the bar. if (orderStats.WinPercent > highestWinPercent && orderStats.WinPercent > _minPercentForBuy && (_matchHigherTimeframe == false || (_matchHigherTimeframe == true && orderStats.StrategyOrderType == Data.HigherTimeframeTrend[currentBar]))) { highestWinPercent = orderStats.WinPercent; highestName = orderStats.StrategyName; highestOrderType = orderStats.StrategyOrderType; highestStats = orderStats; highestBuyConditions = buyConditions; highestSellConditions = sellConditions; } } } // Abbreviated output we only care about the strategy used to do the buy, // not all the ones that could have been found. if (Simulator.Config.UseAbbreviatedOutput == true) { stats = new List <StrategyStatistics>(); stats.Add(highestStats); } Bars[currentBar] = new BarStatistics( highestWinPercent, highestName, highestOrderType, _sizeOfOrder, stats, highestBuyConditions, highestSellConditions); }
/// <summary> /// </summary> /// <param name="currentBar">Current bar of the simulation</param> public override void OnBarUpdate(int currentBar) { base.OnBarUpdate(currentBar); // Save this so we can use it to set the zigzag deviation. _lastAtrValue = ((Atr)_dependents[5]).Value[currentBar]; if (currentBar < 2) { return; } _stdDev = UtilityMethods.StdDev(Data.Close, currentBar, 10); GavalasZones zones = (GavalasZones)_dependents[0]; if (zones.DidBarTouchZone(Data.Low[currentBar], Data.High[currentBar], currentBar) == true) { _barLastZoneHit = currentBar; _lastZoneHitDirection = zones.BuyDirection[currentBar]; } string foundStrategyName = ""; double buyDirection = 0.0; // See if we hit one of our buy zones. if (ShouldBuy(currentBar)) { if (ShouldBuyLong(currentBar)) { buyDirection = Order.OrderType.Long; foundStrategyName = "BullGavalasStrategy"; } else if (ShouldBuyShort(currentBar)) { buyDirection = Order.OrderType.Short; foundStrategyName = "BearGavalasStrategy"; } } if (buyDirection != 0.0) { CalculateTargets(buyDirection, currentBar); List <Indicator> dependentIndicators = GetDependentIndicators(); Order placedOrder = EnterOrder(foundStrategyName, currentBar, buyDirection, Simulator.Config.GavalasMaxRiskAmount, dependentIndicators, GetBuyConditions(), GetSellConditions()); if (placedOrder != null) { // Get things like win/loss percent up to the point this order was started. StrategyStatistics orderStats = Simulator.Orders.GetStrategyStatistics(placedOrder.StrategyName, placedOrder.Type, placedOrder.Ticker.TickerAndExchange, currentBar, Simulator.Config.MaxLookBackBars); AddExtraOrderInfo(placedOrder, currentBar); // Size of order = max amount we'll risk / (current low - stop) double lossPerShare = buyDirection > 0 ? Data.Low[currentBar] - _stopPrice : _stopPrice - Data.High[currentBar]; int sizeOfOrder = Convert.ToInt32(Simulator.Config.GavalasMaxRiskAmount / lossPerShare); //if (orderStats.WinPercent >= Simulator.Config.GavalasPercentForBuy && orderStats.Gain > Simulator.Config.GavalasGainForBuy) if (sizeOfOrder > 0) { Bars[currentBar] = new OrderSuggestion( orderStats.WinPercent, orderStats.Gain, foundStrategyName, buyDirection, sizeOfOrder, dependentIndicators, new List <StrategyStatistics>() { orderStats }, GetBuyConditions(), GetSellConditions(), placedOrder.ExtraInfo); } } } }
static void Main(string[] args) { string nodeName = args[0]; int nodeId = Int32.Parse(args[0]); Console.WriteLine("Node Id: " + nodeId); // These files are for asyncronous communication between this // worker and it's scheduler. // // Decks to evaluate come in the inbox and are dished out of the // outbox. string boxesDirectory = "boxes/"; string inboxPath = boxesDirectory + string.Format("deck-{0,4:D4}-inbox.tml", nodeId); string outboxPath = boxesDirectory + string.Format("deck-{0,4:D4}-outbox.tml", nodeId); // Hailing string activeDirectory = "active/"; string activeWorkerPath = activeDirectory + string.Format("worker-{0,4:D4}.txt", nodeId); string activeSearchPath = activeDirectory + "search.txt"; if (!File.Exists(activeSearchPath)) { Console.WriteLine("No search has been found."); return; } // The opponent deck doesn't change so we can load it here. string[] textLines = File.ReadAllLines(activeSearchPath); Console.WriteLine("Config File: " + textLines[1]); var config = Toml.ReadFile <Configuration>(textLines[1]); // Apply nerfs if nerfs are available ApplyNerfs(config.Nerfs); // Setup the pools of card decks for possible opponents. var deckPoolManager = new DeckPoolManager(); deckPoolManager.AddDeckPools(config.Evaluation.DeckPools); // Setup test suites: (strategy, deck) combos to play against. var suiteConfig = Toml.ReadFile <DeckSuite>( config.Evaluation.OpponentDeckSuite); var gameSuite = new GameSuite(suiteConfig.Opponents, deckPoolManager); // Let the scheduler know we are here. using (FileStream ow = File.Open(activeWorkerPath, FileMode.Create, FileAccess.Write, FileShare.None)) { WriteText(ow, "Hail!"); ow.Close(); } // Loop while the guiding search is running. while (File.Exists(activeSearchPath)) { // Wait until we have some work. while (!File.Exists(inboxPath) && File.Exists(activeSearchPath)) { Console.WriteLine("Waiting... (" + nodeId + ")"); Thread.Sleep(5000); } if (!File.Exists(activeSearchPath)) { break; } // Wait for the file to be finish being written Thread.Sleep(5000); // Run games, evaluate the deck, and then save the results. var playMessage = Toml.ReadFile <PlayMatchesMessage>(inboxPath); Deck playerDeck = playMessage.Deck.ContructDeck(); int numStrats = config.Evaluation.PlayerStrategies.Length; var stratStats = new StrategyStatistics[numStrats]; var overallStats = new OverallStatistics(); overallStats.UsageCounts = new int[playerDeck.CardList.Count]; RecordDeckProperties(playerDeck, overallStats); for (int i = 0; i < numStrats; i++) { // Setup the player with the current strategy PlayerStrategyParams curStrat = config.Evaluation.PlayerStrategies[i]; var player = new PlayerSetup(playerDeck, PlayerSetup.GetStrategy(curStrat.Strategy, config.Network, playMessage.Strategy)); List <PlayerSetup> opponents = gameSuite.GetOpponents(curStrat.NumGames); var launcher = new GameDispatcher( player, opponents ); // Run the game and collect statistics OverallStatistics stats = launcher.Run(); stratStats[i] = new StrategyStatistics(); stratStats[i].WinCount += stats.WinCount; stratStats[i].Alignment += stats.StrategyAlignment; overallStats.Accumulate(stats); } // Write the results overallStats.ScaleByNumStrategies(numStrats); var results = new ResultsMessage(); results.PlayerDeck = playMessage.Deck; results.OverallStats = overallStats; results.StrategyStats = stratStats; Toml.WriteFile <ResultsMessage>(results, outboxPath); // Wait for the TOML file to write (buffers are out of sync) // Then tell the search that we are done writing the file. Thread.Sleep(3000); File.Delete(inboxPath); // Cleanup. GC.Collect(); // Look at all the files in the current directory. // Eliminate anythings that matches our log file. /* * string[] oFiles = Directory.GetFiles(".", "DeckEvaluator.o*"); * foreach (string curFile in oFiles) * { * if (curFile.EndsWith(nodeName)) * { * File.Delete(curFile); * } * }*/ } }
/// <summary> /// </summary> /// <param name="currentBar">Current bar of the simulation</param> public override void OnBarUpdate(int currentBar) { base.OnBarUpdate(currentBar); if (currentBar < 2) { return; } ElliotWaves waves = (ElliotWaves)_dependents[0]; double buyDirection = 0.0; string foundStrategyName = ""; // If we're in a 5th wave, see if the price touched one of the retracement zones. if (DataSeries.IsAbove(waves.FifthWaveValue, 0.0, currentBar, 2) != -1 && IsBarInZone(currentBar)) { buyDirection = waves.FifthWaveDirection[currentBar] * -1.0; // Verify with the mechanical buy signal. DtOscillator dtosc = (DtOscillator)_dependents[2]; if (buyDirection > 0.0 && Data.HigherTimeframeTrend[currentBar] < 0.0) { if (dtosc.SD[currentBar] <= 25.0 && dtosc.SK[currentBar] <= 25.0) { foundStrategyName = "BullElliotWavesStrategy"; } } else if (buyDirection < 0.0 && Data.HigherTimeframeTrend[currentBar] > 0.0) { if (dtosc.SD[currentBar] >= 75.0 && dtosc.SK[currentBar] >= 75.0) { foundStrategyName = "BearElliotWavesStrategy"; } } } if (foundStrategyName.Length > 0) { List <Indicator> dependentIndicators = GetDependentIndicators(); Order placedOrder = EnterOrder(foundStrategyName, currentBar, buyDirection, 10000, dependentIndicators, GetBuyConditions(), GetSellConditions()); if (placedOrder != null) { // Get things like win/loss percent up to the point this order was started. StrategyStatistics orderStats = Simulator.Orders.GetStrategyStatistics(placedOrder.StrategyName, placedOrder.Type, placedOrder.Ticker.TickerAndExchange, currentBar, Simulator.Config.MaxLookBackBars); Bars[currentBar] = new OrderSuggestion( 100.0, orderStats.Gain, foundStrategyName, buyDirection, 10000, dependentIndicators, new List <StrategyStatistics>() { orderStats }, GetBuyConditions(), GetSellConditions(), null); } } }