Strategy Samples ???

Use all the fxcodebase indicator in your application!

Moderator: admin

Strategy Samples ???

Postby Gidien » Mon Oct 25, 2010 4:05 am

Is there samples available , how i can load strategies with the development API ???

best regards

FXCodeBase: Confirmed User
Posts: 106
Joined: Mon Feb 08, 2010 7:39 am
Location: Hamburg

Re: Strategy Samples ???

Postby Nikolay.Gekht » Mon Oct 25, 2010 12:53 pm

Strategy requires a lot of support on the host side for all the trading functions so it is reasonable to develop it for certain Trading API to be used to trade. We're preparing such example for Order2Go API used for trading support.
FXCodeBase: Base Builder
Posts: 1222
Joined: Wed Dec 16, 2009 6:39 pm
Location: Cary, NC

Re: Strategy Samples ???

Postby Gidien » Thu Nov 04, 2010 3:25 am

where can i find the examples??
FXCodeBase: Confirmed User
Posts: 106
Joined: Mon Feb 08, 2010 7:39 am
Location: Hamburg

Re: Strategy Samples ???

Postby Nikolay.Gekht » Fri Nov 05, 2010 9:46 am

The strategy example is in work. Execution of the strategies involves almost all features of indicore and, in fact, "an example" is a full and complete implementation of strategy execution on certain API.
So, it takes time. So, please, be patient.

Also, I strongly recommend to understand and try to implement IHost interface concept first on the indicator, before implementing it for the strategies. Examples for host interface and asynchronous execution support are allready included into the current version of SDK.
FXCodeBase: Base Builder
Posts: 1222
Joined: Wed Dec 16, 2009 6:39 pm
Location: Cary, NC

Re: Strategy Samples ???

Postby allpin » Mon Mar 21, 2011 4:00 pm

Hello! Here is an example of using strategy in .Net application.
In order to create a strategy instance you need a strategy profile, two alive tick streams (“bid” and “ask”), strategy parameters, and a callback function which would be called when a signal (“Buy” or “Sell”) appears or trading order has to be created.
Have a look at the main classes used by application:

The main class Program is responsible for loading a list of indicators and strategies, getting an indicator’s profile, and filling parameters for a strategy. It creates an instance of the strategy (an object of StrategyInstance class implemented as MyStrategyInstance). Strategy instance always uses two tick sources (“bid” and “ask”), so you need to implement IndicatorTickSource class (MyIndicatorTickSource class in the example). Some strategies may use time frames other than “tick”. It means you will need to implement IndicatorBarSource class (MyIndicatorBarSource class in the example). Classes IndicatorTickSource and IndicatorBarSource are subclasses of IndicatorSource.
Strategy uses Host class for host application. Class MyHost implements Host in the example. It is used to execute commands or to get data which are not covered by the standard interface of the indicators or the strategies.
Strategy instance needs a callback function for trading signals and executing orders sent from the strategy, that’s why you have to implement StrategyCallback class (MyStrategyCallback class in the example). Program will notify strategy instance when asynchronous operations requested by strategy are completed.
Let’s have a look at MyHost class:

When MyHost gets commands getTradingDayOffset, getTradingWeekOffset or getTradingProperty, it calls Order2Go class. For GetHistory commands MyHost is using HistoryMgr class. For setTimer and killTimer commands MyHost is using TimersMgr class.
We already mentioned that strategy always uses two tick streams (“bid” and “ask”), and some strategies use bar streams (“hourly” candles, “weekly” candles, etc.) Look at the streams’ creation and usage on the class diagram:

History manager can create either MyIndicatorTickSource or MyIndicatorBarSource (MyIndicatorBarSource uses helper class BarData). History Manager keeps information about streams created for the strategy instance via Ticket class.
Class Order2Go is used for getting trading property, trading day offset, trading week offset, and price history helper (the last is used for getting a candle for specific time). When MyHost gets command findTable, it returns TradingDataTable. Class MyTradingTable implements TradingDataTable and contains information about trading tables (“Accounts”, “Offers”, “Orders”, “Trades”, “Closed Trades”, “Summary”, “Messages”). Class MyTradingTable also uses MyTradingRowEnumerator (subclass of TradingDataTableEnumerator) and MyTradingRow (subclass of TradingDataTableRow).

Let’s do it step by step.
To get a list of strategies and indicators, load them, and fill strategy parameters you would need to use Indicore.
To create alive tick streams you would need to pre-load tick history, and that would require Order2Go. You would also need Order2Go for creating trading orders in case you strategy would be allowed to trade.
So the first steps you would need to do:
1- Add gehtsoft.indicore.dll and FXCore.dll as references to your project
2- Copy indicore2.dll and lua5.1.dll to the target directory
3- If you are going to use standard strategy, you will need to create an strategies\standard\include structure in the target directory and copy files from strategies\standard\include folder there (you will need files helper.lua and helperAlert.lua)

