Saturday, September 26, 2009

Forex Robot Mania

As suggested in my last post...

As a side note, I'm planning to make opposing robots this weekend. They will trade long and short positions in different sub-accounts.
I've put together yet another robot. It will trade the same currency both long and short in separate sub-accounts. I'll have to wait until Monday or Tuesday to activate it.

A few points I feel are worth mentioning:
  • I've been developing software and systems for my entire career -- I don't expect everyone can just snap together trading robots.
  • There are rate limitations, position size limitations and margin use limitations built into a common framework used by all the robots I'm putting together.
Anyway, each robot I make has customizations in several areas. Basically these all involve trade entry and exit conditions -- which can range from very simple to very complex.

Here is a chunk of common code used in each of my robots. Basically, I call the set of information relating a sub-account and a currency pair a trading context. Here is part of a function that gathers this context:

// ***************************************************
// Given strings representing the account to trade and
// the pair to be traded generate a trading context.
// ***************************************************
function getTradingContext(useacct,usepair)
// Determine account ID from it's name
// -----------------------------------
var acctid = 0;
for (id in accounts)
if ( accounts[id].name == useacct )
acctid = id;

if ( acctid == 0 )
write("Account name '" + useacct + "' not found!");
return null;

// Capture sub-account details in the trading context
// --------------------------------------------------
var myContext = accounts[acctid];

Once we have the account details we can determine various trading limitations. Here I use the account balance as well as manually controlled "reserve" and "release" values that determine default lot size and margin limit values:

   // Calculate various balance values for various purposes
// -----------------------------------------------------
reserve = 0.00;
release = 0.00;
bal = myContext.balance;

// Avoid silly mistakes
// --------------------
if ( release > reserve )
release = reserve;

lsbal = bal - reserve; // lot balance
trbal = bal - reserve + release; // margin balance

ls = (lsbal/20) / 100000; // lots size
ml = trbal * 0.099; // margin limit

myContext.reserve = reserve;
myContext.release = release;
myContext.lsbal = lsbal;
myContext.lotsize = ls.toFixed(5);
myContext.trbal = trbal;
myContext.marginlimit = trbal * 0.095;

Before a trade can be made the current account margin usage will be compared to the margin limit determined above. When a trade is made the default size of the trade is the lot size determined above. Some other items loaded into the context are shown here:

   // Capture currency pair details
// -------------------------------
myContext.usepair = usepair;
myContext.pair = pairs[usepair];
myContext.pipsize = pairs[usepair].pip;
myContext.spread = pairs[usepair].ask-pairs[usepair].bid;

// Set a spread limit for various currencies
// -----------------------------------------
myContext.spreadlimit = (4.26 * myContext.pipsize);
if ( usepair == "CHFJPY" )
myContext.spreadlimit = (2.26 * myContext.pipsize);
if ( usepair == "USDJPY" )
myContext.spreadlimit = (2.26 * myContext.pipsize);
if ( usepair == "EURUSD" )
myContext.spreadlimit = (2.01 * myContext.pipsize);

Including the currency pair information, especially the spread, is significant. For example, I do not let my robots trade when the spread is above certain values. This is because higher spreads are generally present when significant news events occur.

Later in my robots, in a function that is called when price changes are detected, I'll have something like the following:

   longctx = getTradingContext("sub1",currentPair);
if ( longctx )

shortctx = getTradingContext("sub2",currentPair);
if ( shortctx )

Generally, I'll use short term charts and limit robot operations to the opening of a new candle. This avoids needless processing but how you activate your trading functions is up to you. Notice how I can simply pass the context, as developed above, into a trading function? The trading functions have the job of deciding whether or not to open a position in a sub-account that it controls. It may or may not use all the details available to it.

There you go. While this isn't complete it is by far the majority of a basic robot framework. If you are a programmer you simply have to figure out the trading rules to apply and write one or more functions that embodies those rules. For example, you may want to apply indicators to a chart, examine previously opened orders, or even trigger an email signal.

