public static void Main(string[] args) { // Splitting the series into slices TimeSeries series = CsvTradesLoader.loadBitstampSeries(); IList <TimeSeries> subseries = series.split(Period.hours(6), Period.weeks(1)); // Building the map of strategies IDictionary <Strategy, string> strategies = buildStrategiesMap(series); // The analysis criterion AnalysisCriterion profitCriterion = new TotalProfitCriterion(); foreach (TimeSeries slice in subseries) { // For each sub-series... Console.WriteLine("Sub-series: " + slice.SeriesPeriodDescription); foreach (KeyValuePair <Strategy, string> entry in strategies.SetOfKeyValuePairs()) { Strategy strategy = entry.Key; string name = entry.Value; // For each strategy... TradingRecord tradingRecord = slice.run(strategy); double profit = profitCriterion.calculate(slice, tradingRecord); Console.WriteLine("\tProfit for " + name + ": " + profit); } Strategy bestStrategy = profitCriterion.chooseBest(slice, new List <Strategy>(strategies.Keys)); Console.WriteLine("\t\t--> Best strategy: " + strategies[bestStrategy] + "\n"); } }
public static void Main(string[] args) { // Getting the time series TimeSeries series = CsvTradesLoader.loadBitstampSeries(); // Building the trading strategy Strategy strategy = MovingMomentumStrategy.buildStrategy(series); /// <summary> /// Building chart datasets /// </summary> TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(buildChartTimeSeries(series, new ClosePriceIndicator(series), "Bitstamp Bitcoin (BTC)")); /// <summary> /// Creating the chart /// </summary> JFreeChart chart = ChartFactory.createTimeSeriesChart("Bitstamp BTC", "Date", "Price", dataset, true, true, false); // generate URLs? - generate tooltips? - create legend? - data - y-axis label - x-axis label - title XYPlot plot = (XYPlot)chart.Plot; DateAxis axis = (DateAxis)plot.DomainAxis; axis.DateFormatOverride = new SimpleDateFormat("MM-dd HH:mm"); /// <summary> /// Running the strategy and adding the buy and sell signals to plot /// </summary> addBuySellSignals(series, strategy, plot); /// <summary> /// Displaying the chart /// </summary> displayChart(chart); }
/// <summary> /// Builds a moving time series (i.e. keeping only the maxTickCount last ticks) </summary> /// <param name="maxTickCount"> the number of ticks to keep in the time series (at maximum) </param> /// <returns> a moving time series </returns> private static TimeSeries initMovingTimeSeries(int maxTickCount) { TimeSeries series = CsvTradesLoader.loadBitstampSeries(); Console.Write("Initial tick count: " + series.TickCount); // Limitating the number of ticks to maxTickCount series.MaximumTickCount = maxTickCount; LAST_TICK_CLOSE_PRICE = series.getTick(series.End).ClosePrice; Console.WriteLine(" (limited to " + maxTickCount + "), close price = " + LAST_TICK_CLOSE_PRICE); return(series); }
public static void Main(string[] args) { /// <summary> /// Getting time series /// </summary> TimeSeries series = CsvTradesLoader.loadBitstampSeries().subseries(0, Period.hours(6)); /// <summary> /// Creating the OHLC dataset /// </summary> OHLCDataset ohlcDataset = createOHLCDataset(series); /// <summary> /// Creating the additional dataset /// </summary> TimeSeriesCollection xyDataset = createAdditionalDataset(series); /// <summary> /// Creating the chart /// </summary> JFreeChart chart = ChartFactory.createCandlestickChart("Bitstamp BTC price", "Time", "USD", ohlcDataset, true); // Candlestick rendering CandlestickRenderer renderer = new CandlestickRenderer(); renderer.AutoWidthMethod = CandlestickRenderer.WIDTHMETHOD_SMALLEST; XYPlot plot = chart.XYPlot; plot.Renderer = renderer; // Additional dataset int index = 1; plot.setDataset(index, xyDataset); plot.mapDatasetToRangeAxis(index, 0); XYLineAndShapeRenderer renderer2 = new XYLineAndShapeRenderer(true, false); renderer2.setSeriesPaint(index, Color.blue); plot.setRenderer(index, renderer2); // Misc plot.RangeGridlinePaint = Color.lightGray; plot.BackgroundPaint = Color.white; NumberAxis numberAxis = (NumberAxis)plot.RangeAxis; numberAxis.AutoRangeIncludesZero = false; plot.DatasetRenderingOrder = DatasetRenderingOrder.FORWARD; /// <summary> /// Displaying the chart /// </summary> displayChart(chart); }
public static void Main() { // Getting the time series var series = CsvTradesLoader.LoadBitstampSeries(); // Building the trading strategy var strategy = BuildStrategy(series); // Running the strategy var tradingRecord = series.Run(strategy); Console.WriteLine("Number of trades for the strategy: " + tradingRecord.TradeCount); // Analysis Console.WriteLine("Total profit for the strategy: " + (new TotalProfitCriterion()).Calculate(series, tradingRecord)); }
public static void Main(string[] args) { // Run the various examples in turn... var demo = new Quickstart(); demo.QuickStart(); PressAnyKey(); CsvTicksLoader.Main(); PressAnyKey(); CsvTradesLoader.Main(); PressAnyKey(); CCICorrectionStrategy.Main(); PressAnyKey(); GlobalExtremaStrategy.Main(); PressAnyKey(); MovingMomentumStrategy.Main(); PressAnyKey(); RSI2Strategy.Main(); PressAnyKey(); var s = new StrategyAnalysis(); s.RunCciCorrection(); PressAnyKey(); s.RunGlobalExtrema(); PressAnyKey(); s.RunMovingMomentum(); PressAnyKey(); s.RunRSI2(); PressAnyKey(); }
public void QuickStart() { // Getting a time series (from any provider: CSV, web service, etc.) var series = CsvTradesLoader.LoadBitstampSeries(); // Getting the close price of the ticks var firstClosePrice = series.GetTick(0).ClosePrice; Console.WriteLine("First close price: " + firstClosePrice.ToDouble()); // Or within an indicator: var closePrice = new ClosePriceIndicator(series); // Here is the same close price: Console.WriteLine(firstClosePrice.IsEqual(closePrice.GetValue(0))); // equal to firstClosePrice // Getting the simple moving average (SMA) of the close price over the last 5 ticks var shortSma = new SmaIndicator(closePrice, 5); // Here is the 5-ticks-SMA value at the 42nd index Console.WriteLine("5-ticks-SMA value at the 42nd index: " + shortSma.GetValue(42).ToDouble()); // Getting a longer SMA (e.g. over the 30 last ticks) var longSma = new SmaIndicator(closePrice, 30); // Ok, now let's building our trading rules! // Buying rules // We want to buy: // - if the 5-ticks SMA crosses over 30-ticks SMA // - or if the price goes below a defined price (e.g $800.00) var buyingRule = (new CrossedUpIndicatorRule(shortSma, longSma)) .Or(new CrossedDownIndicatorRule(closePrice, Decimal.ValueOf("800"))); // Selling rules // We want to sell: // - if the 5-ticks SMA crosses under 30-ticks SMA // - or if if the price looses more than 3% // - or if the price earns more than 2% var sellingRule = (new CrossedDownIndicatorRule(shortSma, longSma)) //.Or(new CrossedDownIndicatorRule(new TrailingStopLossIndicator(closePrice, Decimal.ValueOf("30")), closePrice )) .Or(new StopLossRule(closePrice, Decimal.ValueOf("3"))) .Or(new StopGainRule(closePrice, Decimal.ValueOf("2"))); // Running our juicy trading strategy... var tradingRecord = series.Run(new Strategy(buyingRule, sellingRule)); Console.WriteLine("Number of trades for our strategy: " + tradingRecord.TradeCount); // Analysis // Getting the cash flow of the resulting trades var cashFlow = new CashFlow(series, tradingRecord); // Getting the profitable trades ratio IAnalysisCriterion profitTradesRatio = new AverageProfitableTradesCriterion(); Console.WriteLine("Profitable trades ratio: " + profitTradesRatio.Calculate(series, tradingRecord)); // Getting the reward-risk ratio IAnalysisCriterion rewardRiskRatio = new RewardRiskRatioCriterion(); Console.WriteLine("Reward-risk ratio: " + rewardRiskRatio.Calculate(series, tradingRecord)); // Total profit of our strategy // vs total profit of a buy-and-hold strategy IAnalysisCriterion vsBuyAndHold = new VersusBuyAndHoldCriterion(new TotalProfitCriterion()); Console.WriteLine("Our profit vs buy-and-hold profit: " + vsBuyAndHold.Calculate(series, tradingRecord)); // Your turn! }
public static void Main(string[] args) { /// <summary> /// Getting time series /// </summary> TimeSeries series = CsvTradesLoader.loadBitstampSeries(); /// <summary> /// Creating indicators /// </summary> // Close price ClosePriceIndicator closePrice = new ClosePriceIndicator(series); // Typical price TypicalPriceIndicator typicalPrice = new TypicalPriceIndicator(series); // Price variation PriceVariationIndicator priceVariation = new PriceVariationIndicator(series); // Simple moving averages SMAIndicator shortSma = new SMAIndicator(closePrice, 8); SMAIndicator longSma = new SMAIndicator(closePrice, 20); // Exponential moving averages EMAIndicator shortEma = new EMAIndicator(closePrice, 8); EMAIndicator longEma = new EMAIndicator(closePrice, 20); // Percentage price oscillator PPOIndicator ppo = new PPOIndicator(closePrice, 12, 26); // Rate of change ROCIndicator roc = new ROCIndicator(closePrice, 100); // Relative strength index RSIIndicator rsi = new RSIIndicator(closePrice, 14); // Williams %R WilliamsRIndicator williamsR = new WilliamsRIndicator(series, 20); // Average true range AverageTrueRangeIndicator atr = new AverageTrueRangeIndicator(series, 20); // Standard deviation StandardDeviationIndicator sd = new StandardDeviationIndicator(closePrice, 14); /// <summary> /// Building header /// </summary> StringBuilder sb = new StringBuilder("timestamp,close,typical,variation,sma8,sma20,ema8,ema20,ppo,roc,rsi,williamsr,atr,sd\n"); /// <summary> /// Adding indicators values /// </summary> //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int nbTicks = series.getTickCount(); int nbTicks = series.TickCount; for (int i = 0; i < nbTicks; i++) { sb.Append(series.getTick(i).EndTime.Millis / 1000d).Append(',').Append(closePrice.getValue(i)).Append(',').Append(typicalPrice.getValue(i)).Append(',').Append(priceVariation.getValue(i)).Append(',').Append(shortSma.getValue(i)).Append(',').Append(longSma.getValue(i)).Append(',').Append(shortEma.getValue(i)).Append(',').Append(longEma.getValue(i)).Append(',').Append(ppo.getValue(i)).Append(',').Append(roc.getValue(i)).Append(',').Append(rsi.getValue(i)).Append(',').Append(williamsR.getValue(i)).Append(',').Append(atr.getValue(i)).Append(',').Append(sd.getValue(i)).Append('\n'); } /// <summary> /// Writing CSV file /// </summary> System.IO.StreamWriter writer = null; try { writer = new System.IO.StreamWriter("indicators.csv"); writer.Write(sb.ToString()); } catch (IOException ioe) { //JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method: Logger.getLogger(typeof(IndicatorsToCsv).FullName).log(Level.SEVERE, "Unable to write CSV file", ioe); } finally { try { if (writer != null) { writer.Close(); } } catch (IOException) { } } }