Пример #1
0
        public void MOCs()
        {
            SimBroker broker = new SimBroker();

            broker.BrokerModel = _trans;
            ForexSecurity tsec = new ForexSecurity(S);

            tsec.LotSize       = 1;
            tsec.OrderStepSize = 1;

            OrderImpl moc = new OrderImpl(tsec, Direction.Long, 200);

            moc.ValidInstruct = OrderInstructionType.MOC;
            PendingOrderImpl pmoc = new PendingOrderImpl(moc);

            Assert.True(moc.ValidInstruct == OrderInstructionType.MOC, "unexpected order instruction: " + moc.ValidInstruct);
            Assert.Equal(0, broker.SendOrderStatus(pmoc));

            TickImpl openingTick  = TickImpl.NewTrade(S, Util.ToQLDate(DateTime.Now), Util.QL2FT(9, 30, 00, 000), 9, 10000, "NYS");
            TickImpl endMornTick  = TickImpl.NewTrade(S, Util.ToQLDate(DateTime.Now), Util.QL2FT(12, 00, 00, 000), 9, 10000, "NYS");
            TickImpl endLunchTick = TickImpl.NewTrade(S, Util.ToQLDate(DateTime.Now), Util.QL2FT(14, 15, 00, 000), 9, 10000, "NYS");
            TickImpl closingTick  = TickImpl.NewTrade(S, Util.ToQLDate(DateTime.Now), Util.QL2FT(16, 00, 00, 000), 9, 10000, "NYS");

            int c = 0;

            c = broker.Execute(openingTick); Assert.Equal(0, c);
            c = broker.Execute(endMornTick); Assert.Equal(0, c);
            c = broker.Execute(endLunchTick); Assert.Equal(0, c);
            c = broker.Execute(closingTick); Assert.Equal(1, c); // should execute on the first tick at/after 16:00:00
        }
Пример #2
0
        public void DayFill()
        {
            SimBroker broker = new SimBroker();

            broker.BrokerModel = _trans;
            ForexSecurity tsec = new ForexSecurity(S);

            tsec.LotSize       = 1;
            tsec.OrderStepSize = 1;

            OrderImpl        day  = new OrderImpl(tsec, Direction.Long, 200);
            PendingOrderImpl pday = new PendingOrderImpl(day);

            broker.SendOrderStatus(pday);

            TickImpl openingTick  = TickImpl.NewTrade(S, Util.ToQLDate(DateTime.Now), Util.QL2FT(9, 30, 00, 000), 9, 10000, "NYS");
            TickImpl endMornTick  = TickImpl.NewTrade(S, Util.ToQLDate(DateTime.Now), Util.QL2FT(12, 00, 00, 000), 9, 10000, "NYS");
            TickImpl endLunchTick = TickImpl.NewTrade(S, Util.ToQLDate(DateTime.Now), Util.QL2FT(14, 15, 00, 000), 9, 10000, "NYS");
            TickImpl closingTick  = TickImpl.NewTrade(S, Util.ToQLDate(DateTime.Now), Util.QL2FT(16, 00, 00, 000), 9, 10000, "NYS");

            int c;

            c = broker.Execute(openingTick); Assert.Equal(1, c); // should execute on first received tick
            c = broker.Execute(endMornTick); Assert.Equal(0, c);
            c = broker.Execute(endLunchTick); Assert.Equal(0, c);
            c = broker.Execute(closingTick); Assert.Equal(0, c);
        }
