Ejemplo n.º 1
0
        internal PCSCIso7816Protocol(byte[] atr, PCSCCard card)
        {
            // Reference the reader
            myCard = card;

            // Get the ATR value
            this.Atr = Atr.Parse(atr);

            // Map the PC/SC comms protocol to the appropriate CardFramework protocol
            switch (myCard.CommsProtocol)
            {
            case SCardProtocol.T0:
                CommsProtocol = Iso7816CommsProtocol.T0;
                break;

            case SCardProtocol.T1:
                CommsProtocol = Iso7816CommsProtocol.T1;
                break;

            case SCardProtocol.Raw:
                CommsProtocol = Iso7816CommsProtocol.Raw;
                break;

            default:
                throw PCSCException.ThrowUnsupportedProtocol();
            }
        }
Ejemplo n.º 2
0
        private static SecurityElement AtrToXml(Atr a)
        {
            SecurityElement ret = new SecurityElement("ATR");

            ret.AddAttribute("Value", Convert.ToBase64String(a.GetValue()));
            ret.AddAttribute("Mask", Convert.ToBase64String(a.GetMask()));
            return(ret);
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Adds an ATR to the allowed list.
 /// </summary>
 /// <param name="atr">The ATR to add.</param>
 /// <exception cref="ArgumentNullException"><i>atr</i> is invalid.</exception>
 public void AddAllowedAtr(Atr atr)
 {
     if (atr == null)
     {
         throw new ArgumentNullException("atr", ResourceController.GetString("Error_ParamNull"));
     }
     AddAllowedAtrs(new Atr[] { atr });
 }
Ejemplo n.º 4
0
        public AtrViewerModel(Atr atr)
        {
            this.Atr = atr;
            this.Atr.PropertyChanged += this.AtrChanged;
            this.atrValue             = atr.Bytes.ToHexString(" ");

            this.AddValidationForProperty(() => this.AtrValue)
            .AddValidation(_ => this.Error == null, _ => this.Error);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Internal method that analyzes the ATR Historical Bytes,
        /// it populate the object with info about the ICC
        /// </summary>
        private void DetectCard()
        {
            if (AtrInformation.HistoricalBytes.Length > 1)
            {
                byte categoryIndicator;

                using (DataReader reader = DataReader.FromBuffer(AtrInformation.HistoricalBytes))
                {
                    categoryIndicator = reader.ReadByte();

                    if (categoryIndicator == (byte)CategoryIndicator.StatusInfoPresentInTlv)
                    {
                        while (reader.UnconsumedBufferLength > 0)
                        {
                            const byte appIdPresenceIndTag    = 0x4F;
                            const byte appIdPresenceIndTagLen = 0x0C;

                            var tagValue  = reader.ReadByte();
                            var tagLength = reader.ReadByte();

                            if (tagValue == appIdPresenceIndTag && tagLength == appIdPresenceIndTagLen)
                            {
                                byte[] pcscRid     = { 0xA0, 0x00, 0x00, 0x03, 0x06 };
                                byte[] pcscRidRead = new byte[pcscRid.Length];

                                reader.ReadBytes(pcscRidRead);

                                if (pcscRid.SequenceEqual(pcscRidRead))
                                {
                                    byte   storageStandard = reader.ReadByte();
                                    ushort cardName        = reader.ReadUInt16();

                                    PcscCardName    = (Pcsc.CardName)cardName;
                                    PcscDeviceClass = DeviceClass.StorageClass;
                                }

                                reader.ReadBuffer(4); // RFU bytes
                            }
                            else
                            {
                                reader.ReadBuffer(tagLength);
                            }
                        }
                    }
                }
            }
            else
            {
                // Compare with Mifare DesFire card ATR
                byte[] desfireAtr = { 0x3B, 0x81, 0x80, 0x01, 0x80, 0x80 };

                if (Atr.SequenceEqual(desfireAtr))
                {
                    PcscDeviceClass = DeviceClass.MifareDesfire;
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Gets a list of the allowed ATRs.
        /// </summary>
        /// <returns>An array containing the allowed ATRs.</returns>
        public Atr[] GetAllowedAtrs()
        {
            Atr[] ret = new Atr[m_AllowedAtrs.Count];
            int   i   = 0;

            foreach (Atr a in m_AllowedAtrs)
            {
                ret[i++] = (Atr)a.Clone();
            }
            return(ret);
        }
Ejemplo n.º 7
0
        public void TestAtr()
        {
            var atr = new Atr();

            TestRoundTripEquality(atr);
            atr.CommandLine = "This is a test";
            TestRoundTripEquality(atr);
            atr.ModifiedTime = DateTime.Now.TruncateToSeconds();
            atr.CommandLine  = null;
            TestRoundTripEquality(atr);
            atr.ModifiedTime = null;
            TestRoundTripEquality(atr);
        }
Ejemplo n.º 8
0
        internal TokenizedAtr(Atr owner, byte[] atr)
        {
            this.owner = owner;
            AtrReadStream AtrStream = new AtrReadStream(atr);

            //Read preamble
            this.Preamble = new AtrPreambleToken(this, AtrStream);

            //read interface byte groups
            this.InterfaceByteGroups = new AtrInterfaceByteGroupTokenCollection(this);
            NextInterfaceBytesIndicator NextInterfaceBytesIndicator = this.Preamble.NextInterfaceBytesIndicator;

            while (NextInterfaceBytesIndicator != null)
            {
                AtrInterfaceByteGroupToken InterfaceByteGroup = new AtrInterfaceByteGroupToken(this, AtrStream, NextInterfaceBytesIndicator);
                this.InterfaceByteGroups.AppendGroup(InterfaceByteGroup);

                NextInterfaceBytesIndicator = NextInterfaceBytesIndicator.TdExists
                    ? new NextInterfaceBytesIndicator(AtrStream.GetNextByte(), false)
                    : null;
            }

            //Read and parse historical characters
            if (this.Preamble.NumberOfHistoricalCharacters > 0)
            {
                byte[] HistoricalCharacters = AtrStream.GetNextBytes(this.Preamble.NumberOfHistoricalCharacters);
                this.HistoricalCharacters = new AtrHistoricalCharactersToken(this, HistoricalCharacters);
            }
            else
            {
                this.HistoricalCharacters = new AtrHistoricalCharactersToken(this, new byte[0]);
            }

            //Read checksum if needed
            if (this.ChecksumRequired)
            {
                this.atrChecksum = new AtrChecksumToken(AtrStream);
            }

            //Read additional bytes
            int AdditionalBytes = AtrStream.GetRemainingLength();

            if (AdditionalBytes > 0)
            {
                this.ExtraBytes = new AtrExtraBytesToken(AtrStream, AdditionalBytes);
            }
        }
Ejemplo n.º 9
0
        public event Action <MarketFaze> MarketFazeChangeEvent; // событие изменения фазы рынка

        #endregion

        /// <summary>
        /// Конструктор класса робота
        /// </summary>
        /// <param name="name">имя робота</param>
        /// <param name="startProgram">программа, которая запустила робота</param>
        public OneLegArbitrageMy(string name, StartProgram startProgram) : base(name, startProgram)
        {
            //Запоминаем имя программы, которая запустила бота
            //Это может быть тестер, оптимизатор, терминал
            _startProgram = startProgram;

            //Создаем вкладки бота
            TabCreate(BotTabType.Simple);
            TabCreate(BotTabType.Index);

            _tabSec   = TabsSimple[0];
            _tabIndex = TabsIndex[0];

            // создаем настроечные параметры робота
            LenghtMa           = CreateParameter("Lenght MA", 100, 50, 200, 10);
            LenghtBollinger    = CreateParameter("Lenght Bollinger", 100, 50, 200, 10);
            DeviationBollinger = CreateParameter("Deviation Bollinger", 1, 0.5m, 2.5m, 0.5m);
            LenghtAtr          = CreateParameter("Lenght ATR", 20, 20, 100, 10);
            MultiplyAtr        = CreateParameter("Multiplay ATR", 1, 1, 5, 0.5m);

            // cоздаем индикаторы
            _ma        = new MovingAverage(name + "MA", false);
            _ma        = (MovingAverage)_tabIndex.CreateCandleIndicator(_ma, "Prime");
            _ma.Lenght = LenghtMa.ValueInt;
            _ma.Save();

            _bollinger           = new Bollinger(name + "Bollinger", false);
            _bollinger           = (Bollinger)_tabIndex.CreateCandleIndicator(_bollinger, "Prime");
            _bollinger.Lenght    = LenghtBollinger.ValueInt;
            _bollinger.Deviation = DeviationBollinger.ValueDecimal;
            _bollinger.Save();

            _atr        = new Atr(name + "ATR", false);
            _atr        = (Atr)_tabIndex.CreateCandleIndicator(_atr, "Second");
            _atr.Lenght = LenghtAtr.ValueInt;
            _atr.Save();

            // загружаем настроечные параметры робота
            Load();

            // подписываемся на события
            _tabIndex.SpreadChangeEvent += TabIndex_SpreadChangeEvent;
            _tabSec.CandleFinishedEvent += TabSec_CandleFinishedEvent;
            ParametrsChangeByUser       += OneLegArbitrage_ParametrsChangeByUser;
            DeleteEvent += OneLegArbitrage_DeleteEvent;
            //todo доработать OneLegArbitrage_DeleteEvent, чтобы удалялись все файлы робота
        }
Ejemplo n.º 10
0
        public FractialMA_work(string name, StartProgram startProgram)
            : base(name, startProgram)
        {
            TabCreate(BotTabType.Simple);
            _tab = TabsSimple[0];

            _pc = new PriceChannel(name + "PriceChannel", false)
            {
                LenghtUpLine = 3, LenghtDownLine = 3, ColorUp = Color.DodgerBlue, ColorDown = Color.DarkRed
            };
            _atr = new Atr(name + "ATR", false)
            {
                Lenght = 14, ColorBase = Color.DodgerBlue,
            };

            _pc.Save();
            _atr.Save();

            _tab.CandleFinishedEvent        += Strateg_CandleFinishedEvent;
            _tab.PositionOpeningSuccesEvent += Strateg_PositionOpen;
            _tab.PositionOpeningFailEvent   += Strateg_PositionOpeningFailEvent;
            _tab.PositionClosingSuccesEvent += Strateg_PositionClosingSuccesEvent;
            Regime = CreateParameter("Regime", "Off", new[] { "Off", "On", "OnlyClosePosition", "OnlyShort", "OnlyLong" });

            Slipage    = CreateParameter("Slipage", 0m, 0m, 20, 0.1m);
            VolumeFix1 = CreateParameter("VolumeFix1", 0m, 0.01m, 20, 0.01m);
            VolumeFix2 = CreateParameter("VolumeFix2", 0m, 0.01m, 20, 0.01m);

            LengthAtr  = CreateParameter("LengthAtr", 14, 0, 200, 1);
            LengthUp   = CreateParameter("LengthUp", 3, 0, 200, 1);
            LengthDown = CreateParameter("LengthDown", 3, 0, 200, 1);
            //Slipage = 10;
            //VolumeFix1 = 1;
            //VolumeFix2 = 1;
            //LengthAtr = 14;
            KofAtr = 0.5m;
            //LengthUp = 3;
            //LengthDown = 3;

            DeleteEvent += Strategy_DeleteEvent;

            Thread closerThread = new Thread(CloseFailPosition);

            closerThread.IsBackground = true;
            closerThread.Start();
        }
Ejemplo n.º 11
0
        private static void GetInfoFromType()
        {
            Type t = typeof(double);

            Console.WriteLine("Namespace : {0}", t.Namespace);
            Console.WriteLine("Fullname : {0}", t.FullName);
            Console.WriteLine("Is ValueType : {0}", t.IsValueType);
            Console.WriteLine("Is Sealed : {0}", t.IsSealed);
            Console.WriteLine("Is Serializable : {0}", t.IsSerializable);
            Console.WriteLine("Is Public : {0}", t.IsPublic);
            Console.WriteLine("Is Primitive : {0}", t.IsPrimitive);
            Console.WriteLine("Is Class : {0}", t.IsClass);

            foreach (Attribute Atr in t.GetCustomAttributes(false))
            {
                Console.WriteLine(" {0}", Atr.GetType().Name);
            }
            Console.WriteLine();
        }
Ejemplo n.º 12
0
 public void NotifyGetAttrib(object sender, AfterGetAttribEventArgs eventArgs)
 {
     if (eventArgs.ReturnValue == ErrorCode.Success)
     {
         WriteInfo(sender, String.Format(">> Error: {0}", eventArgs.ReturnValue));
         WriteInfo(sender, String.Format(">> byte[]: [{0}]", eventArgs.Buffer.ToHexa()));
         if (eventArgs.Attrib == Attrib.AtrString)
         {
             var atr = new Atr(eventArgs.Buffer);
             WriteInfo(sender, String.Format(">> ATR: [{0}]", atr));
         }
         else if (eventArgs.Attrib != Attrib.AtrString)
         {
             WriteInfo(sender, String.Format(">> string: \"{0}\"", eventArgs.Buffer.ToAsciiString()));
         }
     }
     else
     {
         WriteWarning(sender, String.Format(">> Error: {0}", eventArgs.ReturnValue));
     }
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Gets the value.
        /// </summary>
        /// <returns></returns>
        public override IEnumerable <double> Update(Period period, bool normalize = true)
        {
            var adx     = 0.0;
            var plusDI  = 0.0;
            var minusDI = 0.0;

            if (PreviousPeriod != null)
            {
                var upMove   = period.High - PreviousPeriod.High;
                var downMove = period.Low - PreviousPeriod.Low;

                var plusDM  = upMove > downMove && upMove > 0.0 ? upMove : 0.0;
                var minusDM = downMove > upMove && downMove > 0.0 ? downMove : 0.0;

                var atr            = Atr.Update(period).First();
                var plusDMOverATR  = atr != 0.0 ? plusDM / atr : 0.0;
                var minusDMOverATR = atr != 0.0 ? minusDM / atr : 0.0;

                PreviousEMAPlusDI  = IndicatorUtils.EMA(plusDMOverATR, PreviousEMAPlusDI, Multiplier);
                PreviousEMAMinusDI = IndicatorUtils.EMA(minusDMOverATR, PreviousEMAMinusDI, Multiplier);

                plusDI  = 100 * PreviousEMAPlusDI;
                minusDI = 100 * PreviousEMAMinusDI;

                var val = (plusDI + minusDI) != 0.0 ? Math.Abs((plusDI - minusDI) / (plusDI + minusDI)) : 0.0;
                PreviousEmaADX = IndicatorUtils.EMA(val, PreviousEmaADX, Multiplier);

                adx = 100 * PreviousEmaADX;
            }

            PreviousPeriod = period;

            Value = new double[3] {
                adx, plusDI, minusDI
            };

            return(normalize ? Value.Select(v => Normalizers.DMI.Normalize(v)) : Value);
        }
Ejemplo n.º 14
0
        /// <summary>
        ///     Internal method that analyzes the ATR Historical Bytes,
        ///     it populate the object with info about the ICC
        /// </summary>
        private void DetectCard()
        {
            if (AtrInformation.HistoricalBytes.Length > 1)
            {
                using (var reader = new BinaryReader(new MemoryStream(AtrInformation.HistoricalBytes)))
                {
                    var categoryIndicator = reader.ReadByte();

                    if (categoryIndicator == (byte)CategoryIndicator.StatusInfoPresentInTlv)
                    {
                        var bytesRemaining = reader.BaseStream.Length - 1; // already read a byte
                        while (bytesRemaining > 0)
                        {
                            const byte appIdPresenceIndTag    = 0x4F;
                            const byte appIdPresenceIndTagLen = 0x0C;

                            var tagValue = reader.ReadByte();
                            bytesRemaining--;
                            var tagLength = reader.ReadByte();
                            bytesRemaining--;

                            if (tagValue == appIdPresenceIndTag && tagLength == appIdPresenceIndTagLen)
                            {
                                byte[] pcscRid     = { 0xA0, 0x00, 0x00, 0x03, 0x06 };
                                var    pcscRidRead = new byte[pcscRid.Length];

                                reader.Read(pcscRidRead, 0, pcscRidRead.Length);
                                bytesRemaining -= pcscRidRead.Length;

                                if (pcscRid.SequenceEqual(pcscRidRead))
                                {
                                    var storageStandard = reader.ReadByte();
                                    bytesRemaining--;

                                    // This is a big-endian value, so swap the bytes
                                    var cnb = new byte[2];
                                    cnb[1] = reader.ReadByte();
                                    cnb[0] = reader.ReadByte();
                                    var cardName = BitConverter.ToUInt16(cnb, 0);
                                    bytesRemaining -= 2;

                                    PcscCardName    = (CardName)cardName;
                                    PcscDeviceClass = DeviceClass.StorageClass;
                                }

                                reader.ReadBytes(4); // RFU bytes
                                bytesRemaining -= 4;
                            }
                            else
                            {
                                reader.ReadBytes(tagLength);
                                bytesRemaining -= tagLength;
                            }
                        }
                    }
                }
            }
            else
            {
                // Compare with Mifare DesFire card ATR
                byte[] desfireAtr = { 0x3B, 0x81, 0x80, 0x01, 0x80, 0x80 };

                if (Atr.SequenceEqual(desfireAtr))
                {
                    PcscDeviceClass = DeviceClass.MifareDesfire;
                }
            }
        }
Ejemplo n.º 15
0
 public override string ToString()
 {
     return(@"ISO 7816 over ISO 14443-4 Protocol (ATR: " + Atr.ToString() + ")");
 }
Ejemplo n.º 16
0
        // сервис
        public StrategyBearish(string name, StartProgram startProgram) : base(name, startProgram)
        {
            TabCreate(BotTabType.Simple);
            _tab = TabsSimple[0];

            _atr = new Atr(name + "Atr", false)
            {
                Lenght    = 14,
                ColorBase = Color.DodgerBlue,
                PaintOn   = true,
            };

            _atr = _tab.CreateCandleIndicator(_atr, "atrArea");
            _atr.Save();

            _chandelier = new Line(name + "chandelier", false)
            {
                ColorBase = Color.DodgerBlue,
                PaintOn   = true,
            };

            _chandelier = _tab.CreateCandleIndicator(_chandelier, "Prime");
            _chandelier.Save();

            _alert      = new AlertToPrice(NameStrategyUniq);
            _alert.IsOn = false;
            _tab.DeleteAllAlerts();
            _tab.SetNewAlert(_alert);

            _tab.CandleFinishedEvent += StrategyAdxVolatility_CandleFinishedEvent;

            IsOn                = false;
            Volume              = 1;
            SlipageOpenSecond   = 0;
            SlipageCloseSecond  = 0;
            TimeFrom            = 10;
            TimeTo              = 22;
            AlertIsOn           = false;
            SlipageToAlert      = 10;
            LagTimeToOpenClose  = new TimeSpan(0, 0, 0, 15);
            LagPunctToOpenClose = 20;
            EmulatorIsOn        = false;

            Multiple       = 1.5m;
            WhiteJohnson   = 1;
            ChandelierMult = 4m;

            Load();

            Thread worker = new Thread(TimeWatcherArea);

            worker.IsBackground = true;
            worker.Start();

            Thread worker2 = new Thread(WatcherOpenPosition);

            worker2.IsBackground = true;
            worker2.Start();

            Thread worker3 = new Thread(AreaCloserPositionThread);

            worker3.IsBackground = true;
            worker3.Start();

            _tab.OrderUpdateEvent         += _tab_OrderUpdateEvent;
            _tab.NewTickEvent             += _tab_NewTickEvent;
            _tab.PositionClosingFailEvent += _tab_PositionClosingFailEvent;
            _tab.PositionOpeningFailEvent += _tab_PositionOpeningFailEvent;
        }
Ejemplo n.º 17
0
        public PriceChanel_work(string name, StartProgram startProgram)
            : base(name, startProgram)
        {
            TabCreate(BotTabType.Simple);
            _tab = TabsSimple[0];

            _pc = new PriceChannel(name + "PriceChannel", false)
            {
                LenghtUpLine = 3, LenghtDownLine = 3, ColorUp = Color.DodgerBlue, ColorDown = Color.DarkRed
            };
            _atr = new Atr(name + "ATR", false)
            {
                Lenght = 14, ColorBase = Color.DodgerBlue,
            };

            _pc.Save();
            _atr.Save();

            _tab.CandleFinishedEvent        += Strateg_CandleFinishedEvent;
            _tab.PositionOpeningSuccesEvent += Strateg_PositionOpen;
            _tab.PositionOpeningFailEvent   += Strateg_PositionOpeningFailEvent;
            _tab.PositionClosingSuccesEvent += Strateg_PositionClosingSuccesEvent;
            this.ParametrsChangeByUser      += PriceChanel_work_ParametrsChangeByUser;
            _tab.BestBidAskChangeEvent      += _tab_BestBidAskChangeEvent;

            Regime        = CreateParameter("Regime", "Off", new[] { "Off", "On", "OnlyClosePosition", "OnlyShort", "OnlyLong" });
            leverage      = CreateParameter("Маржинальное плечо", 1m, 1m, 10, 0.1m);
            DepoCurrency  = CreateParameter("DepoCurrency", "Currency2", new[] { "Currency1", "Currency2" });
            isContract    = CreateParameter("Торгуем контрактами", false);
            MaxStop       = CreateParameter("MaxStop", 1, 1, 10, 0.1m);
            Fractaillenth = CreateParameter("Длина фрактала", 51, 5, 200, 1);

            Slipage = CreateParameter("Slipage", 0m, 0m, 20, 0.1m);

            LengthAtr  = CreateParameter("LengthAtr", 14, 14, 200, 1);
            LengthUp   = CreateParameter("LengthUp", 14, 14, 200, 1);
            LengthDown = CreateParameter("LengthDown", 14, 14, 200, 1);

            LengthPC = CreateParameter("Длина скользящей для PriceChannel", 14, 14, 200, 1);

            LengthAtr.ValueInt  = LengthPC.ValueInt;
            LengthUp.ValueInt   = LengthPC.ValueInt;
            LengthDown.ValueInt = LengthPC.ValueInt;

            //Slipage = 10;
            //VolumeFix1 = 1;
            //VolumeFix2 = 1;
            //LengthAtr = 14;
            KofAtr = 0.5m;
            //LengthUp = 3;
            //LengthDown = 3;

            DeleteEvent += Strategy_DeleteEvent;

            FastMA = new MovingAverage(name + "FastMA", false)
            {
                ColorBase = System.Drawing.Color.Yellow, Lenght = 15, TypePointsToSearch = PriceTypePoints.Close, TypeCalculationAverage = MovingAverageTypeCalculation.Simple
            };
            FastMA        = (MovingAverage)_tab.CreateCandleIndicator(FastMA, "Prime");
            FastMA.Lenght = 15;
            FastMA.Save();

            SlowMA = new MovingAverage(name + "SlowMA", false)
            {
                ColorBase = System.Drawing.Color.Blue, Lenght = 30, TypePointsToSearch = PriceTypePoints.Close, TypeCalculationAverage = MovingAverageTypeCalculation.Simple
            };
            SlowMA        = (MovingAverage)_tab.CreateCandleIndicator(SlowMA, "Prime");
            SlowMA.Lenght = 30;
            SlowMA.Save();

            Fractail = IndicatorsFactory.CreateIndicatorByName("Fractail_lenth", name + "Fractail", false);
            Fractail = (Aindicator)_tab.CreateCandleIndicator(Fractail, "Prime");
            Fractail.ParametersDigit[0].Value = Fractaillenth.ValueInt;
            Fractail.Save();

            Thread closerThread = new Thread(CloseFailPosition);

            closerThread.IsBackground = true;
            closerThread.Start();
        }
Ejemplo n.º 18
0
        public EnvelopTrendBitmex(string name, StartProgram startProgram) : base(name, startProgram)
        {
            TabCreate(BotTabType.Simple);
            _tab = TabsSimple[0];

            _tab.CandleFinishedEvent        += _tab_CandleFinishedEvent;
            _tab.PositionOpeningSuccesEvent += _tab_PositionOpeningSuccesEvent;
            _tab.PositionClosingSuccesEvent += _tab_PositionClosingSuccesEvent;
            _envelop = new Envelops(name + "Envelop", false);
            _envelop = (Envelops)_tab.CreateCandleIndicator(_envelop, "Prime");
            _envelop.Save();

            _atr = new Atr(name + "ATR", false)
            {
                Lenght = 14, ColorBase = Color.DodgerBlue,
            };
            _atr.Save();

            this.ParametrsChangeByUser += EnvelopTrendBitmex_ParametrsChangeByUser;
            this.DeleteEvent           += Strategy_DeleteEvent;

            Regime   = CreateParameter("Regime", "Off", new[] { "Off", "On", "OnlyClosePosition", "OnlyShort", "OnlyLong" });
            RegimeML = CreateParameter("RegimeML", "Off", new[] { "Off", "Parser", "Client" });

            Slippage            = CreateParameter("Slippage", 0, 0, 20, 1);
            EnvelopDeviation    = CreateParameter("Envelop Deviation", 0.3m, 0.3m, 4, 0.1m);
            EnvelopMovingLength = CreateParameter("Envelop Moving Length", 10, 10, 200, 5);
            TrailStop           = CreateParameter("Trail Stop", 0.1m, 0m, 5, 0.1m);
            MinProfitTraling    = CreateParameter("Минимальный профит для трэйлинга", 0.2m, 0.2m, 2, 0.1m);
            leverage            = CreateParameter("Маржинальное плечо", 0.1m, 0.1m, 10, 0.1m);
            MaxStop             = CreateParameter("MaxStop", 1, 1, 10, 0.1m);
            isContract          = CreateParameter("Торгуем контрактами", false);
            DepoCurrency        = CreateParameter("DepoCurrency", "Currency2", new[] { "Currency1", "Currency2" });
            VolumeDecimals      = CreateParameter("Volume Decimals", 0, 0, 20, 1);

            FastMA = new MovingAverage(name + "FastMA", false)
            {
                ColorBase = System.Drawing.Color.Yellow, Lenght = 15, TypePointsToSearch = PriceTypePoints.Close, TypeCalculationAverage = MovingAverageTypeCalculation.Simple
            };
            FastMA        = (MovingAverage)_tab.CreateCandleIndicator(FastMA, "Prime");
            FastMA.Lenght = 15;
            FastMA.Save();

            SlowMA = new MovingAverage(name + "SlowMA", false)
            {
                ColorBase = System.Drawing.Color.Blue, Lenght = 30, TypePointsToSearch = PriceTypePoints.Close, TypeCalculationAverage = MovingAverageTypeCalculation.Simple
            };
            SlowMA        = (MovingAverage)_tab.CreateCandleIndicator(SlowMA, "Prime");
            SlowMA.Lenght = 30;
            SlowMA.Save();

            _envelop.Deviation            = EnvelopDeviation.ValueDecimal;
            _envelop.MovingAverage.Lenght = EnvelopMovingLength.ValueInt;
            _name = name;

            #region ML Region
            //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            Load();
            if (RegimeML.ValueString != "Off") // создаем файл(ы) если несуществуют и очищаем если существуют
            {
                initML();
            }
            //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            #endregion
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Internal method that analyzes the ATR Historical Bytes,
        /// it populate the object with info about the ICC
        /// </summary>
        private void DetectCard()
        {
            if (AtrInformation.HistoricalBytes.Length > 1)
            {
                byte categoryIndicator;

                using (MemoryStream mem = new MemoryStream(AtrInformation.HistoricalBytes))
                    using (BinaryReader reader = new BinaryReader(mem))
                    {
                        categoryIndicator = reader.ReadByte();

                        if (categoryIndicator == (byte)CategoryIndicator.StatusInfoPresentInTlv)
                        {
                            while (reader.BaseStream.Position < reader.BaseStream.Length)
                            {
                                const byte appIdPresenceIndTag    = 0x4F;
                                const byte appIdPresenceIndTagLen = 0x0C;

                                var tagValue  = reader.ReadByte();
                                var tagLength = reader.ReadByte();

                                if (tagValue == appIdPresenceIndTag && tagLength == appIdPresenceIndTagLen)
                                {
                                    byte[] pcscRid     = { 0xA0, 0x00, 0x00, 0x03, 0x06 };
                                    byte[] pcscRidRead = reader.ReadBytes(pcscRid.Length);

                                    if (pcscRid.SequenceEqual(pcscRidRead))
                                    {
                                        byte storageStandard = reader.ReadByte();

                                        byte[] cardNameData = reader.ReadBytes(2);
                                        if (BitConverter.IsLittleEndian)
                                        {
                                            Array.Reverse(cardNameData);
                                        }

                                        PcscCardName    = (PcscSdk.CardName)BitConverter.ToUInt16(cardNameData, 0);
                                        PcscDeviceClass = DeviceClass.StorageClass;
                                    }

                                    reader.ReadBytes(4); // RFU bytes
                                }
                                else
                                {
                                    reader.ReadBytes(tagLength);
                                }
                            }
                        }
                    }
            }
            else
            {
                // Compare with Mifare DesFire card ATR
                byte[] desfireAtr = { 0x3B, 0x81, 0x80, 0x01, 0x80, 0x80 };

                if (Atr.SequenceEqual(desfireAtr))
                {
                    PcscDeviceClass = DeviceClass.MifareDesfire;
                }
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Returns what type of orders are allowed for this bar based on the
        /// higher time frame momentum analysis.
        /// </summary>
        /// <param name="ticker">Ticker data</param>
        /// <param name="lastState">Last state of the higher timeframe</param>
        /// <returns>Order type allowed for the last bar of the ticker data</returns>
        private double GetHigherTimerframeExtras(TickerData ticker, double lastState)
        {
            // Get all the bars for the higher timeframe.
            TickerData higherTickerData = GetHigherTimeframeBars(ticker);

            Sma sma = new Sma(higherTickerData)
            {
                Period = 35
            };

            sma.Initialize();
            sma.RunToBar(higherTickerData.NumBars - 1);
            sma.Shutdown();
            ticker.HigherTimeframeValues["Sma"].Add(sma.Avg.Last());

            Atr atrInd = new Atr(higherTickerData)
            {
                Period = 14
            };

            atrInd.Initialize();
            atrInd.RunToBar(higherTickerData.NumBars - 1);
            atrInd.Shutdown();
            ticker.HigherTimeframeValues["Atr"].Add(atrInd.Value.Last());

            KeltnerChannel keltner = new KeltnerChannel(higherTickerData);

            keltner.Initialize();
            keltner.RunToBar(higherTickerData.NumBars - 1);
            keltner.Shutdown();
            ticker.HigherTimeframeValues["KeltnerUpper"].Add(keltner.Upper.Last());
            ticker.HigherTimeframeValues["KeltnerMidline"].Add(keltner.Midline.Last());
            ticker.HigherTimeframeValues["KeltnerLower"].Add(keltner.Lower.Last());

            DtOscillator dtosc = new DtOscillator(higherTickerData);

            dtosc.Initialize();
            dtosc.RunToBar(higherTickerData.NumBars - 1);
            dtosc.Shutdown();
            ticker.HigherTimeframeValues["DtoscSK"].Add(dtosc.SK.Last());
            ticker.HigherTimeframeValues["DtoscSD"].Add(dtosc.SK.Last());

            ticker.HigherTimeframeValues["Close"].Add(higherTickerData.Close.Last());

            // Return what kind orders are allowed.
            double state = GetHigherTimeframeStateFromIndicator(dtosc, dtosc.Data.NumBars - 1, lastState);

            ////////////////// START HIGHER TIME FRAME DEBUGGING ////////////////////
            if (Simulator.Config.OutputHigherTimeframeData)
            {
                DateTime      outputDate = higherTickerData.Dates[higherTickerData.Dates.Count - 1];
                List <double> states     = new List <double>(ticker.HigherTimeframeTrend);
                states.Add(state);
                Simulator.DataOutput.OutputHigherTimeframeData(
                    outputDate,
                    new List <Indicator>()
                {
                    dtosc, atrInd, keltner, sma
                },
                    higherTickerData,
                    ticker,
                    states);
            }
            //////////////////  END  HIGHER TIME FRAME DEBUGGING ////////////////////

            return(state);
        }
Ejemplo n.º 21
0
 public AtrInvalidHistoricalCharacters(Atr owner)
     : base(owner)
 {
     this.IsApplicable = true;
 }
Ejemplo n.º 22
0
        private void UpdateTimer_Tick(object sender, System.EventArgs e)
        {
            // check for updates
            if (NativeMethods.SCardGetStatusChange(m_Context, 0, m_States, m_States.Length) != NativeMethods.SCARD_S_SUCCESS)
            {
                return;
            }
            // update info
            bool update;
            bool ok = false;

            for (int i = 0; i < m_Readers.Length; i++)
            {
                update = (CardReaderList.FocusedItem == m_Readers[i].item);
                if ((m_States[i].dwEventState & NativeMethods.SCARD_STATE_PRESENT) != 0)
                {
                    Atr  insertedAtr = new Atr(m_States[i].rgbAtr, m_States[i].cbAtr);
                    bool isValid     = false;
                    if (m_Atrs == null)
                    {
                        isValid = true;
                    }
                    else
                    {
                        for (int j = 0; j < m_Atrs.Length; j++)
                        {
                            if (m_Atrs[j].Match(insertedAtr))
                            {
                                isValid = true;
                                break;
                            }
                        }
                    }

                    if (isValid)
                    {
                        m_Readers[i].item.ImageIndex = 2;
                        if (update)
                        {
                            CardTypeText.Text   = ResourceController.GetString("SelectReaderForm_ValidCard");
                            CardStatusText.Text = ResourceController.GetString("SelectReaderForm_ValidCardDesc");
                            ok = true;
                        }
                    }
                    else
                    {
                        m_Readers[i].item.ImageIndex = 1;
                        if (update)
                        {
                            CardTypeText.Text   = ResourceController.GetString("SelectReaderForm_UnknownCard");
                            CardStatusText.Text = ResourceController.GetString("SelectReaderForm_UnknownCardDesc");
                        }
                    }
                }
                else if ((m_States[i].dwEventState & NativeMethods.SCARD_STATE_EMPTY) != 0)
                {
                    m_Readers[i].item.ImageIndex = 0;
                    if (update)
                    {
                        CardTypeText.Text   = ResourceController.GetString("SelectReaderForm_NoCard");
                        CardStatusText.Text = ResourceController.GetString("SelectReaderForm_NoCardDesc");
                    }
                }
                else
                {
                    m_Readers[i].item.ImageIndex = 3;
                    if (update)
                    {
                        CardTypeText.Text   = ResourceController.GetString("SelectReaderForm_UnknownStatus");
                        CardStatusText.Text = ResourceController.GetString("SelectReaderForm_UnknownStatusDesc");
                    }
                }
            }
            if (OkButton.Enabled != ok)
            {
                OkButton.Enabled = ok;
            }
        }
 public AtrDirDataReferenceHistoricalCharacters(Atr owner)
     : base(owner)
 {
 }
Ejemplo n.º 24
0
 public InterpretedAtrAdapter(Atr atr)
 {
     this.atr = atr;
     this.indicateProtocolCommand = new DelegateCommand <EnumerationAdapter <ProtocolType> >(this.IndicateProtocol);
 }
Ejemplo n.º 25
0
 void OnEnable()
 {
     //获取当前自定义的Inspector对象
     atr = (Atr)target;
 }
 public AtrNoHistoricalCharacters(Atr owner) : base(owner)
 {
 }
        internal static TradeIdeasGeneratorArgument Create(List <Signal> signals, HistoricalData historicalData)
        {
            TradeIdeasGeneratorArgument result = new TradeIdeasGeneratorArgument();

            SmaVol smaVol20 = new SmaVol(20);
            Sma    sma50    = new Sma(50);
            Rsi    stRsi5   = new Rsi(5);
            Rsi    rsi14    = new Rsi(14);
            Rsi    ltrsi50  = new Rsi(50);
            Cci    stCci5   = new Cci(5);
            Cci    cci14    = new Cci(14);
            Cci    ltCci50  = new Cci(50);
            Stoch  stoch14  = new Stoch(14, 14, 3);
            WillR  willr14  = new WillR(14);
            Mfi    mfi14    = new Mfi(14);
            Adx    adx20    = new Adx(20);
            Atr    atr20    = new Atr(20);

            //Assuming that signals are sorted by dates descending and all signals are present. otherwize an exception will be thrown during fetching signals (First())

            #region Indicators

            result.Rsi14           = GetValue(signals.LatestForIndicator(rsi14));
            result.YesterdayRsi14  = GetValue(signals.PreviousForIndicator(rsi14, 1));
            result.StRsi5          = GetValue(signals.LatestForIndicator(stRsi5));
            result.YesterdayStRsi5 = GetValue(signals.PreviousForIndicator(stRsi5, 1));
            result.LtRsi50         = GetValue(signals.LatestForIndicator(ltrsi50));

            result.Cci14           = GetValue(signals.LatestForIndicator(cci14));
            result.YesterdayCci14  = GetValue(signals.PreviousForIndicator(cci14, 1));
            result.StCci5          = GetValue(signals.LatestForIndicator(stCci5));
            result.YesterdayStCci5 = GetValue(signals.PreviousForIndicator(stCci5, 1));
            result.LtCci50         = GetValue(signals.LatestForIndicator(ltCci50));

            result.Stoch14          = GetValue(signals.LatestForIndicator(stoch14));
            result.YesterdayStoch14 = GetValue(signals.PreviousForIndicator(stoch14, 1));

            result.WillR14          = GetValue(signals.LatestForIndicator(willr14));
            result.YesterdayWillR14 = GetValue(signals.PreviousForIndicator(willr14, 1));

            result.Mfi14          = GetValue(signals.LatestForIndicator(mfi14));
            result.YesterdayMfi14 = GetValue(signals.PreviousForIndicator(mfi14, 1));

            result.SmaVol20 = GetValue(signals.LatestForIndicator(smaVol20));
            result.Sma50    = GetValue(signals.LatestForIndicator(sma50));

            result.Adx20 = GetValue(signals.LatestForIndicator(adx20));

            result.Atr20 = GetValue(signals.LatestForIndicator(atr20));

            //Long Term Sentiment(6 months)
            Signal syrahSentiment = signals.LatestForIndicator(LongTermSentimentForDependencies);
            int?   sentimentValue = syrahSentiment == null
                ? null
                : (int?)syrahSentiment.Value;
            result.LongTermSentiment = SyrahSentiment.MakeInterpretationInTermsOfSentiment(sentimentValue);

            //Short Term Sentiment(1 month)
            syrahSentiment = signals.LatestForIndicator(ShortTermSentimentForDependencies);
            sentimentValue = syrahSentiment == null
                ? null
                : (int?)syrahSentiment.Value;
            result.ShortTermSentiment = SyrahSentiment.MakeInterpretationInTermsOfSentiment(sentimentValue);

            #endregion

            //if (expandedQuote == null)
            //{
            //    result.LastPrice = historicalData.Close[historicalData.Count - 1];
            //}
            //else
            //{
            //    result.LastPrice = expandedQuote.Last;
            //    result.HasOption = expandedQuote.HasOption;
            //}

            result.RangeStdDev = historicalData.GetPriceRangeStdDevFor6Months();

            //result.NearestSupport = supportAndResistance.GetClosestSupport(expandedQuote.Last);
            //result.NearestResistance = supportAndResistance.GetClosestResistance(expandedQuote.Last);

            //TODO: check
            int yesterdayIndex = historicalData.High.Length - 2;
            result.YesterdayHigh = historicalData.High[yesterdayIndex];
            result.YesterdayLow  = historicalData.Low[yesterdayIndex];

            return(result);
        }