public static Storage GiveTotalSoldProduct(ISeller seller, Product product) { var res = new Storage(product); foreach (var deal in seller.AllSellDeals().Where(x => x.Value.Product == product)) { // Key is a market, Value is a Storage var market = deal.Key; var sentToMarket = deal.Value; if (sentToMarket.get() > 0f) { Value DSB = new Value(market.getDemandSupplyBalance(sentToMarket.Product, false)); if (DSB.get() == Options.MarketInfiniteDSB) { DSB.SetZero(); // real DSB is unknown } else if (DSB.get() > Options.MarketEqualityDSB) { DSB.Set(Options.MarketEqualityDSB); } var realSold = sentToMarket.Multiply(DSB); if (realSold.isNotZero()) { res.Add(realSold); } } } return(res); }
protected TradeAction(ICustomer customer, ISeller seller) { ThrowNewArgumentNullException(customer, seller); _customer = customer; _seller = seller; }
public BaseInvoice(int code, int discount, int tax, IProduct[] products, ICustomer customer, ISeller seller) { Code = code; Discount = discount; Tax = tax; Products = products; Customer = customer; Seller = seller; }
public MajorTradeAction(ICustomer customer, ISeller seller, List<ITradeAction> actions) : base(customer, seller) { if (actions == null) { throw new NullReferenceException(nameof(actions)); } _actions = actions; }
/// <summary> /// Brings money for sold product /// </summary> public static void GiveMoneyForSoldProduct(ISeller seller) { foreach (var deal in seller.AllSellDeals()) { // Key is a market, Value is a Storage var market = deal.Key; var sentToMarket = deal.Value; if (sentToMarket.get() > 0f) { Value DSB = new Value(market.getDemandSupplyBalance(sentToMarket.Product, false)); if (DSB.get() == Options.MarketInfiniteDSB) { DSB.SetZero(); // real DSB is unknown } else if (DSB.get() > Options.MarketEqualityDSB) { DSB.Set(Options.MarketEqualityDSB); } decimal realSold = (decimal)sentToMarket.get(); realSold *= (decimal)DSB.get(); if (realSold > 0m) { MoneyView cost = market.getCost(sentToMarket.Product).Copy().Multiply(realSold); // adding unsold product // assuming gainGoodsThisTurn & realSold have same product //if (storage.isExactlySameProduct(gainGoodsThisTurn)) // storage.add(gainGoodsThisTurn); //else // storage = new Storage(gainGoodsThisTurn); //storage.Subtract((float)realSold); if (market.CanPay(cost)) //&& Country.market.tmpMarketStorage.has(realSold)) { market.Pay(seller as Agent, cost, Register.Account.MarketOperations); } else { if (Game.devMode)// && Country.market.HowMuchLacksMoneyIncludingDeposits(cost).Get() > 10m) { Debug.Log("Failed market - lacks " + market.HowMuchLacksMoneyIncludingDeposits(cost) + " for " + realSold + " " + sentToMarket.Product + " " + seller + " trade: " + cost); // money in market ended... Only first lucky get money } market.PayAllAvailableMoney(seller as Agent, Register.Account.MarketOperations); } } } } }
public decimal AdjustWithQuote(Quote quote, ISeller quoteSeller) { LastSize = 0; if (_totalSize >= quote.MinSize) { LastSize = quote.MinSize; var quoteSatoshi = decimal.Floor((quote.QuoteSize - quote.MinSize) / quote.Stepsize); if (quoteSatoshi > 0) { var extraSatoshi = decimal.Floor((_totalSize - quote.MinSize) / quote.Stepsize); var satoshiSize = Math.Min(extraSatoshi, quoteSatoshi) * quote.Stepsize; LastSize += satoshiSize; } _totalSize -= LastSize; } LastPrice = quote.QuotePrice; LastSeller = quoteSeller; return(LastSize); }
public ConsoleApplication(ICustomer customer, ISeller seller) { if (customer == null) throw new ArgumentNullException(nameof(customer)); if (seller == null) throw new ArgumentNullException(nameof(seller)); customer.BuyFrom(seller); var actions = new List<ITradeAction> { new PayTradeAction(customer, seller), new ChooseProductTradeAction(customer, seller), new RequestChangeTradeAction(customer, seller) }; Main = new MajorTradeAction(customer, seller, actions); }
public override int GetPrice(ISeller distributor) => Value;
private readonly ISeller sellerrepos;// = new SellerRepositiry(); public SellerController(ISeller se) { sellerrepos = se; }
public override TradeRecords Execute(string code, Properties strategyParam, BacktestParameter backtestParam, ISeller seller = null) { //获取行情数据 IndicatorRepository repository = (IndicatorRepository)backtestParam.Get <Object>("repository"); if (repository == null) { return(null); } TimeSerialsDataSet ds = repository[code]; if (ds == null) { return(null); } KLine kline = ds.DayKLine; if (kline == null) { return(null); } DateTime beginDate = backtestParam.BeginDate; DateTime endDate = backtestParam.EndDate; int bIndex = kline.IndexOf(beginDate, false); if (bIndex < 0) { return(null); } //获取参数 int maxholddays = strategyParam.Get <int>("maxholddays"); double maxprofilt = strategyParam.Get <double>("maxprofilt"); //遍历K线 List <Object[]> listEarn = new List <object[]>(); List <Object[]> listLoss = new List <object[]>(); TradeRecords tr = new TradeRecords(); for (int index = bIndex; index < kline.Count; index++) { KLineItem item = kline[index]; if (item.Date >= endDate) { break; } double buyPrice = item.CLOSE; double maxProfiltEffenicePerStock = double.MinValue + 1; double maxLossEffenicePerStock = double.MaxValue - 1; int maxProfiltHoldDays = 0; int maxLossHoldDays = 0; KLineItem sellEarnItem = null; KLineItem sellLossItem = null; for (int i = 1; i < maxholddays; i++) { if (index + i >= kline.Count) { break; } KLineItem item2 = kline[index + i]; if ((item2.Date - item.Date).TotalDays > maxholddays) { break; } double eraningRates = (item2.CLOSE - buyPrice) / buyPrice; if (eraningRates > 0 && eraningRates >= maxprofilt && maxProfiltEffenicePerStock < eraningRates) { maxProfiltEffenicePerStock = eraningRates / i; maxProfiltHoldDays = i; sellEarnItem = item2; } if (eraningRates < 0 && maxLossEffenicePerStock > eraningRates) { maxLossEffenicePerStock = eraningRates; maxLossHoldDays = i; sellLossItem = item2; } } if (maxProfiltHoldDays > 0) { Object[] objs = new Object[] { item, sellEarnItem, maxProfiltEffenicePerStock, (sellEarnItem.CLOSE - buyPrice) / buyPrice }; listEarn.Add(objs); index = kline.IndexOf(sellEarnItem); } if (maxLossHoldDays > 0) { Object[] objs = new Object[] { item, sellLossItem, maxLossEffenicePerStock, (sellLossItem.CLOSE - buyPrice) / buyPrice }; listLoss.Add(objs); } } if (listEarn.Count <= 0) { return(null); } Comparison <Object[]> comparsionEran = (x, y) => { return((int)((double)y[2] - (double)x[2])); }; listEarn.Sort(comparsionEran); List <String> strs = new List <string>(); foreach (Object[] objs in listEarn) { KLineItem buyItem = (KLineItem)objs[0]; KLineItem sellItem = (KLineItem)objs[1]; String str = code + "," + ((double)objs[2]).ToString("F3") + "," + ((double)objs[3]).ToString("F3") + "," + (sellItem.Date - buyItem.Date).TotalDays.ToString() + "," + buyItem.Date.ToString("yyyyMMdd") + "," + sellItem.Date.ToString("yyyyMMdd") + "," + buyItem.CLOSE.ToString("F2") + "," + sellItem.CLOSE.ToString("F2"); strs.Add(str); logger.Info(str); } System.IO.File.AppendAllLines(backtestParam.Resultpath + "temp.csv", strs.ToArray(), Encoding.UTF8); return(null); }
public override int Insert(string name, ISeller primarySeller) { throw new NotImplementedException(); }
public static void PrintSomething(this ISeller seller) { Console.WriteLine(seller.GetType()); }
public abstract int GetPrice(ISeller distributor);
public void BuyFrom(ISeller seller) { _seller = seller; }
public SellerController(ISeller repo) { _repo = repo; }
protected void ThrowNewArgumentNullException(ICustomer customer, ISeller seller) { if (customer == null) { throw new ArgumentNullException(nameof(customer)); } if (seller == null) { throw new ArgumentNullException(nameof(seller)); } }
public override TradeRecords Execute(string code, Properties strategyParam, BacktestParameter backtestParam, ISeller seller = null) { IndicatorRepository repository = (IndicatorRepository)backtestParam.Get <Object>("repository"); if (repository == null) { return(null); } TimeSerialsDataSet ds = repository[code]; if (ds == null) { return(null); } TimeSeries <ITimeSeriesItem <char> > ts = ds.DayTradeLine.buysellPoints; if (ts == null) { return(null); } TimeSeries <ITimeSeriesItem <List <double> > > fundTrends = ds.DayFundTrend; KLine kline = ds.DayKLine; TradeRecords tr = new TradeRecords(code); GetInMode getin = GetInMode.Parse(strategyParam.Get <String>("getinMode")); int diffdays = strategyParam.Get <int>("diffdays"); for (int i = 0; i < ts.Count; i++) { if (ts[i].Date.Date < backtestParam.BeginDate) { continue; } if (ts[i].Date.Date >= backtestParam.EndDate) { continue; } if (ts[i].Value == 'S') { continue; } TradeBout bout = new TradeBout(code); //主力线大于散户线,且连续diffdays天与散户线拉大距离 if (diffdays > 0 && fundTrends != null) { int fi = fundTrends.IndexOf(ts[i].Date); if (fi < 0 || fi < diffdays - 1) { continue; } ITimeSeriesItem <List <double> > ftItem = fundTrends[fi]; if (ftItem.Value[0] >= 30) { continue; } double diff = ftItem.Value[0] - ftItem.Value[1]; if (diff <= 0) { continue; } bool continuekuoda = true; for (int t = 1; t < diffdays; t++) { ftItem = fundTrends[fi - i]; double tDiff = ftItem.Value[0] - ftItem.Value[1]; if (diff < tDiff) { continuekuoda = false; break; } diff = tDiff; } if (!continuekuoda) { continue; } } KLineItem item = kline[ts[i].Date]; bout.RecordTrade(1, ts[i].Date, TradeDirection.Buy, item.CLOSE, (int)(getin.Value / item.CLOSE), backtestParam.Volumecommission, backtestParam.Stampduty, "B"); tr.Bouts.Add(bout); } return(tr); }
public DependencyInjection(ISeller iseller) { _iseller = iseller; }
public override TradeRecords Execute(string code, Properties strategyParam, BacktestParameter backtestParam, ISeller seller = null) { throw new NotImplementedException(); }
public override TradeRecords Execute(string code, Properties strategyParam, BacktestParameter backtestParam, ISeller seller = null) { IndicatorRepository repository = (IndicatorRepository)backtestParam.Get <Object>("repository"); //取得策略参数 double buy_mainlow = strategyParam.Get <double>("buy_mainlow"); //主力线低位买入 int buy_cross = strategyParam.Get <int>("buy_cross"); GetInMode p_getinMode = (GetInMode)strategyParam.Get <GetInMode>("getinMode"); TradeRecords tr = new TradeRecords(code); TimeSerialsDataSet ds = repository[code]; if (ds == null) { return(null); } KLine kline = ds.DayKLine; if (kline == null) { return(null); } TimeSeries <ITimeSeriesItem <List <double> > > dayFunds = ds.DayFundTrend; TimeSeries <ITimeSeriesItem <double> > dayFundsCross = ds.DayFundTrendCross; if (buy_cross == 0 && dayFunds == null) { return(null); } else if (buy_cross == 1 && (dayFundsCross == null || dayFunds == null)) { return(null); } #region 判断主力线低位决定买入点 if (buy_cross == 0) { for (int i = 0; i < dayFunds.Count; i++) { if (dayFunds[i].Date.Date <backtestParam.BeginDate || dayFunds[i].Date.Date> backtestParam.EndDate) { continue; } if (double.IsNaN(dayFunds[i].Value[0])) { continue; } if (dayFunds[i].Value[0] > buy_mainlow) { continue; } //主力线开始低于buy_mainlow... i += 1; while (i < dayFunds.Count) { if (dayFunds[i].Value[0] <= buy_mainlow) { i += 1; continue; } //主力线出了buy_mainlow KLineItem klineItem = kline[dayFunds[i].Date]; if (klineItem == null) { break; } int tIndex = kline.IndexOf(klineItem); if (tIndex >= kline.Count - 1) { break; } KLineItem klineItemNext = kline[tIndex + 1]; TradeBout bout = new TradeBout(code); double price = klineItem.CLOSE; if (price > klineItemNext.HIGH || price < klineItemNext.LOW) { break; } bout.RecordTrade(1, dayFunds[i].Date.Date, TradeDirection.Buy, price, (int)(p_getinMode.Value / price), backtestParam.Volumecommission, backtestParam.Stampduty, "主力线低于" + buy_mainlow.ToString("F2")); tr.Bouts.Add(bout); break; } } } #endregion #region 判断金叉决定买入点 else if (buy_cross == 1) { for (int i = 0; i < dayFundsCross.Count; i++) { if (dayFundsCross[i].Date.Date <backtestParam.BeginDate || dayFundsCross[i].Date.Date> backtestParam.EndDate) { continue; } if (dayFundsCross[i].Value <= 0) { continue; } ITimeSeriesItem <List <double> > dayFundItem = dayFunds[dayFundsCross[i].Date]; if (dayFundItem == null) { continue; } if (buy_mainlow != 0 && dayFundItem.Value[0] >= buy_mainlow) { continue; } KLineItem klineItem = kline[dayFundItem.Date]; if (klineItem == null) { continue; } int tIndex = kline.IndexOf(klineItem); if (tIndex >= kline.Count - 1) { continue; } KLineItem klineItemNext = kline[tIndex + 1]; TradeBout bout = new TradeBout(code); double price = klineItem.CLOSE; if (price > klineItemNext.HIGH || price < klineItemNext.LOW) { continue; } bout.RecordTrade(1, dayFunds[i].Date.Date, TradeDirection.Buy, price, (int)(p_getinMode.Value / price), backtestParam.Volumecommission, backtestParam.Stampduty, "主力线低于" + buy_mainlow.ToString("F2")); tr.Bouts.Add(bout); } } #endregion return(tr); }
public PayTradeAction(ICustomer customer, ISeller seller) : base(customer, seller) { }
public abstract TradeRecords Execute(string code, Properties strategyParam, BacktestParameter backtestParam, ISeller seller = null);
public SellersController(ISeller iSeller) { this._ISeller = iSeller; }
public override TradeRecords Execute(String code, Properties strategyParam, BacktestParameter backtestParam, ISeller seller = null) { IndicatorRepository repository = (IndicatorRepository)backtestParam.Get <Object>("repository"); if (repository == null) { return(null); } //取得策略参数 double buy_mainlow = strategyParam.Get <double>("buy_mainlow"); //主力线低位买入 int buy_cross = strategyParam.Get <int>("buy_cross"); GetInMode p_getinMode = (GetInMode)strategyParam.Get <GetInMode>("getinMode"); //取得行情数据 TradeRecords tr = new TradeRecords(code); TimeSerialsDataSet ds = repository[code]; if (ds == null) { return(null); } KLine kline = ds.DayKLine; if (kline == null) { return(null); } MACD macd = (MACD)ds.Create("macd", TimeUnit.day, false); if (macd == null) { return(null); } //买入条件判定 for (int i = 0; i < macd.Count; i++) { MACDItem macdItem = macd[i]; if (macdItem.Date < backtestParam.BeginDate || macdItem.Date >= backtestParam.EndDate) { continue; } if (macdItem.CROSS <= 0) { continue; } if (macdItem.DIF > buy_mainlow) { continue; } DateTime d = macdItem.Date; KLineItem klineItem = kline[d]; if (klineItem == null) { continue; } TradeBout bout = new TradeBout(code); bout.RecordTrade(1, d, TradeDirection.Buy, klineItem.CLOSE, (int)(p_getinMode.Value / klineItem.CLOSE), backtestParam.Volumecommission, backtestParam.Stampduty, "低位金叉" + macdItem.DIF.ToString("F2")); tr.Bouts.Add(bout); } return(tr); }
public RequestChangeTradeAction(ICustomer customer, ISeller seller) : base(customer, seller) { }
public ChooseProductTradeAction(ICustomer customer, ISeller seller) : base(customer, seller) { }
public abstract int Insert(string name, ISeller primarySeller);
/// <summary> /// 读取配置文件 /// </summary> /// <param name="path"></param> private void readConfigfile(String path = "") { String configfilename = "strategy.xml"; String fullfilename = FileUtils.GetDirectory(path) + configfilename; if (!File.Exists(fullfilename)) { throw new Exception("找不到策略文件文件"); } configFile = new FileInfo(fullfilename); configuration = FileUtils.XmlFileRead <StrategyConfiguration>(fullfilename, Encoding.UTF8, true); //读取买入算法类配置 if (configuration.buyers == null) { configuration.buyers = new List <TypeDescriptorElement>(); } foreach (TypeDescriptorElement e in configuration.buyers) { IBuyer buyer = e.CreateType <IBuyer>(); if (buyer == null) { continue; } this.buyers.Add(buyer); } //读出卖出算法配置 if (configuration.sellers == null) { configuration.sellers = new List <TypeDescriptorElement>(); } foreach (TypeDescriptorElement e in configuration.sellers) { ISeller seller = e.CreateType <ISeller>(); if (seller == null) { continue; } this.sellers.Add(seller); } //读出回测参数 backtestParam = new BacktestParameter(); foreach (Property prop in configuration.backtest.properties) { backtestParam.Put(prop.Name, prop.Value); } //读取策略 foreach (TypePropertyElement e in configuration.strategys) { if (e.ClassName == null || e.ClassName == "") { e.ClassName = "insp.Security.Strategy.StrategyMeta"; } IStrategyMeta meta = e.CreateType <StrategyMeta>(); if (meta == null) { continue; } IBuyer buyer = this.GetBuyer(e.properties.FirstOrDefault(x => x.Name == "buyer").Value); ISeller seller = this.GetSeller(e.properties.FirstOrDefault(x => x.Name == "seller").Value); if (buyer != null) { meta.Parameters.AddRange(((Buyer)buyer).PDList); } if (seller != null) { meta.Parameters.AddRange(((Seller)seller).PDList); } strategys.Add(meta); List <Property> ps = meta.Parameters.Check(e.properties); Properties props = new Properties(ps); strategyParams.Add(props); } }
public override TradeRecords Execute(string code, Properties strategyParam, BacktestParameter backtestParam, ISeller seller = null) { IndicatorRepository repository = (IndicatorRepository)backtestParam.Get <Object>("repository"); if (repository == null) { return(null); } TimeSerialsDataSet ds = repository[code]; if (ds == null) { return(null); } String modeName = strategyParam.Get <String>("mode"); Mode mode = Mode.Find(modeName); if (mode == null) { return(null); } return(mode.DoBuy(ds, strategyParam, backtestParam)); }
public override TradeRecords Execute(string code, Properties strategyParam, BacktestParameter backtestParam, ISeller seller = null) { IndicatorRepository repository = (IndicatorRepository)backtestParam.Get <Object>("repository"); if (repository == null) { return(null); } //创建数据集 TimeSerialsDataSet ds = repository[code]; if (ds == null) { return(null); } KLine klineDay = ds.DayKLine; if (klineDay == null || klineDay.Count < 0) { return(null); } TimeSeries <ITimeSeriesItem <List <double> > > fundDay = ds.DayFundTrend; if (fundDay == null || fundDay.Count <= 0) { return(null); } double p_mainforcelow = strategyParam.Get <double>("mainforcelow"); int p_monthbutpt = strategyParam.Get <int>("monthbutpt", 0); //double p_mainforceclimb = strategyParam.Get<double>("mainforceclimb"); double p_mainforceslope = strategyParam.Get <double>("mainforceslope"); int p_mainforcerough = strategyParam.Get <int>("mainforcerough"); int p_buypointdays = strategyParam.Get <int>("buypointdays"); int p_maxbuynum = strategyParam.Get <int>("maxbuynum"); GetInMode p_fundpergetin = GetInMode.Parse(strategyParam.Get <String>("getinMode")); TradeRecords tradeRecords = new TradeRecords(code); //遍历回测中的每一天 DateTime d = backtestParam.BeginDate; int beginIndex = klineDay.IndexOf(d, true); if (beginIndex < 0) { return(tradeRecords); } for (int index = beginIndex; index < klineDay.Count; index++) { KLineItem klineItemDay = klineDay[index]; if (klineItemDay == null) { continue; } d = klineItemDay.Date; ITimeSeriesItem <List <double> > fundItemDay = fundDay[d]; if (fundItemDay == null) { continue; } int fIndex = fundDay.IndexOf(fundItemDay); //是否进入到主力线低位 if (p_mainforcelow != 0 && fundItemDay.Value[0] >= p_mainforcelow) { continue; } //是否主力线爬升离开低位 if (p_mainforcelow != 0) { for (fIndex = fIndex + 1; fIndex < fundDay.Count; fIndex++) { fundItemDay = fundDay[fIndex]; if (fundItemDay == null) { continue; } if (fundItemDay.Value[0] <= p_mainforcelow) { continue; } if (fundItemDay.Date < backtestParam.BeginDate || fundItemDay.Date > backtestParam.EndDate)//数据错误 { return(tradeRecords); } d = fundItemDay.Date; index = klineDay.IndexOf(d); klineItemDay = klineDay[index]; break; } if (fIndex >= fundDay.Count) { return(tradeRecords); } } //看主力线爬升速度 if (p_mainforceslope != 0 && fIndex > 0) { //爬升速度不够快 if ((fundItemDay.Value[0] - fundDay[fIndex - 1].Value[0]) < p_mainforceslope) { continue; } } //看主力线是否持续爬升 if (p_mainforcerough > 0) { bool cont = true; for (int temp = 0; temp < p_mainforcerough; temp++) { fIndex += temp; if (fIndex >= fundDay.Count) { cont = false; break; } fundItemDay = fundDay[fIndex]; if (fundItemDay.Value[0] < fundDay[fIndex - 1].Value[0]) { cont = false; break; } } if (!cont) { continue; } d = fundItemDay.Date; index = klineDay.IndexOf(d); klineItemDay = klineDay[index]; } //看是否在买点附近 TradingLine tradingLine = ds.DayTradeLine; if (p_buypointdays >= 0 && tradingLine != null && tradingLine.buysellPoints != null && tradingLine.buysellPoints.Count > 0) { int bsptIndex = tradingLine.buysellPoints.IndexOf(d, true); ITimeSeriesItem <char> bsptItemDay = bsptIndex < 0 ? null : tradingLine.buysellPoints[bsptIndex]; if (bsptItemDay != null && bsptItemDay.Value == 'S') { bsptItemDay = bsptIndex >= tradingLine.buysellPoints.Count - 1 ? null : tradingLine.buysellPoints[bsptIndex + 1]; } if (bsptItemDay == null || (bsptItemDay.Date.Date - d).TotalDays > p_buypointdays) { continue; } } //月线买点才能买入 TimeSeries <ITimeSeriesItem <char> > ptMonths = ds.CubePtCreateOrLoad(TimeUnit.month); if (p_monthbutpt == 1 && ptMonths != null && ptMonths.Count > 0) { int t1 = 0; for (; t1 < ptMonths.Count - 1; t1++) { if (d.Date >= ptMonths[t1].Date.Date && d.Date <= ptMonths[t1 + 1].Date.Date) { break; } } if (t1 < ptMonths.Count - 1) { if (ptMonths[t1].Value != 'B') { continue; } } } //准备执行买入 String reason = ""; double price = klineItemDay.CLOSE; double fund = p_fundpergetin.Value;// price * p_maxholdnum; int amount = (int)(fund / price); TradeBout newBout = new TradeBout(ds.Code); newBout.RecordTrade(1, d, TradeDirection.Buy, price, amount, backtestParam.Volumecommission, 0, reason); tradeRecords.Bouts.Add(newBout); } return(tradeRecords); }