I know mql4 ok, but I'm lost with c++

 

I have been up and running with automated trading with Metatrader 4 for about a year now, but I'm trying to figure out Oanda's API using c++ now and I just don't understand about half of what is in the code. wondering if anyone here knows how to take what I have in a mql4 program and turn it into a c++ program that will work with the following example that I recieved from Oanda. Sorry it is so long, but this is what they gave me as an example... looks a lot harder to learn than was the MACD Sample that came with Metatrader! If someone could even just make a sample program of this type that was like the MACD sample I would really appreciate it!

/*

Example 2

Comprehensive example of use of the FXTrade API

Ported from Java by Chris MacGregor, January 2006

*/

#include

#include

#include

#include "FXGame.h"

#include

#include

#define WIN32_LEAN_AND_MEAN

#include

using namespace std;

using namespace Oanda;

string VERSION = "1.2";

// Global variables

string g_username, g_password;

FXGame g_fxclient;

User *g_user;

Account *g_account;

RateTable *g_rateTable;

//=========================================================================================

// Case statement branches

================================================================

//=========================================================================================

void caseListAccounts()

{

if (!g_fxclient.isLoggedIn()) return;

// fetch and print out a list of accounts to the screen

vector accounts = g_user->getAccounts();

for (unsigned int count = 0; count < accounts.size(); count++)

{

Account *account = accounts.at(count);

cout << endl

<< "[" << (count + 1) << "]" << endl

<< "Account Name : " <accountName() <<

endl

<< "Account ID : " <accountId() << endl

<< "Acct. Creation Date: " <createDate() << endl

<< "Margin rate : " <marginRate() << endl

<< "Home Currency : " <homeCurrency() <<

endl;

}

}

void caseSwitchAccounts()

{

if (!g_fxclient.isLoggedIn()) return;

// fetch and print out a list of accounts to the screen

vector accounts = g_user->getAccounts();

caseListAccounts();

// get user selection

cout << endl

<< "Enter the account number or place in list to switch to [0]: ";

unsigned int accountNumber;

cin >> accountNumber;

// return if the user presses enter or 0

if (accountNumber == 0) return;

if (accountNumber <= accounts.size())

{

// if the input number is small, assume the user is picking from the list

g_account = accounts.at(accountNumber - 1);

accountNumber = g_account->accountId();

cout << "Now trading on account " << accountNumber << endl;

}

else

{

// otherwise, assume they tried to enter an actual account number

Account *temp = g_user->getAccountWithId(accountNumber);

// check if they actually did

if (temp == NULL)

{

cerr << accountNumber << " is not a valid account number"

<< ", current account not switched\n";

return;

}

else

{

cout << "Now trading on account " << accountNumber << endl;

g_account = temp;

}

}

}

void casePrintAccountData()

{

if (!g_fxclient.isLoggedIn()) return;

// print out some financial information for the current account

cout << endl;

printf("Balance : %12.2f\n", g_account->balance());

printf("Unrealized P/L : %12.2f\n", g_account->unrealizedPL());

printf("Net Asset Value : %12.2f\n",

g_account->balance() + g_account->unrealizedPL());

printf("Realized P/L : %12.2f\n", g_account->realizedPL());

printf("Margin Used : %12.2f\n", g_account->marginUsed());

printf("Margin Avalailable: %12.2f\n", g_account->marginAvailable());

}

void caseListOpenMarketOrders()

{

if (!g_fxclient.isLoggedIn()) return;

// fetch and print out the list of currently open market orders

vector marketOrders = g_account->getTrades();

cout << "\n###| Ticket | Pair | Units | Price | Profit \n"

<< "---------------------------------------------------\n";

for (unsigned int count = 0; count < marketOrders.size(); count++)

{

MarketOrder mo = marketOrders.at(count);

printf("%3i %i %s/%s %9i %9.4f %9.2f\n",

count + 1,

mo.orderNumber(),

mo.base(),

mo.quote(),

mo.units(),

mo.price(),

mo.unrealizedPL(g_rateTable->getRate(mo.pair())));

}

cout << endl;

}

