Ejemplo n.º 1
0
        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");
        }
        public async Task <long> CreateOrderAsync(TradeType tradeType, string tradingPair, decimal rate, decimal amount)
        {
            var createdTs      = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            var formParameters = $"symbol={tradingPair}" +
                                 $"&side={tradeType.ToString().ToUpper()}" +
                                 "&type=LIMIT" +
                                 "&timeInForce=GTC" +
                                 $"&quantity={Math.Round(amount, 5).ToString(CultureInfo.InvariantCulture)}" +
                                 $"&price={Math.Round(rate, 2).ToString(CultureInfo.InvariantCulture)}" +
                                 $"&recvWindow={RecvWindow}" +
                                 $"&timestamp={createdTs}";

            using (var client = GetClient())
            {
                client.DefaultRequestHeaders.Add("X-MBX-APIKEY", _binanceOptions.ApiKey);
                var signature = SignPostBody(formParameters);

                var requestBody = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("symbol", tradingPair),
                    new KeyValuePair <string, string>("side", tradeType.ToString().ToUpper()),
                    new KeyValuePair <string, string>("type", "LIMIT"),
                    new KeyValuePair <string, string>("timeInForce", "GTC"),
                    new KeyValuePair <string, string>("quantity", Math.Round(amount, 5).ToString(CultureInfo.InvariantCulture)),
                    new KeyValuePair <string, string>("price", Math.Round(rate, 2).ToString(CultureInfo.InvariantCulture)),
                    new KeyValuePair <string, string>("recvWindow", RecvWindow.ToString()),
                    new KeyValuePair <string, string>("timestamp", createdTs.ToString()),
                    new KeyValuePair <string, string>("signature", signature.ToLower())
                });

                using (var response = await client.PostAsync("/api/v3/order", requestBody))
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        throw new Exception($"Response code: {response.StatusCode}, body: {response.Content.ReadAsStringAsync().Result}");
                    }

                    var responseDefinition = new { OrderId = long.MaxValue };
                    var responseContent    = await response.Content.ReadAsStringAsync();

                    if (responseContent.ToLower().Contains("error"))
                    {
                        Console.WriteLine($"Create order error: Error: {responseContent}");
                        return(-1);
                    }
                    var deserializedResponse = JsonConvert.DeserializeAnonymousType(responseContent, responseDefinition);
                    return(deserializedResponse.OrderId);
                }
            }
        }
        private void _open(ChartTrendLine myline, TradeType mytype, string directive = "0,01", double slippage = 20)
        {
            double myLots = 0.01;

            try
            {
                // --> double con la virgola e non con il punto
                if (directive.IndexOf('.') == -1)
                {
                    NumberFormatInfo provider = new NumberFormatInfo();
                    provider.NumberDecimalSeparator = ",";
                    provider.NumberGroupSeparator   = ".";
                    provider.NumberGroupSizes       = new int[]
                    {
                        3
                    };

                    myLots = Convert.ToDouble(directive, provider);
                }
            } catch
            {
            }

            var volumeInUnits = Symbol.QuantityToVolumeInUnits(myLots);

            TradeResult result = ExecuteMarketRangeOrder(mytype, Symbol.Name, volumeInUnits, slippage, mytype == TradeType.Buy ? Ask : Bid, MyLabel, 0, 0);

            if (!result.IsSuccessful)
            {
                _log("can't open new trade " + mytype.ToString("G") + " (" + result.Error + ")");
            }

            // --> Anche se non dovesse aprire la disabilito, potrebbe creare più problemi che altro
            // --> myline.ToDelivered();
        }
        /// <summary>
        /// Get order information
        /// </summary>
        /// <param name="symbol">string of symbol</param>
        /// <param name="tradeType">Trade type</param>
        /// <param name="orderId">long of orderId</param>
        /// <param name="page">Page number, default 1</param>
        /// <param name="limit">Number of fills to return, default 20</param>
        /// <returns>OrderResponse object</returns>
        public async Task <OrderListDetail> GetOrder(string symbol, TradeType tradeType, long orderId, int page = 1, int limit = 20)
        {
            var endpoint = "/v1/order/detail";
            var url      = baseUrl + endpoint;
            var kuPair   = _helper.CreateDashedPair(symbol);

            var queryString = new List <string>
            {
                $"symbol={kuPair}",
                $"type={tradeType.ToString()}",
                $"limit={limit}",
                $"page={page}",
                $"orderOid={orderId}"
            };

            var headers = GetRequestHeaders(endpoint, queryString.ToArray());

            try
            {
                var response = await _restRepo.GetApiStream <ApiResponse <DealOrder <OrderListDetail> > >(url, headers);

                return(response.data.datas);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Performs a scan for all filtered symbols
        /// </summary>
        /// <returns></returns>
        public async Task <Signal> ScanAsync(string symbol)
        {
            try
            {
                // download the new candles
                var candles = (await _api.GetCandlesAsync(symbol, 60 * _minutes, DateTime.Now.AddMinutes(-5 * 50))).Reverse().ToList();
                candles = AddMissingCandles(candles);
                // scan candles for buy/sell signal
                TradeType tradeType = TradeType.Long;
                var       strategy  = new DayTradingStrategy(symbol, _settings);
                if (strategy.IsValidEntry(candles, 0, out tradeType))
                {
                    // ignore signals for shorts when not allowed
                    if (tradeType == TradeType.Short && !_settings.AllowShorts)
                    {
                        return(null);
                    }

                    // got buy/sell signal.. write to console
                    Console.Beep();
                    return(new Signal()
                    {
                        Symbol = symbol,
                        Trade = tradeType.ToString(),
                        Date = $"{candles[0].Timestamp.AddHours(2):dd-MM-yyyy HH:mm}"
                    });
                }
        /// <summary>
        /// Instantiate to be able to get the trades required.
        /// </summary>
        /// <param name="service">The type of API service.</param>
        /// <param name="trade">The type of trade.</param>
        public TradesFetcher(IPowerService service, TradeType trade, IServiceLogger logger)
        {
            this.service = service;
            this.trade   = trade;
            this.logger  = logger;

            Environment.SetEnvironmentVariable("Trade", trade.ToString());
        }
        public async Task <long> CreateOrderAsync(TradeType tradeType, string tradingPair, decimal rate, decimal amount)
        {
            var nonce          = GenerateNonce();
            var formParameters = $"command={tradeType.ToString().ToLower()}" +
                                 $"&nonce={nonce}" +
                                 $"&currencyPair={tradingPair}" +
                                 $"&rate={rate.ToString(CultureInfo.InvariantCulture)}" +
                                 $"&amount={amount.ToString(CultureInfo.InvariantCulture)}";

            using (var client = GetClient())
            {
                client.DefaultRequestHeaders.Add("Key", _poloniexOptions.ApiKey);
                client.DefaultRequestHeaders.Add("Sign", SignPostBody(formParameters));

                var requestBody = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("command", tradeType.ToString().ToLower()),
                    new KeyValuePair <string, string>("nonce", nonce.ToString()),
                    new KeyValuePair <string, string>("currencyPair", tradingPair),
                    new KeyValuePair <string, string>("rate", rate.ToString(CultureInfo.InvariantCulture)),
                    new KeyValuePair <string, string>("amount", amount.ToString(CultureInfo.InvariantCulture))
                });

                using (var response = await client.PostAsync(PrivateEndpointPath, requestBody))
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        throw new Exception($"Response code: {response.StatusCode}");
                    }

                    var responseDefinition = new { OrderNumber = long.MaxValue, ResultingTrades = new List <PoloniexTrade>() };
                    var responseContent    = await response.Content.ReadAsStringAsync();

                    if (responseContent.ToLower().Contains("error"))
                    {
                        Console.WriteLine($"Create order error: Error: {responseContent}");
                        return(-1);
                    }
                    var deserializedResponse = JsonConvert.DeserializeAnonymousType(responseContent, responseDefinition);
                    return(deserializedResponse.OrderNumber);
                }
            }
        }
