Forex



Go Back   Forex Trading > Discussion Areas > Setup Questions
Forex Forum Register More recent Blogs Calendar Advertising Others Help






Register
Welcome to Forex-TSD!, one of the largest Forex forums worldwide, where you will be able to find the most complete and reliable Forex information imaginable.

From the list below, select the forum that you want to visit and register to post, as many times you want. It’s absolutely free. Click here for registering on Forex-TSD.

Exclusive Forum
The Exclusive Forum is the only paid section. Once you subscribe, you will get free access to real cutting-edge Trading Systems (automated and not), Indicators, Signals, Articles, etc., that will help and guide you, in ways that you could only imagine, with your Forex trading.
  • Elite Section
    Get access to private discussions, specialized support, indicators and trading systems reported every week.
  • Advanced Elite Section
    For professional traders, trading system developers and any other member who may need to use and/or convert, the most cutting-edge exclusive indicators and trading systems for MT4 and MT5.
See more

Reply
 
Thread Tools Display Modes
  #1 (permalink)  
Old 04-10-2007, 10:07 AM
Willis11of12's Avatar
Senior Member
 
Join Date: Dec 2005
Posts: 105
Willis11of12 is on a distinguished road
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!

Quote:
/*
Example 2
Comprehensive example of use of the FXTrade API
Ported from Java by Chris MacGregor, January 2006
*/

#include <iostream>
#include <string>
#include <vector>
#include "FXGame.h"
#include <stdio.h>
#include <stdlib.h>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>


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<Account*> 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 : " << account->accountName() <<
endl
<< "Account ID : " << account->accountId() << endl
<< "Acct. Creation Date: " << account->createDate() << endl
<< "Margin rate : " << account->marginRate() << endl
<< "Home Currency : " << account->homeCurrency() <<
endl;
}
}


void caseSwitchAccounts()
{
if (!g_fxclient.isLoggedIn()) return;

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

vector<Account*> 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<MarketOrder> 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<LimitOrder> 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<Transaction> 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 [b]: ";
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;
}
}
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!StumbleUpon this Post!Reddit this Post!Facebook this Post!BlinkList this Post!Google Bookmarks this Post!Yahoo! My Web this Post!
Reply With Quote
  #2 (permalink)  
Old 04-10-2007, 10:08 AM
Willis11of12's Avatar
Senior Member
 
Join Date: Dec 2005
Posts: 105
Willis11of12 is on a distinguished road
more...

here's more of it:

Quote:
void caseModifyMarketOrder()
{
if (!g_fxclient.isLoggedIn()) return;

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

vector<MarketOrder> 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<MarketOrder> 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 [b]: ";
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<LimitOrder> 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;
}
}

Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!StumbleUpon this Post!Reddit this Post!Facebook this Post!BlinkList this Post!Google Bookmarks this Post!Yahoo! My Web this Post!
Reply With Quote
  #3 (permalink)  
Old 04-10-2007, 10:10 AM
Willis11of12's Avatar
Senior Member
 
Join Date: Dec 2005
Posts: 105
Willis11of12 is on a distinguished road
and some more.....

Quote:
void caseCancelLimitOrder()
{
if (!g_fxclient.isLoggedIn()) return;

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

vector<LimitOrder> 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<FXHistoryPoint> 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<Position> 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<Position> positions = g_account->getPositions();
vector<double> positionProfit(positions.size());
vector<FXTick> rates(positions.size());
vector<MarketOrder> trades = g_account->getTrades();

vector<Position>::iterator pitr = positions.begin();
while (pitr != positions.end())
{
rates.at(distance(positions.begin(), pitr)) =
g_rateTable->getRate(pitr->pair());
vector<MarketOrder>::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 << pitr->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";
}

Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!StumbleUpon this Post!Reddit this Post!Facebook this Post!BlinkList this Post!Google Bookmarks this Post!Yahoo! My Web this Post!
Reply With Quote
  #4 (permalink)  
Old 04-10-2007, 10:11 AM
Willis11of12's Avatar
Senior Member
 
Join Date: Dec 2005
Posts: 105
Willis11of12 is on a distinguished road
And here's the last of part of the example they gave me....

Quote:
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] << " <username> <password>" << endl;
}
}



#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#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 " << rei->tick()->timestamp();
cout << " ask " << rei->tick()->ask();
cout << " bid " << rei->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 " << *(aei->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;
}
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!StumbleUpon this Post!Reddit this Post!Facebook this Post!BlinkList this Post!Google Bookmarks this Post!Yahoo! My Web this Post!
Reply With Quote
  #5 (permalink)  
Old 04-10-2007, 10:13 AM
Willis11of12's Avatar
Senior Member
 
Join Date: Dec 2005
Posts: 105
Willis11of12 is on a distinguished road
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.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!StumbleUpon this Post!Reddit this Post!Facebook this Post!BlinkList this Post!Google Bookmarks this Post!Yahoo! My Web this Post!
Reply With Quote
  #6 (permalink)  
Old 04-10-2007, 07:54 PM
Willis11of12's Avatar
Senior Member
 
Join Date: Dec 2005
Posts: 105
Willis11of12 is on a distinguished road
Is there nobody here that understands this?
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!StumbleUpon this Post!Reddit this Post!Facebook this Post!BlinkList this Post!Google Bookmarks this Post!Yahoo! My Web this Post!
Reply With Quote
Reply

Bookmarks


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Welcome to the MQL4 course codersguru Metatrader 4 mql 4 - Development course 124 10-12-2009 01:45 AM
Lost magic number and comment after partially closing GP2X Metatrader 4 4 10-09-2006 03:38 AM
Lost in TimeZone et_phonehome_2 General Discussion 1 08-16-2006 09:03 PM
www.mql4.com DeSt Metatrader 4 18 02-02-2006 12:59 AM


All times are GMT. The time now is 09:26 PM.



Search Engine Friendly URLs by vBSEO 3.2.0 ©2008, Crawlability, Inc.