void caseListOpenLimitOrders()

{

if (!g_fxclient.isLoggedIn()) return;

// fetch and print out the list of currently open limit orders

vector limitOrders = g_account->getOrders();

cout << "\n###| Ticket | Pair | Units | Price | Expiry

\n"

<<

"------------------------------------------------------------------\n";

for (unsigned int count = 0; count < limitOrders.size(); count++)

{

LimitOrder lo = limitOrders.at(count);

// convert expiration time to string

const time_t temp = lo.duration();

DateString ds = FXClient::timestampToString(temp);

//string expiry = ctime(&temp);

//expiry[24] = 0; // chomp newline from time string

printf("%3i %i %s/%s %9i %9.4f %s\n",

count + 1,

lo.orderNumber(),

lo.base(),

lo.quote(),

lo.units(),

lo.price(),

ds.c_str());

}

cout << endl;

}

void caseListActivityLog()

{

if (!g_fxclient.isLoggedIn()) return;

// fetch and print out the list of past transatcions

vector transactions = g_account->getTransactions();

cout << endl

<< " Ticket | Type | Pair | Units | Price | Link

| Diaspora "

<< "| Time \n"

<<

"---------------------------------------------------------------------------------"

<< "-------------------------\n";

for (unsigned int count = 0; count < transactions.size(); count++)

{

Transaction t = transactions.at(count);

// convert timestamp time to string

const time_t temp = t.timestamp();

DateString ds = FXClient::timestampToString(temp);

//string timestamp = ctime(&temp);

//timestamp[24] = 0; // chomp newline from time string

// for Box orders, use 2-digit precision, otherwise, use 5-digit

string desc = t.getDescription();

int precision = 2;

if (desc.find("Box") == string::npos) precision = 5;

printf("%10i %20s %s/%s %9i %9.*f %10i %10i %s\n",

t.transactionNumber(),

t.getDescription(),

t.base(),

t.quote(),

t.units(),

precision,

t.price(),

t.link(),

t.diaspora(),

ds.c_str());

}

cout << endl;

}

void casePrintRateTable()

{

if (!g_fxclient.isLoggedIn()) return;

// print out an up-to-date list of the popular currency pair's rates

cout << "\n Pair | Bid | Ask | Date \n"

<< "-----------------------------------------------------\n";

string pairs[] = {"AUD/USD", "EUR/CHF", "EUR/GBP", "EUR/JPY",

"EUR/USD", "GBP/CHF", "GBP/JPY", "GBP/USD",

"USD/CAD", "USD/CHF", "USD/JPY"};

for (unsigned int count = 0; count < 11; count++)

{

FXPair pair(pairs[count].c_str());

FXTick rate = g_rateTable->getRate(pair);

// convert timestamp time to string

const time_t temp = rate.timestamp();

DateString ds = FXClient::timestampToString(temp);

//string timestamp = ctime(&temp);

//timestamp[24] = 0; // chomp newline from time string

printf("%s %10.5f %10.5f %s\n",

pairs[count].c_str(),

rate.bid(),

rate.ask(),

ds.c_str());

}

}

void caseExecuteMarketOrder()

