WealthScript Techniques | Portfolio-wide conditions

Modified on 2017/05/22 18:44 by Administrator — Categorized as: Knowledge Base

The problem

"I am working on a day-trading strategy that operates on a portfolio of symbols.

I would like to be able to read and write variables that operate across the entire portfolio, and are evaluated sequentially in time.

Example: after I get two losing short trades in the same day, set a dont_trade_short flag, always checked before opening a new position, and cleared when the date changes."

The approach

Strategy execution in Wealth-Lab runs the Strategy per bar per symbol. However, for this kind of task you would like to modify the execution loop order. It is possible in Single Symbol Mode by looping through all of the DataSet's components.

Below is a symbol-per-bar example:

Code example

Run the Strategy below in Single Symbol Mode by clicking the symbol with the most complete history in a DataSet:


using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using WealthLab;
using WealthLab.Indicators;

namespace WealthLab.Strategies { public class MyStrategy : WealthScript { private bool dont_trade = false; // here's your "global" private bool SymbolIsActive(string sym) { foreach (Position p in ActivePositions) if( sym == p.Bars.Symbol ) return true; return false; } protected override void Execute() { for(int bar = 20; bar < Bars.Count; bar++) { // Entry logic foreach (string sym in DataSetSymbols) { if( !dont_trade && !SymbolIsActive(sym) ) { SetContext( sym, true ); if (Bars.FirstActualBar > bar) continue; SMA sma = SMA.Series( Close, 20 ); if( CrossOver( bar, Close, sma ) ) BuyAtMarket( bar+1, "SMA CrossOver" ); } } RestoreContext(); // Exit logic int loserCount = 0; for( int p = ActivePositions.Count - 1; p >= 0; p-- ) { Position pos = ActivePositions[p]; if( bar >= pos.EntryBar ) { string sym = pos.Bars.Symbol; SetContext( sym, true ); SMA sma = SMA.Series( Close, 20 ); if( CrossUnder( bar, Close, sma ) ) { SellAtMarket( bar+1, pos, "Time-Based" ); if( pos.NetProfitPercent < 0 ) loserCount++; } } } dont_trade = (loserCount >= 2); } } } }