Have a look at the Program class which is a hub of the application.
The command line for the program should look like:
[application].exe [username] [password] [instrument (optional)] [time frame (optional)]
Our example uses defaults “EUR/USD” as an instrument and “m1” as a timeframe.
What you have to do:
4- Create Indicore Manager object
5- Create Core object of Order2Go
6- Create trade desk object
Some strategies have getHistory requests (they may need history from time frame other than “tick”). Accomplishment of these requests takes time, so you would need to use asynchronous functions.
7- Subscribe to events OnPriceHistoryCompleted and OnPriceHistoryFailed
Strategies can be allowed to trade. Creating trading orders should be done asynchronously as well.
8- Subscribe to event OnRequestCompleted and OnRequestFailed
9- Login to trade desk
10- Load a list of indicators and a list of strategies
11- Get a strategy profile (MA_ADVISOR is used in the example)
12- Get a new instance of indicator parameters
13- Fill the values of the parameters. For the strategy MA_ADVISOR used in the example you would need to set parameter CANTRADE to “Yes”, and parameter ACCOUNT to account ID (which can be extracted by helper function GetAccountID) in case the strategy is allowed to trade.
A strategy uses host application, so you will need a host class.
14- Implement a Host class in your code
15- Create an object of the Host class (MyHost), and set it as a Host for your Indicore Manager object
Host has method findTable returning TradingDataTable.
16- Implement TradingDataTable (see class MyTradingTable). You can omit this step if the strategy is not allowed to trade.
A strategy uses callback function for trading signals and creating orders.
17- Implement a StrategyCallback class in your code (see class MyStrategyCallBack)
18- Create an object of the implementing class
A strategy always need two “tick” streams for “bid” and “ask” prices.
19- Implement IndicatorTickSource class (see class MyIndicatorTickSource).
A strategy may also need “bar” stream
20- Implement IndicatorBarSource in case the strategy can use time frame other than “tick” (see class MyIndicatorBarSource)
Prepare tick sources for the strategy.
21- Enable pending events for the trading desk (it will allow you to store and later extract coming ticks). It is important to do it before the call to get last 300 ticks.
22- Ask HistoryMgr class to prepare ticks for you. You need the tick history up to “now” (use 0 as date “from” and date “to”, and “t1” as time frame). History manager would do the work of merging “historic” ticks and “new” ticks.
23- Now (happy moment!) you can create a strategy instance, using two “tick” streams, strategy callback function, and parameters.
24- History manager (HistoryMgr) keeps all streams for the strategy instance. “Bid” and “ask” tick streams are special, because they were created before the strategy instance was born. That’s that is why you have to attach them to strategy instance right after creating a strategy instance with those streams.
25- Get into the loop. Program will ask history manager to process pending events (it is done by function ProcessPendingEvents), and in case there are new prices, all price streams associated with the strategy instance would get new ticks (bars), and the strategy instance would be updated.
26- Each time when event OnPriceHistoryCompleted happens, check the dictionary in history manager, find a stream for the price history request, fill it with the prices you got, add new ticks stored in the buffer for the stream (if any), mark stream as completed, and call notifyFinished for the strategy instance (function FxCore_OnPriceHistoryCompleted).
27- Notify strategy instance in case OnPriceHistoryFailed happens (function FxCore_OnPriceHistoryFailed).
28- If the strategy is allowed to trade, notify strategy instance when events OnRequestCompleted or OnRequestFailed happen (functions FXCore_OnRequestCompleted and FXCore_OnRequestFailed). Check Order2Go dictionary, find information about the order for specific request, get a cookie for the strategy, and call notifyFinished for the strategy instance. Information about order requests older than one minute can be removed from the dictionary.

Class MyHost implements Host class. It is called by strategy for executing commands, finding trading tables, logging, getting trading day offset, trading week offset, and trading properties.
Host returns TradingDataTable in findTable method.
Class MyTradingTable implements TradingDataTable and reflects real trading tables (“Accounts”, “Offers”, “Orders”, “Trades”, “Closed Trades”, “Summary”, “Messages”):
Class TradingDataTable returns TradingDataTableRow in function findRow. That’s why you need to implement TradingDataTableRow (class MyTradingRow in the example).
Class MyTradingTable returns TradingDataTableEnumerator in a function getEnumerator. It means you need to implement TradingDataTableEnumerator (class MyTradingRowEnumerator in the example).

MyHost uses class Order2Go to get trading day offset, trading week offset, and trading properties. Order2Go is also used for price history helper (the last is used for getting a candle for specific time).
Class Order2Go also keeps information about the trading orders requested by the strategy. In the example below the information is kept in a dictionary where strategy instance is a key, and the list with information about corresponding orders is a value. A helper class OrderInfo is used to keep information about an order (request ID, strategy’s cookie, and time of request).

Look closer to class Order2Go.
Function GetTradingProperty gets trading properties like baseUnitSize or canCreateEntry.It uses helper functions GetInstrument and GetAccount. These helper functions extract instrument and account from the list of arguments for trading property. Function GetTradingProperty also uses CheckPermissions function for permission properties. CheckPermissions converts an integer returned by permission checker for specific instrument into the boolean value. Function GetPrimaryKey gets a primary key for the table like OrderID for Orders table.