Hey, as a bonus for reading this far, here is a function that examines current open orders to see how many fall within a price range. Basically, I use this function to make sure that my robots aren't able to accumulate positions around any particular price point. Notice that one of the parameters is the trading context developed above.

// ***************************************************
// How many orders are open between min an max prices?
// ***************************************************
function rangeOrderQty(ctx,min,max)
var qty=0;

for (ticket in activeOrders)
if ( activeOrders[ticket].accountId != )
if ( activeOrders[ticket].pair != ctx.usepair )

if ( activeOrders[ticket].price >= min
&& activeOrders[ticket].price <= max )
return qty;

Finally, the previous code is for the FxSpyder trading platform. This is what I'm using to write robots these days. I continue to trade via Oanada.

Friday, September 25, 2009

Friday Market Analysis

I am following CNBC regularly (via their web site) these days. I see many of the pundits advocating panic and doom. I suspect they all want to be able to claim they were right when we finally do experience some type of pullback.

However, these braying naysayers of doom really don't have much of import to say. All they really do is act as large forces on the emotions of market players. Everyone is appropriately skittish due to the massive bear movements over the last year or more. It's only natural.

All of these fools who only imagine one direction for the markets will be right from time to time. What they say is not important. What's important is to understand the volatility, or level of price fluctuation, and the amount of risk that this implies when you are trading.

For example, the odd negative number here and there doesn't mean all that much. This doesn't mean the market won't throw a tantrum, but it does mean that there could be a spate of good numbers in another week or two. These trends have variations in them as well. Perhaps because the media jumps on whichever bandwagon has the most passengers the market sentiment gets rapidly overblown.

So, sure, we could see some type of sell-off coming soon. So what? So, don't risk all your money on the notion that the markets, carry trades, risk appetite, GDP growth, corporate profits or whatever will only go up. In fact, cushion yourself by assuming a mini-panic could be right around the corner. Seriously, hasn't everyone been hiding under their sheets due solely to the fact that we're in September?

What am I going to do? I'm going to move more capital into my account. Any serious downtown represents a good opportunity to scale in. So, let it rain, I'm going to wait until all the overextended or panicked fools get forced out, then I'm going to take a peck at an opportunity here and there. Again, just make sure to nibble your way in at appropriate times.

Remember, fear and downward movement provides opportunity, but only if you don't assume you can predict the bottom and thus assume too much risk. When you aren't being pushed into making decisions by market movements you can make much better decisions.

So, early next week, fresh capital into my account. I can apportion this to my robot trading army (I know, but it sounds more fun this way) in small chunks as we come up to significant resistance levels. Unless the world collapses, and if it does my trading account will be the least of my worries, there will eventually be another upturn.

As a side note, I'm planning to make opposing robots this weekend. They will trade long and short positions in different sub-accounts. I expect that one of the two will be earning during up or down movements. I expect both of them will earn during periods that the market is moving sideways. You can't see it but I'm rubbing my hands together in a greedy manner -- think Mr Burns.

Good luck out there.

Thursday Robot Recap

Thursday was a very slow day.

The market was down. The yen crosses took a dive. Everyone is getting antsy about stocks, news reports, and the month of September. OMG, the risk! My robot snoozed for much of the day and had little chance to earn anything useful.

However, amidst all the whining I have to realize that being up about 4.5% for the week isn't so bad.

Regardless, I did tweak things a tiny amount. Basically, the idea is to keep the robot trading for a while longer during downturns. This can be done by shaving a little bit off of positions and forcing a little bit more space between trades.

It seems like a good trade-off. Earn a small fraction less during good days but enable more trading on poorer days. If things don't work out it will be very easy to reverse these minor tweaks.

I also created a new robot this evening. Of course, it's based on the current system, but somewhat simplified. It's running on it's own sub-account with a tiny amount of capital. So, rather than attempting major adjustments on something that is already proven, I'll once again get into an A/B situation and see if there is a clear winner between the two.

