OPENING AND CLOSING TRADES USING STREAMING

In this tutorial you will learn how to use streaming to open, store and close opened positions.
The code will be written in C#, but it is not complicated and could be easily rewritten to any other language.

The key of this tutorial is to understand the trade records sent in streaming and to interpret them properly.
The whole code used in this tutorial is available here:

The ReceiveTradeRecord method checks the type field in the tradeRecord.
Depending on its value, it adds or removes order and position numbers from appriopriate lists.

Every position is opened and closed by an order.
Notice that the acceptedTradeOrders list holds numbers of the orders that open positions.
When the field type
has STREAMING_TRADE_TYPE.OPEN value we know that the position was opened. Then we remove the order that opened the position from acceptedTradeOrders
using the order2 field and add the position number to the openedPositions list using the
position field.

In case the type has the STREAMING_TRADE_TYPE.CLOSE value we
can remove the position from openedPositions list as the position is closed.

Define ReceiveTickRecord function which will get current symbol prices in real time and store them in currentAskPrice
and currentBidPrice variables described in the Step 1. The code is listed below:

Define the ReceiveTradeStatusRecord function which adds accepted trade orders which open and close positions to the
acceptedTradeOrders list.
The unacceptedTradeOrders list holds the trade orders that open and close the positions, but have not been unaccepted yet.
The method removes the order from unacceptedTradeOrders in case it was accepted.

We open the SELL trade using the currentBidPrice and symbol variables
which were explained in the beginning.

Additionally, we add the order number to the unacceptedTradeOrders and wait for it to be accepted via streaming in the ReceiveTradeStatusRecord.

This is the output of the application in the console:

We can see that there are three StreamingTradeRecords during opening the position:

two for the order (number 202496) that opens the position with type = 1

one for the opened (type = 0) position (number 202497) with the number of the order that opened the position (202496) under order2 field.

Step 5. Close the trade

Closing of the trade is also executed by the tradeTransaction command, but in this case we use the Ask price and add the position number
we are willing to close. We can get the position number from openedPositions list.