StrategyQuant
Q AI AssistantAlgoCloudQuantAnalyzerQuantDataManager
Free CourseCompany
BlogDocumentationForumContact us
BlogMarketplace
Log in
Create free account

Product

  • Pricing & licenses
  • Learn
  • Marketplace
  • Start free trial

Legal

  • Terms of Service
  • Privacy Policy
  • Cookies

Contact

[email protected]

Company

StrategyQuant s.r.o.

Korunní 2569/108, Vinohrady, 101 00 Praha 10, Czech Republic, EU

IČ: 04000498

DIČ: CZ04000498

Social

  • Legal Notice | PROCESSING AND PROTECTION OF PERSONAL DATA

    Past performance is no guarantee of future success. All information should be viewed as educational only

    UNITED STATES Disclaimer required by Government - Commodity Futures Trading Commission informs: Futures and options trading have great potential rewards, but also great potential risk. You must be aware of the risks and be willing to accept them in order to invest in the futures and options markets. Don't trade with money you can't afford to lose. This is neither a solicitation nor an offer to buy/sell futures, shares or options on the same. No representation is being made that any account will or is likely to realise profits or losses similar to those discussed in this document. The past performance of any trading system or methodology is not necessarily indicative of future results.

    CFTC RULE 4.41 - HYPOTHETICAL OR SIMULATED PERFORMANCE RESULTS HAVE CERTAIN LIMITATIONS. UNLIKE A RECORD OF ACTUAL PERFORMANCE, SIMULATED RESULTS DO NOT REPRESENT ACTUAL TRADING. ALSO, SINCE THE TRADES WERE NOT EXECUTED, THE RESULTS MAY HAVE OFFSET THE IMPACT, IF ANY, OF CERTAIN MARKET FACTORS, SUCH AS LACK OF LIQUIDITY. SIMULATED TRADING PROGRAMMES IN GENERAL ARE ALSO SUBJECT TO THE FACT THAT THEY ARE DESIGNED WITH THE BENEFIT OF HINDSIGHT. NO REPRESENTATION IS BEING MADE THAT ANY ACCOUNT WILL OR IS LIKELY TO REALISE PROFITS OR LOSSES SIMILAR TO THOSE SHOWN.

    NO REPRESENTATION IS BEING MADE THAT ANY ACCOUNT WILL, OR IS LIKELY TO, REALISE PROFITS OR LOSSES SIMILAR TO THOSE DISCUSSED WITHIN THIS SITE. IF YOU DECIDE TO INVEST REAL MONEY, ALL TRADING DECISIONS IN THE FINANCIAL MARKETS SHOULD BE YOUR OWN.

    © StrategyQuant 2026

    Powered by Klaudie.ai

    Back to marketplaceDIGITAL

    Close All positions except one

    StrategyQuantPlugins
    Close All positions except one

    Close all open positions matching specified criteria while keeping one protected by magic number. Useful for selective portfolio management and risk control in multi-position trading strategies.

    Close All positions except one : the selected “Magic Number Excluded”

    package SQ.Blocks.Order.Close;
    import SQ.Functions.OrderFunctions;
    import SQ.Internal.ActionBlock;
    import com.strategyquant.lib.*;
    import com.strategyquant.datalib.*;
    import com.strategyquant.tradinglib.*;
    // Modified in France by Emmanuel Evrard for the StrategyQuantX Community :)
    @BuildingBlock(returnType = ReturnTypes.Action)
    @Help("Close All positions except one")
    @SortOrder(600)																			// In AlgoWizard, this is a dropbox position (400 or 500 or 600 etc.) of this function in the menu of "Add New Condition", you may have to adjust it depending on the function already installed on the same dropbox. 
    @IgnoreInBuilder
    @NotSupportedFor(engines="EL")
    public class CloseAllPositionsExcept extends ActionBlock 
    {
        @Parameter(defaultValue="Current", category="Order identification", showIfDefault=false, allowAny=true)
        public String Symbol;
        @Parameter(defaultValue="1", category="Order identification", showIfDefault=false)
        @Editor(type=Editors.Selection, values="Long=1,Short=-1,Any=0")
        public int Direction;
        @Parameter(defaultValue="MagicNumber", category="Order identification", showIfDefault=false)
        @Help("Magic number that can identify the order.")
        @Editor(type=Editors.SelectionVariablesWithAny)
        public int MagicNumber;
        @Parameter(defaultValue="MagicNumber", category="Order identification", showIfDefault=false)
        @Help("MagicNumber of the Excluded order, this order will not be closed")
        @Editor(type=Editors.SelectionVariables)
        public int MagicNumberExcluded;
        //@Parameter(defaultValue="", category="Order identification", showIfDefault=false)
        //@Help("Comment can be also used to identify the order. In case of Comment, order matches if the order comments contains the text specified here.")
        public String Comment;
        //------------------------------------------------------------------------
        //------------------------------------------------------------------------
        //------------------------------------------------------------------------
        public CloseAllPositionsExcept() 
        {
        }
        //------------------------------------------------------------------------
        @Override
        public void OnAction() throws TradingException 
        {
            int total = Strategy.Trader.getOpenOrdersCount(false);
            for(int i=total-1; i>=0; i--) 
            {
                ILiveOrder order = Strategy.Trader.getOpenOrder(i, false);
                if(OrderFunctions.identify(order, Strategy, Symbol, Direction, MagicNumber, Comment)) 
                {
                    if (order.getMagicNumber() != MagicNumberExcluded)	
                    {
                        order.setExitIndex((byte) -1);
                        order.Close(OrderCloseTypes.ExitSignal);
                    }
                }			
            }
        }
    }
    
    Past performance is no guarantee of future success. All information should be viewed as educational only UNITED STATES Disclaimer required by Government - Commodity Futures Trading Commission informs: Futures and options trading have great potential rewards, but also great potential risk. You must be aware of the risks and be willing to accept them in order to invest in the futures and options markets. Don't trade with money you can't afford to lose. This is neither a solicitation nor an offer to buy/sell futures, shares or options on the same. No representation is being made that any account will or is likely to realise profits or losses similar to those discussed in this document. The past performance of any trading system or methodology is not necessarily indicative of future results. CFTC RULE 4.41 - HYPOTHETICAL OR SIMULATED PERFORMANCE RESULTS HAVE CERTAIN LIMITATIONS. UNLIKE A RECORD OF ACTUAL PERFORMANCE, SIMULATED RESULTS DO NOT REPRESENT ACTUAL TRADING. ALSO, SINCE THE TRADES WERE NOT EXECUTED, THE RESULTS MAY HAVE OFFSET THE IMPACT, IF ANY, OF CERTAIN MARKET FACTORS, SUCH AS LACK OF LIQUIDITY. SIMULATED TRADING PROGRAMMES IN GENERAL ARE ALSO SUBJECT TO THE FACT THAT THEY ARE DESIGNED WITH THE BENEFIT OF HINDSIGHT. NO REPRESENTATION IS BEING MADE THAT ANY ACCOUNT WILL OR IS LIKELY TO REALISE PROFITS OR LOSSES SIMILAR TO THOSE SHOWN. NO REPRESENTATION IS BEING MADE THAT ANY ACCOUNT WILL, OR IS LIKELY TO, REALISE PROFITS OR LOSSES SIMILAR TO THOSE DISCUSSED WITHIN THIS SITE. IF YOU DECIDE TO INVEST REAL MONEY, ALL TRADING DECISIONS IN THE FINANCIAL MARKETS SHOULD BE YOUR OWN.
    Free

    Files

    • Snippet-CloseAllpositionsexceptone.sqm4 KBLocked

    Download unlocks after purchase or with an active tier.

    Details
    Version1.0.0
    PublishedOctober 19, 2026
    Last updatedOctober 22, 2026
    AppSQ
    TypeSnippet
    AuthorEmmanuel
    App version145.3058
    Codebase categoryOrder