On another note, I'm wondering how simple a robot can be and still be effective. Something to ponder as I drift off this evening.

Thursday, September 24, 2009

Wednesday Status

Wednesday was a slow day.

The AUDJPY was very quiet, which left little opportunity for my robot to extract revenue. In fact, with the DOW drop at the end of the trading day today we may be looking at a bit of a downward correction over the next little while.

My robot is not very active during downward movements. So, I'll get bored, worry about long term profitability, and otherwise be motivated to "do something" or "fix something" when I shouldn't. I must resist!

Anyway, while today was very slow, my currency trading robot did pull in 1.1% with over 4.3% for the week.

On a different note, I need to name my trading system. It would be nice to call it something other than "robot" every day. I could name it ARTFAB (A Rising Tide Floats All Boats) or something? Hmm, maybe FARTBAD or BADSINE?

Hey, BREAD might work... Basic Robot Earning All Day. Okay, tentatively, BREAD v1.0 is on the job. Unfortunately, bread is pretty passive, getting sliced, diced and toasted regularly. Zzzzz. I'll sleep on it.

Tuesday, September 22, 2009

Monday Robot Review

If you are a new visitor I should let you know I'm reviewing my own proprietary forex robot -- I'm not providing a general review of robots.

The Good
Profitability continues. Sunday evening the robot earned 0.2% and over the course of Monday it earned 2.0% return. It's not obvious, but when capital is added to the robot old smaller positions provide less return when closed profitably. This means that it will take a little while to flush out those old trades and get accurate profitability numbers.

The Bad
The newly added meta-trading aspect didn't work. Well, I was able to get meta-trades to open in a separate account, but the platform hung after each purchase. I don't know if it's a platform issue or if I did something inappropriate with my code. Perhaps next weekend I'll have a chance to ferret out the details.

The Pending
The robot hasn't yet been in a situation where it has had to stop trading due to accumulated risk. So, at this point, I haven't had a chance to test the notification system under live conditions.

Sunday, September 20, 2009

Weekend Robot Development II

While not fully tested, as the market isn't open for trading, I have also completed both the meta-robot concept and a notification system.

The meta-robot will look at the trades made via the current profitable robot and impose rules that require trades to open at a better price. The required difference, in pips, will be divided in two and added to the meta-robot's take profit point. For example, if the existing robot makes 6 pips on a position then the new meta-robot may open two pips lower and require a take profit of 7 pips.

The combination of a lower entry point and a lower take profit point imply that the meta-robot will always get a better deal. It will also have a higher chance of getting out of it's positions faster. Heh, nothing wrong with making pips faster! Of course, this also implies that the meta-robot may have less ability to open positions as better priced positions may not always be available. There is a bit more complexity to it but I won't bore you with the details.

Anyway, as usual, real life trading will tell the real story.

Finally, the notification system is implemented as a request to a web site. The web site will be able to look at the request parameters and decide what to do. For now, the web site does nothing interesting. Once I've seen the system in action for a while, and I decide it's working well and that it's useful, I'll see about putting more effort into a delivery system.

Saturday, September 19, 2009

Weekend Robot Development

Now that the weekend is here it's time to put on the thinking cap and figure out how to increase earnings, reduce risk or both.

As mentioned in a reply to a comment on the previous post I've reallocated funds, put in a reserve amount and added a manual release amount.

The reserve amount holds back capital from the lot size calculation and the total margin available calculation. This capital is ignored such that the robot acts as if it only has balance - reserve under management.

The release amount, if any, adds capital into the margin available calculation but does not change the lot size calculation. The purpose of this is allow a series of discretionary actions to reactivate the robot once it has stopped trading due to an extended period of unhelpful price movement without adjusting the risk per trade.

The amount of capital released can be reduced as the price moves in a profitable direction. I'm also hoping that the robot will earn above it's target rate so that some capital can be painlessly shifted to reserved status each week.