Ejemplo n.º 8
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("-------------------------------------\r\n");
            sb.Append("成交时间:" + TimerHelper.ConvertStringToDateTime(ExchangeTimeStamp).ToLocalTime().ToString() + "\r\n");
            sb.Append("交易ID:" + TradeID + "类别:" + Type.ToString() + "\r\n");
            sb.Append("价格:" + Price.ToString() + "   数量:" + Amount.ToString() + "\r\n");
            return(sb.ToString());
        }
Ejemplo n.º 9
0
        public TradeOrder PlaceOrder(int parentOrderID, TradeType tradeType, string symbol, double price, double qty, string exchange = null, OrderType orderType = OrderType.LMT)
        {
            if (tradeType != TradeType.Buy && tradeType != TradeType.Sell)
            {
                throw new Exception("Unsupported TradeType: " + tradeType);
            }
            TradeOrder res = null;

            var parent = ParentOrderManager.Instance.GetParentOrderByParentID(parentOrderID);

            if (tradeType == TradeType.Sell && parent.Qty == 0)
            {
                Log.Error("Parent zero qty");
                return(res);
            }
            if (tradeType == TradeType.Sell && parent.Qty <= qty)
            {
                qty = parent.Qty;
                Log.Info("Reduce qty to parent open qty " + qty);
            }



            lock (trade_locker)
            {
                int orderID = -1;
                if (Broker == Broker.IB)
                {
                    orderID = IBClient.PlaceOrder(symbol, price, qty, tradeType, exchange, orderType);
                }
                else
                {
                    orderID = TDClient.PlaceOrder(symbol, price, qty, tradeType, exchange, orderType);
                }
                res = new TradeOrder();
                res.ParentOrderID = parentOrderID;
                res.OrderID       = orderID;
                res.Status        = TradeOrderStatus.PendingSubmit;
                res.Side          = tradeType.ToString();
                res.Price         = price;

                ParentOrderManager.Instance.AddChildOrder(res);

                if (IsInitialized)
                {
                    StateManager.Save();
                }
            }

            Log.Info(string.Format("Place order ID {0}, TradeType {1}, symbol {2}, price {3}, qty {4}, exchange {5}, parentOrderID {6}",
                                   res.OrderID, tradeType, symbol, price, qty, exchange, parentOrderID));

            return(res);
        }