{

if (!g_fxclient.isLoggedIn()) return;

// === construct the market order to open

FXPair pair;

MarketOrder marketOrder;

// get the currency pair

cout << "Pair [EUR/USD]: ";

string pairInput;

cin >> pairInput;

if (strcmp(pairInput.c_str(), "") == 0) pair.pair("EUR/USD");

else pair.pair(pairInput.c_str());

marketOrder.base(pair.base());

marketOrder.quote(pair.quote());

// get the number of units

cout << "Number of units [100]: ";

int numUnitsInput;

cin >> numUnitsInput;

if (numUnitsInput == 0) numUnitsInput = 100; //default to 100

marketOrder.units(numUnitsInput);

// find out if it's a buy or a sell

cout << "(B)uy or (S)ell : ";

string buySell;

cin >> buySell;

bool buy = true; // default to buy

if (strcmp(buySell.c_str(), "") != 0) buy = (buySell[0] == 'B');

if (!buy) marketOrder.units(-1 * marketOrder.units()); // negative units for a

sell

marketOrder.lowPriceLimit(marketOrder.price() - 5);

marketOrder.highPriceLimit(marketOrder.price() - 5);

// === submit the constructed market order

cout << "Submitting market order...";

try

{

g_account->execute(marketOrder);

cout << "submission successful" << endl;

}

catch (OAException se)

{

cout << "submission failed: " << se.type() << endl;

}

}

 

more...

here's more of it:

void caseModifyMarketOrder()

{

if (!g_fxclient.isLoggedIn()) return;

// fetch and print a list of the users open market orders

vector marketOrders = g_account->getTrades();

if (marketOrders.size() == 0)

{

cout << "Cannot modify: no market orders currently open\n";

return;

}

caseListOpenMarketOrders();

// === fetch the market order to modify

MarketOrder marketOrder;

// get user selection

cout << "Please enter a ticket number or place in list [0]: ";

unsigned int ticket;

cin >> ticket;

// return if the user presses enter or 0

if (ticket == 0) return;

if (ticket <= marketOrders.size())

{

// if the ticket number is low, assume it is a list position

marketOrder = marketOrders.at(ticket - 1);

ticket = marketOrder.orderNumber();

}

else

{

// otherwise, get market order via ticket number

bool foundTrade = g_account->getTradeWithId(marketOrder, ticket);

if (!foundTrade) // Bail if the trade was not found

{

cerr << "Could not find market order #" << ticket << endl;

return;

}

}

// === get the updated stop loss and take profit for the market order

cout << "Stop Loss [" << marketOrder.stopLossOrder.price() << "]: ";

double tempSL;

cin >> tempSL;

if (tempSL != 0) marketOrder.stopLossOrder.price(tempSL);

cout << "Take Profit [" << marketOrder.takeProfitOrder.price() << "]: ";

double tempTP;

cin >> tempTP;

if (tempTP != 0) marketOrder.takeProfitOrder.price(tempTP);

// == submit changes to market order

cout << "Modifying market order #" << ticket << "...";

try

{

g_account->modify(marketOrder);

cout << "modification successful\n";

}

catch (OAException se)

{

cout << "modification failed: " << se.type() << endl;

}

}

void caseCloseMarketOrder()

{

if (!g_fxclient.isLoggedIn()) return;

// fetch and print a list of the users open trades

vector marketOrders = g_account->getTrades();

if (marketOrders.size() == 0)

{

cout << "Cannot modify: no market orders currently open\n";

return;

}

caseListOpenMarketOrders();

// === fetch the market order to modify

MarketOrder marketOrder;

// get user selection

cout << "Please enter a ticket number or place in list [0]: ";

unsigned int ticket;

cin >> ticket;

// return if the user presses enter or 0

if (ticket == 0) return;

if (ticket <= marketOrders.size())

{

// if the ticket number is low, assume it is a list position

marketOrder = marketOrders.at(ticket - 1);

ticket = marketOrder.orderNumber();

}

else

{

// otherwise, get market order via ticket number

bool foundTrade = g_account->getTradeWithId(marketOrder,

ticket);

if (!foundTrade) // Bail if the trade was not found

{

cerr << "Could not find market order #" << ticket <<

endl;

return;

}

}

// === close the order

cout << "Closing market order #" << ticket << "...";

try

{

g_account->close(marketOrder);

cout << "close successful\n";

}

catch (OAException se)

{

cout << "close failed: " << se.type() << endl;

}

}

