/// <summary> /// Initializes a new instance of the <see cref="SubmitTradeRequest"/> class. /// </summary> /// <param name="market">The Cryptopia market identifier.</param> /// <param name="type">The type of trade.</param> /// <param name="amount">The amount of coins.</param> /// <param name="rate">The price of the coins.</param> public SubmitTradeRequest(string market, TradeType type, decimal amount, decimal rate) { Market = market; Type = type; Amount = amount; Rate = rate; }
private void Open(TradeType tradeType) { var position = Positions.Find("SampleRSI", Symbol, tradeType); if (position == null) ExecuteMarketOrder(tradeType, Symbol, Volume, "SampleRSI"); }
internal Trade(double price, double amount, DateTime time, TradeType type) { Price = price; Amount = amount; Type = type; Time = time; }
private void ExecuteOrder(long volume, TradeType tradeType) { var result = ExecuteMarketOrder(tradeType, Symbol, volume, "Alembex", StopLoss, TakeProfit); if (result.Error == ErrorCode.NoMoney) Stop(); }
/// <summary> /// Initializes a new instance of the <see cref="SubmitTradeRequest"/> class. /// </summary> /// <param name="tradepairId">The Cryptopia tradepair identifier.</param> /// <param name="type">The type of trade.</param> /// <param name="amount">The amount of coins.</param> /// <param name="rate">The price of the coins.</param> public SubmitTradeRequest(int tradepairId, TradeType type, decimal amount, decimal rate) { TradePairId = tradepairId; Type = type; Amount = amount; Rate = rate; }
/// <summary> /// Initialize <see cref="Trade"/> class. /// </summary> /// <param name="clientName">Client name.</param> public Trade(string clientName, IDigicoinBroker broker, TradeType type, int order, decimal value) { ClientName = clientName; Broker = broker; Type = type; Order = order; Value = value; }
private void ExecuteOrder(double quantity, TradeType tradeType) { var volumeInUnits = Symbol.QuantityToVolume(quantity); var result = ExecuteMarketOrder(tradeType, Symbol, volumeInUnits, "Martingale", StopLoss, TakeProfit); if (result.Error == ErrorCode.NoMoney) Stop(); }
public Order(BtcePair pair, TradeType type, decimal amount, decimal rate, UInt32 timestamp, int status) { Pair = pair; Amount = amount; Rate = rate; TimestampCreated = timestamp; Status = status; }
/// <summary> /// Initializes a new instance of the Buy class. /// </summary> /// <param name="stockPoint">The stock point for the purchase.</param> /// <param name="tradeTypes">The type of the buy: short or long.</param> /// <param name="shares">The number of shares purchased.</param> public Buy(StockPoint stockPoint, TradeType tradeType, int shares) { this.Date = stockPoint.Date; this.Time = stockPoint.PointDateTime.AddMinutes(-5).ToString("HH:mm"); this.Price = stockPoint.Open; this.TradeType = tradeType; this.Shares = shares; }
private void Open(TradeType tradeType) { var position = Positions.Find("SampleRSI", Symbol, tradeType); var volumeInUnits = Symbol.QuantityToVolume(Quantity); if (position == null) ExecuteMarketOrder(tradeType, Symbol, volumeInUnits, "SampleRSI"); }
public static string ToString(TradeType v) { if (v == TradeType.Sell) return "sell"; if (v == TradeType.Buy) return "buy"; throw new NotSupportedException(); }
private void ExecuteOrder(TradeType tradeType, long volume, string prefixLabel = partialLabel) { int parties = 6, part1 = 2, part2 = 2; long partialVolume = Symbol.NormalizeVolume(volume/parties,RoundingMode.ToNearest); var result1 = ExecuteMarketOrder(tradeType, Symbol, partialVolume * part1, prefixLabel + "1"); var result2 = ExecuteMarketOrder(tradeType, Symbol, partialVolume * part2, prefixLabel + "2"); var result3 = ExecuteMarketOrder(tradeType, Symbol, volume - (part1 + part2) * partialVolume, prefixLabel + "3"); }
public TradeCoinRequest(string fromCoin, string toCoin, TradeType tradeType, TradeSide tradeSide, decimal tradePrice, decimal units, TradeLevel tradeLevel) { this.FromCoinSymbol = fromCoin; this.ToCoinSymbol = toCoin; this.TradeType = (int)tradeType; this.TradeSide = (int)tradeSide; this.TradePrice = tradePrice; this.Units = units; this.TradeLevel = (int)tradeLevel; }
public void TestDisplayName() { Assert.AreEqual("Trailer (TR)", new TradeType { Code = "TR", Name = "Trailer" }.DisplayName); Assert.AreEqual("Buy (B)", new TradeType { Code = "\r B\n\r", Name = "\t Buy\t\n\r" }.DisplayName); Assert.AreEqual("Surrender", new TradeType { Name = "Surrender" }.DisplayName); Assert.AreEqual("BUY", new TradeType { Code = "BUY" }.DisplayName); var tradeType = new TradeType { Name = " " }; Assert.AreEqual("TradeType (Id: '{0}')".Form(tradeType.Id.ToString()), tradeType.DisplayName); }
private void manageOpen(TradeType tradeType, long volume, string prefixLabel = botLabel) { int nVolumePartition = 10, part1 = 5, part2 = 3; long nVol = (long)Math.Floor((double)(volume / (microVolume * nVolumePartition))); long partialVolume = nVol * microVolume; var result1 = ExecuteMarketOrder(tradeType, Symbol, partialVolume * part1, prefixLabel + tradeType.ToString() + "-1"); var result2 = ExecuteMarketOrder(tradeType, Symbol, partialVolume * part2, prefixLabel + tradeType.ToString() + "-2"); var result3 = ExecuteMarketOrder(tradeType, Symbol, volume - (part1 + part2) * partialVolume, prefixLabel + tradeType.ToString() + "-3"); }
private decimal Trade(string clientName, TradeType type, int order) { Validate(clientName, order); var hundreds = (int)(order / 100); var result = TradeHundrets(clientName, type, order, hundreds); result = TradeTens(clientName, type, order, hundreds, result); return result; }
public Trade(BtcePair pair, TradeType type, decimal amount, decimal rate, int orderId, bool isYourOrder, UInt32 timestamp) { Pair = pair; Type = type; Amount = amount; Rate = rate; OrderId = orderId; IsYourOrder = isYourOrder; Timestamp = timestamp; }
public Trade(bool sim, int _lotDigits, string _logFileName, NQuotes.MqlApi mql4) : base(mql4) { this.logFileName = _logFileName; this.tradeType = TradeType.FLAT; this.startingBalance = mql4.AccountBalance(); this.endingBalance = 0; this.lotDigits = _lotDigits; this.state = null; this.actualEntry = -1; this.actualClose = -1; this.takeProfit = 0; this.cancelPrice = 0; this.initialProfitTarget = 0; this.plannedEntry = 0; this.stopLoss = 0; this.originalStopLoss = 0; this.positionSize = 0; this.logSize = 0; this.realizedPL = 0.0; this.minUnrealizedPL = 0.0; this.maxUnrealizedPL = 0.0; this.spreadOrderOpen = -1; this.spreadOrderClose = -1; this.tradeOpenedDate = mql4.TimeCurrent(); this.orderPlacedDate = new DateTime(); this.orderFilledDate = new DateTime(); this.tradeClosedDate = new DateTime(); this.finalState = false; if (sim) { this.order = new biiuse.SimOrder(this, mql4); this.id = "SIM_" + mql4.Symbol() + (mql4.TimeCurrent() + TimeSpan.FromSeconds(OFFSET)).ToString(); } else { this.order = new Order(this, mql4); this.id = mql4.Symbol() + (mql4.TimeCurrent() + TimeSpan.FromSeconds(OFFSET)).ToString(); } if (!mql4.IsTesting()) { string filename = mql4.Symbol() + "_" + mql4.TimeCurrent().ToString(); int filehandle = mql4.FileOpen(filename, MqlApi.FILE_WRITE | MqlApi.FILE_READ | MqlApi.FILE_TXT); mql4.FileSeek(filehandle, 0, MqlApi.SEEK_END); string output = "****Trade: " + this.id + " ****"; mql4.FileWriteString(filehandle, output, output.Length); mql4.FileWriteString(filehandle, "\n", 1); mql4.FileClose(filehandle); } }
private void ExecuteOrder(int volume, TradeType tradeType) { var request = new MarketOrderRequest(tradeType, volume) { Label = "BerthoRobot", StopLossPips = StopLoss, TakeProfitPips = TakeProfit }; Trade.Send(request); }
/// <summary> /// Constructor /// </summary> /// <param name="ticker">The stock ticker symbol</param> /// <param name="shares">The number of shares to trade</param> /// <param name="tradeTradeType">TradeType.Buy or TradeType.Sell</param> /// <param name="tradeStatus"> /// A TradeStatus enum that describes the status of the /// Trade /// </param> /// <param name="tadingSessionId"> /// Each trading session is given a unique identifier of type, Guid. /// Either create a TradingSessionId if you are starting a trade. Or pass in the existing /// TradingSessionId if you are part of a trade. /// </param> /// <param name="message">An arbitrary message</param> protected AbstractTrade(string ticker, int shares, TradeType tradeTradeType, TradeStatus tradeStatus, Guid tadingSessionId, string message = null) { Ticker = ticker; Shares = shares; TradeType = tradeTradeType; TadingSessionId = tadingSessionId; CreateTime = DateTime.UtcNow; TradeStatus = tradeStatus; Message = message; }
private void seta_variaveis(TradeType oper) { carregar_fibo(); if (oper == TradeType.Buy) price = precos(fibo, Symbol.Ask, oper); else price = precos(fibo, Symbol.Bid, oper); stop = stopcalc(oper, fibo); gain = gaincalc(oper, fibo); }
public TradeCoinResponse New(string fromCoin, string toCoin, TradeType tradeType, TradeSide tradeSide, decimal tradePrice, decimal units, TradeLevel tradeLevel) { return this.CallMethod<TradeCoinResponse>( new RequestBuilder(RequestType.POST, "order/new") .AddUrlSegment(new CoinsPairSegment(fromCoin, toCoin)) .AddUrlSegment(tradeType) .AddUrlSegment(tradeSide) .AddUrlSegment(tradePrice) .AddUrlSegment(units) .AddUrlSegment(tradeLevel)); }
public ShortContractDetail(TradeType tradeType, ContractType contractType, PageMode pageMode, string pageName) : base(pageMode, pageName) { InitializeComponent(); ModuleName = ContractHomeVM.GetModuleNameByContractType(contractType); TradeType = tradeType; ContractType = contractType; VM = new ShortContractDetailVM(tradeType, contractType); InitPage(); BindData(); }
internal TradingRecord(DateTime time, TradeType type, string stockCode, double price, int quantity) { Time = time; Type = type; StockCode = stockCode; Quantity = quantity; Price = price; Commissions = TradeCost.GetCommission(Price, Quantity); StampDuty = TradeCost.GetStampDuty(Type, StockCode, Price, Quantity); TransferFees = TradeCost.GetTransferFees(StockCode, Price, Quantity); FeesSettlement = 0m; }
/// <summary> /// Adds new trade to repository. /// </summary> /// <param name="clientName">Client name.</param> /// <param name="broker">Broker.</param> /// <param name="type">Trade type.</param> /// <param name="order">Trade order.</param> /// <param name="value">Trade value.</param> /// <exception cref="ArgumentException">Client name must be provided.</exception> /// <exception cref="ArgumentException">Broker must be provided.</exception> public void Add(string clientName, IDigicoinBroker broker, TradeType type, int order, decimal value) { if (string.IsNullOrWhiteSpace(clientName)) { throw new ArgumentException("Client name must be provided!"); } if (broker == null) { throw new ArgumentException("Broker must be provided!"); } var trade = new Trade(clientName, broker, type, order, value); _trades.Add(trade); }
private Ticker GetTicker(TradeType tradeType) { var jsonString = Get(TickerUrl(tradeType)); dynamic json = JsonConvert.DeserializeObject(jsonString); return new Ticker { TickerType = (byte)tradeType, WritingDate = EkbDataTimeNow, LastPrice = json.ticker.last, BuyPrice = json.ticker.buy, SellPrice = json.ticker.sell }; }
/// <summary> /// 计算印花税 /// </summary> /// <param name="type"></param> /// <param name="code"></param> /// <param name="price"></param> /// <param name="quantity"></param> /// <returns></returns> public static decimal GetStampDuty(TradeType type, string code, double price, int quantity) { if(type != TradeType.Sell) { return 0; } if(!IsStock(code)) { return 0; } return (decimal)price * quantity * Broker.StampDutyRate; }
public OrderParams(TradeType? tradeType, Symbol symbol, double? volume, string label, double? stopLoss, double? takeProfit, double? slippage, string comment, int? id, List<double> parties) { TradeType = tradeType; Symbol = symbol; Volume = volume; Label = label; StopLoss = stopLoss; TakeProfit = takeProfit; Slippage = slippage; Comment = comment; Id = id; Parties = parties; }
public ShortContractDetail(TradeType tradeType, ContractType contractType, int id, PageMode pageMode, string pageName,bool isSplit) : base(pageMode, pageName) { InitializeComponent(); IsSpilt = isSplit; ModuleName = ContractHomeVM.GetModuleNameByContractType(contractType); TradeType = tradeType; ContractType = contractType; IsEdit = true; VM = new ShortContractDetailVM(tradeType, contractType, id, isSplit); InitPage(); BindData(); }
public void FromString_ConvertToTradeType(string convertableString, bool valueExists) { bool parsedSuccessfully; TradeType currency = ConvertionHelper.FromString <TradeType>(convertableString, out parsedSuccessfully); if (!valueExists) { Assert.IsFalse(parsedSuccessfully); Assert.AreEqual(TradeType.unknown, currency); } else { Assert.IsTrue(parsedSuccessfully); } }
private void ExecuteOrder(TradeType tradeType, string label, double stopLoss, double takeProfit) { var volumeInUnits = Symbol.QuantityToVolume(Quantity); var position = Positions.Find(label, Symbol, tradeType); if (position == null) { var result = ExecuteMarketOrder(tradeType, Symbol, volumeInUnits, label, stopLoss, takeProfit); if (result.Error == ErrorCode.NoMoney) { Stop(); } } }
private void FilterTinyCandlesAndExecute(TradeType _TradeType) { // Order execution when avoiding tiny candles. if (FilterTinyCandles == true) { if (Math.Abs(BarArray.ToList()[CandlesNumber - 1]) > MinCandleSize * Symbol.PipSize) { ExecuteOrder(_TradeType); } } else { ExecuteOrder(_TradeType); } }
public static string StringToTradeType(string tradeType) { string result = ""; try { TradeType tradeType2 = (TradeType)int.Parse(tradeType); result = MemberHelper.GetEnumDescription(tradeType2); } catch { result = "其他交易类型"; } return(result); }
internal static string ToSerializedValue(this TradeType value) { switch (value) { case TradeType.Unknown: return("Unknown"); case TradeType.Buy: return("Buy"); case TradeType.Sell: return("Sell"); } return(null); }
/// <summary> /// Constructor /// </summary> /// <param name="repo">Repository interface</param> public VolumeTradeBuilder(ITradeBuilder trader , BotSettings settings, decimal lastBuy = 0, decimal lastSell = 0, TradeType tradeType = TradeType.BUY) { _trader = trader; SetBotSettings(settings); if (lastBuy != 0) { _lastBuy = lastBuy; } if (lastSell != 0) { _lastSell = lastSell; } _tradeType = tradeType; }
private void OpenPosition(TradeType type) { if (_position != null) Trade.Close(_position); Volume = GetVolume; Print(Volume); Request request = new MarketOrderRequest(type, Volume) { Label = "CCI 20", StopLossPips = StopLoss > 0 ? StopLoss : (int?) null, TakeProfitPips = TakeProfit > 0 ? TakeProfit : (int?) null, }; Trade.Send(request); }
private UnifiedPrePayMessage UnifiedPrePay(UnifiedWxPayModel model, TradeType tradeType) { //JSAPI支付, 追加客户openid if (tradeType == TradeType.JSAPI && gatewayInfo.DataList.Count > 4) { this.openid = gatewayInfo.DataList[4]; } string payPack = model.CreatePrePayPackage(body, out_trade_no, total_fee, notify_url, tradeType, openid); //预支付 UnifiedPrePayMessage result = Utils.WeiXinHelper.UnifiedPrePay(payPack); //Core.Globals.WriteText(new System.Text.StringBuilder(gatewayInfo.NotifyUrl)); System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (result == null) { sb.AppendFormat("获取PrepayId 失败 result is NULL"); } else if (!result.ReturnSuccess) { sb.AppendFormat( "获取PrepayId 失败 result.ReturnSuccess:{0}|result.Return_Code:{1}|result.Return_Msg:{2}", result.ReturnSuccess, result.Return_Code, result.Return_Msg); } else if (!result.ResultSuccess && result.Err_Code_Des == "该订单已支付") { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Write("该订单已支付!"); HttpContext.Current.Response.End(); return(result); } else if (!result.ResultSuccess) { sb.AppendFormat( "获取PrepayId 失败 result.ResultSuccess:{0}|result.Result_Code:{1}|result.Err_Code:{2}|result.Err_Code_Des:{3}", result.ResultSuccess, result.Result_Code, result.Err_Code, result.Err_Code_Des); } else if (string.IsNullOrEmpty(result.Prepay_Id)) { sb.AppendFormat("获取PrepayId 失败 result.Prepay_Id is NULL"); } if (sb.Length > 0) { Core.Globals.WriteText(sb); return(result); } return(result); }
private void OpenPosition(TradeType tradeType, double stopLossInPips, double takeProfitInPips, double volumeInUnits) { if (volumeInUnits == 0) { return; } if (Template.MaxStopLossPips > 0) { #if cAlgo // TODO: only print if not backtesting if (!IsBacktesting) { Print($"[sl] MaxStopLossPips {Template.MaxStopLossPips}. Reducing from {stopLossInPips}."); } #endif stopLossInPips = double.IsNaN(stopLossInPips) ? Template.MaxStopLossPips : Math.Min(Template.MaxStopLossPips, stopLossInPips); #if cAlgo if (!IsBacktesting) { Print($" -- confirm: {stopLossInPips}."); } #endif } //if (tradeType == TradeType.Sell) { stopLossInPips = -stopLossInPips; } TradeResult result = null; if (Modes.HasFlag(BotMode.Live) || Modes.HasFlag(BotMode.Demo) || IsBacktesting) { result = ExecuteMarketOrder(tradeType, Symbol, volumeInUnits, Label, stopLossInPips, takeProfitInPips); } if (!IsBacktesting) { var accountPosition = result?.Position; if (accountPosition != null || Modes.HasFlag(BotMode.Paper) || Modes.HasFlag(BotMode.Scanner)) { var botPosition = new BotPosition(accountPosition, this, this.Symbol, tradeType, stopLossInPips, takeProfitInPips, volumeInUnits); if (accountPosition != null) { BotPositionDict.Add(accountPosition, botPosition); } OnNewPosition(botPosition); } } }
private void EnableInputBoxes(TradeType type) { IsCointypeEnabled = true; IsUnitPriceEnabled = true; IsRelativeFeeEnabled = true; IsAbsoluteFeeEnabled = true; _isNotCaptialTradeMode = true; switch (type) { case TradeType.DEPOSIT: AFeeText = "0"; RFeeText = "0"; IsRelativeFeeEnabled = false; IsAbsoluteFeeEnabled = false; if (SelectedCoin.Equals("WON")) { IsUnitPriceEnabled = false; UnitPriceText = "0"; } break; case TradeType.WITHDRAWAL: IsCointypeEnabled = false; UnitPriceText = "0"; IsUnitPriceEnabled = false; break; case TradeType.TRANSFER: UnitPriceText = "0"; IsUnitPriceEnabled = false; break; case TradeType.BUY: if (SelectedCoin.Equals("WON")) { _isNotCaptialTradeMode = false; } break; case TradeType.SELL: if (SelectedCoin.Equals("WON")) { _isNotCaptialTradeMode = false; } break; } }
private void OpenPosition(Symbol symbol, TradeType tradeType) { if (HasPosition(symbol, tradeType)) { return; } ExecuteMarketOrder(tradeType, Volume); { Label = MyLabel Symbol = symbol } Trade.Send(request); }
private Order CreateOrder(double qty, TradeType tradeType) { Order order = new Order(); order.OrderId = NextOrderId; order.Action = (tradeType == TradeType.Buy) ? "BUY" : "SELL"; order.TotalQuantity = qty; order.Account = ""; order.ModelCode = ""; order.Tif = "DAY"; if (!string.IsNullOrEmpty(tradeAccount)) { order.Account = tradeAccount; } return(order); }
public TradingSignal( Instrument instrument, string orderId, OrderCommand command, TradeType tradeType, decimal?price, decimal volume, bool isMarginOrder, DateTime time, OrderType orderType = OrderType.Market) { Instrument = instrument; OrderId = orderId; Command = command; TradeType = tradeType; Price = price; Volume = volume; Time = time; OrderType = orderType; IsMarginOrder = isMarginOrder; }
private void OnPositionClosed(PositionClosedEventArgs args) { if (args.Position.Label == Label && args.Position.SymbolName == Symbol.Name && args.Reason == PositionCloseReason.TakeProfit) { if (args.Position.TradeType == TradeType.Buy) { _buyPipStep = _initialPipStep; _sideInSofference = TradeType.Sell; } else if (args.Position.TradeType == TradeType.Sell) { _sellPipStep = _initialPipStep; _sideInSofference = TradeType.Buy; } } }
public double Cap(bool increaseOnly, double?existingValue, double newValue, TradeType tradeType) { if (!increaseOnly || !existingValue.HasValue) { return(newValue); } if (tradeType == TradeType.Buy) { return(Math.Max(existingValue.Value, newValue)); } else { return(Math.Min(existingValue.Value, newValue)); } }
/// <summary> /// 修改用户余额 /// </summary> /// <param name="uid"></param> /// <param name="amt"></param> public void UpdateUserBanance(int uid, decimal amt, TradeType tp, string relevanceNo, int moneryType) { //修改当前用户余额 var item = new SysUserBalanceDetail() { OpUserId = uid, SerialNo = "d" + Ytg.Comm.Utils.BuilderNum(), Status = 0, TradeType = tp, UserId = uid, RelevanceNo = relevanceNo }; mSysUserBalanceService.UpdateUserBalance(item, moneryType == 0 ? amt : -amt); }
public Grid(string id, TradeType type, Position[] positions) { Id = id; Type = type; GridPositions = positions; if (type == TradeType.Buy) { LastClosedTradeTP = double.NegativeInfinity; } else if (type == TradeType.Sell) { LastClosedTradeTP = double.PositiveInfinity; } }
private double stopcalc(TradeType oper, List<double> sr) { organizarVetores(); if (oper == TradeType.Sell) sr.Sort(); if (idx < sr.Count - 1 && Math.Abs(sr[idx] - Symbol.Bid) / Symbol.PipSize > 5) return sr[idx + 1]; else if (oper == TradeType.Buy) return sr[idx] - 20 * Symbol.PipSize; else if (oper == TradeType.Sell) return sr[idx] + 20 * Symbol.PipSize; return 0; }
private void ExecuteOrder(double quantity) { ExponentialMovingAverage EMA50 = Indicators.ExponentialMovingAverage(SourceSeries, EmaValue); TradeType tradeType = TradeType.Sell; if (EMA50.Result.Last(0) > EMA50.Result.Last(5)) { tradeType = TradeType.Buy; } var volumeInUnits = Symbol.QuantityToVolume(quantity); var result = ExecuteMarketOrder(tradeType, Symbol, volumeInUnits, "Martingale", StopLoss, TakeProfit); }
protected void setLastProfitPrice(TradeType lastProfitTradeType) { if (lastProfitTradeType == TradeType.Buy) { _lastProfitPrice = Symbol.Ask; //Set a BreakEven once the price is past the buffer _lastProfitBreakEvenPrice = _lastProfitPrice - BreakEvenProfitBuffer * (1 / Symbol.PipSize); } if (lastProfitTradeType == TradeType.Sell) { _lastProfitPrice = Symbol.Bid; //Set a BreakEven once the price is past the buffer _lastProfitBreakEvenPrice = _lastProfitPrice + BreakEvenProfitBuffer; } }
/// <summary> /// Constructor /// </summary> /// <param name="repo">Repository interface</param> public OrderBookTradeBuilder(ITradeBuilder trader , BotSettings settings, decimal lastBuy = 0, decimal lastSell = 0, TradeType tradeType = TradeType.BUY) { _trader = trader; _fileRepo = new FileRepository(); SetBotSettings(settings); if (lastBuy != 0) { _lastBuy = lastBuy; } if (lastSell != 0) { _lastSell = lastSell; } _tradeType = tradeType; }
private void FilterAndExecuteTrades(TradeType _TradeType) { //Order execution when using difference between candles. if (UseCandleDifference == true) { var Difference = BarArray.ToList()[CandlesNumber - 1] * 100 / BarArrayAverage - 100; if (Difference >= DifferenceBetweenCandles) { FilterTinyCandlesAndExecute(_TradeType); } } else { FilterTinyCandlesAndExecute(_TradeType); } }
/// <summary> /// Trading action. /// </summary> /// <param name="tradeType">Trading type sell or buy</param> /// <param name="number">Number of trading action.</param> /// <returns>Result of trading</returns> public string Trade(TradeType tradeType, int number, List <IOption> options) { switch (tradeType) { case TradeType.Sell: trade = new SellTrading(); return(trade.Execute(SellRate, number, options)); case TradeType.Buy: trade = new BuyTrading(); return(trade.Execute(BuyRate, number, options)); default: return("Trade type is invalid"); } }
private int o_tm(TradeType TrdTp) { int TSide = 0; for (int i = Positions.Count - 1; i >= 0; i--) { var position = Positions[i]; if (position.Label == cBotLabel && position.SymbolCode == Symbol.Code) { if (position.TradeType == TrdTp) { TSide++; } } } return(TSide); }
private int CountOfTradesOfType(TradeType tradeType) { var tradeCount = 0; foreach (var position in Positions) { if (position.Label == Label && position.SymbolCode == Symbol.Code) { if (position.TradeType == tradeType) { tradeCount++; } } } return(tradeCount); }
private long clt(TradeType TrdTp) { long Result = 0; for (int i = Positions.Count - 1; i >= 0; i--) { position = Positions[i]; if (position.Label == Label && position.SymbolCode == Symbol.Code) { if (position.TradeType == TrdTp) { Result += position.Volume; } } } return(Result); }
/// <summary> /// Does the search on market. /// </summary> /// <param name="sortType">Type of the sort.</param> /// <param name="matcher">The matcher.</param> /// <param name="resealesFilter">The level.</param> /// <param name="inCristals">if set to <c>true</c> [in cristals].</param> /// <param name="inGold">if set to <c>true</c> [in gold].</param> public void DoSearchOnMarket(TradeType sortType, string matcher, ResealesFilter resealesFilter, bool inCristals, bool inGold) { var url = string.Format("{0}&order={1}&dir=asc", UrlTradeNow, (sortType == TradeType.Sale ? "buy" : "bid")); if (inCristals != inGold) { url = url + "&money=" + (inGold ? 1 : 2); } var postData = string.Format("range={0}&filter={1}", (int)resealesFilter, HttpUtility.UrlEncode(Encoding.Default.GetBytes(matcher)).ToUpper()); GoTo(url, postData); }
public TradeAnswer Trade(WexPair pair, TradeType type, decimal rate, decimal amount) { var args = new NameValueDictionary { { "pair", WexPairHelper.ToString(pair) }, { "type", TradeTypeHelper.ToString(type) }, { "rate", DecimalToString(rate) }, { "amount", DecimalToString(amount) } }; var result = JObject.Parse(Query("Trade", args)); if (result.Value <int>("success") == 0) { throw new WexApiException(result.Value <string>("error")); } return(TradeAnswer.ReadFromJObject(result["return"] as JObject)); }
//Calculate a next orderCount number when tick sequence gaps public int CalculateNextOrderNumber(TradeType tradeType, double currentTickPrice, double firstEntryPrice) { double currentPipsIntoRange = 0; switch (tradeType) { case TradeType.Buy: currentPipsIntoRange = firstEntryPrice - currentTickPrice; break; case TradeType.Sell: currentPipsIntoRange = currentTickPrice - firstEntryPrice; break; } currentPipsIntoRange = CalcPipsForBroker(currentPipsIntoRange); return(OrderSpacingCalculator.GetOrderNumberFromPips(currentPipsIntoRange)); }
//Return the position count of trades of specific type (BUY/SELL) private int activeDirectionCount(TradeType TrdTp) { int TSide = 0; for (int i = Positions.Count - 1; i >= 0; i--) { position = Positions[i]; if (position.Label == Label && position.SymbolCode == Symbol.Code) { if (position.TradeType == TrdTp) { TSide++; } } } return(TSide); }
private PayReturnModel CreatePayReturnModel(TradeType tradeType, string nonceStr, string xmlResult) { string timeStamp = WechatCommonUtlis.GetTimestamp(); PackageParamModel packageDic = new PackageParamModel();//坑2 参数区分大小写 APP是小写 string prepay_id = GetPrepayId(xmlResult); string package; if (tradeType == TradeType.JSAPI) { packageDic.AddValue("appId", this.AppId);// 注意这里的大小写 应用AppID 坑4 packageDic.AddValue("timeStamp", timeStamp); packageDic.AddValue("nonceStr", nonceStr); package = string.Format("prepay_id={0}", prepay_id); packageDic.AddValue("package", package);//坑3 packageDic.AddValue("signType", this._signType); } else if (tradeType == TradeType.APP) { packageDic.AddValue("appid", this.AppId); packageDic.AddValue("partnerid", _mchId); packageDic.AddValue("prepayid", prepay_id); package = "Sign=WXPay"; packageDic.AddValue("package", package);//APP支付固定设置参数 packageDic.AddValue("timestamp", timeStamp); packageDic.AddValue("noncestr", nonceStr); } else { throw new WxPayException("暂未实现的支付类型"); } var paySign = WechatCommonUtlis.GetMD5Sign(packageDic, this._appKey);//坑1 APPKey可能也有错 PayReturnModel model = new PayReturnModel { timeStamp = timeStamp, nonceStr = nonceStr, package = package, paySign = paySign, signType = this._signType, appId = AppId, prepayId = prepay_id,//JSAPI支付忽略此字段 partnerId = _mchId }; return(model);//最终返回前端的参数 }