Matlab Design

This is on how to take your first thought and turn it into a good design. Good design for the sake of easy tweaking, gaining confidence that there are no bugs, and making it easy to tell what’s going on after not looking at the code for a while. Explains the process from an atomic alpha idea, to a full system, to tweaking the strategy and execution. Shows how to go from your first thought to the most natural final design.

Three parts: 1 on the basic structure, 2 on a more adaptable FSM design, 3 on managing complexity as new functionality is added. To be followed in order.

Let’s say you think of a strategy. Your first thought on how a system to trade it might look is,

%system.m
import API
global VARS
parameters
API.connect
API.registercallbacks
API.subscribebars
while(true)
strategy()
wait(1)
end
%strategy.m
function()
p=getnewprice
if(signal(p))
buy
wait(60)
sell
end

Or if you know something about APIs it might be,

%system.m
import API
global VARS
parameters
API.connect
API.registercallbacks
API.registerstrategycallback
API.subscribebars
%strategycallback.m
function(newprice)
if(signal(newprice))
buy
wait(60)
sell
end

This design fits strategies that react to every bar. The loop design fits strategies that need to aggregate data from multiple sources and react to it periodically.

Actually the first design doesn’t work in Matlab because it’s single-threaded. You have to schedule the strategy function to run periodically rather than having it in a while loop which blocks the API’s software callbacks,

%system.m
import API
global VARS
parameters
API.connect
API.registercallbacks
API.subscribebars
timer(timerfcn, @strategy, 'period', 1)
%strategy.m
function()
p=getnewprice
if(signal(p))
buy
wait(60)
sell
end

These are generally the forms you use when you want to throw together a new system in a day. The loop/timer design works better for things signals that need external clock synchronization, perhaps aggregating multiple data streams or having long sequential logic. You can get a good software development or plugin . The event/callback-driven design works better for signals that are based on a single data source, or absolutely need the most up-to-date-data, or are just very simple and have no external dependencies. Tiered structures, with some processing in the callback before combination in the loop.

Like what you read? Give Pepe López a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.