MyHost class calls history manager class (HistoryMgr) in order for getHistory requests of the strategy.
Have a look at HistoryMgr class.
Class HistoryMgr is used to prepare price streams: “bid” and “ask” sources for the strategy, as well as streams for strategy’s getHistory requests. History manager keeps strategy instance with a list of price streams for this instance.
History manager has function PrepareTicks to create “bid” and “ask” sources for strategy. First it gets historic prices. It this case application uses synchronous call because prices have to be filled in order to create strategy instance. There could be new ticks coming from the moment of the GetPriceHistory call to the moment of getting the result with 300 ticks. Function GetPendingEvents of the trading desk is used to get new ticks. Function MergeTicksHistWithTicksBuffer is used to merge historic and new ticks. Ticks should not overlap, so there is a helper function IsSamePatternStarted (it is used to check for the exact match between history ticks and tick buffer to avoid overlapping when merging).
History manager has function GetPriceHistoryAsync for getPriceHistory request from strategy. One of the arguments is a cookie from the strategy to be used in notifyFinished. GetPriceHistoryAsync function creates an empty stream, and sends an asynchronous call to get historic prices. Application does not wait for prices to be filled. Instead it gets request ID for the history request (it would be used in event OnPriceHistoryCompleted). The empty stream is attached to the instance of a strategy together with supporting information (price history request ID, cookie for notifyFinished). The stream would be kept with a flag PriceHistoryCompleted as “false” until prices would be filled.
Function ProcessPendingEvents checks pending events, and in case there were new prices (“new offer” events), new ticks are added for all completed streams (ticks are kept in a buffer for uncompleted streams).
Function ProcessTick adds new tick for all corresponding tickets (the tick should be stored in the tick buffer in case stream is not filled yet).
Function AddTick2Stream adds a tick to tick stream or bar stream.
Function Attach2Instance attaches price stream to strategy instance to keep them together in a dictionary. Class Ticket is used to keep all this information.

Ticket holds price stream itself (could be “tick” or “bar), flag showing whether price stream was filled, request id for asynchronous GetPriceHistoryAsync method (string to be used in OnPriceHistoryCompleted), asynchronous operation cookie (an integer to be sent to AsyncOperationFinished function of the strategy when data is loaded), flag indicating whether price stream keeps prices up to "now", and “tick buffer” to keep ticks from the moment of calling GetPriceHistory until price history would be completed.
When price history would be completed, the “ticks”from the buffer would be added to the historic price stream.
Streams with a flag “till now” would pick up new “ticks”.

Some strategies use setTimer and killTimer commands. MyHost class calls timers manager class (TimersMgr) for setTimer and killTimer commands of the strategy. TimersMgr uses helper class TimerInfo. Function AddTimer starts the timer and keeps information about the timer in the list timersInfo. When “timer elapsed” event happens (function timer_Elapsed) the timer is found in the list timersInfo, and strategy instance is notified with cookie belonging to this timer as an argument for AsyncOperationFinished. Function KillTimer stops the timer. The timer is found in the list timersInfo by using timer ID.

Class MyStrategyCallBack implements StrategyCallBack class.
Strategy will use MyStrategyCallBack class for “Buy” and “Sell” signals (sending alerts) and for executing trading orders if trading is allowed. executeOrder and alert functions are the heart of the application. Function executeOrder needs to get arguments for creating an order. executeOrder uses helper functions GetStringParamFromValueMap and GetNumberParamFromValueMap to extract string or number parameter from ValueMap argument. executeOrder also uses helper function GetValueFromTable if the argument for creating an order can be extracted from the trading table. Function GetValueFromTable gets value for the specific column of the trading table where the row is determined by the primary key value.
Function GetTimeInForce converts a string for time in force (“GTC” for “good till cancelled”, “IOC” for “immediate or cancel”, “FOK” for “fill or kill”) into an integer expected by Order2Go functions creating an order.
Function GetValuesForRangeOrder is used for the “range” orders (“OM” or “CM”). If minimum and maximum rates are used, this function will calculate “medium” value and range in points (minimum and maximum values are not used by “classic” Order2Go functions for creating an order).
Function GetStopLimitType gets an integer to be used as a type of “Stop” and “Limit” for creating an order.
Now when everything is ready it is a time to create an order. Application uses asynchronous functions (OpenTrade3Async, CloseTrade2Async, CreateEntryOrder3Async, and ChangeEntryOrderStopLimit3Async) for creating an order. Each of these functions returns request ID. Function AttachToInstance of Order2Go class would keep request ID and the cookie in a dictionary together with the time of request. When an event OnRequestCompleted or OnRequestFailed happens, the strategy instance would be notified. In order to avoid keeping too many orders you can remove orders with request time older than one minute from the dictionary.

You can download the project for using strategy here:
Project involving use of strategy in .NET
(41.01 KiB) Downloaded 1192 times
FXCodeBase: Confirmed User
Posts: 21
Joined: Thu Aug 19, 2010 3:29 pm

Return to C++/.NET API

Who is online

Users browsing this forum: No registered users and 1 guest