Package com.collective2.signalEntry.adapter.dynamicSimulator

Examples of com.collective2.signalEntry.adapter.dynamicSimulator.SystemManager


    public void tick(DataProvider dataProvider, C2EntryService entryService) {

        //ensure existing requests are submitted.
        entryService.awaitPending();

        SystemManager system = systems.get(entryService.systemId());

        //can not tick and transmit at same moment in order to keep simulator repeatable
        synchronized(lock) {
               //look at ordered list of signals for each system and do all those older than time now.
            this.time = dataProvider.endingTime();
            system.tick(time, dataProvider);
            lastTickDataProvider = dataProvider;
        }

        for(GainListenerManager manager:gainListeners) {
            manager.send(gainExecutor, dataProvider, system);
View Full Code Here


    private XMLEventReader simpleTransmit(Request request) {

        logger.trace("transmit "+request.toString());

        synchronized(lock) {
            SystemManager system = null;
            if (request.containsKey(Parameter.SystemId)) {
                system = lookupSystem(request);
                if (system==null) {
                    return new SimulatedResponseError(ERROR,"no system","");
                }
            }

            XMLEventReader xmlEventReader;
            Command command = request.command();
            switch (command) {
                case Signal:

                     long timeToExecute       = extractTimeToExecute(request);
                     int[] signalIdArray      = system.scheduleSignal(timeToExecute,request);
                     int signalId             = signalIdArray[0];
                     int stopLossSignalId     = signalIdArray[1];
                     int profitTargetSignalId = signalIdArray[2];
                     return new SimulatedResponseSignal(signalId,
                                                        stopLossSignalId==SystemManager.NO_ID?null:stopLossSignalId,
                                                        profitTargetSignalId==SystemManager.NO_ID?null:profitTargetSignalId,
                                                        OK);

                case GetBuyPower:
                   //  long lastTickTime = lastTickDataProvider.endingTime();
                     BigDecimal buyPower = system.portfolio().cash().add(system.totalMargin());
                     return new SimulatedResponseGetBuyPower(OK,time,buyPower);

                case Cancel:

                    Integer id = (Integer)request.get(Parameter.SignalId);
                    assert(id>=0) : "DynamicSimulator only uses positive signalIds";

                    system.cancelSignal(id,time);
                    return new SimulatedResponseCancel(OK);

                case CancelAllPending:

                    system.cancelAllPending(time);
                    return new SimulatedResponseCancelAllPending(OK);

                case CloseAllPositions:

                    system.portfolio().closeAllPositions();
                    return new SimulatedResponseCloseAllPositions(OK);

                case FlushPendingSignals:

                    system.flushPendingSignals(lastTickDataProvider);
                    return new SimulatedResponseFlushPendingSignals(OK);

                case AllSignals:
                    //not filled, cancelled or expired!
                    //only for this subscriber
                    String subscriberEmail = (String)request.get(Parameter.EMail);
                    Map<Integer,List<Integer>> allPendingSignals = new HashMap<Integer,List<Integer>>();
                    for(SystemManager sys:systems) {
                        if (sys.isSubscribed(subscriberEmail)) {
                            Integer sysId = sys.id();
                            allPendingSignals.put(sysId,sys.allPendingSignals());
                        }
                    }
                    return new SimulatedResponseGetAllSignals(OK, allPendingSignals);

                case GetSystemEquity:

                    long lastTickTime = lastTickDataProvider.endingTime();
                    Number equity = system.portfolio().equity(lastTickDataProvider);
                    return new SimulatedResponseGetSystemEquity(OK,lastTickTime,equity);

                case GetSystemHypothetical:

                    List<Map<C2Element, Object>> data = new ArrayList<Map<C2Element, Object>>();

                    for(SystemManager sys:systems) {
                        Map<C2Element, Object> map = new HashMap<C2Element, Object>();
                        //populate this map for this system.
                        map.put(C2Element.ElementSystemId, sys.id());
                        map.put(C2Element.ElementSystemName, sys.name());

                        //NOTE: very basic margin calculations where negative cash is margin, should improve some day.
                        BigDecimal sysCash = sys.portfolio().cash();
                        BigDecimal sysEquity = sys.portfolio().equity(lastTickDataProvider);
                        BigDecimal totalEquityAvail = sysCash.add(sysEquity);
                        BigDecimal marginUsed = (sysCash.compareTo(BigDecimal.ZERO)<0 ? sysCash.negate() : BigDecimal.ZERO);

                        map.put(C2Element.ElementTotalEquityAvail, totalEquityAvail);
                        map.put(C2Element.ElementCash, sysCash);
                        map.put(C2Element.ElementEquity, sysEquity);
                        map.put(C2Element.ElementMarginUsed, marginUsed);

                        data.add(map);
                    }

                    return new SimulatedResponseGetSystemHypothetical(data);

                case PositionStatus:

                    String symbol = (String)request.get(Parameter.Symbol);
                    Integer position = system.portfolio().position(symbol).quantity();
                    return new SimulatedResponsePositionStatus(OK,time,symbol,position);

                case RequestOCAId:

                    Integer ocaid = system.generateNewOCAId();
                    return new SimulatedResponseRequestOCAId(ocaid,OK);

                case Reverse:
                    //the same as a signal but its done now and can not be parked
                    Integer reverseId = system.scheduleSignal(time, request)[0];
                    return new SimulatedResponseReverse(OK);

                case SendSubscriberBroadcast:

                    String email = (String)request.get(Parameter.EMail);
                    String message = (String)request.get(Parameter.Message);
                    system.sendSubscriberBroadcast(email,message);
                    return new SimulatedResponseSendSubscriberBroadcast(OK);

                case SetMinBuyPower:

                    Number minBuyPower = (Number)request.get(Parameter.BuyPower);
                    system.minBuyPower(minBuyPower);
                    return new SimulatedResponseSetMinBuyPower(OK);

                case NewComment:

                    Integer signalIdForComment = (Integer)request.get(Parameter.SignalId);
                    String comment   = (String)request.get(Parameter.Commentary);
                    String previousComment = system.newComment(signalIdForComment,comment);
                    return new SimulatedResponseNewComment(OK,signalIdForComment,previousComment);

                case AllSystems:     //lookup the systems here
                    throw new UnsupportedOperationException("Not implemented at this time");

                case AddToOCAGroup:   //lookup existing signalid and add it to this existing oca group
                    throw new UnsupportedOperationException("Not implemented at this time");

                case SignalStatus:

                    Integer signalIdInput = (Integer)request.get(Parameter.SignalId);
                    Integer systemId = SystemManager.extractSystemId(signalIdInput);

                    SystemManager systemForSignal = systems.get(systemId);


                    String signalSubscriberEmail = (String)request.get(Parameter.EMail);
                    boolean isSubscribed = systemForSignal.isSubscribed(signalSubscriberEmail);
                    if (!isSubscribed) {
                        return new SimulatedResponseError(ERROR,"email not subscribed",signalSubscriberEmail);
                    }

                    String subscriberPassword = (String)request.get(Parameter.Password);
                    boolean isSystemPassword = systemForSignal.isPassword(signalSubscriberEmail,subscriberPassword);
                    if (!isSystemPassword) {
                        return new SimulatedResponseError(ERROR,"not system password",signalSubscriberEmail);
                    }

                    Order order = systemForSignal.lookupOrder(signalIdInput);

                    String systemName = systemForSignal.name();
                    String postedwhen = order.postedWhen();
                    String emailedWhen = order.eMailedWhen();
                    String killedWhen = order.killedWhen();
                    String tradedWhen = order.tradedWhen();
                    BigDecimal tradePrice = order.tradePrice();
View Full Code Here

        String password = (String)request.get(Parameter.Password);
        Integer systemId = (Integer)request.get(Parameter.SystemId);
        if (systemId>systems.size()) {
            return null;
        }
        SystemManager system = systems.get(systemId);
        if (system.isPassword(password)) {
            return system;
        } else {
            return null;
        }
View Full Code Here

    public synchronized Integer createSystem(String name, String password, Portfolio portfolio, BigDecimal commission) {

        Integer systemId = systems.size();

        SystemManager system = new SystemManager(portfolio, systemId, name, password, commission, marginAccount);

        systems.add(system);

        return systemId;
    }
View Full Code Here

        return systemId;
    }

    public void subscribe(String eMail, Integer systemId, String userPassword) {
        SystemManager system = systems.get(systemId);
        system.subscribe(eMail, userPassword);
    }
View Full Code Here


    @Test
    public void  marketBTOTest() {

        Portfolio portfolio = new SimplePortfolioFactory().createPortfolio(new BigDecimal("1000.00"));

        int id = 42;
        long time = stop;
        Instrument instrument = Instrument.Forex;
        String symbol = "GG";
        SignalAction action = SignalAction.BTO;
        Integer quantity = 10;
        QuantityComputable quantityComputable = new QuantityComputableFixed(quantity);
        long cancelAtMs = Long.MAX_VALUE;
        Duration timeInForce = Duration.GoodTilCancel;
        OrderProcessorMarket processor = new OrderProcessorMarket(time, symbol);
        Order order = new Order(null, id,instrument,symbol,action,quantityComputable,cancelAtMs,timeInForce,processor, null);

        //test only the processor and do it outside the order
        boolean processed = processor.process(dataProvider, portfolio, commission, order, action, quantityComputable, null);

        assertTrue(processed);
        assertEquals(new BigDecimal("961.00"),portfolio.cash());
        assertEquals(quantity,portfolio.position("GG").quantity());
        assertEquals(new BigDecimal("60"),portfolio.equity(dataProvider));

        //sell to close this open position.

        action = SignalAction.STC;
        order = new Order(null, id,instrument,symbol,action,quantityComputable,cancelAtMs,timeInForce,processor, null);

        //test only the processor and do it outside the order
        processed = processor.process(dataProvider, portfolio, commission, order, action, quantityComputable, null);

        assertTrue(processed);
        assertEquals(new BigDecimal("982.00"),portfolio.cash());
        assertEquals(Integer.valueOf(0),portfolio.position("GG").quantity());
        assertEquals(new BigDecimal("0"),portfolio.equity(dataProvider));

    }
View Full Code Here

    }


    private void  marketShortTest(SignalAction sellAction) {

        Portfolio portfolio = new SimplePortfolioFactory().createPortfolio(new BigDecimal("1000.00"));

        int id = 42;
        long time = stop;
        Instrument instrument = Instrument.Forex;
        String symbol = "GG";
        Integer quantity = 10;
        QuantityComputable quantityComputable = new QuantityComputableFixed(quantity);
        long cancelAtMs = Long.MAX_VALUE;
        Duration timeInForce = Duration.GoodTilCancel;
        OrderProcessorMarket processor = new OrderProcessorMarket(time, symbol);
        Order order = new Order(null, id,instrument,symbol,sellAction,quantityComputable,cancelAtMs,timeInForce,processor, null);

        //test only the processor and do it outside the order
        boolean processed = processor.process(dataProvider, portfolio, commission, order, sellAction, quantityComputable, null);

        assertTrue(processed);
        assertEquals(new BigDecimal("1021.00"),portfolio.cash());
        assertEquals(Integer.valueOf(-quantity),portfolio.position("GG").quantity());
        assertEquals(new BigDecimal("-60"),portfolio.equity(dataProvider));

        //Buy to cover this short position

        SignalAction action = SignalAction.BTC;
        order = new Order(null, id,instrument,symbol,action,quantityComputable,cancelAtMs,timeInForce,processor, null);

        processed = processor.process(dataProvider, portfolio, commission, order, action, quantityComputable, null);

        assertTrue(processed);
        assertEquals(new BigDecimal("982.00"),portfolio.cash());
        assertEquals(Integer.valueOf(0),portfolio.position("GG").quantity());
        assertEquals(new BigDecimal("0"),portfolio.equity(dataProvider));

    }
View Full Code Here


    @Test
    public void  conditionalOrderTest() {

        Portfolio portfolio = new SimplePortfolioFactory().createPortfolio(new BigDecimal("1000.00"));

        int id = 42;
        long time = stop;
        Instrument instrument = Instrument.Forex;
        String symbol = "GG";
        SignalAction action = SignalAction.BTO;
        Integer quantity = 10;
        QuantityComputable quantityComputable = new QuantityComputableFixed(quantity);
        long cancelAtMs = Long.MAX_VALUE;
        Duration timeInForce = Duration.GoodTilCancel;
        OrderProcessorMarket processor = new OrderProcessorMarket(time, symbol);
        Order buyOrder = new Order(null, id,instrument,symbol,action,quantityComputable,cancelAtMs,timeInForce,processor, null);

        //final quantity is not known until this order is processed
        //this however has the quantity because QuantityComputableFixed is used above
        assertEquals(Integer.valueOf(10), Integer.valueOf(buyOrder.quantity()));

        action = SignalAction.STC;
        quantityComputable = new QuantityComputableEntry(buyOrder);
        Order sellOrder = new Order(null, id,instrument,symbol,action,quantityComputable,cancelAtMs,timeInForce,processor, buyOrder);

        //final quantity is not known until this order is processed
        //this however has the quantity because QuantityComputableFixed is used above
        assertEquals(Integer.valueOf(10), Integer.valueOf(sellOrder.quantity()));

        assertTrue(buyOrder.process(dataProvider,portfolio,commission,null));

        assertEquals(quantity, Integer.valueOf(buyOrder.quantity()));
        assertEquals(quantity, Integer.valueOf(sellOrder.quantity()));

        assertTrue(sellOrder.process(dataProvider, portfolio, commission,null));

        assertEquals(new BigDecimal("982.00"),portfolio.cash());
        assertEquals(Integer.valueOf(0),portfolio.position("GG").quantity());
        assertEquals(new BigDecimal("0"),portfolio.equity(dataProvider));

    }
View Full Code Here

    }

    private void limitBTOTest(RelativeNumber buyBelow, RelativeNumber sellAbove, BigDecimal expectedBuy, BigDecimal expectedSell) {

        BigDecimal startingCash = new BigDecimal("1000.00");
        Portfolio portfolio = new SimplePortfolioFactory().createPortfolio(startingCash);

        int id = 42;
        long time = stop;
        Instrument instrument = Instrument.Forex;
        String symbol = "GG";
        SignalAction action = SignalAction.BTO;
        Integer quantity = 10;
        QuantityComputable quantityComputable = new QuantityComputableFixed(quantity);
        long cancelAtMs = Long.MAX_VALUE;
        Duration timeInForce = Duration.GoodTilCancel;


        OrderProcessorLimit processor = new OrderProcessorLimit(time, symbol, buyBelow);
        Order order = new Order(null,id,instrument,symbol,action,quantityComputable,cancelAtMs,timeInForce,processor,null);

        //test only the processor and do it outside the order
        boolean processed = processor.process(dataProvider, portfolio, commission, order, action, quantityComputable,null);

        assertTrue(processed);
        BigDecimal expectedCash = startingCash.subtract(expectedBuy.multiply(new BigDecimal(quantity)).add(commission));

        assertEquals(expectedBuy, processor.transactionPrice());
        assertEquals(expectedCash, portfolio.cash());
        assertEquals(quantity,portfolio.position("GG").quantity());
        assertEquals(new BigDecimal("60"),portfolio.equity(dataProvider));

        //sell to close this open position.

        action = SignalAction.STC;

        OrderProcessorLimit sellProcessor = new OrderProcessorLimit(time, symbol, sellAbove);
        order = new Order(null, id,instrument,symbol,action,quantityComputable,cancelAtMs,timeInForce,sellProcessor,null);

        //test only the processor and do it outside the order
        processed = sellProcessor.process(dataProvider, portfolio, commission, order, action, quantityComputable,null);

        assertTrue(processed);
        expectedCash = expectedCash.add(expectedSell.multiply(new BigDecimal(quantity))).subtract(commission);

        assertEquals(expectedSell, sellProcessor.transactionPrice());
        assertEquals(expectedCash,portfolio.cash());
        assertEquals(Integer.valueOf(0),portfolio.position("GG").quantity());
        assertEquals(new BigDecimal("0"),portfolio.equity(dataProvider));

    }
View Full Code Here


    private void  limitShortTest(SignalAction sellAction, RelativeNumber sellAbove, RelativeNumber buyBelow, BigDecimal expectedSell, BigDecimal expectedBuy) {

        BigDecimal startingCash = new BigDecimal("1000.00");
        Portfolio portfolio = new SimplePortfolioFactory().createPortfolio(startingCash);

        int id = 42;
        long time = stop;
        Instrument instrument = Instrument.Forex;
        String symbol = "GG";
        Integer quantity = 10;
        QuantityComputable quantityComputable = new QuantityComputableFixed(quantity);
        long cancelAtMs = Long.MAX_VALUE;
        Duration timeInForce = Duration.GoodTilCancel;

        OrderProcessorLimit processor = new OrderProcessorLimit(time,symbol,sellAbove);
        Order order = new Order(null, id,instrument,symbol,sellAction,quantityComputable,cancelAtMs,timeInForce,processor,null);

        //test only the processor and do it outside the order
        boolean processed = processor.process(dataProvider, portfolio, commission, order, sellAction, quantityComputable,null);

        BigDecimal expectedCash = startingCash.add(expectedSell.multiply(new BigDecimal(quantity)).subtract(commission));

        assertTrue(processed);
        assertEquals("sell ", expectedSell, processor.transactionPrice());
        assertEquals(expectedCash,portfolio.cash());
        assertEquals(Integer.valueOf(-quantity),portfolio.position("GG").quantity());
        assertEquals(new BigDecimal("-60"),portfolio.equity(dataProvider));

        //Buy to cover this short position

        SignalAction action = SignalAction.BTC;
        OrderProcessorLimit buyProcessor = new OrderProcessorLimit(time,symbol,buyBelow);
        order = new Order(null, id,instrument,symbol,action,quantityComputable,cancelAtMs,timeInForce,buyProcessor,null);

        processed = buyProcessor.process(dataProvider, portfolio, commission, order, action, quantityComputable,null);
        expectedCash = expectedCash.subtract(expectedBuy.multiply(new BigDecimal(quantity))).subtract(commission);

        assertTrue(processed);
        assertEquals("buy ",expectedBuy, buyProcessor.transactionPrice());
        assertEquals(expectedCash,portfolio.cash());
        assertEquals(Integer.valueOf(0),portfolio.position("GG").quantity());
        assertEquals(new BigDecimal("0"),portfolio.equity(dataProvider));

    }
View Full Code Here

TOP

Related Classes of com.collective2.signalEntry.adapter.dynamicSimulator.SystemManager

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.