Пример #3
0
        public void Fill_RegularLiquidity()
        {
            SimBroker broker = new SimBroker();

            broker.BrokerModel = _trans;
            ForexSecurity tsec = new ForexSecurity(S);

            tsec.LotSize       = 1;
            tsec.OrderStepSize = 1;

            OrderImpl limitBuy  = new OrderImpl(tsec, Direction.Long, 1, 133m);
            OrderImpl limitSell = new OrderImpl(tsec, Direction.Short, 1, 133.5m);
            OrderImpl stopBuy   = new OrderImpl(tsec, Direction.Long, 3, 0, 135.70m);
            OrderImpl stopSell  = new OrderImpl(tsec, Direction.Short, 4, 0, 135.75m);

            PendingOrderImpl plimitBuy  = new PendingOrderImpl(limitBuy);
            PendingOrderImpl plimitSell = new PendingOrderImpl(limitSell);
            PendingOrderImpl pstopBuy   = new PendingOrderImpl(stopBuy);
            PendingOrderImpl pstopSell  = new PendingOrderImpl(stopSell);

            broker.SendOrderStatus(plimitBuy);
            broker.SendOrderStatus(plimitSell);
            broker.SendOrderStatus(pstopBuy);
            broker.SendOrderStatus(pstopSell);

            // OHLC for 6/21/2012 on SPY
            TickImpl openingTick  = TickImpl.NewTrade(S, Util.ToQLDate(DateTime.Now), Util.QL2FT(9, 30, 00, 000), 135.67m, 10670270, "NYS");
            TickImpl endMornTick  = TickImpl.NewTrade(S, Util.ToQLDate(DateTime.Now), Util.QL2FT(12, 00, 00, 000), 135.78m, 10670270, "NYS");
            TickImpl endLunchTick = TickImpl.NewTrade(S, Util.ToQLDate(DateTime.Now), Util.QL2FT(14, 15, 00, 000), 132.33m, 10670270, "NYS");
            TickImpl closingTick  = TickImpl.NewTrade(S, Util.ToQLDate(DateTime.Now), Util.QL2FT(16, 00, 00, 000), 132.44m, 10670270, "NYS");

            broker.Execute(openingTick);
            broker.Execute(endMornTick);
            broker.Execute(endLunchTick);
            broker.Execute(closingTick);

            List <Trade> trades = broker.GetTradeList();

            Assert.True(trades.Count == 4);

            foreach (Trade trade in trades)
            {
                if (trade.Xsize == 1)
                {
                    Assert.Equal(132.33m, trade.Xprice);
                }
                else if (trade.Xsize == 2)
                {
                    Assert.Equal(132.33m, trade.Xprice);
                }
                else if (trade.Xsize == 3)
                {
                    Assert.Equal(135.78m, trade.Xprice);
                }
                else if (trade.Xsize == 4)
                {
                    Assert.Equal(135.78m, trade.Xprice);
                }
            }
        }
Пример #4
0
 void HistSource_gotTick(Tick t)
 {
     // process next tick if present
     if (hasnext)
     {
         // execute any pending orders
         SimBroker.Execute(next);
         // send existing tick
         if (hasevent)
         {
             GotTick(next);
         }
         // update last time
         lasttime = next.datetime;
         orderok &= lasttick || (t.datetime >= next.datetime) || (cidx != next.symidx);
     }
     if (lasttick)
     {
         hasnext = false;
         return;
     }
     // update next tick
     next          = t;
     next.symidx   = cidx;
     hasnext       = true;
     _nextticktime = t.datetime;
     _tickcount++;
 }
Пример #5
0
        void FlushCache(long endsim)
        {
            bool simrunning = true;

            while (simrunning)
            {
                // get next times of ticks in cache
                long[] times = nexttimes();
                // copy our master index list into a temporary for sorting
                Buffer.BlockCopy(idx, 0, cidx, 0, idx.Length * 4);
                // sort loaded instruments by time
                Array.Sort(times, cidx);
                int nextidx = 0;
                // get next time from all instruments we have loaded
                while ((nextidx < times.Length) && (times[nextidx] == -1))
                {
                    nextidx++;
                }
                // test to see if ticks left in simulation
                simrunning = (nextidx < times.Length) && (times[nextidx] <= endsim);
                // if no ticks left or we exceeded simulation time, quit
                if (!simrunning)
                {
                    break;
                }
                // get next tick
                Tick k = Workers[cidx[nextidx]].NextTick();
                // process pending orders
                _executions += SimBroker.Execute(k);
                // notify tick
                GotTick(k);
                // count tick
                _tickcount++;
            }
        }
Пример #6
0
        public void OpGs()
        {
            SimBroker broker = new SimBroker();

            broker.BrokerModel = _trans;
            const string  s    = "NYS";
            ForexSecurity tsec = new ForexSecurity(s);

            tsec.LotSize       = 1;
            tsec.OrderStepSize = 1;

            // build and send an OPG order
            OrderImpl        opg  = new OrderImpl(tsec, Direction.Long, 200, 10);
            PendingOrderImpl popg = new PendingOrderImpl(opg);

            Assert.Equal(0, broker.SendOrderStatus(popg));

            // build a tick on another exchange
            TickImpl it = TickImpl.NewTrade(s, 9, 100);

            it.Exchange = "ISLD";

            // fill order (should fail)
            int c = broker.Execute(it);

            Assert.Equal(0, c);

            // build opening price for desired exchange
            TickImpl nt = TickImpl.NewTrade(s, 9, 10000);

            nt.Exchange = "NYS";
            // fill order (should work)

            c = broker.Execute(nt);

            Assert.Equal(1, c);

            // add another OPG, make sure it's not filled with another tick

            TickImpl next = TickImpl.NewTrade(s, 9, 2000);

            next.Exchange = "NYS";

            OrderImpl        late  = new OrderImpl(tsec, Direction.Long, 200, 10);
            PendingOrderImpl plate = new PendingOrderImpl(late);

            broker.SendOrderStatus(plate);
            c = broker.Execute(next);
            Assert.Equal(0, c);
        }
