Package com.collective2.signalEntry.adapter.dynamicSimulator.portfolio

Examples of com.collective2.signalEntry.adapter.dynamicSimulator.portfolio.Portfolio



    @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

        // validates commands and returns hard coded (canned) responses
        DynamicSimulationAdapter simulationAdapter = new DynamicSimulationAdapter(false);

        String password = "P455w0rd";
        String eMail = "someone@somewhere.com";
        Portfolio portfolio = new SimplePortfolioFactory().createPortfolio(new BigDecimal("10000"));
        BigDecimal commission = new BigDecimal("10.00");
        Integer systemId = simulationAdapter.createSystem("first system",password,portfolio,commission);
        simulationAdapter.subscribe(eMail,systemId,password);
        C2ServiceFactory factory = new C2ServiceFactory(simulationAdapter);
        C2EntryService sentryService = factory.signalEntryService(password, systemId, eMail);

        validateStartingBalances(systemId, sentryService);

        assertEquals(0, portfolio.position("msft").quantity().intValue());
        Response openResponse = sentryService.stockSignal(ActionForStock.BuyToOpen)
                                        .marketOrder().quantity(10).symbol("msft")
                                        .duration(Duration.GoodTilCancel).send();

        Integer signalId = openResponse.getInteger(C2Element.ElementSignalId);

        assertEquals(0,signalId.intValue());

        long timeStep = 60000l*60l*24l;
        long time = 100000l;
        BigDecimal fixedPrice = new BigDecimal("80.43");

        DynamicSimulationMockDataProvider dataProvider = new DynamicSimulationMockDataProvider(time,fixedPrice,fixedPrice,fixedPrice,fixedPrice,time+timeStep);

        simulationAdapter.tick(dataProvider,sentryService);

        Number buyPower = sentryService.buyPower(); // 10000 - ((10 * 80.43)+10) = 10000-814.30
        assertEquals(9185.7d,buyPower.doubleValue(),DELTA);

        Number systemEquity = sentryService.systemEquity(); //10 * 80.43 = 804.30
        assertEquals(804.30d,systemEquity.doubleValue(),DELTA);

        final Set<C2Element> checkedElements = new HashSet<C2Element>();
        sentryService.sendSystemHypotheticalRequest(systemId).visitC2Elements(new C2ElementVisitor() {
            @Override
            public void visit(C2Element element, String data) {

                switch (element) {
                    case ElementTotalEquityAvail:
                        checkedElements.add(element);
                        assertEquals(9990d, Double.parseDouble(data), DELTA);
                        break;
                    case ElementCash:
                        checkedElements.add(element);
                        assertEquals(9185.70d, Double.parseDouble(data), DELTA);
                        break;
                    case ElementEquity:
                        checkedElements.add(element);
                        assertEquals(804.30d, Double.parseDouble(data), DELTA);
                        break;
                    case ElementMarginUsed:
                        checkedElements.add(element);
                        assertEquals(0d, Double.parseDouble(data), DELTA);
                        break;
                    default:
                        //nothing
                }
            }
        },C2Element.ElementTotalEquityAvail,
                C2Element.ElementCash,
                C2Element.ElementEquity,
                C2Element.ElementMarginUsed);
        assertEquals("expected to check 4 elements",4,checkedElements.size());
        assertEquals(10, portfolio.position("msft").quantity().intValue());

        ///////////////////
        //market order sell test
        ///////////////////
        Response marketOrderResponse = sentryService.stockSignal(ActionForStock.SellToClose)
                .marketOrder().quantity(10).symbol("msft")
                .duration(Duration.GoodTilCancel).send();

        //force request response now
        marketOrderResponse.getXML();

        ///////////////////////
        //tick for market buy
        /////////////////////
        long startTime = time+timeStep;
        long closeTime = startTime+timeStep;
        BigDecimal closePrice = new BigDecimal("160.86");
        dataProvider = new DynamicSimulationMockDataProvider(startTime,fixedPrice,closePrice,fixedPrice,closePrice,closeTime);
        simulationAdapter.tick(dataProvider,sentryService);

        ////////////////////
        //confirm values
        ///////////////////
        assertEquals(0, portfolio.position("msft").quantity().intValue());
        buyPower = sentryService.buyPower();
        assertEquals(9980d,buyPower.doubleValue(),DELTA);

        systemEquity = sentryService.systemEquity(); //10 * 80.43 = 804.30
        assertEquals(0d,systemEquity.doubleValue(),DELTA);

        ///////////////////
        //limit order test
        //////////////////
        BigDecimal failLimit = new BigDecimal("65.10");
        Response limitOrderResponse = sentryService.stockSignal(ActionForStock.BuyToOpen)
                .limitOrder(failLimit).quantity(10).symbol("msft")
                .duration(Duration.DayOrder).send();


        ///////////////////////////
        //tick for limit order fail
        ////////////////////////////
        dataProvider = dataProvider.incTime(timeStep);
        simulationAdapter.tick(dataProvider,sentryService);

        ////////////////////
        //confirm unchanged values
        ///////////////////
        assertEquals(0, portfolio.position("msft").quantity().intValue());
        buyPower = sentryService.buyPower();
        assertEquals(9980d,buyPower.doubleValue(),DELTA);

        systemEquity = sentryService.systemEquity(); //10 * 80.43 = 804.30
        assertEquals(0d,systemEquity.doubleValue(),DELTA);

        ///////////////////
        //limit order test
        //////////////////
        BigDecimal successLimit = new BigDecimal("170.10");
        limitOrderResponse = sentryService.stockSignal(ActionForStock.BuyToOpen)
                .limitOrder(successLimit).quantity(10).symbol("msft")
                .duration(Duration.DayOrder).send();

        //force request response now
        Integer openSignalId = limitOrderResponse.getInteger(C2Element.ElementSignalId);

        ///////////////////////////
        //tick for limit order success
        ////////////////////////////
        dataProvider = dataProvider.incTime(timeStep);
        simulationAdapter.tick(dataProvider,sentryService);

        ////////////////////
        //confirm changed
        ///////////////////
        BigDecimal entryPrice = portfolio.position("msft").openPrice();
        assertTrue(null == entryPrice || entryPrice.compareTo(successLimit)<=0);

        BigDecimal shares = new BigDecimal("10");
        assertEquals(shares.intValue(), portfolio.position("msft").quantity().intValue());

        BigDecimal openEquity = entryPrice.multiply(shares);
        BigDecimal expectedBuyPower = new BigDecimal("9980").subtract(commission.add(openEquity));

        buyPower = sentryService.buyPower();
        assertEquals(expectedBuyPower.doubleValue(),buyPower.doubleValue(),DELTA);

        BigDecimal closeEquity = closePrice.multiply(shares);
        systemEquity = sentryService.systemEquity();
        assertEquals(closeEquity.doubleValue(),systemEquity.doubleValue(),DELTA);


        ///////////////////
        //market limit sell fail test
        ///////////////////
        BigDecimal sellLimitFail = new BigDecimal("180.10");
        Response marketLimitSellResponse = sentryService.stockSignal(ActionForStock.SellToClose)
                .limitOrder(sellLimitFail).quantity(10).symbol("msft")
                .duration(Duration.DayOrder).send();

        //force request response now
        marketLimitSellResponse.getXML();

        ///////////////////////////
        //tick for limit order fail
        ////////////////////////////
        dataProvider = dataProvider.incTime(timeStep);
        simulationAdapter.tick(dataProvider,sentryService);

        ////////////////////
        //confirm nothing changed
        ///////////////////
        entryPrice = portfolio.position("msft").openPrice();
        assertTrue(entryPrice.compareTo(successLimit)<=0);

        shares = new BigDecimal("10");
        assertEquals(shares.intValue(), portfolio.position("msft").quantity().intValue());

        openEquity = entryPrice.multiply(shares);
        expectedBuyPower = new BigDecimal("9980").subtract(commission.add(openEquity));

        buyPower = sentryService.buyPower();
        assertEquals(expectedBuyPower.doubleValue(),buyPower.doubleValue(),DELTA);

        closeEquity = closePrice.multiply(shares);
        systemEquity = sentryService.systemEquity();
        assertEquals(closeEquity.doubleValue(),systemEquity.doubleValue(),DELTA);

        ///////////////////
        //market limit sell success test
        ///////////////////
        BigDecimal sellLimitSuccess = new BigDecimal("110.10");
        marketLimitSellResponse = sentryService.stockSignal(ActionForStock.SellToClose)
                .limitOrder(sellLimitSuccess).quantity(10).symbol("msft")
                .duration(Duration.DayOrder).send();

        ///////////////////////////
        //tick for limit order success
        ////////////////////////////
        dataProvider = dataProvider.incTime(timeStep);
        simulationAdapter.tick(dataProvider,sentryService);

        shares = new BigDecimal("0");
        assertEquals(shares.intValue(), portfolio.position("msft").quantity().intValue());

        //extra simple methods

        boolean ok = sentryService.flushPendingSignals();
        assertTrue(ok);