void caseExecuteLimitOrder()

{

if (!g_fxclient.isLoggedIn()) return;

// === construct the limit order to open

FXPair pair;

LimitOrder limitOrder;

// get the currency pair

cout << "Pair [EUR/USD]: ";

string pairInput;

cin >> pairInput;

if (strcmp(pairInput.c_str(), "") == 0) pair.pair("EUR/USD");

else pair.pair(pairInput.c_str());

limitOrder.base(pair.base());

limitOrder.quote(pair.quote());

// get the number of units

cout << "Number of units [100]: ";

int numUnitsInput;

cin >> numUnitsInput;

if (numUnitsInput == 0) numUnitsInput = 100; //default to 100

limitOrder.units(numUnitsInput);

// get whether it's a buy or a sell

cout << "(B)uy or (S)ell : ";

string buySell;

cin >> buySell;

bool buy = true; // default to buy

if (strcmp(buySell.c_str(), "") != 0) buy = (buySell[0] == 'B');

if (!buy) limitOrder.units(-1 * limitOrder.units()); // negative units

for a sell

// get the price

double defaultQuote = buy?g_rateTable->getRate(pair).ask():

g_rateTable->getRate(pair).bid();

cout << "Quote [" << defaultQuote << "]: ";

double quote;

cin >> quote;

if (quote == 0) quote = defaultQuote;

limitOrder.price(quote);

// get the duration

cout << "Duration (in hours) [24]: ";

double hours;

cin >> hours;

if (hours == 0) hours = 24;

// since durations are stored as timestamps relative to server time, convert

the

// input hours to seconds and add it to the current server time (which is

// culled from an FXRate, since there's no direct access method)

limitOrder.duration(g_rateTable->getRate(pair).timestamp() + ((long)hours *

3600));

// === create the constructed limit order

cout << "Creating limit order...";

try

{

g_account->execute(limitOrder);

cout << "created successful\n";

}

catch (OAException se)

{

cout << "creation failed: " << se.type() << endl;

}

}

void caseModifyLimitOrder()

{

if (!g_fxclient.isLoggedIn()) return;

// fetch and print a list of the user's open limit orders

vector limitOrders = g_account->getOrders();

if (limitOrders.size() == 0)

{

cout << "Cannot modify: no limit orders currently in place\n";

return;

}

caseListOpenLimitOrders();

// === fetch the limit order to modify

LimitOrder limitOrder;

// get user selection

cout << "Please enter a ticket number or place in list [0]: ";

unsigned int ticket;

cin >> ticket;

// return if the user presses enter or 0

if (ticket == 0) return;

if (ticket <= limitOrders.size())

{

// if the ticket number is low, assume it is a list position

limitOrder = limitOrders.at(ticket - 1);

ticket = limitOrder.orderNumber();

}

else

{

// otherwise, get limit order via ticket number

bool foundTrade = g_account->getOrderWithId(limitOrder, ticket);

if (!foundTrade) // Bail if the trade was not found

{

cerr << "Could not find limit order #" << ticket <<

endl;

return;

}

}

// === modify limit order

double inputDouble;

int inputInt;

long inputLong;

cout << "Units [" << limitOrder.units() << "]: ";

cin >> inputInt;

if (inputInt != 0) limitOrder.units(inputInt);

cout << "Quote [" << limitOrder.price() << "]: ";

cin >> inputDouble;

if (inputDouble != 0) limitOrder.price(inputDouble);

cout << "Lower Bound [" << limitOrder.lowPriceLimit() << "]: ";

cin >> inputDouble;

if (inputDouble != 0) limitOrder.lowPriceLimit(inputDouble);

cout << "Upper Bound [" << limitOrder.highPriceLimit() << "]: ";

cin >> inputDouble;

if (inputDouble != 0) limitOrder.highPriceLimit(inputDouble);

cout << "Stop Loss [" << limitOrder.stopLossOrder.price() << "]: ";

cin >> inputDouble;

if (inputDouble != 0) limitOrder.stopLossOrder.price(inputDouble);

cout << "Take Profit [" << limitOrder.takeProfitOrder.price() << "]: ";

cin >> inputDouble;

if (inputDouble != 0) limitOrder.takeProfitOrder.price(inputDouble);

// get the server time via the timestamp of a fresh FXTick

FXPair eurusd("EUR/USD");

FXTick timestampTick = g_rateTable->getRate(eurusd);

double hours = (limitOrder.duration() - timestampTick.timestamp())

/ (double) (60 * 60);

cout << "Duration [" << hours << "]: ";

cin >> inputLong;

if (inputLong != 0)

limitOrder.duration(inputLong * 3600 + timestampTick.timestamp());

// == submit the modified limit order

cout << "Modifying limit order...";

try

{

g_account->modify(limitOrder);

cout << "modification successful\n";

}

catch (OAException se)

{

cout << "modification failed: " << se.type() << endl;

}

}

 