Пример #7
0
        public void Basics()
        {
            ForexSecurity tsec = new ForexSecurity(S);

            tsec.LotSize       = 1;
            tsec.PipValue      = 1;
            tsec.PipSize       = 1;
            tsec.OrderStepSize = 1;

            SimAccount account = new SimAccount("TEST", "testing", 1000M, 100);

            account.Securities.AddSecurity(tsec);

            SimBroker broker = new SimBroker(account, _trans);

            broker.BrokerModel = _trans;
            broker.GotFill    += broker_GotFill;
            broker.GotOrder   += broker_GotOrder;
            OrderImpl        o  = new OrderImpl();
            PendingOrderImpl po = new PendingOrderImpl(o);
            int error           = broker.SendOrderStatus(po);

            Assert.NotEqual((int)StatusType.OK, error);
            Assert.True(_orders == 0);
            Assert.True(_fills == 0);

            o  = new OrderImpl(tsec, Direction.Long, 100);
            po = new PendingOrderImpl(o);

            broker.SendOrderStatus(po);
            Assert.True(_orders == 1);
            Assert.True(_fills == 0);
            Assert.True(broker.Execute(TickImpl.NewTrade(S, 10, 200)) == 1);
            Assert.True(_fills == 1);

            // test that a limit order is not filled outside the market
            o  = new OrderImpl(tsec, Direction.Long, 100, 9);
            po = new PendingOrderImpl(o);

            broker.SendOrderStatus(po);
            Assert.Equal(0, broker.Execute(TickImpl.NewTrade(S, 10, 100)));
            Assert.True(_fills == 1); // redundant but for counting

            // test that limit order is filled inside the market
            Assert.Equal(1, broker.Execute(TickImpl.NewTrade(S, 8, 100)));
            Assert.True(_fills == 2);
        }
Пример #8
0
        void runopt()
        {
            isRunning = true;
            while (isNextAvail)
            {
                gauntletArgs ga = new gauntletArgs(DLL, RNAME, SIM);
                ga.value = NextParam;
                ga.id    = id;
                Response r = ResponseLoader.FromDLL(ga.response, ga.dll);
                if (changeVars(ref r, ga.value))
                {
                    //GauntletEngine ge = new GauntletEngine(r, ga.hsim);
                    //Thread.SpinWait(1000);
                    //debugControl1.GotDebug("Starting a Gauntlet instance");
                    debug("Started Gauntlet Engine: " + ga.id);
                    Go();

                    List <Trade> trades  = SimBroker.GetTradeList();
                    Results      results = Results.ResultsFromTradeList(trades, 0, .01m, new DebugDelegate(debug));

                    GauntletOptimizationResults gor = new GauntletOptimizationResults();
                    gor.parameter         = ga.value;
                    gor.results           = results;
                    gor.resultsCalculated = true;
                    allResults.Add(gor);
                    decimal rv = 0;
                    getresult(results, out rv);
                    debug("optimize " + ga.id + " finished.  Used: " + gor.parameter + " -> " + OptimizeDecisionsName + ": " + rv + " trades: " + gor.results.Trades + " SimsRemaining: " + OptimizeRemain);
                    progress(id, OptimizeCount);
                }
                else
                {
                    debug("Unable to start gauntlet engine: " + ga.id + " with: " + ga.value);
                }
            }
            debug("All optimization runs complete, computing optimum...");
            var sorted = calculateBest(allResults);

            // unbind
            UnbindEvents();
            if (SendOptimizationCompleteEvent != null)
            {
                SendOptimizationCompleteEvent(sorted);
            }
            isRunning = false;
        }