View Full Code Here

        // validates commands and returns hard coded (canned) responses
        DynamicSimulationAdapter simulationAdapter = new DynamicSimulationAdapter(false);

        String password = "P455w0rd";
        String eMail = "someone@somewhere.com";
        Portfolio portfolio = new SimplePortfolioFactory().createPortfolio(new BigDecimal("10000"));
        BigDecimal commission = new BigDecimal("10.00");
        Integer systemId = simulationAdapter.createSystem("first system",password,portfolio,commission);
        simulationAdapter.subscribe(eMail,systemId,password);
        C2ServiceFactory factory = new C2ServiceFactory(simulationAdapter);
        C2EntryService sentryService = factory.signalEntryService(password, systemId, eMail);

        validateStartingBalances(systemId, sentryService);

        BigDecimal stopLoss = new BigDecimal("20.50");
        BigDecimal profitTarget = new BigDecimal("120.50");

        assertEquals(0, portfolio.position("msft").quantity().intValue());
        Response openResponse = sentryService.stockSignal(ActionForStock.BuyToOpen)
                .marketOrder().quantity(10).symbol("msft")
                .stopLoss(BasePrice.Absolute,stopLoss,noOCA).profitTarget(profitTarget)
                .duration(timeInForce).send();

        final AtomicInteger signalId = new AtomicInteger(0);
        final AtomicInteger profitTargetSignalId = new AtomicInteger(0);
        final AtomicInteger stopLossSignalId = new AtomicInteger(0);

        openResponse.visitC2Elements(new C2ElementVisitor() {
            @Override
            public void visit(C2Element element, String data) {
                switch(element) {
                    case ElementSignalId:
                        signalId.set(Integer.valueOf(data));
                        break;
                    case ElementProfitTaretSignalId:
                        profitTargetSignalId.set(Integer.valueOf(data));
                        break;
                    case ElementStopLossSignalId:
                        stopLossSignalId.set(Integer.valueOf(data));
                        break;
                    default:
                        //nothing
                }
            }
        }, C2Element.ElementSignalId, C2Element.ElementStopLossSignalId, C2Element.ElementProfitTaretSignalId );


        long timeStep = 60000l*60l*24l;
        long openTime = 0l;
        long closeTime = openTime+timeStep;

        BigDecimal lowPrice = new BigDecimal("80");
        BigDecimal highPrice = new BigDecimal("100");
        DynamicSimulationMockDataProvider dataProvider = new DynamicSimulationMockDataProvider(
                openTime,lowPrice,highPrice,lowPrice,highPrice,closeTime);


        final Set<Integer> pendingSignalIdSet = new HashSet<Integer>();
        sentryService.sendAllSignalsRequest().visitC2Elements(new C2ElementVisitor() {
            @Override
            public void visit(C2Element element, String data) {
                if (C2Element.ElementSignalId==element) {
                    pendingSignalIdSet.add(Integer.parseInt(data));
                }
            }
        },C2Element.ElementSignalId);

        assertEquals(profitTargetSignalId.toString(),3,pendingSignalIdSet.size());
        assertTrue(pendingSignalIdSet.contains(profitTargetSignalId.intValue()));
        assertTrue(pendingSignalIdSet.contains(stopLossSignalId.intValue()));

        //confirm that the target can be adjusted
        BigDecimal newTarget = new BigDecimal("10");
        Response adjClose = sentryService.stockSignal(ActionForStock.SellToClose)
                .stopOrder(newTarget).quantity(10).symbol("msft")
                .duration(Duration.GoodTilCancel)
                .xReplace(stopLossSignalId.intValue()).send();

        Integer newCloseSignalId = adjClose.getInteger(C2Element.ElementSignalId);

        //confirm the pending list of signals has been updated
        updateSetWithPendingSignalIds(sentryService, pendingSignalIdSet);

        assertTrue(pendingSignalIdSet.contains(newCloseSignalId));
        if (noOCA) {
            assertTrue(pendingSignalIdSet.toString(),pendingSignalIdSet.contains(profitTargetSignalId.intValue()));
            assertEquals(3,pendingSignalIdSet.size());
        } //else can not be tested because it's modified when tick is called

        //not filled yet so quantity should be zero
        //this however has the quantity because QuantityComputableFixed is used above
        assertEquals(Integer.valueOf(10),sentryService.sendSignalStatusRequest(newCloseSignalId,true).getInteger(C2Element.ElementQuant));

        //send tick data to force open position if its still in force
        dataProvider = dataProvider.incTime(timeStep,new BigDecimal("13"));
        simulationAdapter.tick(dataProvider,sentryService);

        updateSetWithPendingSignalIds(sentryService, pendingSignalIdSet);

        assertEquals(10, portfolio.position("msft").quantity().intValue());

        assertTrue(pendingSignalIdSet.contains(newCloseSignalId));

        //get signal details
        assertEquals(Integer.valueOf(10),sentryService.sendSignalStatusRequest(newCloseSignalId,true).getInteger(C2Element.ElementQuant));

        if (noOCA) {
            assertTrue(pendingSignalIdSet.toString()+" can not find profit target signal "+profitTargetSignalId,pendingSignalIdSet.contains(profitTargetSignalId.intValue()));
            assertEquals(2,pendingSignalIdSet.size());
            assertEquals(Integer.valueOf(10),sentryService.sendSignalStatusRequest(profitTargetSignalId.intValue(),true).getInteger(C2Element.ElementQuant));

        } else {
            assertEquals(1,pendingSignalIdSet.size());
        }

        dataProvider = dataProvider.incTime(timeStep,new BigDecimal("9"));
        simulationAdapter.tick(dataProvider,sentryService);
        assertEquals(0, portfolio.position("msft").quantity().intValue());

        //for oca orders the other order will get cancelled when the first is triggered.
        //for non oca orders there will be one closing order however it should not be valid
        //because its a close against something closed.