and some more.....

void caseCancelLimitOrder()

{

if (!g_fxclient.isLoggedIn()) return;

// fetch and print a list of the users open market orders

vector limitOrders = g_account->getOrders();

if (limitOrders.size() == 0)

{

cout << "Cannot modify: no limit orders currently in place\n";

return;

}

caseListOpenLimitOrders();

// === fetch the market order to modify

LimitOrder limitOrder;

// get user selection

cout << "Please enter a ticket number or place in list [0]: ";

unsigned int ticket;

cin >> ticket;

// return if the user presses enter or 0

if (ticket == 0) return;

if (ticket <= limitOrders.size())

{

// if the ticket number is low, assume it is a list position

limitOrder = limitOrders.at(ticket - 1);

ticket = limitOrder.orderNumber();

}

else

{

// otherwise, get market order via ticket number

bool foundTrade = g_account->getOrderWithId(limitOrder, ticket);

if (!foundTrade) // Bail if the trade was not found

{

cerr << "Could not find limit order #" << ticket <<

endl;

return;

}

}

// === cancel the selected limit order

cout << "Cancelling limit order...";

try

{

g_account->close(limitOrder);

cout << "cancellation successful" << endl;

}

catch (OAException se)

{

cout << "cancellation failed: " << se.type() << endl;

}

}

void casePrintRateHistory()

{

if (!g_fxclient.isLoggedIn()) return;

// get the currency pair

cout << endl << "Pair [EUR/USD]: ";

string pairInput;

cin >> pairInput;

FXPair pair;

if (strcmp(pairInput.c_str(), "") == 0) pair.pair("EUR/USD");

else pair.pair(pairInput.c_str());

// get the interval

cout << "Please enter the interval in seconds [5]: ";

long interval;

cin >> interval;

if (interval == 0) interval = 5;

interval *= 1000; // convert to milliseconds

// get the number of ticks

cout << "Please enter the number of ticks (max 500) [100]: ";

int ticks;

cin >> ticks;

if (ticks == 0) ticks = 100; // default to 100 ticks

if (ticks > 500) ticks = 500;

// make the history request

cout << "Requesting desired rate information...";

vector history;

try

{

g_rateTable->getHistory(history, pair, interval, ticks);

}

catch (OAException se)

{

cerr << "request denied: " << se.type() << endl;

return;

}

cout << "request accepted\n\n";

cout << " | | OpenBid |CloseBid | MinBid | MaxBid

\n"

<< "###| Timestamp | OpenAsk |CloseAsk | MinAsk | MaxAsk

\n"

<<

"--------------------------------------------------------------------\n";

for (unsigned int count = 0; count < history.size(); count++)

{

FXHistoryPoint hp = history.at(count);

// convert timestamp time to string

const time_t temp = hp.getTimestamp();

DateString ds = FXClient::timestampToString(temp);

//string timestamp = ctime(&temp);

//timestamp[24] = 0; // chomp newline from time string

printf("%28s %9.5f %9.5f %9.5f %9.5f\n%3i %s %9.5f %9.5f %9.5f %9.5f",

"",

hp.getOpen().bid(),

hp.getClose().bid(),

hp.getMin().bid(),

hp.getMax().bid(),

count + 1,

ds.c_str(),

hp.getOpen().ask(),

hp.getClose().ask(),

hp.getMin().ask(),

hp.getMax().ask());

if (count == history.size() - 1)

{

cout << "(current)";

}

cout << endl;

}

cout << endl;

}