Пример #9
0
        public void BBO()
        {
            SimBroker broker = new SimBroker();

            broker.BrokerModel = _trans;
            ForexSecurity tsec = new ForexSecurity(S);

            tsec.LotSize       = 1;
            tsec.OrderStepSize = 1;
            const decimal p1 = 10m;
            const decimal p2 = 11m;
            const int     x = 100;
            Order         bid, offer;

            // send bid, make sure it's BBO (since it's only order on any book)
            broker.SendOrderStatus(new PendingOrderImpl(new OrderImpl(tsec, Direction.Long, x, p1)));
            bid   = broker.BestBid(S);
            offer = broker.BestOffer(S);
            Assert.True(bid.IsValid && (bid.LimitPrice == p1) && (bid.Quantity == x), bid.ToString());
            Assert.True(!offer.IsValid, offer.ToString());

            // add better bid, make sure it's BBO
            OrderImpl o;

            // Order#1... 100 shares buy at $11
            o = new OrderImpl(tsec, Direction.Long, x, p2);
            PendingOrderImpl po = new PendingOrderImpl(o);

            broker.SendOrderStatus(po);
            bid   = broker.BestBid(S);
            offer = broker.BestOffer(S);
            Assert.True(bid.IsValid);
            Assert.Equal(p2, bid.LimitPrice);
            Assert.Equal(x, bid.Size);
            Assert.True(!offer.IsValid, offer.ToString());

            // add another bid at same price on another account, make sure it's additive
            //order #2... 100 shares buy at $11
            o             = new OrderImpl(tsec, Direction.Long, x, p2);
            po            = new PendingOrderImpl(o, new SimAccount("ANOTHER_ACCOUNT"));
            o.AccountName = "ANOTHER_ACCOUNT";
            broker.SendOrderStatus(po);
            bid   = broker.BestBid(S);
            offer = broker.BestOffer(S);
            Assert.True(bid.IsValid);
            Assert.Equal(p2, bid.LimitPrice);
            Assert.Equal(x * 2, bid.Size);
            Assert.True(!offer.IsValid, offer.ToString());

            // cancel order and make sure bbo returns
            po.Cancel();
            bid   = broker.BestBid(S);
            offer = broker.BestOffer(S);
            Assert.True(bid.IsValid);
            Assert.Equal(p2, bid.LimitPrice);
            Assert.Equal(x, bid.Size);
            Assert.True(!offer.IsValid, offer.ToString());

            // other test ideas
            // replicate above tests for sell-side
        }
Пример #10
0
        public SimpleBacktester(PortfolioManager nsystem, string folder, int cpunr, string[] filter = null)
        {
            try
            {
                //Set start time
                Started = DateTime.Now;
                var transactioncosts = new GenericBrokerModel()
                {
                    CommPerLot = 0M, SlippageInPips = 0M, LatencyInMS = 0, SpreadInPips = 0M
                };
                SimBroker = new SimBroker((SimAccount)nsystem.Account, transactioncosts);

                //Initialize
                nsystem.Initialize();
                foreach (var stream in nsystem.Streams)
                {
                    ((OHLCBarStream)stream.Value).Initialize();
                }

                //set response
                portfolio = nsystem;

                //Set progress
                if (OnProgress != null)
                {
                    OnProgress(this, "Starting...", cpunr);
                }

                //Set simulator
                if (filter == null || nsystem.Streams.Count == 1)
                {
                    histsim = new SingleSimImpl(filter);
                }
                else
                {
                    histsim = new MultiSimImpl(filter);
                }

                //Set events
                histsim.GotTick          += histsim_GotTick;
                SimBroker.GotFill        += SimBroker_GotFill;
                SimBroker.GotOrder       += SimBroker_GotOrder;
                SimBroker.GotOrderCancel += SimBroker_GotOrderCancel;
                SimBroker.GotOrderUpdate += SimBroker_GotOrderChanged;
                BindPortfolioEvents();

                //Start simulation
                histsim.PlayTo(SingleSimImpl.Endsim);

                //Notify Complete
                if (OnProgress != null)
                {
                    OnProgress(this, "Finished!", cpunr);
                }
                Stopped = DateTime.Now;

                if (OnMessage != null)
                {
                    OnMessage(this, string.Format("SystemID: {0} - CPU: {1} - Finished in: {2} seconds - Tick p/s: {3} - Trades - {4}",
                                                  0,
                                                  cpunr,
                                                  Math.Round((Stopped - Started).TotalSeconds, 2),
                                                  Math.Round(TicksSecond),
                                                  SimBroker.GetTradeList().Count
                                                  ));
                }

                Thread.Sleep(1000);
                WriteResults();
            }
            catch (Exception exc)
            {
                if (OnProgress != null)
                {
                    OnProgress(this, "FAILED: Exception!", cpunr);
                }
                if (OnMessage != null)
                {
                    OnMessage(this, string.Format("Error (cpu {0}) Message: {1} Stacktrace: {2}", cpunr, exc.Message, exc.StackTrace));
                }
            }
        }