View Full Code Here

        // validates commands and returns hard coded (canned) responses
        DynamicSimulationAdapter simulationAdapter = new DynamicSimulationAdapter(false);

        String password = "P455w0rd";
        String eMail = "someone@somewhere.com";
        Portfolio portfolio = new SimplePortfolioFactory().createPortfolio(new BigDecimal("10000"));
        BigDecimal commission = new BigDecimal("10.00");
        Integer systemId = simulationAdapter.createSystem("first system",password,portfolio,commission);
        simulationAdapter.subscribe(eMail,systemId,password);
        C2ServiceFactory factory = new C2ServiceFactory(simulationAdapter);
        C2EntryService sentryService = factory.signalEntryService(password, systemId, eMail);

        validateStartingBalances(systemId, sentryService);

        BigDecimal stopLoss = new BigDecimal("20.50");
        BigDecimal profitTarget = new BigDecimal("120.50");

        assertEquals(0, portfolio.position("msft").quantity().intValue());

        Response openResponse = sentryService.stockSignal(ActionForStock.BuyToOpen)
                .marketOrder().quantity(10).symbol("msft")
                .stopLoss(stopLoss).profitTarget(BasePrice.Absolute,profitTarget,noOCA)
                .duration(timeInForce).send();

        final AtomicInteger signalId = new AtomicInteger(0);
        final AtomicInteger profitTargetSignalId = new AtomicInteger(0);
        final AtomicInteger stopLossSignalId = new AtomicInteger(0);

        openResponse.visitC2Elements(new C2ElementVisitor() {
            @Override
            public void visit(C2Element element, String data) {
                switch(element) {
                    case ElementSignalId:
                        signalId.set(Integer.valueOf(data));
                        break;
                    case ElementProfitTaretSignalId:
                        profitTargetSignalId.set(Integer.valueOf(data));
                        break;
                    case ElementStopLossSignalId:
                        stopLossSignalId.set(Integer.valueOf(data));
                        break;
                    default:
                        //nothing
                }
            }
        }, C2Element.ElementSignalId, C2Element.ElementStopLossSignalId, C2Element.ElementProfitTaretSignalId );

        sentryService.awaitPending();
        assertTrue(signalId.intValue()>=0);
        assertTrue(profitTargetSignalId.intValue()>0);
        assertTrue(stopLossSignalId.intValue()>0);

        long timeStep = 60000l*60l*24l;
        long openTime = 0l;
        long closeTime = openTime+timeStep;

        BigDecimal closePrice = new BigDecimal("160.86");
        BigDecimal lowPrice = new BigDecimal("80");
        BigDecimal highPrice = new BigDecimal("100");
        DynamicSimulationMockDataProvider dataProvider = new DynamicSimulationMockDataProvider(
                openTime,lowPrice,highPrice,lowPrice,highPrice,closeTime);

        final Set<Integer> pendingSignalIdSet = new HashSet<Integer>();
        sentryService.sendAllSignalsRequest().visitC2Elements(new C2ElementVisitor() {
            @Override
            public void visit(C2Element element, String data) {
                if (C2Element.ElementSignalId==element) {
                    pendingSignalIdSet.add(Integer.parseInt(data));
                }
            }
        },C2Element.ElementSignalId);

        assertEquals(profitTargetSignalId.toString(),3,pendingSignalIdSet.size());
        assertTrue(pendingSignalIdSet.contains(profitTargetSignalId.intValue()));
        assertTrue(pendingSignalIdSet.contains(stopLossSignalId.intValue()));

        //confirm that the target can be adjusted
        BigDecimal newTarget = new BigDecimal("160");
        Response adjClose = sentryService.stockSignal(ActionForStock.SellToClose)
                .limitOrder(newTarget).quantity(10).symbol("msft")
                .duration(Duration.GoodTilCancel)
                .xReplace(profitTargetSignalId.intValue()).send();

        Integer newCloseSignalId = adjClose.getInteger(C2Element.ElementSignalId);

        dataProvider = dataProvider.incTime(timeStep,new BigDecimal("121"));
        simulationAdapter.tick(dataProvider,sentryService);

        //these tests do not work for DayOrders because all the signals have already expired
        if (timeInForce==Duration.GoodTilCancel) {
            assertEquals(10, portfolio.position("msft").quantity().intValue());

            updateSetWithPendingSignalIds(sentryService, pendingSignalIdSet);

            assertTrue(pendingSignalIdSet.contains(newCloseSignalId));
            if (noOCA) {
                assertTrue(pendingSignalIdSet.contains(stopLossSignalId.intValue()));
                assertEquals(2,pendingSignalIdSet.size());
            } else {
                assertEquals(1,pendingSignalIdSet.size());
            }
            dataProvider = dataProvider.incTime(timeStep,new BigDecimal("161"));
            simulationAdapter.tick(dataProvider,sentryService);
            assertEquals(0, portfolio.position("msft").quantity().intValue());

            //for oca orders the other order will get cancelled when the first is triggered.
            //for non oca orders there will be one closing order however it should not be valid
            //because its a close against something closed.

View Full Code Here

        // validates commands and returns hard coded (canned) responses
        DynamicSimulationAdapter simulationAdapter = new DynamicSimulationAdapter(false);

        String password = "P455w0rd";
        String eMail = "someone@somewhere.com";
        Portfolio portfolio = new SimplePortfolioFactory().createPortfolio(new BigDecimal("10000"));
        BigDecimal commission = new BigDecimal("10.00");
        Integer systemId = simulationAdapter.createSystem("first system",password,portfolio,commission);
        simulationAdapter.subscribe(eMail,systemId,password);
        C2ServiceFactory factory = new C2ServiceFactory(simulationAdapter);
        C2EntryService sentryService = factory.signalEntryService(password, systemId, eMail);

        validateStartingBalances(systemId, sentryService);

        assertEquals(0, portfolio.position("msft").quantity().intValue());
        Response openResponse = sentryService.stockSignal(ActionForStock.BuyToOpen)
                                        .marketOrder().quantity(10).symbol("msft")
                                        .duration(Duration.GoodTilCancel).send();

        Integer signalId = openResponse.getInteger(C2Element.ElementSignalId);

        assertEquals(0,signalId.intValue());

        long timeStep = 60000l*60l*24l;
        long time = 100000l;
        BigDecimal fixedPrice = new BigDecimal("80.43");

        DynamicSimulationMockDataProvider dataProvider = new DynamicSimulationMockDataProvider(time,fixedPrice,fixedPrice,fixedPrice,fixedPrice,time+timeStep);

        simulationAdapter.tick(dataProvider,sentryService);

        Number buyPower = sentryService.buyPower(); // 10000 - ((10 * 80.43)+10) = 10000-814.30
        assertEquals(9185.7d,buyPower.doubleValue(),DELTA);

        Number systemEquity = sentryService.systemEquity(); //10 * 80.43 = 804.30
        assertEquals(804.30d,systemEquity.doubleValue(),DELTA);

        final Set<C2Element> checkedElements = new HashSet<C2Element>();
        sentryService.sendSystemHypotheticalRequest(systemId).visitC2Elements(new C2ElementVisitor() {
            @Override
            public void visit(C2Element element, String data) {

                switch (element) {
                    case ElementTotalEquityAvail:
                        checkedElements.add(element);
                        assertEquals(9990d, Double.parseDouble(data), DELTA);
                        break;
                    case ElementCash:
                        checkedElements.add(element);
                        assertEquals(9185.70d, Double.parseDouble(data), DELTA);
                        break;
                    case ElementEquity:
                        checkedElements.add(element);
                        assertEquals(804.30d, Double.parseDouble(data), DELTA);
                        break;
                    case ElementMarginUsed:
                        checkedElements.add(element);
                        assertEquals(0d, Double.parseDouble(data), DELTA);
                        break;
                    default:
                        //nothing
                }
            }
        },C2Element.ElementTotalEquityAvail,
          C2Element.ElementCash,
          C2Element.ElementEquity,
          C2Element.ElementMarginUsed);
        assertEquals("expected to check 4 elements",4,checkedElements.size());
        assertEquals(10, portfolio.position("msft").quantity().intValue());

        ///////////////////
        //market order sell test
        ///////////////////
        Response marketOrderResponse = sentryService.stockSignal(ActionForStock.SellToClose)
                .marketOrder().quantity(10).symbol("msft")
                .duration(Duration.GoodTilCancel).send();

        //force request response now
        marketOrderResponse.getXML();

        ///////////////////////
        //tick for market buy
        /////////////////////
        long startTime = time+timeStep;
        long closeTime = startTime+timeStep;
        BigDecimal closePrice = new BigDecimal("160.86");
        dataProvider = new DynamicSimulationMockDataProvider(startTime,fixedPrice,closePrice,fixedPrice,closePrice,closeTime);
        simulationAdapter.tick(dataProvider,sentryService);

        ////////////////////
        //confirm values
        ///////////////////
        assertEquals(0, portfolio.position("msft").quantity().intValue());
        buyPower = sentryService.buyPower();
        assertEquals(9980d,buyPower.doubleValue(),DELTA);

        systemEquity = sentryService.systemEquity(); //10 * 80.43 = 804.30
        assertEquals(0d,systemEquity.doubleValue(),DELTA);

        ///////////////////
        //limit order test
        //////////////////
        BigDecimal failLimit = new BigDecimal("65.10");
        Response limitOrderResponse = sentryService.stockSignal(ActionForStock.BuyToOpen)
                .limitOrder(failLimit).quantity(10).symbol("msft")
                .duration(Duration.DayOrder).send();


        ///////////////////////////
        //tick for limit order fail
        ////////////////////////////
        dataProvider = dataProvider.incTime(timeStep);
        simulationAdapter.tick(dataProvider,sentryService);

        ////////////////////
        //confirm unchanged values
        ///////////////////
        assertEquals(0, portfolio.position("msft").quantity().intValue());
        buyPower = sentryService.buyPower();
        assertEquals(9980d,buyPower.doubleValue(),DELTA);

        systemEquity = sentryService.systemEquity(); //10 * 80.43 = 804.30
        assertEquals(0d,systemEquity.doubleValue(),DELTA);

        ///////////////////
        //limit order test
        //////////////////
        BigDecimal successLimit = new BigDecimal("170.10");
        limitOrderResponse = sentryService.stockSignal(ActionForStock.BuyToOpen)
                .limitOrder(successLimit).quantity(10).symbol("msft")
                .duration(Duration.DayOrder).send();

        //force request response now
        Integer openSignalId = limitOrderResponse.getInteger(C2Element.ElementSignalId);

        ///////////////////////////
        //tick for limit order success
        ////////////////////////////
        dataProvider = dataProvider.incTime(timeStep);
        simulationAdapter.tick(dataProvider,sentryService);

        ////////////////////
        //confirm changed
        ///////////////////
        BigDecimal entryPrice = portfolio.position("msft").openPrice();
        assertTrue(entryPrice == null || entryPrice.compareTo(successLimit)<=0);

        BigDecimal shares = new BigDecimal("10");
        assertEquals(shares.intValue(), portfolio.position("msft").quantity().intValue());

        BigDecimal openEquity = entryPrice.multiply(shares);
        BigDecimal expectedBuyPower = new BigDecimal("9980").subtract(commission.add(openEquity));

        buyPower = sentryService.buyPower();
        assertEquals(expectedBuyPower.doubleValue(),buyPower.doubleValue(),DELTA);

        BigDecimal closeEquity = closePrice.multiply(shares);
        systemEquity = sentryService.systemEquity();
        assertEquals(closeEquity.doubleValue(),systemEquity.doubleValue(),DELTA);


        ///////////////////
        //market limit sell fail test
        ///////////////////
        BigDecimal sellLimitFail = new BigDecimal("180.10");
        Response marketLimitSellResponse = sentryService.stockSignal(ActionForStock.SellToClose)
                .limitOrder(sellLimitFail).quantity(10).symbol("msft")
                .duration(Duration.DayOrder).send();

        //force request response now
        marketLimitSellResponse.getXML();

        ///////////////////////////
        //tick for limit order fail
        ////////////////////////////
        dataProvider = dataProvider.incTime(timeStep);
        simulationAdapter.tick(dataProvider,sentryService);

        ////////////////////
        //confirm nothing changed
        ///////////////////
        entryPrice = portfolio.position("msft").openPrice();
        assertTrue(entryPrice.compareTo(successLimit)<=0);

        shares = new BigDecimal("10");
        assertEquals(shares.intValue(), portfolio.position("msft").quantity().intValue());

        openEquity = entryPrice.multiply(shares);
        expectedBuyPower = new BigDecimal("9980").subtract(commission.add(openEquity));

        buyPower = sentryService.buyPower();
        assertEquals(expectedBuyPower.doubleValue(),buyPower.doubleValue(),DELTA);

        closeEquity = closePrice.multiply(shares);
        systemEquity = sentryService.systemEquity();
        assertEquals(closeEquity.doubleValue(),systemEquity.doubleValue(),DELTA);

        ///////////////////
        //market limit sell success test
        ///////////////////
        BigDecimal sellLimitSuccess = new BigDecimal("110.10");
        marketLimitSellResponse = sentryService.stockSignal(ActionForStock.SellToClose)
                .limitOrder(sellLimitSuccess).quantity(10).symbol("msft")
                .duration(Duration.DayOrder).send();

        ///////////////////////////
        //tick for limit order success
        ////////////////////////////
        dataProvider = dataProvider.incTime(timeStep);
        simulationAdapter.tick(dataProvider,sentryService);

        shares = new BigDecimal("0");
        assertEquals(shares.intValue(), portfolio.position("msft").quantity().intValue());

        //extra simple methods

        boolean ok = sentryService.flushPendingSignals();
        assertTrue(ok);
View Full Code Here

        // validates commands and returns hard coded (canned) responses
        DynamicSimulationAdapter simulationAdapter = new DynamicSimulationAdapter(false);

        String password = "P455w0rd";
        String eMail = "someone@somewhere.com";
        Portfolio portfolio = new SimplePortfolioFactory().createPortfolio(new BigDecimal("10000"));
        BigDecimal commission = new BigDecimal("10.00");
        Integer systemId = simulationAdapter.createSystem("first system",password,portfolio,commission);
        simulationAdapter.subscribe(eMail,systemId,password);
        C2ServiceFactory factory = new C2ServiceFactory(simulationAdapter);
        C2EntryService sentryService = factory.signalEntryService(password, systemId, eMail);

        validateStartingBalances(systemId, sentryService);

        BigDecimal stopLoss = new BigDecimal("20.50");
        BigDecimal profitTarget = new BigDecimal("120.50");

        assertEquals(0, portfolio.position("msft").quantity().intValue());

        int time = 10000;
        long timeStep = 60000l*60l*24l;
        BigDecimal price = new BigDecimal("50");
        simulationAdapter.tick(new DynamicSimulationMockDataProvider(
                time,price,price,price,price,time+=timeStep),sentryService);

        Response openResponse = sentryService.stockSignal(ActionForStock.BuyToOpen)
                .marketOrder().quantity(10).symbol("msft")
                .stopLoss(BasePrice.Absolute,stopLoss,noOCA).profitTarget(profitTarget)
                .duration(timeInForce).send();

        final AtomicInteger signalId = new AtomicInteger(0);
        final AtomicInteger profitTargetSignalId = new AtomicInteger(0);
        final AtomicInteger stopLossSignalId = new AtomicInteger(0);

        openResponse.visitC2Elements(new C2ElementVisitor() {
            @Override
            public void visit(C2Element element, String data) {
                switch(element) {
                    case ElementSignalId:
                        signalId.set(Integer.valueOf(data));
                        break;
                    case ElementProfitTaretSignalId:
                        profitTargetSignalId.set(Integer.valueOf(data));
                        break;
                    case ElementStopLossSignalId:
                        stopLossSignalId.set(Integer.valueOf(data));
                        break;
                    default:
                        //nothing
                }
            }
        }, C2Element.ElementSignalId, C2Element.ElementStopLossSignalId, C2Element.ElementProfitTaretSignalId );



        BigDecimal lowPrice = new BigDecimal("80");
        BigDecimal highPrice = new BigDecimal("100");
        DynamicSimulationMockDataProvider dataProvider = new DynamicSimulationMockDataProvider(
                time,lowPrice,highPrice,lowPrice,highPrice,time+=timeStep);
        simulationAdapter.tick(dataProvider,sentryService);

        assertEquals(10, portfolio.position("msft").quantity().intValue());

        dataProvider = dataProvider.incTime(timeStep,new BigDecimal("22"));
        simulationAdapter.tick(dataProvider,sentryService);

        assertEquals(10, portfolio.position("msft").quantity().intValue());

        final Set<Integer> pendingSignalIdSet = new HashSet<Integer>();
        sentryService.sendAllSignalsRequest().visitC2Elements(new C2ElementVisitor() {
            @Override
            public void visit(C2Element element, String data) {
View Full Code Here

TOP

Related Classes of com.collective2.signalEntry.adapter.dynamicSimulator.portfolio.Portfolio

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.