void casePrintMarketPosition()

{

if (!g_fxclient.isLoggedIn()) return;

// get the currency pair

cout << endl << "Pair [all]: ";

string pairInput;

cin >> pairInput;

if (strcmp(pairInput.c_str(), "all") == 0 || strcmp(pairInput.c_str(), "") ==

0)

{

//getPosiiton() for all positions

cout << "\n Pair | Units | Avg. | Profit(base)" << endl

<< "-----------------------------------------" << endl;

vector positions = g_account->getPositions();

for (unsigned int count = 0; count < positions.size(); count++)

{

FXTick positionRate = g_rateTable->getRate(positions.at(count).pair());

printf ("%s %9li %9.4f %13.2f\n",

positions.at(count).pair().pair(),

positions.at(count).units(),

positions.at(count).price(),

positions.at(count).unrealizedPL(positionRate) );

}

}

else

{

//getPosition(...) for a particular position

cout << "\n Pair | Units | Avg. | Profit(base)" << endl

<< "-----------------------------------------" << endl;

FXPair pair(pairInput.c_str());

Position position;

if (g_account->getPosition(position, pair.pair()))

{

FXTick positionRate = g_rateTable->getRate(position.pair());

printf ("%s %9li %9.4f %13.2f\n",

position.pair().pair(),

position.units(),

position.price(),

position.unrealizedPL(positionRate) );

}

else

{

cout << "No current position for " << pair.pair() << endl;

}

}

}

void caseTestProfits()