Ejemplo n.º 10
0
        public int PlaceOrder(string symbol, double price, double qty, TradeType tradeType, string exchange = null, OrderType orderType = OrderType.LMT)
        {
            int  orderID       = -1;
            bool isMarketOrder = (orderType == OrderType.MKT);

            try
            {
                TDInstrument inst = new TDInstrument();
                inst.assetType = TDConstantVal.AssetType_EQUITY;
                inst.symbol    = symbol;

                OrderLegCollection col = new OrderLegCollection();

                if (tradeType == TradeType.Buy)
                {
                    col.instruction = TDConstantVal.OrderTradeType_Buy;
                }
                else if (tradeType == TradeType.Sell)
                {
                    col.instruction = TDConstantVal.OrderTradeType_Sell;
                }
                else
                {
                    Log.Error("Unsupported trade type: " + tradeType.ToString());
                }
                col.quantity   = (int)qty; //truncate decimal
                col.instrument = inst;


                TDContract contract = new TDContract();
                contract.duration          = TDConstantVal.OrderTIF_Day;
                contract.price             = price;
                contract.orderType         = isMarketOrder? TDConstantVal.OrderType_MKT: TDConstantVal.OrderType_LMT;
                contract.session           = TDConstantVal.OrderSession_Normal;
                contract.orderStrategyType = TDConstantVal.OrderStrategyType_Single;

                contract.orderLegCollection = new List <OrderLegCollection>()
                {
                    col
                };

                string msg = JsonConvert.SerializeObject(contract);

                var res = SendMessage(OrderURL, "POST", msg);

                orderID = ParseOrderID(res.Item1);
            }catch (Exception ex)
            {
                Log.Error(string.Format("Error placing order: {0}", ex.Message));
                throw ex;
            }

            return(orderID);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 获取请求参数
        /// </summary>
        /// <returns></returns>
        public IDictionary <string, string> GetParameters()
        {
            var parameteers = new Dictionary <string, string>();

            if (!string.IsNullOrEmpty(DeviceInfo))
            {
                parameteers.Add("device_info", DeviceInfo);
            }
            parameteers.Add("body", Body);
            if (!string.IsNullOrEmpty(Detail))
            {
                parameteers.Add("detail", Detail);
            }
            if (!string.IsNullOrEmpty(Attach))
            {
                parameteers.Add("attach", Attach);
            }
            parameteers.Add("out_trade_no", OutTradeNo);
            if (!string.IsNullOrEmpty(FeeType))
            {
                parameteers.Add("fee_type", FeeType);
            }
            parameteers.Add("total_fee", TotalFee.ToString());
            parameteers.Add("spbill_create_ip", SpbillCreateIp);
            if (TimeStart.HasValue)
            {
                parameteers.Add("time_start", TimeStart.Value.ToString("yyyyMMddHHmmss"));
            }
            if (TimeExpire.HasValue)
            {
                parameteers.Add("time_expire", TimeExpire.Value.ToString("yyyyMMddHHmmss"));
            }
            if (!string.IsNullOrEmpty(GoodsTag))
            {
                parameteers.Add("goods_tag", GoodsTag);
            }
            parameteers.Add("notify_url", NotifyUrl);
            parameteers.Add("trade_type", TradeType.ToString());
            if (!string.IsNullOrEmpty(ProductId))
            {
                parameteers.Add("product_id", ProductId);
            }
            if (!string.IsNullOrEmpty(LimitPay))
            {
                parameteers.Add("limit_pay", LimitPay);
            }
            parameteers.Add("openid", OpenId);
            return(parameteers);
        }
        /// <summary>
        /// Make a trade
        /// </summary>
        /// <param name="orderPrice">Trade price</param>
        /// <returns>TradeResponse object</returns>
        private TradeResponse MakeTrade(decimal orderPrice)
        {
            var quantity = GetTradeQuantity(orderPrice);

            var trade = new TradeParams
            {
                price       = orderPrice,
                symbol      = _symbol,
                side        = tradeType.ToString(),
                type        = OrderType.LIMIT.ToString(),
                quantity    = quantity,
                timeInForce = "GTC"
            };

            var response = PlaceTrade(trade);

            return(response);
        }
Ejemplo n.º 13
0
        private string GenerateStatusText()
        {
            var statusText     = "";
            var buyPositions   = "";
            var sellPositions  = "";
            var buyPipsStep    = "";
            var sellPipsStep   = "";
            var spread         = "";
            var buyDistance    = "";
            var sellDistance   = "";
            var sofferenceSide = "";

            spread         = "\nSpread = " + Math.Round(CurrentSpread, 1);
            sofferenceSide = "\nSofference Side = " + _sideInSofference.ToString();
            buyPositions   = "\nBuy Positions = " + CountOfTradesOfType(TradeType.Buy);
            sellPositions  = "\nSell Positions = " + CountOfTradesOfType(TradeType.Sell);
            buyPipsStep    = "\nBuy Pips Step = " + _buyPipStep.ToString();
            sellPipsStep   = "\nSell Pips Step = " + _sellPipStep.ToString();

            if (CountOfTradesOfType(TradeType.Buy) > 0)
            {
                var averageBuyFromCurrent = Math.Round((CalculateAveragePositionPrice(TradeType.Buy) - Symbol.Bid) / Symbol.PipSize, 1);
                buyDistance = "\nBuy Target Away = " + averageBuyFromCurrent;
            }
            if (CountOfTradesOfType(TradeType.Sell) > 0)
            {
                var averageSellFromCurrent = Math.Round((Symbol.Ask - CalculateAveragePositionPrice(TradeType.Sell)) / Symbol.PipSize, 1);
                sellDistance = "\nSell Target Away = " + averageSellFromCurrent;
            }
            if (CurrentSpread > MaxSpread)
            {
                statusText = "MAX SPREAD EXCEED";
            }
            else
            {
                statusText = "Smart Grid" + spread + buyPositions + sellPositions + buyPipsStep + sellPipsStep + sofferenceSide;
            }
            return(statusText);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Performs a scan for all filtered symbols
        /// </summary>
        /// <returns></returns>
        public async Task <Signal> ScanAsync(ExtendedSymbol symbol, int minutes)
        {
            try
            {
                // download the new candles
                var candles = (await _api.GetCandlesAsync(symbol.Symbol.MarketSymbol, 60 * minutes, DateTime.Now.AddMinutes(-5 * 50))).Reverse().ToList();
                candles = AddMissingCandles(candles, minutes);
                // scan candles for buy/sell signal
                TradeType tradeType = TradeType.Long;

                var strategy = new DayTradingStrategy(symbol.Symbol.MarketSymbol, _settings);
                if (strategy.IsValidEntry(candles, 0, out tradeType, out decimal bandwitdh))
                {
                    // ignore signals for shorts when not allowed
                    if (tradeType == TradeType.Short && !_settings.AllowShorts)
                    {
                        return(null);
                    }

                    // got buy/sell signal.. write to console
                    int beepFrequency = symbol.Trends[1].Trend > 0 ? 1000 : 500;
                    Console.Beep(beepFrequency, 200);

                    return(new Signal()
                    {
                        Symbol = symbol.Symbol.MarketSymbol,
                        Trade = tradeType.ToString(),
                        Date = $"{candles[0].Timestamp.AddHours(2):dd-MM-yyyy HH:mm}",
                        TimeFrame = $"{minutes} min",
                        HyperTraderURI = GetHyperTradeURI(symbol.Symbol, minutes),
                        Volume = symbol.Ticker.Volume,
                        FourHourTrend = String.Format("{00:P2}", symbol.Trends[0].Trend),
                        OneHourTrend = String.Format("{00:P2}", symbol.Trends[1].Trend),
                        FourHourTrendObject = symbol.Trends[0],
                        OneHourTrendObject = symbol.Trends[1],
                        BBBandwidth = String.Format("{0:0.0#}", bandwitdh)
                    });
                }
Ejemplo n.º 15
0
        /// <summary>
        /// 生成 预支付 请求参数(XML)
        /// </summary>
        /// <param name="description"></param>
        /// <param name="tradeNo"></param>
        /// <param name="totalFee"></param>
        /// <param name="createIp"></param>
        /// <param name="notifyUrl"></param>
        /// <param name="openid"></param>
        /// <returns></returns>
        public string CreatePrePayPackage(string description, string tradeNo, string totalFee, string notifyUrl, TradeType tradeType, string openid = null)
        {
            Dictionary <string, string> nativeObj = new Dictionary <string, string>();
            string spbill_create_ip;  //用户的公网ip,不是商户服务器IP

            nativeObj.Add("appid", AppId);
            nativeObj.Add("mch_id", PartnerId);
            nativeObj.Add("nonce_str", CommonUtil.CreateNoncestr());
            nativeObj.Add("body", description); //商品描述
            nativeObj.Add("out_trade_no", tradeNo);
            nativeObj.Add("total_fee", totalFee);
            //nativeObj.Add("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));//交易起始时间
            //nativeObj.Add("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));//交易结束时间

            switch (tradeType)
            {
            case TradeType.JSAPI:
                spbill_create_ip = getRealIp();
                nativeObj.Add("openid", openid);
                break;

            case TradeType.APP:
            default:
                spbill_create_ip = getRealIp();
                break;

            case TradeType.NATIVE:
                spbill_create_ip = HttpContext.Current.Request.ServerVariables["Local_Addr"];
                nativeObj.Add("product_id", tradeNo);
                break;
            }
            nativeObj.Add("spbill_create_ip", spbill_create_ip);
            nativeObj.Add("notify_url", notifyUrl);
            nativeObj.Add("trade_type", tradeType.ToString()); //交易类型
            nativeObj.Add("sign", GetCftPackage(nativeObj));

            return(DictionaryToXmlString(nativeObj));
        }
Ejemplo n.º 16
0
        private bool OperTrade(RechargeInput input, TradeType tradeTyppe)
        {
            var account = _financeAccount.FirstOrDefault(m => m.UserId == input.userId);

            if (account != null)
            {
                if (input.Amount < 0 && account.Blance + input.Amount < 0)
                {
                    throw new UserFriendlyException("账户余额不足, 扣款失败");
                }

                account.Blance = account.Blance + input.Amount;

                FinanceTradeDetail entity = new FinanceTradeDetail();
                entity.UserId           = input.userId;
                entity.Amount           = input.Amount;
                entity.FinanceAccountId = account.Id;
                entity.TradeType        = tradeTyppe.ToString();
                entity.SerialNo         = _tradeManager.GenerateTradeNo(tradeTyppe);
                return(_tradeManager.CreateTrade(entity));
            }
            throw new UserFriendlyException("未找到此账户");
        }
Ejemplo n.º 17
0
        public TradeOrder PlaceTrailStopOrder(int parentOrderID, TradeType tradeType, string symbol, double qty, double trailStopPrice, double trailPct, string exchange = null)
        {
            TradeOrder res     = null;
            int        orderID = -1;

            lock (trade_locker)
            {
                if (Broker == Broker.IB)
                {
                    orderID = IBClient.PlaceTrailStopOrder(symbol, qty, trailStopPrice, trailPct, tradeType, exchange);
                }
                else
                {
                    //orderID = TDClient.PlaceOrder(symbol, price, qty, tradeType, exchange, orderType);
                }

                res = new TradeOrder();
                res.ParentOrderID  = parentOrderID;
                res.OrderID        = orderID;
                res.Status         = TradeOrderStatus.PendingSubmit;
                res.Side           = tradeType.ToString();
                res.TrailStopPrice = trailStopPrice;
                res.TrailingPct    = trailPct;

                ParentOrderManager.Instance.AddChildOrder(res);

                if (IsInitialized)
                {
                    StateManager.Save();
                }
            }

            Log.Info(string.Format("Place trailingstop order ID {0}, TradeType {1}, symbol {2}, qty {3}, trailStoppPrice {4}, trailingPct {5}%, exchange {6}",
                                   orderID, tradeType, symbol, qty, trailStopPrice, trailPct * 100, exchange));

            return(res);
        }
Ejemplo n.º 18
0
 internal Trade(double price, double amount, TradeType type)
 {
     this.price = price.ToString();
     this.amount = amount.ToString();
     this.type = type.ToString().ToLower();
 }
Ejemplo n.º 19
0
        protected override void OnBar()
        {
            // This Bar is a potential Trigger Bar.
            MA20 = Indicators.MovingAverage(SourceSeries, 20, MAType);
            MA34 = Indicators.MovingAverage(SourceSeries, 34, MAType);
            MA27 = Indicators.MovingAverage(SourceSeries, 27, MAType);
            DateTime EntryExpiration = MarketSeries.OpenTime.LastValue.AddMinutes(PendingOrderEpiration);


            // Only run during Market Opening Times..
            if (MarketSeries.OpenTime.LastValue.TimeOfDay <= new TimeSpan(8, 0, 0) & MarketSeries.OpenTime.LastValue.TimeOfDay >= new TimeSpan(11, 0, 0))
            {
                return;
            }


            // Reasons not to take the trade:
            if ((MarketSeries.High.Last(1) - MarketSeries.Low.Last(1)) > 50)
            {
                Print("Signal Bar greater than 50 points, exiting...");
                return;
            }

            // Reasons not to take the trade:
            if ((MarketSeries.High.Last(1) - MarketSeries.Low.Last(1)) < MinSignalLength)
            {
                Print("Signal Bar too small, exiting...");
                return;
            }

            // Reasons not to take the trade:
            if (IsPreviousBarsOK() == false)
            {
                Print("Previous Bars fail");
                return;
            }


            // Only look for trades if there are no existing positions open.
            if (Positions.Count == 0)
            {
                //  Only trade if there is a sufficient Gap between MA's
                double MAGap = Math.Abs(MA20.Result.Last(1) - MA34.Result.Last(1));
                if (MAGap >= MinMAGap)
                {
                    // Only trade if Candle is touching the MA lines
                    if (DoesCandleTouch(MarketSeries.High.Last(1), MarketSeries.Low.Last(1), MA20.Result.Last(1), MA34.Result.Last(1)) == true)
                    {
                        //Get Direction Of Signal Bar
                        TradeType SignalBarDirection = TradeType.Sell;
                        if (MarketSeries.Open.Last(1) < MarketSeries.Close.Last(1))
                        {
                            SignalBarDirection = TradeType.Buy;
                        }
                        else
                        {
                            SignalBarDirection = TradeType.Sell;
                        }

                        Print("Bar Direction: " + SignalBarDirection.ToString());

                        if (IsCloseWithinPercent(MarketSeries.High.Last(1), MarketSeries.Low.Last(1), SignalBarDirection, MarketSeries.Close.Last(1)) == true)
                        {
                            // Rule 10: Make sure the candle is in the same direction as the trend

                            // string Trend = GetMACDTrend();
                            string Trend = GetMA27Trend();


                            // Check for Minimum Trend Movement
                            bool MinSignal = CheckMovment(SignalBarsBack, MinSignalEMAMovement, MaxSignalEMAMovement, "Signal Movement Result:");

                            if (!MinSignal)
                            {
                                Print("Signal movement was not sufficient.");
                                return;
                            }

                            // Check for Minimum Trend Movement
                            bool MinTrend = CheckMovment(TrendBarsBack, MinTrendEMAMovement, MaxTrendEMAMovement, "Trend Movement Result:");

                            if (!MinTrend)
                            {
                                Print("Trned movement was not sufficient.");
                                return;
                            }



                            if (Trend == "UP" & SignalBarDirection == TradeType.Buy)
                            {
                                double EntryPrice      = MarketSeries.High.Last(1) + 2;
                                double InitialStopLoss = GetStopLoss(SignalBarDirection, EntryPrice);

                                TradeResult CurrentOrder = PlaceLimitOrder(SignalBarDirection, Symbol, DefaultContractSize, EntryPrice, "Woo!", InitialStopLoss, InitialStopLoss, EntryExpiration);

                                if (CurrentOrder.IsSuccessful)
                                {
                                    Print("Buy Successful!");
                                }
                                else
                                {
                                    Print("Buy Error: " + CurrentOrder.Error.Value.ToString());
                                }
                            }



                            if (Trend == "DOWN" & SignalBarDirection == TradeType.Sell)
                            {
                                double EntryPrice      = MarketSeries.Low.Last(1) - 2;
                                double InitialStopLoss = GetStopLoss(SignalBarDirection, EntryPrice);

                                TradeResult CurrentOrder = PlaceLimitOrder(SignalBarDirection, Symbol, DefaultContractSize, EntryPrice, "Woo!", InitialStopLoss, InitialStopLoss, EntryExpiration);

                                if (CurrentOrder.IsSuccessful)
                                {
                                    Print("Buy Successful!");
                                }
                                else
                                {
                                    Print("Buy Error: " + CurrentOrder.Error.Value.ToString());
                                }
                            }
                        }

                        else
                        {
                            Print("Signal didnt close within 25% of Close.");
                        }
                    }
                    else
                    {
                        Print("Cannot trade due to Candles dont touch");
                    }
                }
                else
                {
                    Print("Cannot trade due to EMA Gap being too small");
                }
            }
            else
            {
                Print("Cannot trade due to Open Position");
            }
        }
Ejemplo n.º 20
0
        private void manageOpen(TradeType tradeType, long volume, string prefixLabel = botLabel)
        {
            int parties = 10, part1 = 5, part2 = 3;
			long partialVolume = Symbol.NormalizeVolume(volume / parties, RoundingMode.ToNearest);

			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");
        }
Ejemplo n.º 21
0
        public void ToString_ConvertionOfTradeType(TradeType tradeTypeEnum)
        {
            string convertionResult = ConvertionHelper.EnumToString(tradeTypeEnum);

            Assert.AreEqual(tradeTypeEnum.ToString(), convertionResult);
        }
Ejemplo n.º 22
0
 public string GenerateTradeNo(TradeType tradeType)
 {
     return(UniqueNumber.GetUniqueNumber(tradeType.ToString()));
 }
Ejemplo n.º 23
0
        public void TestToString()
        {
            Assert.AreEqual("Trailer (TR)", new TradeType { Code = "TR", Name = "Trailer" }.ToString());
            Assert.AreEqual("Buy (B)", new TradeType { Code = "\r B\n\r", Name = "\t  Buy\t\n\r" }.ToString());
            Assert.AreEqual("Surrender", new TradeType { Name = "Surrender" }.ToString());
            Assert.AreEqual("BUY", new TradeType { Code = "BUY" }.ToString());

            var tradeType = new TradeType { Name = "   " };
            Assert.AreEqual("TradeType (Id: '{0}')".Form(tradeType.Id.ToString()), tradeType.ToString());
        }
Ejemplo n.º 24
0
        private string GetNettingKey(Trade trade)
        {
            TradeType nettedTradeType = trade.Direction == TradeType.Buy ? TradeType.Sell : TradeType.Buy;

            return(nettedTradeType.ToString() + "~" + trade.Underlying.ToLowerInvariant());
        }
Ejemplo n.º 25
0
        public string EditQuery()
        {
            roundParams();
            int iTradeClosed = 0;

            if (TradeClosed == false)
            {
                iTradeClosed = 0;
                ClosingPrice = 0;
                Comission    = 0;
                Taxes        = 0;
                Profit       = 0;
            }
            else
            {
                iTradeClosed = 1;
            }

            int iTradeType      = 0;
            int iInstrumentType = 0;

            switch (InstrumentType.ToString())
            {
            case "Валюта":
                iInstrumentType = 0;
                break;

            case "Акция":
                iInstrumentType = 1;
                break;

            case "Фьючерс":
                iInstrumentType = 2;
                break;
            }
            switch (TradeType.ToString())
            {
            case "Long":
                iTradeType = 0;
                break;

            case "Short":
                iTradeType = 1;
                break;
            }

            //UPDATE `tradesassistant`.`trades` SET `trade_type`='0', `trade_sum`='2120.00' WHERE `id`='6';
            string query = "UPDATE `" + Schema + "`.`" + Table + "` SET " +
                           "`instrument_name`='" + InstrumentName + "', " +
                           "`instrument_class`='" + iInstrumentType.ToString() + "', " +
                           "`instrument_ticker`='" + Ticker + "', " +
                           "`trade_type`='" + iTradeType.ToString() + "', " +
                           "`opening_price`='" + OpeningPrice.ToString().Replace(",", ".") + "', " +
                           "`trade_volume`='" + TradeSize.ToString() + "', " +
                           "`trade_sum`='" + TradeSum.ToString().Replace(",", ".") + "', " +
                           "`trade_closed`='" + iTradeClosed.ToString() + "', " +
                           "`closing_price`='" + ClosingPrice.ToString().Replace(",", ".") + "', " +
                           "`comissions`='" + Comission.ToString().Replace(",", ".") + "', " +
                           "`taxes`='" + Taxes.ToString().Replace(",", ".") + "', " +
                           "`profit`='" + Profit.ToString().Replace(",", ".") + "' " +
                           "WHERE `id`='" + TradeId + "';";

            return(query);
        }
Ejemplo n.º 26
0
        //метод формирования строки удаления записи
        public string AddQuery()
        {
            roundParams();
            int iTradeClosed = 0;

            if (TradeClosed == false)
            {
                iTradeClosed = 0;
            }
            else
            {
                iTradeClosed = 1;
            }

            int iTradeType      = 0;
            int iInstrumentType = 0;

            switch (InstrumentType.ToString())
            {
            case "Валюта":
                iInstrumentType = 0;
                break;

            case "Акция":
                iInstrumentType = 1;
                break;

            case "Фьючерс":
                iInstrumentType = 2;
                break;
            }
            switch (TradeType.ToString())
            {
            case "Long":
                iTradeType = 0;
                break;

            case "Short":
                iTradeType = 1;
                break;
            }

            string query = "INSERT INTO `" + Schema + "`.`" + Table + "` " +
                           "(`instrument_name`, " +
                           "`instrument_class`, " +
                           "`instrument_ticker`, " +
                           "`trade_type`, " +
                           "`opening_price`, " +
                           "`trade_volume`, " +
                           "`trade_sum`, " +
                           "`trade_closed`, " +
                           "`closing_price`, " +
                           "`comissions`, " +
                           "`taxes`, " +
                           "`profit`) " +
                           "VALUES ('" +
                           InstrumentName + "', '"
                           + iInstrumentType.ToString() + "', '"
                           + Ticker + "', '"
                           + iTradeType.ToString() + "', '"
                           + OpeningPrice.ToString().Replace(",", ".") + "', '"
                           + TradeSize.ToString() + "', '"
                           + TradeSum.ToString().Replace(",", ".") + "', '"
                           + iTradeClosed.ToString() + "', '"
                           + ClosingPrice.ToString().Replace(",", ".") + "', '"
                           + Comission.ToString().Replace(",", ".") + "', '"
                           + Taxes.ToString().Replace(",", ".") + "', '"
                           + Profit.ToString().Replace(",", ".") + "');";

            return(query);
        }
Ejemplo n.º 27
0
        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");
        }
 public static void ShowPopup(this INotifications notifications, TimeFrame timeFrame, Symbol symbol, TradeType type, string triggeredBy, double price, string comment, DateTimeOffset time)
 {
     ShowPopup(notifications, timeFrame.ToString(), symbol.Name.ToString(), type.ToString(), triggeredBy, price, comment, DateTimeOffset.Now);
 }
Ejemplo n.º 29
0
        private void manageOpen(TradeType tradeType, long volume, string prefixLabel = botLabel)
        {
            int  parties = 10, part1 = 5, part2 = 3;
            long partialVolume = Symbol.NormalizeVolume(volume / parties, RoundingMode.ToNearest);

            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");
        }
Ejemplo n.º 30
0
        protected bool CreateGridPositions(TradeType direction)
        {
            // Compute take profit for each grid level.
            double[] tpLevels = new double[GridLevelCount];

            for (int i = 0; i < tpLevels.Length; i++)
            {
                if (direction == TradeType.Buy)
                {
                    tpLevels[i] = BB.Main.Last(BBShift + firstIndex) - i * (BB.Main.Last(BBShift + firstIndex) - BB.Bottom.Last(BBShift + firstIndex)) / GridLevelCount;
                }

                else if (direction == TradeType.Sell)
                {
                    tpLevels[i] = BB.Main.Last(BBShift + firstIndex) + i * (BB.Top.Last(BBShift + firstIndex) - BB.Main.Last(BBShift + firstIndex)) / GridLevelCount;
                }
            }

            Position[] gridPositions      = new Position[GridLevelCount];
            bool       errorEnteringTrade = true;

            for (int i = 0; i < GridLevelCount; i++)
            {
                double currentUnitCostPips = (UnitTradingCost + 2 * Symbol.Spread / Symbol.PipSize);
                double TPPips = Math.Round(Math.Abs(Bars.ClosePrices.Last(firstIndex) - tpLevels[i]) / Symbol.PipSize, 1);

                // If the cost of trading level i position is greater than the target return, don't enter this level's or the following level's positions.
                if ((currentUnitCostPips + MinNetInitialTPPips) >= TPPips)
                {
                    if (i > 0)
                    {
                        Print(string.Format("New grid entered with only {0} levels, due to cost/target return inefficiency.", i));
                        break;
                    }

                    else
                    {
                        return(errorEnteringTrade);
                    }
                }

                string positionLabel = string.Format("{0} - Level {1}", RobotId, i + 1);

                TradeResult result = ExecuteMarketOrder(direction, Symbol.Name, ComputeKellyVolume(i), positionLabel, InitialSLPips, TPPips);

                if (result.IsSuccessful)
                {
                    gridPositions[i]   = result.Position;
                    errorEnteringTrade = false;
                }

                else
                {
                    Print(string.Format("Grid level {0} {1} position could not be entered. Error: {2}.", i + 1, direction.ToString(), result.Error));
                }
            }

            string gridId = "";

            foreach (Position pos in gridPositions)
            {
                if (pos != null)
                {
                    gridId += pos.Id + ".";
                }

                else
                {
                    gridId += "-1.";
                }
            }

            gridId = gridId.Substring(0, gridId.Length - 1);

            ActiveGrids.Add(new Grid(gridId, direction, gridPositions));

            return(!errorEnteringTrade);
        }