Unfortunately, all of this might make it harder to report standard profitability numbers. Whether rightly or wrongly I'm going to use the unreserved capital balance as the measurement value of the account. It's what the lot size is based on and I intend to grow that amount X% per week. I'll also be using that value for my theoretical compounding calculations.

Remaining on the burner are concepts such as the meta-robot and email notifications to be issued when the meta-robot identifies various conditions suitable for discretionary decisions. If these turn out to be useful I might even set up some type of free mailing list.

Wednesday, September 16, 2009

Forex Robot Wars

As you can see by my last few posts I've had a couple of trading robots slugging it out for the last few days.

I'm happy to announce that the latest robot has absolutely thrashed my initial robot. Here are the recent earnings for this week:

    Sun 0.19%
    Mon 3.23%
    Tue 3.16%
    Wed 3.26%
Obviously, I'm going to retire the previous robot, which earned at an average pace of approximately 0.5% per day, and allocate it's funds to the newer robot.

The next question is... can I find ways to improve this robot's operation? I'll have to think about that.


I do have an improvement idea. Basically, use the trading and positions of one account to act as signals for another account. This way you can spot the inefficiencies in one and adjust for them with another -- while coding for them directly might require much more effort.

I foresee a second robot that would open less positions but at a higher rate of risk. It could potentially have better performance characteristics based on what I'm seeing happen on my charts.

Maybe I'll dub this concept "meta-robot" in the event that I eventually build it and post about it.

Monday, September 14, 2009

Two Live Robots

Sunday evening I unleashed another trading robot.

Here's how I set up my sub-accounts to do this in a reasonably safe manner.

  • My initial or primary account is used to add or remove funds.
  • Each robot trades in it's own sub-account
This let's me track the returns for each robot in a trivial manner. It also means that each robot is 100% independent.

If you do this be sure to name your sub-accounts in a neutral manner. Personally, I'd be tweaked if I ended up with names related to robots that were eventually no longer in use.

Now that I have multiple robots I can do A/B testing between robots, under various conditions, and then scale funds into the robot that seems to be working best.

What are the results?

Currently, since last night, my new robot has about five times the return of my older robot. It's already over 2% for today. However, I do expect that this robot to be unable to trade in conditions that the slower robot is able to exploit. I have a turtle vs hare experiment here.

For those of you who may be new to my blog I trade with Oanda. I haven't purchased their API since I am using the FxSpyder platform for that instead. The FxSpyder software still has a few rough edges but I am comfortable with it. Finally, for discretionary trading I still prefer the Oanda platform.

Update: This robot finished up over 3.2% today!

Saturday, September 12, 2009

Oanda Robot Trading -- Cost Efficiently

If you are trading with Oanda, as I am, you are probably aware that you have to trade a fair amount before their monthly API fees are waived.

However, there is an alternative. The first time I tried their platform, probably shortly after it was released, I didn't find it very inviting. However, about a month ago I tried again. Guess what? While I might not use the platform for discretionary trading it seems like a good option for robot trading.

Which platform am I talking about? FxSpyder of course. While using FxSpyder with Oanda isn't free the cost is much less than Oanda's API fee.

FxSpyder connects to your Oanda account and can be used as a manual trading platform. While you won't find it exactly the same as what you are used to, that has no bearing on whether or not you'll be able to use it for robot trading.

Now, don't get all excited, robot trading doesn't seem to be the way to instant riches. Well, at least not with the robot that I've written and am trading with. At the moment my average return is about 0.5% per trading day -- this includes the partial trading days on Sunday and Friday.

Compared to traditional investments this represents a ridiculous rate of return. Assuming 20 trading days a month that would equate to 10% per month, compounded. I'm working on improving this but find that it's harder than it sounds. This is partially because my work and family duties keep me far busier than I am used to.

In short, I've got ideas but little time to implement them. Some day I hope I'll be able to transition to trading, or at least tweaking my robots, as my full time job. It would certainly give me back a lot of my time.