{

vector positions = g_account->getPositions();

vector positionProfit(positions.size());

vector rates(positions.size());

vector trades = g_account->getTrades();

vector::iterator pitr = positions.begin();

while (pitr != positions.end())

{

rates.at(distance(positions.begin(), pitr)) =

g_rateTable->getRate(pitr->pair());

vector::iterator titr = trades.begin();

while (titr != trades.end())

{

if(pitr->pair() == titr->pair())

{

if(pitr->units() > 0)

{

positionProfit.at(distance(positions.begin(), pitr)) +=

titr->units() * (titr->price() - rates.at(distance(positions.begin(),

pitr)).bid());

}

else

{

positionProfit.at(distance(positions.begin(), pitr)) +=

titr->units() * (titr->price() -

rates.at(distance(positions.begin(), pitr)).ask());

}

}

titr++;

}

cout <pair() << ": Profit(" <<

pitr->unrealizedPL(rates.at(distance(positions.begin(), pitr))) << ") TradeSum

("

<< positionProfit.at(distance(positions.begin(), pitr)) << endl;

pitr++;

}

}

void printMenu()

{

cout << "OANDA FX Client Test v"+VERSION+"\n"

<< "--------------------------\n"

<< "1. List Accounts\n"

<< "2. Print Current Account Information\n"

<< "3. Switch Accounts\n"

<< "4. List Activity Log\n"

<< "\n"

<< "5. Print Current Rate Table\n"

<< "6. Print Currency Rate History\n"

<< "\n"

<< "7. List Open Market Orders\n"

<< "8. Open New Market Order\n"

<< "9. Modify Market Order\n"

<< "10. Close Market Order\n"

<< "\n"

<< "11. List Open Limit Orders\n"

<< "12. Create New Limit Order\n"

<< "13. Modify Limit Order\n"

<< "14. Cancel Limit Order\n"

<< "\n"

<< "15. Print Current Market Positions\n"

<< "\n"

<< "0. Show Menu\n"

<< "99. Quit\n";

}

 

And here's the last of part of the example they gave me....

void establishConnection()

{

g_fxclient.setWithRateThread(true);

/*time_t delay;

delay = 120;

g_fxclient.setTimeout(delay);*/

g_fxclient.login(g_username.c_str(), g_password.c_str());

g_rateTable = g_fxclient.getRateTable();

g_user = g_fxclient.getUser();

g_account = g_user->getAccounts().at(0);

}

void eventLoop()

{

cout << endl;

printMenu();

bool keepgoing = true;

while(keepgoing)

{

cout << endl << "Please choose an option from the menu" << endl < ";

int opt;

cin >> opt;

switch(opt)

{

case (1): caseListAccounts(); break;

case (2): casePrintAccountData(); break;

case (3): caseSwitchAccounts(); break;

case (4): caseListActivityLog(); break;

case (5): casePrintRateTable(); break;

case (6): casePrintRateHistory(); break;

case (7): caseListOpenMarketOrders(); break;

case (8): caseExecuteMarketOrder(); break;

case (9): caseModifyMarketOrder(); break;

case (10): caseCloseMarketOrder(); break;

case (11): caseListOpenLimitOrders(); break;

case (12): caseExecuteLimitOrder(); break;

case (13): caseModifyLimitOrder(); break;

case (14): caseCancelLimitOrder(); break;

case (15): casePrintMarketPosition(); break;

case (20): caseTestProfits(); break;

case (0):

cout << endl << endl; printMenu(); cout << endl; break;

case (99):

cout << "Exiting example program" << endl; keepgoing = false; break;

}

if (!g_fxclient.isLoggedIn())

{

cout << "Connection was terminated, attempting to reconnect...";

establishConnection();

cout << "connection restored" << endl;

}

}

g_fxclient.logout();

}

int main(int argc, char* argv[])

{

if (argc == 3)

{

cout << "Attempting login with username = \""

<< argv[1] << "\"..." << flush;

try

{

g_username = argv[1];

g_password = argv[2];

establishConnection();

}

catch (OAException e)

{

cerr << "login failed: " << e.type() << endl ;

exit(1);

}

cout << "login successful\n";

eventLoop();

}

else

{

cerr << "Usage: " << argv[0] << " " << endl;

}

}

#include

#include

#include

#define WIN32_LEAN_AND_MEAN

#include

#include "FXGame.h"

#ifdef DEBUG

#include "Common.h"

#endif

using namespace std;

using namespace Oanda;

class TSLEvent : public FXRateEvent {

public:

TSLEvent(const FXPair * p)

: FXRateEvent(p)

{

transient(false); // keeps active

}

virtual void handle(const FXEventInfo *ei, FXEventManager *);

virtual bool match(const FXEventInfo *ei);

void setWatch(Account * acc, MarketOrder * market, const double delta);

private:

Account * _acc;

MarketOrder * _market;

double _delta;

double error;

bool _isbuy;

double _sl;

};

void TSLEvent::setWatch(Account * acc, MarketOrder * market, const double delta)

{

_acc = acc;

_market = market;

_delta = delta;

_isbuy = market->units() > 0;

_sl = market->stopLossOrder.price();

}

bool TSLEvent::match(const FXEventInfo *ei)

{

cout << "TSLEvent::match\n";

if(ei->type() != FXIT_Rate) {

cout << "should be throwing an exception" << endl;

return false;

}

FXRateEventInfo * rei = (FXRateEventInfo*) ei;

if(!match_pair(ei)) {

return false;

}

error = rei->tick()->ask()/200000;

bool cond = ( _isbuy

? rei->tick()->ask() - _delta - error > _sl

: rei->tick()->bid() + _delta + error < _sl );

cout << "tick ";

cout << " time " <tick()->timestamp();

cout << " ask " <tick()->ask();

cout << " bid " <tick()->bid();

cout << " matches... " << cond << endl;

return cond;

}

void TSLEvent::handle(const FXEventInfo *ei, FXEventManager *fxem)

{

cout << "TSLEvent::handle\n";

FXRateEventInfo * rei = (FXRateEventInfo*) ei;

MarketOrder nmarket;

bool cond = ( _isbuy

? rei->tick()->ask() - _delta - error > _sl

: rei->tick()->bid() + _delta + error < _sl );

if(!cond) { // captures repeated ticks

return;

}

bool succ = _acc->getTradeWithId(nmarket, _market->ticketNumber());

if(!succ) {

fxem->remove(this);

cout << "dequeing event, market order no longer exists" << endl;

} else {

cout << "modifying ticket " << nmarket.ticketNumber();

cout << " old sl " << _sl;

_sl = ( _isbuy

? rei->tick()->ask() - _delta

: rei->tick()->bid() + _delta );

cout << " new sl " << _sl;

cout << endl;

nmarket.stopLossOrder.price(_sl);

_acc->modify(nmarket);

}

}

class SLEvent : public FXAccountEvent {

public:

SLEvent(int tlink, FXEvent * event, RateTable * rates)

: FXAccountEvent("Stop Loss")

, _tlink(tlink)

, _event(event)

, _rates(rates)

{

cout << "watching sl on ticket " << tlink << endl;

transient(true);

}

virtual bool match(const FXEventInfo * ei)

{

FXAccountEventInfo * aei = (FXAccountEventInfo*) ei;

cout << " checking " <transaction()) << endl;

bool res = match_transaction_type(ei)

&& (aei->transaction()->link()

== _tlink);

cout << " result is " << res << endl;

return res;

}

virtual void handle(const FXEventInfo *, FXEventManager *)

{

cout << "removing the rate tracking event" << endl;

_rates->eventManager()->remove(_event);

}

private:

int _tlink;

FXEvent * _event;

RateTable * _rates;

};

int main(int argc, char* argv[])

{

FXGame fxgame;

#ifdef DEBUG

//Common::setLogMode("SCREEN");

#endif

char* username=argv[1];

char* password=argv[2];

char* withthrd=argv[3];

fxgame.setWithRateThread(true); // needs thread to operate

cout << "creating rate thread" << endl;

while(1)

{

try

{

fxgame.login(username,password);

}

catch(OAException e)

{

cout << "sample1: caught exception type=" << e.type() << endl;

cout << "sample1: unable to connect, retrying...." << endl;

Sleep(5000);

continue;

}

break;

}

const char * base = "GBP";

const char * quote = "JPY";

FXPair mypair(base,quote);

TSLEvent myevent(&mypair);

User * user = fxgame.getUser();

Account * myaccount = user->getAccounts()[0];

RateTable * rates = fxgame.getRateTable();

FXTick mytick = rates->getRate(mypair);

const double delta = (mytick.ask() - mytick.bid())*2.2;

MarketOrder market;

market.units(3);

market.base(base);

market.quote(quote);

market.price((market.units() > 0 ? mytick.ask() : mytick.bid()));

market.stopLossOrder.price((market.units() > 0

? market.price()-delta

: market.price()+delta));

myaccount->execute(market);

SLEvent slevent(market.ticketNumber(),&myevent,rates);

myevent.setWatch(myaccount,&market,delta);

rates->eventManager()->add(&myevent);

myaccount->eventManager()->add(&slevent);

Sleep(2000000);

fxgame.logout();

return 0;

}

 

Please!!! Anybody that can help, I feel so lost looking at this and I really want to use Oanda's API since the spreads are much cheaper there and they don't have the requotes and restrictions about where you can put your orders in at.

 

Is there nobody here that understands this?

Reason: