/* MI newsletter automation v1.0 beta. Pure parsing and validation; no network. */ var MINewsletter = (function () { "use strict"; function requireThat(ok, reason) { if (!ok) throw new Error(reason); } function text(html) { return html.replace(/<(script|style)\b[\s\S]*?<\/\1>/gi, '') .replace(/<[^>]*>/g, ' ').replace(/"/g, '"').replace(/'|'/g, "'") .replace(/</g, '<').replace(/>/g, '>').replace(/ /g, ' ') .replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16))) .replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n))).replace(/&/g, '&'); } function canonical(v) { if (Array.isArray(v)) return '[' + v.map(canonical).join(',') + ']'; if (v && typeof v === 'object') return '{' + Object.keys(v).sort().map(k => JSON.stringify(k) + ':' + canonical(v[k])).join(',') + '}'; return JSON.stringify(v); } // Parse JSON without silently accepting duplicate keys. Never eval mail content. function parseAt(s, start) { let i = start; function ws() { while (/\s/.test(s[i] || '') && i < s.length) i++; } function val(depth) { requireThat(depth < 35, 'JSON nesting limit'); ws(); if (s[i] === '"') { const a = i++; while (i < s.length) { if (s[i] === '\\') { i += 2; continue; } if (s[i++] === '"') return JSON.parse(s.slice(a, i)); } throw new Error('Unterminated JSON string'); } if (s[i] === '{') { i++; ws(); const o = Object.create(null); if (s[i] === '}') { i++; return o; } for (;;) { requireThat(s[i] === '"', 'Invalid JSON key'); const k = val(depth + 1); ws(); requireThat(!Object.prototype.hasOwnProperty.call(o, k), 'Duplicate JSON key'); requireThat(s[i++] === ':', 'Invalid JSON separator'); o[k] = val(depth + 1); ws(); if (s[i++] === '}') return o; requireThat(s[i - 1] === ',', 'Invalid JSON object'); ws(); } } if (s[i] === '[') { i++; ws(); const a = []; if (s[i] === ']') { i++; return a; } for (;;) { a.push(val(depth + 1)); ws(); if (s[i++] === ']') return a; requireThat(s[i - 1] === ',', 'Invalid JSON array'); } } const m = /^(true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(s.slice(i)); requireThat(m, 'Invalid JSON value'); i += m[0].length; const v = JSON.parse(m[0]); requireThat(typeof v !== 'number' || Number.isFinite(v), 'Nonfinite JSON'); return v; } return {value: val(0), end: i}; } function keys(o, expected) { requireThat(o && !Array.isArray(o) && typeof o === 'object' && Object.keys(o).sort().join('|') === expected.slice().sort().join('|'), 'Unsupported or missing JSON fields'); } function day(s) { requireThat(typeof s === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(s) && new Date(s + 'T12:00:00Z').toISOString().slice(0,10) === s, 'Invalid date'); return s; } function number(v, name) { const n=Number(v); requireThat(v !== '' && v !== null && typeof v !== 'boolean' && Number.isFinite(n), 'Invalid ' + name); return n; } const rules = {order:'exits_before_entries',wait_for_exit_fills:true,validity:'effective_session_only',historical_backfill:false,holdings_are_not_buy_instructions:true,rebalance_existing_positions:false,exit_scope:'strategy_and_position_entry_date',deduplicate_by:'action_id',changed_action_requires_review:true,account_mode:'subscriber_selected_paper_or_live',broker_orders_authorized_by_this_data:false}; const strategies = {free:'MI_FREE_V1',pro:'MI_PRO_V1'}; const legacyStrategies = {"free":"a880be01fe62f3f891af59e999e18922934150d5b65c636228b7e487c132ca10","pro":"215cd48170207e0553a621c68bc900a891ebfaf5837065c97c7b6bb30e54449c"}; const legacyIssuePrefixes = {"free":"bc69ab9a2b0de92b7e5f735b5c93bdfb81115f0b77cf7b16a6a7ed55e440adbd","pro":"c2bf8c66ede378cc5da7d85590ce6ffb784a568146fee484e0f7b439b7974eb0"}; function validate(v, tier, hash) { keys(v,['schema','publisher','product_version','tier','strategy_id','issue_id','issue_date','completed_equity_session','timezone','kind','evidence','status','rules','actions']); const legacy = typeof v.product_version==='string' && hash(v.product_version)==='d68c9eb0ca41f67b5780328af5c4a0a1140f2deb4cfa978c71fde5c42911204d'; requireThat(v.schema==='mi.newsletter.delta.v1' && v.publisher==='Mount Inflection' && (v.product_version==='MI' || legacy), 'Unrecognized newsletter version'); requireThat(v.tier===tier && Object.prototype.hasOwnProperty.call(strategies,tier) && typeof v.strategy_id==='string' && (legacy ? hash(v.strategy_id)===legacyStrategies[tier] : v.strategy_id===strategies[tier]), 'Wrong newsletter tier/strategy'); const issueDate=day(v.issue_date); requireThat(typeof v.issue_id==='string' && (legacy ? v.issue_id.endsWith(issueDate) && hash(v.issue_id.slice(0,-10))===legacyIssuePrefixes[tier] : v.issue_id==='mi-'+tier+'-'+issueDate), 'Invalid issue identity'); requireThat(day(v.completed_equity_session)<=v.issue_date && v.timezone==='America/New_York', 'Invalid source date/timezone'); requireThat(v.kind==='entry_exit_delta' && v.evidence==='hypothetical_model_signals_not_fills', 'Invalid signal type'); requireThat(canonical(v.rules)===canonical(rules), 'Execution rules changed'); requireThat(['new_actions','no_new_actions','review_only'].includes(v.status) && Array.isArray(v.actions) && v.actions.length<=100, 'Invalid action status/count'); requireThat((v.status==='new_actions') === (v.actions.length>0), 'Action/status mismatch'); const ids=new Set(), groups={}; let openingSeen=false; v.actions.forEach(a=>{ keys(a,['action_id','symbol','action','position_side','signal_date','effective_session','position_entry_date','sizing']); requireThat(/^[A-Z][A-Z0-9.\-]{0,14}$/.test(a.symbol), 'Invalid symbol'); requireThat((tier==='free'?['BUY','SELL']:['BUY','SELL','SHORT','COVER']).includes(a.action), 'Unsupported action'); const enter=['BUY','SHORT'].includes(a.action), side=['BUY','SELL'].includes(a.action)?'long':'short'; requireThat(a.position_side===side, 'Side mismatch'); requireThat(day(a.signal_date)<=v.completed_equity_session && day(a.effective_session)>v.completed_equity_session && a.effective_session>=v.issue_date, 'Invalid signal/session dates'); requireThat(enter?day(a.position_entry_date)===a.effective_session:day(a.position_entry_date)<=a.signal_date, 'Invalid position episode'); requireThat(enter || !openingSeen, 'Exits must precede entries'); openingSeen=openingSeen||enter; const identity=[v.strategy_id,a.symbol,a.action,a.signal_date,a.effective_session,a.position_entry_date]; requireThat(a.action_id===hash(JSON.stringify(identity)) && !ids.has(a.action_id), 'Invalid or duplicate action identity'); ids.add(a.action_id); if(enter) { keys(a.sizing,['model_equity_fraction','subscriber_mapping_required']); requireThat(typeof a.sizing.model_equity_fraction==='number' && a.sizing.model_equity_fraction>0 && a.sizing.model_equity_fraction<=1 && a.sizing.subscriber_mapping_required===true,'Invalid sizing reference'); } else { requireThat(canonical(a.sizing)===canonical({close:'entire_strategy_owned_episode',if_not_owned:'skip'}),'Invalid exit ownership'); } (groups[a.symbol]||(groups[a.symbol]=[])).push(a.action); }); requireThat(new Set(v.actions.map(a=>a.effective_session)).size<=1,'Mixed effective sessions'); Object.values(groups).forEach(g=>requireThat(g.length===1 || (g.length===2 && ['SELL,SHORT','BUY,COVER'].includes(g.slice().sort().join(','))),'Conflicting symbol actions')); return v; } function discover(bodies,tier,hash) { requireThat(bodies.length>0 && bodies.length<=10,'Missing/ambiguous MIME bodies'); const values=[]; bodies.forEach(body=>{ requireThat(body.length<300000,'Message too large'); const begin='MI_AUTOMATION_JSON_BEGIN',end='MI_AUTOMATION_JSON_END'; const bc=body.split(begin).length-1,ec=body.split(end).length-1; if(!bc&&!ec)return; requireThat(bc===1&&ec===1&&body.indexOf(end)>body.indexOf(begin),'Conflicting or truncated footer'); const raw=body.split(begin)[1].split(end)[0].trim(),parsed=parseAt(raw,0); requireThat(raw.slice(parsed.end).trim()==='','Unexpected trailing JSON'); values.push(validate(parsed.value,tier,hash)); }); requireThat(values.length>0,'No v1 JSON footer: wait for a newly generated newsletter'); requireThat(values.every(v=>canonical(v)===canonical(values[0])),'HTML/plain-text footer conflict'); return values[0]; } function config(p) { const mode=p.ALPACA_MODE,tier=p.MI_TIER; requireThat(['paper','live'].includes(mode)&&['free','pro'].includes(tier),'Choose ALPACA_MODE paper/live and MI_TIER free/pro'); const capital=number(p.CAPITAL_PERCENT,'CAPITAL_PERCENT')/100,entry=number(p.MAX_ENTRY_PERCENT,'MAX_ENTRY_PERCENT')/100; const gross=number(p.MAX_GROSS_PERCENT,'MAX_GROSS_PERCENT')/100,maxOrder=number(p.MAX_ORDER_DOLLARS,'MAX_ORDER_DOLLARS'),cashBuffer=number(p.CASH_BUFFER_DOLLARS||'0','CASH_BUFFER_DOLLARS'); requireThat(capital>0&&capital<=1&&entry>0&&entry<=1&&gross>0&&gross<=2&&maxOrder>=1&&cashBuffer>=0,'Sizing limits out of range'); requireThat(tier!=='free'||(gross<=1&&p.ALLOW_SHORTS!=='true'),'Free is long-only without leverage'); requireThat(['true','false'].includes(p.ALLOW_SHORTS||'false'),'ALLOW_SHORTS must be true or false'); return {mode,tier,capital,entry,gross,maxOrder,cashBuffer,shorts:p.ALLOW_SHORTS==='true',account:p.EXPECTED_ACCOUNT_ID||''}; } // Keep newsletter symbols and action IDs unchanged; use Alpaca's class-share symbol at the broker boundary. function brokerSymbol(s) { return s==='BRK-B'?'BRK.B':s; } function positionsMatch(positions,owned,active) { const expected={}; Object.keys(owned).forEach(s=>expected[s]=number(owned[s].qty,'ledger quantity')*(owned[s].side==='short'?-1:1)); if(active) active.rows.forEach(r=>{ if(r.applied||!r.order)return; const q=number(r.order.filled_qty||'0','partial fill'); expected[r.payload.symbol]=(expected[r.payload.symbol]||0)+(r.payload.side==='buy'?q:-q); }); const actual={}; positions.forEach(p=>{ requireThat(!(p.symbol in actual),'Duplicate broker position');actual[p.symbol]=number(p.qty,'position quantity'); }); for(const s of new Set(Object.keys(actual).concat(Object.keys(expected)))) requireThat(Math.abs((actual[s]||0)-(expected[s]||0))<0.00000001,'Untracked position or quantity drift: '+s); } function selections(v,owned,recent,hash) { const exits=[],entries=[],skipped=[], symbols=new Map(); v.actions.forEach(a=>{ const symbol=brokerSymbol(a.symbol); requireThat(!symbols.has(symbol)||symbols.get(symbol)===a.symbol,'Mixed newsletter aliases for '+symbol); symbols.set(symbol,a.symbol); const old=recent[a.action_id]; if(old) { requireThat(old.digest===hash(canonical(a)),'Action changed after processing');skipped.push({symbol:a.symbol,reason:'Already processed'});return; } if(['SELL','COVER'].includes(a.action)) { const held=owned[symbol]; if(!held){skipped.push({symbol:a.symbol,reason:'No strategy-owned position'});return;} requireThat(held.entry===a.position_entry_date&&held.side===a.position_side,'Exit episode mismatch: '+a.symbol); exits.push(a); } else { const held=owned[symbol],closing=exits.find(x=>x.symbol===a.symbol); if(held&&!closing) { requireThat(held.entry===a.position_entry_date&&held.side===a.position_side,'Unexpected existing episode: '+a.symbol); skipped.push({symbol:a.symbol,reason:'Already owned; no top-up'});return; } entries.push(a); } }); return {exits,entries,skipped}; } return {text,canonical,parseAt,day,number,validate,discover,config,positionsMatch,selections,brokerSymbol}; })(); if(typeof module!=='undefined')module.exports=MINewsletter; /* MI Newsletter Trader v1.0 beta \u2014 one private project and dedicated account per strategy. * Credentials stay in Script Properties. No trading occurs until you explicitly enable it. * Free paper predecessor was observed end to end; this generalized release is test-backed beta. */ const MI_VERSION='1.1.1-paper-beta', MI_TZ='America/New_York'; function miProps_(){return PropertiesService.getUserProperties();} function miAssert_(ok,message){if(!ok)throw Error(message);} function miHash_(s){return Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256,s,Utilities.Charset.UTF_8).map(b=>('0'+((b+256)%256).toString(16)).slice(-2)).join('');} function miToday_(){return Utilities.formatDate(new Date(),MI_TZ,'yyyy-MM-dd');} function miMinutes_(){const t=Utilities.formatDate(new Date(),MI_TZ,'HH:mm').split(':');return Number(t[0])*60+Number(t[1]);} function miConfig_(){miCheckContainer_();const c=MINewsletter.config(miProps_().getProperties());miAssert_(c.mode==='paper'&&c.tier==='pro','This template supports Pro paper only.');return c;} function miFingerprint_(c){const p=miProps_();return miHash_(MINewsletter.canonical(c)+':'+miHash_((p.getProperty('ALPACA_'+c.mode.toUpperCase()+'_KEY')||'')+':'+(p.getProperty('ALPACA_'+c.mode.toUpperCase()+'_SECRET')||'')));} function miReport_(v){const r=Object.assign({version:MI_VERSION,checkedAt:new Date().toISOString()},v),raw=JSON.stringify(r);miProps_().setProperty('MI_LAST_REPORT',raw.length<=6000?raw:JSON.stringify({version:MI_VERSION,checkedAt:r.checkedAt,status:r.status,detail:'Full report is in Executions; journal retains the latest receipt.'}));console.log(raw);return r;} function miLoad_(){ const p=miProps_(),head=p.getProperty('MI_STATE_HEAD'); if(!head)return {binding:null,owned:{},recent:{},issues:{},active:null,lastReceipt:null,lastIssueDate:null}; const h=JSON.parse(head);let raw='';for(let i=0;ik.startsWith('MI_S_')&&!k.startsWith('MI_S_'+generation+'_')).forEach(k=>p.deleteProperty(k)); } function miLock_(fn){const l=LockService.getScriptLock();miAssert_(l.tryLock(1000),'Another run is active; try again later');try{return fn();}finally{l.releaseLock();}} function miBinding_(c){return c.mode+':'+c.tier+':'+c.account;} function miCheckBinding_(s,c){miAssert_(!s.binding||s.binding===miBinding_(c),'This project is bound to another account/mode/tier. Use a separate project and account.');} function miCanTrade_(c){ miAssert_(miProps_().getProperty('MI_ARMED')==='true','Trading is paused'); miCheckContainer_(); miAssert_(miProps_().getProperty('MI_ARMED_CONFIG')===miFingerprint_(c),'Settings/credentials changed: preview and enable again'); if(c.mode==='live')miAssert_(miProps_().getProperty('LIVE_CONFIRMATION')==='I ACCEPT LIVE TRADING','Live confirmation missing'); } function miApi_(c,path,method,body,missing){ miAssert_(/^\/v2\//.test(path)&&!path.includes('://'),'Invalid broker path');method=method||'get'; miAssert_(method==='get'||(method==='post'&&path==='/v2/orders'),'Unsupported broker mutation'); if(method==='post')miCanTrade_(c); const p=miProps_(),label=c.mode.toUpperCase(),key=p.getProperty('ALPACA_'+label+'_KEY'),secret=p.getProperty('ALPACA_'+label+'_SECRET'); miAssert_(key&&secret&&key.startsWith(c.mode==='paper'?'PK':'AK'),'Missing or mismatched '+c.mode+' credentials'); const opt={method,muteHttpExceptions:true,followRedirects:false,headers:{'APCA-API-KEY-ID':key,'APCA-API-SECRET-KEY':secret}}; if(body){opt.contentType='application/json';opt.payload=JSON.stringify(body);} miAssert_(c.mode==='paper','Paper-only endpoint guard');const root='https://paper-api.alpaca.markets'; const r=UrlFetchApp.fetch(root+path,opt),code=r.getResponseCode();if(missing&&code===404)return null; miAssert_(code>=200&&code<300,'Alpaca HTTP '+code+' on '+path.split('?')[0]+'. Review account/order status.'); return JSON.parse(r.getContentText()); } function miAccount_(c,connectionOnly){ const a=miApi_(c,'/v2/account'); miAssert_(connectionOnly||(/^[0-9a-f-]{36}$/.test(c.account)&&a.id===c.account),'EXPECTED_ACCOUNT_ID does not match'); miAssert_(a.status==='ACTIVE'&&!a.trading_blocked&&!a.account_blocked&&!a.trade_suspended_by_user,'Account not available for trading'); miAssert_(a.currency==='USD','Only USD accounts are supported'); if(c.shorts||c.gross>1)miAssert_(Number(a.multiplier)>1,'Shorts/leverage require a margin-enabled account'); return a; } function miOpenOrders_(c){const o=miApi_(c,'/v2/orders?status=open&limit=500');miAssert_(o.length<500,'Open order pagination requires review');return o;} function miQuote_(c,symbol){ const p=miProps_(),label=c.mode.toUpperCase(); const r=UrlFetchApp.fetch('https://data.alpaca.markets/v2/stocks/'+encodeURIComponent(MINewsletter.brokerSymbol(symbol))+'/quotes/latest?feed=iex',{muteHttpExceptions:true,followRedirects:false,headers:{'APCA-API-KEY-ID':p.getProperty('ALPACA_'+label+'_KEY'),'APCA-API-SECRET-KEY':p.getProperty('ALPACA_'+label+'_SECRET')}}); miAssert_(r.getResponseCode()===200,'Quote unavailable: '+symbol);const q=JSON.parse(r.getContentText()).quote; miAssert_(q&&Number(q.ap)>0&&Number(q.bp)>0&&Date.now()-Date.parse(q.t)>=-60000&&Date.now()-Date.parse(q.t)<120000,'Fresh regular-session quote required: '+symbol); return q; } // Sizing remains allocation-based. The gap check is a separate, per-entry decision. function miEntryGap_(c,action,sourceSession){ const p=miProps_(); const unavailable={skip:'Entry quote or prior-session close unavailable'}; try{ const path='/v2/stocks/'+encodeURIComponent(MINewsletter.brokerSymbol(action.symbol))+'/snapshot?feed=iex'; const response=UrlFetchApp.fetch('https://data.alpaca.markets'+path,{muteHttpExceptions:true,followRedirects:false, headers:{'APCA-API-KEY-ID':p.getProperty('ALPACA_PAPER_KEY'),'APCA-API-SECRET-KEY':p.getProperty('ALPACA_PAPER_SECRET')}}); if(response.getResponseCode()!==200)return unavailable; const snapshot=JSON.parse(response.getContentText()), q=snapshot.latestQuote, bar=snapshot.prevDailyBar; if(!q||!bar||!Number.isFinite(Date.parse(q.t))||!Number.isFinite(Date.parse(bar.t)))return unavailable; const at=new Date(q.t), age=Date.now()-at.getTime(); const bid=Number(q.bp),ask=Number(q.ap),close=Number(bar.c); if(!(Number.isFinite(bid)&&Number.isFinite(ask)&&Number.isFinite(close)&&close>0&&bid>0&&ask>=bid&& Number(q.bs)>0&&Number(q.as)>0&&(ask-bid)/((ask+bid)/2)<=0.02&&age>=-1000&&age<120000&& Utilities.formatDate(at,MI_TZ,'yyyy-MM-dd')===action.effective_session&& Utilities.formatDate(at,MI_TZ,'HH:mm')>='09:30'&& Utilities.formatDate(new Date(bar.t),MI_TZ,'yyyy-MM-dd')===sourceSession))return unavailable; const short=action.action==='SHORT', observed=short?bid:ask; const move=(short?close-bid:ask-close)/close; return {close,observed,ask,quoteAt:q.t,move,skip:move>0.07+1e-10?'Adverse entry move above 7%':null}; }catch(error){return unavailable;} } function miSkipEntry_(active,action,check){ active.selection.skipped.push({symbol:action.symbol,action:action.action,reason:check.skip,entryCheck:check}); } function miGmail_(path){ const r=UrlFetchApp.fetch('https://gmail.googleapis.com/gmail/v1/users/me/'+path,{muteHttpExceptions:true,followRedirects:false,headers:{Authorization:'Bearer '+ScriptApp.getOAuthToken()}}); miAssert_(r.getResponseCode()===200,'Gmail HTTP '+r.getResponseCode()+': check consent and Gmail API service');return JSON.parse(r.getContentText()); } function miHeader_(m,name){return (m.payload.headers||[]).filter(h=>h.name.toLowerCase()===name.toLowerCase()).map(h=>h.value);} function miAuthentic_(m){ const from=miHeader_(m,'From'),auth=miHeader_(m,'Authentication-Results').filter(s=>/^mx\.google\.com;/.test(s)); miAssert_(from.length===1&&/^(?:Mount Inflection|"Mount Inflection") $/i.test(from[0]),'Unexpected newsletter sender'); miAssert_(auth.length===1&&/dkim=pass\s+header\.i=@mountinflection\.com\b/.test(auth[0])&&/dmarc=pass[^;]*header\.from=mountinflection\.com\b/.test(auth[0]),'Gmail DKIM/DMARC evidence missing or ambiguous'); miAssert_(!(m.labelIds||[]).some(x=>['DRAFT','SPAM','TRASH'].includes(x)),'Draft/spam/trash source rejected'); } function miBodies_(message){ const bodies=[];function walk(p){if(p.filename)return;if(p.body&&p.body.data){const v=Utilities.newBlob(Utilities.base64DecodeWebSafe(p.body.data)).getDataAsString('UTF-8');if(p.mimeType==='text/plain')bodies.push(v);if(p.mimeType==='text/html')bodies.push(MINewsletter.text(v));}(p.parts||[]).forEach(walk);} walk(message.payload);return bodies; } function miReadIssue_(c,latest){ const subject='Mount Inflection '+(c.tier==='free'?'Free weekly view':'Pro daily view')+' \u2014 '; const q='from:hello@mountinflection.com newer_than:8d -in:trash -in:spam -in:drafts subject:"'+(c.tier==='free'?'Free weekly view':'Pro daily view')+'"'; const page=miGmail_('messages?q='+encodeURIComponent(q)+'&maxResults=30');miAssert_(!page.nextPageToken,'Too many newsletter matches; review mailbox'); const candidates=[]; (page.messages||[]).forEach(ref=>{const m=miGmail_('messages/'+ref.id+'?format=full'),h=miHeader_(m,'Subject');if(h.length!==1||!h[0].startsWith(subject))return;const d=h[0].slice(subject.length);if(!/^\d{4}-\d{2}-\d{2}$/.test(d)||d>miToday_()||(!latest&&d!==miToday_()))return;miAuthentic_(m);candidates.push({m,date:d});}); if(!candidates.length)return null; candidates.sort((a,b)=>b.date.localeCompare(a.date));const matches=candidates.filter(x=>x.date===candidates[0].date); miAssert_(matches.length===1,'Multiple/corrected matching issues: manual review required'); const found=matches[0],v=MINewsletter.discover(miBodies_(found.m),c.tier,miHash_); miAssert_(v.issue_date===found.date,'Subject/footer date conflict'); if(c.tier==='free')miAssert_(new Date(v.issue_date+'T12:00:00Z').getUTCDay()===5,'Free issue must be Friday'); return {value:v,digest:miHash_(MINewsletter.canonical(v)),messageId:found.m.id,snapshot:c.rapidRead?MIRapidStart.discover(miBodies_(found.m),v,MINewsletter.parseAt,MINewsletter.canonical):undefined}; } function miInitial_(c,s){ miRepairGuard_(s);miRapidGuardInitial_(s); miCheckBinding_(s,c);const a=miAccount_(c),positions=miApi_(c,'/v2/positions'); miAssert_(!s.active,'An unfinished run needs reconciliation first');miAssert_(miOpenOrders_(c).length===0,'Open orders must be reviewed first'); MINewsletter.positionsMatch(positions,s.owned,null);return {account:a,positions}; } function checkConnections(){return miLock_(()=>{const c=miConfig_(),a=miAccount_(c,true);miGmail_('messages?maxResults=1&q='+encodeURIComponent('from:hello@mountinflection.com'));return miReport_({status:'connections_ok_no_orders',mode:c.mode,tier:c.tier,accountId:a.id,accountSuffix:a.account_number.slice(-4),next:'Copy accountId into EXPECTED_ACCOUNT_ID, then run previewLatestIssue.'});});} function previewLatestIssue(){return miLock_(()=>{ const c=miConfig_(),s=miLoad_(),p=miInitial_(c,s),source=miReadIssue_(c,true);miAssert_(source,'No delivered issue found: confirm your Free/Pro subscription and wait for its next email'); const selected=MINewsletter.selections(source.value,s.owned,s.recent,miHash_); selected.entries.forEach(a=>miAsset_(c,a)); selected.entries.forEach(a=>{const amount=Math.floor(Number(p.account.equity)*c.capital*a.sizing.model_equity_fraction*100)/100;miAssert_(amount>=1&&amount<=c.maxOrder&&c.capital*a.sizing.model_equity_fraction<=c.entry,'Preview exceeds entry limit or is below $1: '+a.symbol);}); const equity=Number(p.account.equity),preview={status:'preview_no_orders',mode:c.mode,tier:c.tier,accountSuffix:p.account.account_number.slice(-4),issue:source.value.issue_id,sourceSession:source.value.completed_equity_session,equityBasis:equity,capitalPercent:c.capital*100,exits:selected.exits.map(a=>({symbol:a.symbol,action:a.action,qty:s.owned[a.symbol].qty})),entries:selected.entries.map(a=>({symbol:a.symbol,action:a.action,referenceDollars:Math.floor(equity*c.capital*a.sizing.model_equity_fraction*100)/100})),skipped:selected.skipped,limits:{maxEntryPercent:c.entry*100,maxOrderDollars:c.maxOrder,maxGrossPercent:c.gross*100},note:'Preview only. Execution rechecks dates, positions, cash, quotes, borrow availability and limits. Shorts round down to whole shares.'}; miProps_().setProperty('MI_PREVIEW',JSON.stringify({fingerprint:miFingerprint_(c),at:Date.now(),issue:source.value.issue_id}));return miReport_(preview); });} function miRemoveTriggers_(handlers){ScriptApp.getProjectTriggers().filter(t=>handlers.includes(t.getHandlerFunction())).forEach(t=>ScriptApp.deleteTrigger(t));} function installSchedule(){return miLock_(()=>{ const c=miConfig_(),s=miLoad_();miInitial_(c,s);miProps_().setProperty('MI_ARMED','false');miRemoveTriggers_(['runScheduled','continueRun']); let b=ScriptApp.newTrigger('runScheduled').timeBased();b=c.tier==='free'?b.everyWeeks(1).onWeekDay(ScriptApp.WeekDay.FRIDAY):b.everyDays(1); b.atHour(9).nearMinute(45).inTimezone(MI_TZ).create(); if(!s.binding){s.binding=miBinding_(c);s.started=miToday_();miSave_(s);} return miReport_({status:'schedule_installed_trading_paused',tier:c.tier,mode:c.mode,schedule:c.tier==='free'?'Friday around 09:45 Eastern':'Daily around 09:45 Eastern',timing:'Google allows approximately \u00b115 minutes; no exact opening-price promise',next:'Run previewLatestIssue, review the account and sizing, then explicitly enable your selected mode.'}); });} function miSendActivationReceipt_(c,accountSuffix,fingerprint){ const props=miProps_(); // An interrupted send has an unknown outcome. Keep the attempt recorded. const save=status=>{props.setProperty('MI_ACTIVATION_EMAIL',JSON.stringify({fingerprint,status}));return status;}; try { const previous=JSON.parse(props.getProperty('MI_ACTIVATION_EMAIL')||'null'); if(previous && previous.fingerprint===fingerprint) return previous.status; save('unconfirmed'); const to=miGmail_('profile').emailAddress; miAssert_(typeof to==='string'&&/^[^\s@,;]+@[^\s@,;]+\.[^\s@,;]+$/.test(to),'Gmail account address unavailable'); const tier=c.tier==='free'?'Free':'Pro'; const mode=c.mode==='paper'?'Paper':'Live'; const menu='\u2699 MI '+mode; const sheetId=SpreadsheetApp.getActiveSpreadsheet().getId(); const schedule=c.tier==='free'?'Fridays':'Daily'; const body=[ 'Your Mount Inflection '+tier+' '+mode+' automation is enabled.', 'Account ending '+accountSuffix+'. '+(c.mode==='paper'?'Paper uses simulated money.':'Live can place real-money orders.'), schedule+' around 9:45 a.m. Eastern (Google may run about 15 minutes early or late). Orders depend on a qualifying issue and market session.', 'Strategy capital: '+(c.capital*100)+'%. Maximum per new order: $'+c.maxOrder+'.', 'Open your Sheet: https://docs.google.com/spreadsheets/d/'+sheetId+'/edit', 'Check: '+menu+' \u2192 Newsletter & activity \u2192 Refresh activity. Review Last check, Result and any Reason. For order fills, check Alpaca.', 'Pause: '+menu+' \u2192 Trading controls \u2192 Pause trading. Pausing stops future submissions. Check Alpaca for open orders and positions.', 'Restart: '+menu+' \u2192 Trading controls \u2192 1. Preview to start or restart. Review it, check the confirmation box, then click Start '+mode+'.', 'Change tier or account: use the matching template and a separate unused Alpaca account. For changes to limits on this copy, pause and contact hello@mountinflection.com before changing the setup.', 'Setup guide: https://mountinflection.com/automation' ].join('\n\n'); MailApp.sendEmail({to,subject:'Mount Inflection '+tier+' '+mode+' automation enabled',body,name:'Mount Inflection Setup'}); return save('sent'); } catch(e) { return 'unconfirmed'; } } function miEnable_(mode){return miLock_(()=>{ const c=miConfig_(),s=miLoad_();miAssert_(c.mode===mode,'Wrong enable function for selected mode');const account=miInitial_(c,s).account; const proof=JSON.parse(miProps_().getProperty('MI_PREVIEW')||'null');miAssert_(proof&&proof.fingerprint===miFingerprint_(c)&&Date.now()-proof.at<7*86400000,'Run previewLatestIssue with these settings first'); miAssert_(ScriptApp.getProjectTriggers().some(t=>t.getHandlerFunction()==='runScheduled'),'Run installSchedule first'); if(mode==='live')miAssert_(miProps_().getProperty('LIVE_CONFIRMATION')==='I ACCEPT LIVE TRADING','Set LIVE_CONFIRMATION explicitly before enabling real-money orders'); miAssert_(s.binding===miBinding_(c),'Schedule/account binding missing'); const container=miCheckContainer_(); miProps_().setProperties({MI_ARMED_CONFIG:miFingerprint_(c),MI_CONTAINER_ARMED_VERSION:String(container.version),MI_ARMED:'true'},false); miProps_().deleteProperty('MI_CONTAINER_STOP'); const confirmationEmail=miSendActivationReceipt_(c,String(account.account_number).slice(-4),proof.fingerprint); return miReport_({status:'trading_enabled',mode,tier:c.tier,confirmationEmail,note:'No order submitted by enable. The next scheduled run can trade current eligible newsletter actions.'}); });} function enablePaperTrading(){return miEnable_('paper');} function enableLiveTrading(){throw Error('Live trading is unavailable in this paper template.');} function pauseTrading(){ // Stop submissions even while another invocation holds the journal lock. miProps_().setProperty('MI_ARMED','false');miProps_().deleteProperty('MI_ACTIVATION_EMAIL');miRemoveTriggers_(['runScheduled','continueRun']); return miReport_({status:'paused',note:'Future submissions stopped. An in-flight request or accepted order may still fill; inspect orders and holdings in Alpaca.'}); } function miResumeAt_(at){miRemoveTriggers_(['continueRun']);const when=Math.max(Date.now()+60000,at||Date.now()+180000);ScriptApp.newTrigger('continueRun').timeBased().at(new Date(when)).create();} function miAsset_(c,a){ const symbol=MINewsletter.brokerSymbol(a.symbol); const asset=miApi_(c,'/v2/assets/'+encodeURIComponent(symbol));miAssert_(asset.symbol===symbol&&asset.status==='active'&&asset.tradable&&asset.class==='us_equity'&&asset.exchange!=='OTC','Unsupported equity: '+a.symbol); if(a.action==='BUY')miAssert_(asset.fractionable,'Fractional long entries unavailable: '+a.symbol); if(a.action==='SHORT')miAssert_(c.tier==='pro'&&c.shorts&&asset.shortable&&asset.easy_to_borrow,'Short permission/borrow unavailable: '+a.symbol); return asset; } function miPrepareEntries_(c,active,a,positions){ const equity=Number(a.equity);miAssert_(equity>0,'Account equity must be positive'); let gross=positions.reduce((n,p)=>n+Math.abs(Number(p.market_value)),0),long=positions.reduce((n,p)=>n+Math.max(0,Number(p.market_value)),0),cash=Number(a.cash)-c.cashBuffer,bp=Number(a.buying_power); const rows=[]; for(const action of active.selection.entries){ miAsset_(c,action);const fraction=action.sizing.model_equity_fraction; const check=miEntryGap_(c,action,active.source.value.completed_equity_session); if(check.skip){miSkipEntry_(active,action,check);continue;} const dollars=Math.floor(equity*c.capital*fraction*100)/100; miAssert_(fraction*c.capital<=c.entry&&dollars>=1&&dollars<=c.maxOrder,'Entry exceeds your sizing limit or is below $1: '+action.symbol); let payload={symbol:MINewsletter.brokerSymbol(action.symbol),side:action.action==='BUY'?'buy':'sell',type:'market',time_in_force:'day'}; if(action.action==='SHORT'){ // Alpaca reserves opening-short buying power using 3% above ask. IEX quote is a sizing reference, not a guaranteed fill. const price=check.ask*1.03,qty=Math.floor(dollars/price); miAssert_(qty>=1,'Short allocation is smaller than one share: '+action.symbol);payload.qty=String(qty);bp-=qty*price;gross+=qty*price; }else{payload.notional=dollars.toFixed(2);cash-=dollars;bp-=dollars;gross+=dollars;long+=dollars;} miAssert_(bp>=0&&cash>=0&&gross<=equity*c.gross,'Insufficient cash/buying power or gross exposure limit'); // This version does not borrow cash for long entries, even when Pro shorts are enabled. miAssert_(long<=equity-c.cashBuffer,'Long holdings exceed cash-only long allocation limit'); rows.push({action,payload,attempted:false,applied:false,order:null}); } active.equityBasis=equity;return rows; } function miViewOrder_(o){return {id:o.id,client_order_id:o.client_order_id,symbol:o.symbol,side:o.side,status:o.status,filled_qty:o.filled_qty,filled_avg_price:o.filled_avg_price};} function miApplyOrder_(s,r,o){ miAssert_(o.client_order_id===r.payload.client_order_id&&o.symbol===r.payload.symbol&&o.side===r.payload.side&&o.type==='market'&&o.time_in_force==='day','Broker order does not match journal'); if(r.payload.qty)miAssert_(Math.abs(Number(o.qty)-Number(r.payload.qty))<1e-8,'Broker quantity mismatch'); if(r.payload.notional)miAssert_(Number(o.notional)===Number(r.payload.notional),'Broker notional mismatch'); r.order=miViewOrder_(o); miAssert_(!['rejected','canceled','expired','suspended','replaced'].includes(o.status),'Order '+o.status+': '+o.symbol+'; inspect partial fills before recovery'); if(o.status==='filled'&&!r.applied){ miAssert_(Number(o.filled_qty)>0,'Filled order has no quantity'); if(['BUY','SHORT'].includes(r.action.action))s.owned[r.payload.symbol]={side:r.action.position_side,qty:o.filled_qty,entry:r.action.position_entry_date,orderId:o.id}; else delete s.owned[r.payload.symbol]; r.applied=true;s.recent[r.action.action_id]={digest:miHash_(MINewsletter.canonical(r.action)),date:r.action.effective_session}; } } function miReconcile_(c,s){ for(const r of s.active.rows){ if(!r.payload.client_order_id)continue; const o=miApi_(c,'/v2/orders:by_client_order_id?client_order_id='+encodeURIComponent(r.payload.client_order_id),'get',null,true); if(o)miApplyOrder_(s,r,o);else miAssert_(!r.attempted,'Order submission is uncertain: do not resend; verify with Alpaca'); } miSave_(s);MINewsletter.positionsMatch(miApi_(c,'/v2/positions'),s.owned,s.active); const allowed=new Set(s.active.rows.map(r=>r.payload.client_order_id).filter(Boolean)); miAssert_(miOpenOrders_(c).every(o=>allowed.has(o.client_order_id)),'Unrelated open order in dedicated account'); } function miOrdinaryRun_(){return miLock_(()=>{ if(miProps_().getProperty('MI_ARMED')!=='true')return miReport_({status:'paused_no_orders'}); try{ const c=miConfig_();miCanTrade_(c);const s=miLoad_();miCheckBinding_(s,c);miAccount_(c); const today=miToday_(); if(!s.active){ if(c.tier==='free'&&new Date(today+'T12:00:00Z').getUTCDay()!==5)return miReport_({status:'outside_free_schedule'}); miInitial_(c,s);const source=miReadIssue_(c,false); if(!source){miAssert_(miMinutes_()<645,'No current newsletter by 10:45 Eastern; review before trading');miResumeAt_();return miReport_({status:'waiting_for_current_newsletter'});} const v=source.value;miAssert_(!s.lastIssueDate||v.issue_date>=s.lastIssueDate,'Older issue rejected'); if(s.issues[v.issue_id]){miAssert_(s.issues[v.issue_id].digest===source.digest,'Issue changed after processing');return miReport_({status:'duplicate_issue_skipped',issue:v.issue_id});} miAssert_(v.issue_date>=s.started,'No historical backfill'); const selection=MINewsletter.selections(v,s.owned,s.recent,miHash_); selection.entries.forEach(a=>miAsset_(c,a)); s.active={source,selection,phase:'exits',rows:selection.exits.map(a=>({action:a,payload:{symbol:MINewsletter.brokerSymbol(a.symbol),side:a.action==='SELL'?'sell':'buy',qty:s.owned[MINewsletter.brokerSymbol(a.symbol)].qty,type:'market',time_in_force:'day'},attempted:false,applied:false,order:null})),observations:0,createdAt:new Date().toISOString(),effective:v.actions.length?v.actions[0].effective_session:today}; miSave_(s); } const active=s.active;active.observations++;miAssert_(active.observations<=80,'Reconciliation budget exhausted; review required'); miReconcile_(c,s); const pending=active.selection.exits.length+active.selection.entries.length>0; if(pending){ miAssert_(today<=active.effective,'Signal expired; no next-day replay'); const clock=miApi_(c,'/v2/clock'); if(todayr.applied)){ const positions=miApi_(c,'/v2/positions'); active.entryRows=miPrepareEntries_(c,active,miAccount_(c),positions);active.rows=active.rows.concat(active.entryRows);delete active.entryRows;active.phase='entries';miSave_(s); } // Only start new submissions in the morning. Existing orders can still be reconciled later. const unsent=active.rows.filter(r=>!r.applied&&!r.attempted); miAssert_(!unsent.length||(miMinutes_()>=570&&miMinutes_()<=645),'New order outside 09:30\u201310:45 Eastern window'); let submissions=0; for(const r of active.rows){ if(r.applied||r.attempted)continue; if(submissions>=8)break; // Stay below the Apps Script execution limit; continue with the same journal. miCanTrade_(c);miAssert_(miApi_(c,'/v2/clock').is_open,'Market closed before submission'); if(['BUY','SHORT'].includes(r.action.action)){ miAsset_(c,r.action); const check=miEntryGap_(c,r.action,active.source.value.completed_equity_session); if(check.skip){miSkipEntry_(active,r.action,check);r.applied=true;miSave_(s);continue;} r.entryCheck=check; const a=miAccount_(c),cost=r.payload.notional?Number(r.payload.notional):Number(r.payload.qty)*check.ask*1.03; miAssert_(cost<=c.maxOrder&&Number(a.buying_power)>=cost,'Order exceeds current buying power/size cap'); if(r.payload.notional)miAssert_(Number(a.cash)-c.cashBuffer>=cost,'Insufficient current cash'); } r.payload.client_order_id='mi-nl-v1-'+miHash_(miBinding_(c)+':'+r.action.action_id).slice(0,32);miSave_(s); const existing=miApi_(c,'/v2/orders:by_client_order_id?client_order_id='+encodeURIComponent(r.payload.client_order_id),'get',null,true); if(existing){r.attempted=true;miApplyOrder_(s,r,existing);miSave_(s);continue;} r.attempted=true;miSave_(s); // A timeout after this point NEVER causes an automatic resubmission. const o=miApi_(c,'/v2/orders','post',r.payload);miApplyOrder_(s,r,o);miSave_(s);submissions++; } if(active.phase==='exits'||!active.rows.every(r=>r.applied)){miResumeAt_();return miReport_({status:'reconciling_orders',mode:c.mode,issue:active.source.value.issue_id,phase:active.phase,filled:active.rows.filter(r=>r.order&&r.order.status==='filled').length,total:active.rows.length});} const v=active.source.value,receipt={status:'rotation_complete',mode:c.mode,tier:c.tier,issue:v.issue_id,completedAt:new Date().toISOString(),filled:active.rows.filter(r=>r.order&&r.order.status==='filled').length,skipped:active.selection.skipped,orders:active.rows.filter(r=>r.order).map(r=>r.order),entryChecks:active.rows.filter(r=>r.entryCheck).map(r=>({symbol:r.action.symbol,...r.entryCheck}))}; s.issues[v.issue_id]={digest:active.source.digest,date:v.issue_date};s.lastIssueDate=v.issue_date;s.lastReceipt=receipt;s.active=null; const cutoff=new Date(Date.now()-8*86400000).toISOString().slice(0,10);for(const k of Object.keys(s.recent))if(s.recent[k].date{ const c=miConfig_(),s=miLoad_();miCheckBinding_(s,c);miAccount_(c);miAssert_(s.active,'No unfinished run; use previewLatestIssue and the enable function'); miAssert_(miProps_().getProperty('MI_ARMED_CONFIG')===miFingerprint_(c),'Recovery cannot change execution settings'); miAssert_(miToday_()===s.active.effective,'Expired run needs manual account reconciliation');miReconcile_(c,s); if(c.mode==='live')miAssert_(miProps_().getProperty('LIVE_CONFIRMATION')==='I ACCEPT LIVE TRADING','Live confirmation missing'); const container=miCheckContainer_();miProps_().setProperties({MI_CONTAINER_ARMED_VERSION:String(container.version),MI_ARMED:'true'},false);miProps_().deleteProperty('MI_CONTAINER_STOP');miResumeAt_();return miReport_({status:'reconciled_resume_scheduled',note:'Future invocation may submit remaining orders. No order submitted by this function.'}); });} function showStatus(){return miLock_(()=>{const c=miConfig_(),s=miLoad_();miCheckBinding_(s,c);const a=miAccount_(c);return miReport_({status:'account_status_no_orders',mode:c.mode,tier:c.tier,armed:miProps_().getProperty('MI_ARMED')==='true',accountSuffix:a.account_number.slice(-4),cash:a.cash,equity:a.equity,positions:miApi_(c,'/v2/positions').map(p=>({symbol:p.symbol,qty:p.qty})),openOrders:miOpenOrders_(c).map(miViewOrder_),active:s.active?{issue:s.active.source.value.issue_id,phase:s.active.phase}:null,lastReceipt:s.lastReceipt,triggers:ScriptApp.getProjectTriggers().map(t=>t.getHandlerFunction())});});} /* MI Pro Paper Setup v1.1.0-beta. User-owned Google Sheet; never a live endpoint. */ const MI_PAPER_SETUP_VERSION='1.1.1-paper-beta'; const MI_PUBLIC_TEMPLATE_ID='1y3yPO7RQBbNhmpGLWkrWYdA8G0JEnnPYSXdEDoipmJY'; function onOpen() { const ui = SpreadsheetApp.getUi(); ui.createMenu('\u2699 MI Paper') .addItem('Trading controls', 'openQuickPaperSetup') .addItem('Newsletter & activity', 'openPaperSetup') .addItem('Pro check & repair', 'openProRepair') .addSeparator() .addItem('Pause trading', 'pausePaperFromMenu') .addToUi(); } function openQuickPaperSetup() { const dialog = HtmlService.createHtmlOutput(MI_QUICK_PAPER_HTML).setWidth(560).setHeight(560); SpreadsheetApp.getUi().showModalDialog(dialog, 'Mount Inflection'); } function openPaperSetup(){SpreadsheetApp.getUi().showSidebar(HtmlService.createHtmlOutput(MI_PAPER_HTML).setTitle('Newsletter & activity'));} function pausePaperFromMenu(){pauseTrading();openQuickPaperSetup();} function miPaperContext_(){ const id=SpreadsheetApp.getActiveSpreadsheet().getId(),p=miProps_(),saved=p.getProperty('MI_CONTAINER_ID'); miAssert_(id!==MI_PUBLIC_TEMPLATE_ID,'Make your own private copy before connecting an account. Use File > Make a copy.'); miAssert_(!saved||saved===id,'This copy needs its own setup. Open \u2699 MI Paper > Trading controls.'); return {id,p}; } function miPaperSettings_(f){ miAssert_(f&&typeof f==='object','Enter your paper settings'); const capital=Number(f.capitalPercent),maxOrder=Number(f.maxOrderDollars),gross=Number(f.maxGrossPercent); miAssert_(Number.isFinite(capital)&&capital>0&&capital<=100,'Choose strategy capital above 0 and at most 100%'); miAssert_(Number.isFinite(maxOrder)&&maxOrder>=1,'Enter a maximum new order of at least $1'); miAssert_(Number.isFinite(gross)&&gross>0&&gross<=200,'Choose gross exposure above 0 and at most 200%'); miAssert_(typeof f.allowShorts==='boolean','Choose whether to allow eligible stock shorts'); return {ALPACA_MODE:'paper',MI_TIER:'pro',CAPITAL_PERCENT:String(capital),MAX_ENTRY_PERCENT:'100',MAX_ORDER_DOLLARS:String(maxOrder),MAX_GROSS_PERCENT:String(gross),ALLOW_SHORTS:String(f.allowShorts),CASH_BUFFER_DOLLARS:'0'}; } function miPaperCheckNewsletter(){ miPaperContext_();const source=miReadIssue_({tier:'pro'},true); if(!source)return {status:'newsletter_missing',note:'Gmail is connected, but no ordinary Pro daily issue was found in the last eight days. Use the Gmail subscribed to Pro and wait for a delivered issue. Welcome emails and private test messages do not qualify.'}; return {status:'newsletter_ready',issue:source.value.issue_id,sourceSession:source.value.completed_equity_session,actions:source.value.actions.length,issueDate:source.value.issue_date,historical:source.value.issue_date!==miToday_(),modelActions:source.value.actions.map(a=>({action:a.action,symbol:a.symbol,effectiveDate:a.effective_session})),note:'Delivered Pro automation data passed sender, footer and tier validation. This check placed no orders.'}; } function miPaperCheckConnection(f){ miPaperContext_();const key=String(f&&f.key||'').trim(),secret=String(f&&f.secret||'').trim(); miAssert_(/^PK[A-Z0-9]+$/.test(key)&&secret.length>=10,'Enter an Alpaca paper key and secret. Live keys are rejected.'); function read(path){ const r=UrlFetchApp.fetch('https://paper-api.alpaca.markets'+path,{method:'get',muteHttpExceptions:true,followRedirects:false,headers:{'APCA-API-KEY-ID':key,'APCA-API-SECRET-KEY':secret}}); miAssert_(r.getResponseCode()===200,'Paper connection check failed (HTTP '+r.getResponseCode()+'). Check the account credentials.');return JSON.parse(r.getContentText()); } const a=read('/v2/account'),positions=read('/v2/positions'),orders=read('/v2/orders?status=open&limit=500'); miAssert_(a.status==='ACTIVE'&&!a.trading_blocked&&!a.account_blocked,'Paper account is not available for trading.'); return {status:'connection_check_only',mode:'paper',accountSuffix:String(a.account_number).slice(-4),equity:Number(a.equity),positionCount:positions.length,openOrderCount:orders.length,eligibleForFreshInstall:positions.length===0&&orders.length===0,note:'Read-only check. No credentials saved, timer created, orders placed or holdings imported.'}; } function miPaperConnect(f){return miLock_(()=>{ const {id,p}=miPaperContext_(),s=miLoad_(); miAssert_(!s.binding&&!s.active&&Object.keys(s.owned).length===0,'This account is already installed. Pause and review its existing journal; reconnecting cannot reset it.'); const settings=miPaperSettings_(f),key=String(f.key||'').trim(),secret=String(f.secret||'').trim(); miAssert_(/^PK[A-Z0-9]+$/.test(key)&&secret.length>=10,'The Key ID must start with PK and the Secret Key must be complete. Live keys are rejected.'); // Credentials are user- and project-scoped. Never put them in worksheet cells or returned values. const before=p.getProperties();p.setProperties({...settings,ALPACA_PAPER_KEY:key,ALPACA_PAPER_SECRET:secret,MI_ARMED:'false'},false); try{ const c=miConfig_(),a=miAccount_(c,true);miAssert_(miApi_(c,'/v2/positions').length===0,'Use an empty paper account. Existing holdings will not be imported or sold.'); miAssert_(miOpenOrders_(c).length===0,'Use a paper account with no open orders. Nothing was canceled.'); p.setProperties({EXPECTED_ACCOUNT_ID:a.id,MI_CONTAINER_ID:id,MI_SETUP_VERSION:MI_PAPER_SETUP_VERSION},false); miGmail_('messages?maxResults=1&q='+encodeURIComponent('from:hello@mountinflection.com')); return {status:'connected_paused',mode:'paper',accountSuffix:String(a.account_number).slice(-4),equity:Number(a.equity),capitalPercent:Number(settings.CAPITAL_PERCENT),maxOrderDollars:Number(settings.MAX_ORDER_DOLLARS),maxGrossPercent:Number(settings.MAX_GROSS_PERCENT),allowShorts:f.allowShorts,next:'Preview your delivered Pro issue. No orders or timer were created.'}; }catch(e){ Object.keys(p.getProperties()).filter(k=>!Object.hasOwnProperty.call(before,k)).forEach(k=>p.deleteProperty(k));p.setProperties(before,false);throw e; } });} function miPaperPreview(){miPaperContext_();const preview=previewLatestIssue();return preview;} function miPaperStart(f){ miPaperContext_();miAssert_(f&&f.confirmPaper===true,'Confirm that this uses simulated money and starts with new supported signals only.'); // Check preview before installing anything. Schedule creation deliberately remains paused. const c=miConfig_(),proof=JSON.parse(miProps_().getProperty('MI_PREVIEW')||'null'); miAssert_(proof&&proof.fingerprint===miFingerprint_(c)&&Date.now()-proof.at<7*86400000,'Preview the delivered Pro issue with these settings first.'); miAssert_(!miLoad_().active,'An unfinished run needs reconciliation before restart.'); installSchedule();enablePaperTrading();return miPaperStatus(); } function miPaperPause(){miPaperContext_();return pauseTrading();} function miPaperRefresh(){if(SpreadsheetApp.getActiveSpreadsheet().getId()===MI_PUBLIC_TEMPLATE_ID)return {status:'template_master',next:'Make your private copy first: File > Make a copy. Do not enter credentials in the shared template.'};miPaperContext_();return miPaperStatus();} function miPaperStatus(){ const p=miProps_();miPaperContext_(); if(!p.getProperty('EXPECTED_ACCOUNT_ID'))return {status:'setup_needed',mode:'paper',version:MI_PAPER_SETUP_VERSION,next:'Connect an unused paper account. Nothing is enabled.'}; const r=showStatus(),last=JSON.parse(p.getProperty('MI_PAPER_LAST_RUN')||'null'); const email=JSON.parse(p.getProperty('MI_ACTIVATION_EMAIL')||'null'); return {...r,confirmationEmail:email&&email.status,version:MI_PAPER_SETUP_VERSION,lastRun:last,settings:miPaperSavedSettings_(),coverage:'US equities only. Eligible shorts use whole shares. No crypto or cash borrowing for longs. New signals only; no existing-model catch-up.',next:r.active?'An unfinished issue needs broker reconciliation. Pausing does not cancel accepted orders.':r.armed?'Waiting for the next eligible Pro issue and market session.':'Paper automation is paused. Preview the current issue before starting.'}; } function miPaperScheduled_(){ try{ const r=miRun_();miProps_().setProperty('MI_PAPER_LAST_RUN',JSON.stringify({at:new Date().toISOString(),status:r.status,issue:r.issue||null}));return r; }catch(e){miProps_().setProperty('MI_PAPER_LAST_RUN',JSON.stringify({at:new Date().toISOString(),status:'paused_needs_review',reason:String(e.message)}));throw e;} } const MI_PAPER_HTML="\n
\n

Newsletter & activity

\n

Read your issue and check the schedule here. Manage your account and start, pause or restart from Trading controls.

\n\n

Your Pro newsletter

\n
Looking for the latest regular issue in this Gmail account\u2026
\n

This reads the dated issue. It does not start the schedule or send orders.

\n

Automation activity

\n
Checking the account and schedule\u2026
\n

Setup guide

\n
\n"; const MI_QUICK_PAPER_HTML = "\n\n\n\n\nMount Inflection trading controls\n\n\n\n
\n

\u00b7 Paper trading controls

\n

Alpaca Paper uses simulated money.

\n\n

Saving connects your account and leaves trading off. Preview, review and click Start Paper to turn it on.

\n

Checking your setup\u2026

\n\n\n
\n\n\n
\n
\n\n\n\n"; /* A stopped file never cancels accepted broker orders or liquidates holdings. */ function miStopForContainer_(reason) { const p=miProps_(); p.setProperty('MI_ARMED','false'); ['MI_PREVIEW','MI_CONTAINER_ARMED_VERSION','LIVE_CONFIRMATION','MI_ACTIVATION_EMAIL'].forEach(k=>p.deleteProperty(k)); p.setProperty('MI_CONTAINER_STOP',JSON.stringify({at:new Date().toISOString(),reason})); miRemoveTriggers_(['runScheduled','continueRun']); throw Error('Trading is OFF. '+reason+' Restore or reopen your private Sheet, review Alpaca, then preview and explicitly Start again.'); } function miCheckContainer_() { let id; try { const sheet=SpreadsheetApp.getActiveSpreadsheet(); id=sheet&&sheet.getId(); } catch(e) {} if(!id)return miStopForContainer_('The Sheet is unavailable.'); miAssert_(id!==MI_PUBLIC_TEMPLATE_ID,'Make your own private copy before connecting an account.'); const p=miProps_(),saved=p.getProperty('MI_CONTAINER_ID'); if(saved&&saved!==id)return miStopForContainer_('This is a different Sheet copy.'); let metadata; try { metadata=Drive.Files.get(id,{fields:'id,mimeType,trashed,version',supportsAllDrives:true}); } catch(e) { return miStopForContainer_('Google Drive could not verify the Sheet. Check its access and the requested Drive metadata permission.'); } if(!metadata||metadata.id!==id||metadata.mimeType!=='application/vnd.google-apps.spreadsheet'||typeof metadata.trashed!=='boolean'||!/^\d+$/.test(String(metadata.version||''))) return miStopForContainer_('Google Drive returned an incomplete Sheet check.'); if(metadata.trashed)return miStopForContainer_('The Sheet is in Google Drive Trash.'); const version=String(metadata.version); if(p.getProperty('MI_ARMED')==='true'&&p.getProperty('MI_CONTAINER_ARMED_VERSION')!==version) return miStopForContainer_('The Sheet changed since trading was started. This also protects a Sheet moved to Trash and restored between checks.'); p.setProperty('MI_CONTAINER_LAST_VERSION',version); return metadata; } function miPaperSavedSettings_() { const props = miProps_(); return { capitalPercent: Number(props.getProperty('CAPITAL_PERCENT')), maxOrderDollars: Number(props.getProperty('MAX_ORDER_DOLLARS')), maxGrossPercent: Number(props.getProperty('MAX_GROSS_PERCENT')), allowShorts: props.getProperty('ALLOW_SHORTS') === 'true' }; } function miPaperUpdateSettings(form) { miLock_(() => { const {id, p} = miPaperContext_(); miAssert_(p.getProperty('MI_CONTAINER_ID') === id && p.getProperty('EXPECTED_ACCOUNT_ID'), 'Connect your paper account first.'); const c = miConfig_(); const state = miLoad_(); miCheckBinding_(state, c); miAssert_(!state.active, 'Review the unfinished run before editing settings.'); const settings = miPaperSettings_(form); const fields = ['CAPITAL_PERCENT', 'MAX_ORDER_DOLLARS', 'MAX_GROSS_PERCENT', 'ALLOW_SHORTS']; if (fields.every(field => settings[field] === p.getProperty(field))) return; const account = miAccount_(c); miAssert_(settings.ALLOW_SHORTS === 'false' && Number(settings.MAX_GROSS_PERCENT) <= 100 || Number(account.multiplier) > 1, 'Shorts or gross exposure above 100% require a margin-enabled paper account.'); miAssert_(miOpenOrders_(c).length === 0, 'Review open paper orders before changing limits.'); const saved = Object.fromEntries(fields.map(field => [field, settings[field]])); p.setProperties({...saved, MI_ARMED:'false'}, false); p.deleteProperty('MI_PREVIEW'); p.deleteProperty('MI_ACTIVATION_EMAIL'); miRemoveTriggers_(['runScheduled','continueRun']); }); return miPaperStatus(); } /* Pro rapid-start planner. Pure functions: no credentials, network or order submission. */ var MIRapidStart = (function () { 'use strict'; function need(ok, reason) { if (!ok) throw Error(reason); } function num(x, name) { need(typeof x === 'number' && Number.isFinite(x), 'Invalid '+name); return x; } function day(x) { need(typeof x==='string' && /^\d{4}-\d{2}-\d{2}$/.test(x) && new Date(x+'T12:00:00Z').toISOString().slice(0,10)===x, 'Invalid session'); return x; } function symbol(x) { need(typeof x==='string' && /^[A-Z][A-Z0-9.\-]{0,14}$/.test(x),'Invalid symbol'); return x==='BRK-B'?'BRK.B':x; } function keys(x, expected) { need(x && typeof x==='object' && !Array.isArray(x) && Object.keys(x).sort().join('|')===expected.sort().join('|'),'Unknown or missing snapshot fields'); } function validate(s, d) { keys(s,['schema','publisher','tier','strategy_id','issue_id','source_session','effective_session','basis','status','cash_weight','positions']); need(s.schema==='mi.portfolio.start.v1' && s.publisher==='Mount Inflection' && s.tier==='pro', 'Not a Pro startup snapshot'); need(d && d.tier==='pro' && s.strategy_id===d.strategy_id && s.issue_id===d.issue_id && s.source_session===d.completed_equity_session,'Snapshot and newsletter differ'); need(s.basis==='next_session_target_weights' && s.status==='ready' && d.status!=='review_only', 'Snapshot is review-only or unsupported'); need(day(s.source_session)=day(d.issue_date),'Snapshot session mismatch'); need(Array.isArray(s.positions) && s.positions.length<=100, 'Snapshot too large'); const map={}, aliases=new Set(); let net=0; s.positions.forEach(p=>{ keys(p,['symbol','side','weight','model_entry_date','reference_price','price_session','asset_class']); const alias=symbol(p.symbol);need(!aliases.has(alias),'Duplicate symbol or broker alias');aliases.add(alias); need(['long','short'].includes(p.side),'Invalid side');need(num(p.weight,'weight')>0&&p.weight<=1,'Weight out of range'); need(num(p.reference_price,'reference price')>0 && day(p.price_session)===s.source_session,'Stale reference price'); need(day(p.model_entry_date)<=s.effective_session,'Invalid model entry episode'); need(p.asset_class==='us_equity','Unsupported instrument: '+p.symbol); map[p.symbol]=p;net+=p.weight*(p.side==='short'?-1:1); }); need(num(s.cash_weight,'cash weight')>=0 && Math.abs(net+s.cash_weight-1)<1e-8,'Cash and net weights do not reconcile'); d.actions.forEach(a=>{ need(a.effective_session===s.effective_session,'Delta and snapshot effective sessions differ'); const p=map[a.symbol]; if(['BUY','SHORT'].includes(a.action)) need(p && p.side===a.position_side && p.model_entry_date===a.position_entry_date && Math.abs(p.weight-a.sizing.model_equity_fraction)<1e-8,'New entry does not match snapshot'); else need(!p || p.side!==a.position_side || p.model_entry_date!==a.position_entry_date,'Exited episode remains in snapshot'); }); return s; } function discover(bodies, delta, parser, canonical) { const found=[]; bodies.forEach(body=>{ const begin='MI_PORTFOLIO_START_JSON_BEGIN',end='MI_PORTFOLIO_START_JSON_END'; const a=body.split(begin).length-1,b=body.split(end).length-1; if(!a&&!b)return; need(a===1&&b===1&&body.indexOf(end)>body.indexOf(begin),'Ambiguous startup snapshot'); const raw=body.split(begin)[1].split(end)[0].trim(),result=parser(raw,0); need(!raw.slice(result.end).trim(),'Trailing startup data');found.push(validate(result.value,delta)); }); need(found.length>0,'This issue has no verified current-portfolio startup data. Use new additions or wait for an eligible issue.'); need(found.every(x=>canonical(x)===canonical(found[0])),'HTML and text startup data conflict'); return found[0]; } function plan(s, c, account, market) { const equity=Number(account.equity),bp=Number(account.buying_power),cash=Number(account.cash); need(Number.isFinite(equity)&&equity>0&&Number.isFinite(bp)&&Number.isFinite(cash),'Invalid account balances'); need(c.tier==='pro' && c.capital>0&&c.capital<=1 && c.entry>0&&c.entry<=1 && c.gross>0&&c.gross<=2 && c.maxOrder>=1 && c.cashBuffer>=0,'Invalid allocation settings'); const budget=equity*c.capital,rows=[],issues=[]; let gross=0,long=0,short=0,reserved=0; s.positions.forEach(p=>{ const ticker=symbol(p.symbol),m=market[ticker],amount=Math.floor(budget*p.weight*100+1e-8)/100; const r={symbol:p.symbol,brokerSymbol:ticker,side:p.side,modelEntryDate:p.model_entry_date,modelWeight:p.weight, targetDollars:amount,referencePrice:p.reference_price,estimateDollars:0,payload:null,reasons:[]}; if(!m||!m.asset||m.asset.symbol!==ticker||m.asset.class!=='us_equity'||m.asset.status!=='active'||!m.asset.tradable||m.asset.exchange==='OTC')r.reasons.push('Unsupported broker instrument'); if(!m || !(m.ask>0) || !(m.bid>0) || m.ask=120000)r.reasons.push('Fresh regular-session quote required'); if(m?.gapBlocked)r.reasons.push('Existing entry-price gap safeguard requires review'); if(amount<1||amount>c.maxOrder||p.weight*c.capital>c.entry)r.reasons.push('Outside chosen order or position limit'); if(p.side==='short' && (!c.shorts||Number(account.multiplier)<=1||!m?.asset?.shortable||!m?.asset?.easy_to_borrow))r.reasons.push('Short permission or borrow unavailable'); if(p.side==='long'&&!m?.asset?.fractionable)r.reasons.push('Fractional long orders unavailable'); if(m?.ask>0) { const price=p.side==='short'?m.ask*1.03:m.ask; const qty=p.side==='short'?Math.floor(amount/price):null; if(qty!==null&&qty<1)r.reasons.push('Less than one short share'); r.estimateDollars=qty===null?amount:qty*price; r.estimatedShares=qty===null?amount/price:qty; r.payload={symbol:ticker,side:p.side==='long'?'buy':'sell',type:'market',time_in_force:'day'}; if(qty===null)r.payload.notional=amount.toFixed(2);else r.payload.qty=String(qty); gross+=r.estimateDollars;reserved+=r.estimateDollars; if(p.side==='long')long+=r.estimateDollars;else short+=r.estimateDollars; } rows.push(r); if(r.reasons.length)issues.push(p.symbol+': '+r.reasons.join('; ')); }); if(gross>equity*c.gross+1e-6)issues.push('Basket exceeds your gross exposure limit'); if(reserved>bp+1e-6)issues.push('Basket exceeds available buying power'); if(c.maxSession!==undefined && rows.reduce((n,r)=>n+r.targetDollars,0)>c.maxSession+1e-6)issues.push('Basket exceeds your market-session entry limit'); // Existing template does not borrow cash to buy longs or spend short-sale proceeds. if(long>Math.min(cash-c.cashBuffer,equity-c.cashBuffer,budget)+1e-6)issues.push('Long basket exceeds funded strategy capital or cash'); return {status:issues.length?'blocked_no_orders':'preview_no_orders',issue:s.issue_id,sourceSession:s.source_session, effectiveSession:s.effective_session,capitalDollars:budget,equityBasis:equity, modelCashDollars:budget*s.cash_weight,estimatedLongDollars:long,estimatedShortReserveDollars:short, estimatedGrossDollars:gross,estimatedWeightCoverage:s.positions.length?rows.reduce((n,r)=>n+(r.reasons.length?0:r.modelWeight),0)/s.positions.reduce((n,r)=>n+r.weight,0):1, rows,issues,note:'One-time entry at current prices; then entry/exit updates. Cash and short proceeds are not interchangeable buying power. No continuous rebalancing or exact-return match.'}; } function csv(plan) { const q=x=>'"'+String(x??'').replace(/"/g,'""')+'"'; const rows=[['Research startup worksheet \u2014 estimates, not fills'],['Issue',plan.issue,'Source',plan.sourceSession,'Session',plan.effectiveSession], ['Strategy amount',plan.capitalDollars,'Model cash reference',plan.modelCashDollars], ['Symbol','Side','Model weight','Target dollars','Estimated shares','Original model entry','Your actual fill date','Your actual fill price','Status']]; plan.rows.forEach(r=>rows.push([r.symbol,r.side,r.modelWeight,r.targetDollars,r.estimatedShares,r.modelEntryDate,'','',r.reasons.join('; ')||'Estimate \u2014 verify broker eligibility'])); plan.issues.forEach(x=>rows.push(['BLOCKER',x]));rows.push([plan.note]); return rows.map(row=>row.map(q).join(',')).join('\r\n')+'\r\n'; } return {validate,discover,plan,csv,symbol}; })(); if(typeof module!=='undefined')module.exports=MIRapidStart; function miRapidSource_(c) { const source=miReadIssue_(Object.assign({},c,{rapidRead:true}),true); miAssert_(source && source.snapshot,'No verified startup snapshot in the latest delivered issue'); return source; } function miRapidSourceHash_(source) { return miHash_(MINewsletter.canonical({delta:source.value,snapshot:source.snapshot})); } function miRapidFresh_(source) { miAssert_(source.snapshot.effective_session===miToday_(), 'Preview current holdings during their stated regular trading session. No old-issue catch-up.'); miAssert_(miMinutes_()>=570&&miMinutes_()<=645,'Startup is available 09:30\u201310:45 Eastern'); } function miRapidGuardInitial_(s){miAssert_(!s.rapid||!['queued','needs_review'].includes(s.rapid.status),'An older startup journal needs review before repair.');} function miRun_(activity){const s=miLoad_();if(s.repair&&s.repair.status==='running')return miRepairRun_(activity);if(s.repair&&s.repair.status==='needs_review')return {status:'repair_needs_review',reason:s.repair.reason};return miOrdinaryRun_(activity);} /* Pro account repair: deterministic planning and fill accounting, no I/O. */ var MIProRepair = (function(){ 'use strict'; function need(x,m){if(!x)throw Error(m);} function n(x){const v=Number(x);need(x!==null&&x!==''&&Number.isFinite(v),'Invalid numeric account value');return v;} function qty(x){return Math.round(x*1e9)/1e9;} function signed(p){return n(p.qty)*(p.side==='short'?-1:1);} function same(positions,owned){const actual={};positions.forEach(p=>{need(!Object.prototype.hasOwnProperty.call(actual,p.symbol),'Duplicate broker position');actual[p.symbol]=n(p.qty);});for(const k of new Set([...Object.keys(actual),...Object.keys(owned)]))need(Math.abs((actual[k]||0)-(owned[k]?signed(owned[k]):0))<1e-8,'Untracked holdings or quantity difference: '+k);} function applyFill(owned,row,order){ need(order&&order.client_order_id===row.payload.client_order_id&&order.symbol===row.payload.symbol&&order.side===row.payload.side&&order.type==='market'&&order.time_in_force==='day','Order identity differs'); if(row.payload.qty)need(Math.abs(n(order.qty)-n(row.payload.qty))<1e-8,'Order quantity differs'); if(row.payload.notional)need(n(order.notional)===n(row.payload.notional),'Order notional differs'); const filled=n(order.filled_qty||'0'),before=n(row.appliedQty||0);need(filled>=before&&filled>=0,'Fill quantity went backwards'); if(row.payload.qty)need(filled<=n(row.payload.qty)+1e-8,'Overfill'); const delta=qty(filled-before);if(!delta)return; const key=row.payload.symbol,old=owned[key],direction=row.positionSide||row.action.position_side,entry=row.entry||row.action.position_entry_date; const start=old?signed(old):0,end=qty(start+(row.payload.side==='buy'?delta:-delta)); if(row.action&&['SELL','COVER'].includes(row.action.action)||row.reduce){need(old&&old.side===direction&&old.entry===entry,'Exit ownership differs');need(start*end>=-1e-8&&Math.abs(end)<=Math.abs(start)+1e-8,'Exit would reverse or increase position');} else need(!old||(old.side===direction&&old.entry===entry),'Entry ownership differs'); if(Math.abs(end)<1e-8)delete owned[key]; else owned[key]={...(old||{}),side:end<0?'short':'long',qty:String(Math.abs(end)),entry,orderId:order.id}; row.appliedQty=filled; } function plan(snapshot,c,account,positions,owned,market,mode){ need(['repair','match'].includes(mode),'Choose repair or match');same(positions,owned); const equity=n(account.equity),budget=equity*c.capital;need(equity>0&&c.capital>0&&c.capital<=1,'Invalid allocation'); const wanted={},rows=[],kept=[],issues=[];snapshot.positions.forEach(p=>{const key=p.symbol==='BRK-B'?'BRK.B':p.symbol;need(!wanted[key],'Duplicate target');wanted[key]=p;}); for(const key of [...new Set([...Object.keys(owned),...Object.keys(wanted)])].sort()){ const old=owned[key],target=wanted[key],m=market[key]; if(old&&target&&(old.side!==target.side||old.entry!==target.model_entry_date)){issues.push(key+': model episode changed; close/reopen requires separate review');continue;} if(old&&target&&mode==='repair'){kept.push({symbol:key,qty:n(old.qty),reason:'Existing episode kept; size drift is not an error'});continue;} if(!m||!m.asset||m.asset.symbol!==key||m.asset.class!=='us_equity'||m.asset.status!=='active'||!m.asset.tradable||m.asset.exchange==='OTC'||!(m.ask>0)||!(m.bid>0)||m.ask=120000){issues.push(key+': current tradable asset and fresh quote required');continue;} const side=target?target.side:old.side; let desired=0; if(target){let raw=budget*target.weight/(side==='short'?m.ask*1.03:m.ask);desired=side==='short'||!m.asset.fractionable?Math.floor(raw):Math.floor(raw*1e9)/1e9;if(desired<=0){issues.push(key+': allocation below minimum quantity');continue;}} const current=old?n(old.qty):0,difference=qty(desired-current);if(Math.abs(difference)<1e-8||target&&Math.abs(difference)*m.ask<1){kept.push({symbol:key,qty:current,reason:'Within $1 rounding tolerance'});continue;} const reduce=difference<0,amount=Math.abs(difference)*m.ask*(side==='short'&&!reduce?1.03:1),action=reduce?(side==='short'?'COVER':'SELL'):(side==='short'?'SHORT':'BUY'); if(!reduce){ if(side==='long'&&!m.asset.fractionable)issues.push(key+': fractional long entries unavailable'); if(m.gapBlocked)issues.push(key+': entry price-gap check requires review'); if(amount>c.maxOrder+1e-8||desired*m.ask>equity*c.entry+1e-8)issues.push(key+': chosen order or position limit'); if(side==='short'&&(!c.shorts||n(account.multiplier)<=1||!m.asset.shortable||!m.asset.easy_to_borrow))issues.push(key+': short permission or borrow unavailable'); } rows.push({symbol:key,sourceSymbol:target?target.symbol:key,positionSide:side,entry:target?target.model_entry_date:old.entry,currentQty:current,targetQty:desired,reduce,actionName:action,estimateDollars:amount,priceReference:m.ask, payload:{symbol:key,side:(side==='long')!==reduce?'buy':'sell',qty:String(Math.abs(difference)),type:'market',time_in_force:'day',extended_hours:false}}); } rows.sort((a,b)=>Number(b.reduce)-Number(a.reduce)||a.symbol.localeCompare(b.symbol)); // Review final exposure using conservative ask values, and do not spend short proceeds. const end={...owned};rows.forEach(r=>{if(r.targetQty===0)delete end[r.symbol];else end[r.symbol]={side:r.positionSide,qty:r.targetQty,entry:r.entry};}); let long=0,gross=0;for(const [k,p] of Object.entries(end)){const price=market[k]?.ask;if(!(price>0)){issues.push(k+': cannot verify exposure');continue;}const dollars=n(p.qty)*price;gross+=dollars;if(p.side==='long')long+=dollars;} if(long>Math.min(equity-c.cashBuffer,budget)+.01)issues.push('Long exposure exceeds funded Pro allocation'); if(gross>equity*c.gross+.01)issues.push('Gross exposure exceeds your limit'); const entryDollars=rows.filter(r=>!r.reduce).reduce((a,r)=>a+r.estimateDollars,0); if(c.maxSession!==undefined&&entryDollars>c.maxSession+.01)issues.push('New orders exceed the session entry limit'); return {mode,status:issues.length?'blocked_no_orders':'preview_no_orders',issue:snapshot.issue_id,effectiveSession:snapshot.effective_session,capitalDollars:budget,rows,kept,issues,estimatedLongDollars:long,estimatedGrossDollars:gross,entryDollars,note:'One-time account change. Current prices, fees and rounding affect results. No continuous rebalancing or exact return match.'}; } return {plan,applyFill,same,qty}; })(); if(typeof module!=='undefined')module.exports=MIProRepair; /* Optional Pro repair. Ordinary daily entry/exit policy is unchanged. */ function miRepairGuard_(s){miAssert_(!s.repair||!['running','needs_review'].includes(s.repair.status),'Account repair is unfinished. Open Pro check & repair.');} function miRepairMarket_(c,snapshot,owned){ const entries=new Map(snapshot.positions.map(p=>[MINewsletter.brokerSymbol(p.symbol),p])); Object.keys(owned).forEach(k=>{if(!entries.has(k))entries.set(k,{symbol:k,side:owned[k].side});}); const market={};for(const [key,p] of entries){try{const asset=miApi_(c,'/v2/assets/'+encodeURIComponent(key)),q=miQuote_(c,key);const gap=typeof miEntryGap_==='function'?miEntryGap_(c,{symbol:p.symbol,action:p.side==='short'?'SHORT':'BUY',effective_session:snapshot.effective_session},snapshot.source_session):{skip:false};market[key]={asset,ask:Number(q.ap),bid:Number(q.bp),ageMs:Date.now()-Date.parse(q.t),gapBlocked:!!gap.skip};}catch(e){market[key]={error:String(e.message)};}}return market; } function miRepairPaused_(c){miAssert_(c.tier==='pro','This option is Pro only');miAssert_(miProps_().getProperty('MI_ARMED')!=='true','Pause trading before checking a repair');} function miProRepairPreview(form){return miLock_(()=>{ const c=miConfig_(),s=miLoad_();miRepairPaused_(c);miRepairGuard_(s);miRapidGuardInitial_(s);miCheckBinding_(s,c); miAssert_(!s.active,'Reconcile the unfinished run first. Do not discard its journal.'); const account=miAccount_(c),positions=miApi_(c,'/v2/positions');miAssert_(!miOpenOrders_(c).length,'Broker orders are still open. Wait for their outcome before a new plan.');MIProRepair.same(positions,s.owned); const source=miRapidSource_(c),plan=MIProRepair.plan(source.snapshot,c,account,positions,s.owned,miRepairMarket_(c,source.snapshot,s.owned),form&&form.mode); if(source.snapshot.effective_session!==miToday_())plan.issues.push('Use a current effective-session snapshot; this is a dated preview.'); if(plan.issues.length)plan.status='blocked_no_orders'; if(c.maxSession!==undefined&&plan.status==='preview_no_orders')miCheckSessionBudget_(c,s,source.snapshot.effective_session,Math.ceil(plan.entryDollars*100)); const proof={at:Date.now(),sourceHash:miRapidSourceHash_(source),fingerprint:miFingerprint_(c),ownedHash:miHash_(MINewsletter.canonical(s.owned)),source,plan}; s.repairPreview=proof;miSave_(s);return {...plan,accountSuffix:String(account.account_number).slice(-4),accountMode:c.mode,token:miHash_(MINewsletter.canonical(proof))}; });} function miProRepairApply(form){return miLock_(()=>{ const c=miConfig_(),s=miLoad_(),p=miProps_();miRepairPaused_(c);miRepairGuard_(s);miRapidGuardInitial_(s);miCheckBinding_(s,c);const v=s.repairPreview; miAssert_(form&&form.confirm===true&&v&&form.token===miHash_(MINewsletter.canonical(v)),'Preview and confirm this exact plan first'); miAssert_(v.plan.status==='preview_no_orders'&&Date.now()-v.at<10*60000&&v.fingerprint===miFingerprint_(c),'Preview expired or settings changed'); miAssert_(!s.active&&v.ownedHash===miHash_(MINewsletter.canonical(s.owned)),'Account journal changed; preview again'); miAssert_(!miOpenOrders_(c).length,'Open orders need review');MIProRepair.same(miApi_(c,'/v2/positions'),s.owned);miAccount_(c); const source=miRapidSource_(c);miRapidFresh_(source);miAssert_(miApi_(c,'/v2/clock').is_open,'Regular market must be open');miAssert_(miRapidSourceHash_(source)===v.sourceHash,'Newsletter changed; preview again'); if(c.mode==='live')miAssert_(form.live==='I ACCEPT LIVE TRADING','Type I ACCEPT LIVE TRADING for real-money changes'); miAssert_(v.plan.rows.length>0,'No repair orders are needed'); const id=Utilities.getUuid();s.repair={id,status:'running',source,sourceHash:v.sourceHash,fingerprint:v.fingerprint,mode:v.plan.mode,capitalDollars:v.plan.capitalDollars,at:new Date().toISOString(),rows:v.plan.rows.map((r,i)=>({...r,appliedQty:0,attempted:false,complete:false,payload:{...r.payload,client_order_id:'mi-fix-'+miHash_(miBinding_(c)+':'+id+':'+i).slice(0,32)}}))}; s.binding=miBinding_(c);if(!s.started)s.started=miToday_();delete s.repairPreview;miSave_(s); const container=miCheckContainer_();if(c.mode==='live')p.setProperty('LIVE_CONFIRMATION',form.live); p.setProperties({MI_ARMED_CONFIG:miFingerprint_(c),MI_CONTAINER_ARMED_VERSION:String(container.version),MI_ARMED:'true'},false);p.deleteProperty('MI_CONTAINER_STOP'); try{miResumeAt_(Date.now()+60000);}catch(e){p.setProperty('MI_ARMED','false');throw e;} return {status:'repair_scheduled',note:'The next scheduled check can submit the reviewed orders. Trading pauses when repair finishes. Check status before resuming ordinary updates.'}; });} function miRepairObserve_(c,s){ const r=s.repair;miAssert_(r,'No repair journal'); for(const row of r.rows){if(!row.attempted)continue;const o=miApi_(c,'/v2/orders:by_client_order_id?client_order_id='+encodeURIComponent(row.payload.client_order_id),'get',null,true);miAssert_(o,'Order outcome uncertain; verify with Alpaca. No retry was submitted.');MIProRepair.applyFill(s.owned,row,o);row.order=miViewOrder_(o);row.complete=o.status==='filled';miSave_(s);} MIProRepair.same(miApi_(c,'/v2/positions'),s.owned); const ids=new Set(r.rows.filter(x=>x.attempted).map(x=>x.payload.client_order_id));miAssert_(miOpenOrders_(c).every(o=>ids.has(o.client_order_id)),'Unrelated broker orders require review'); } function miRepairFinish_(s){ const r=s.repair;r.status='complete';r.completedAt=new Date().toISOString(); s.issues[r.source.value.issue_id]={digest:r.source.digest,date:r.source.value.issue_date}; r.source.value.actions.forEach(a=>{s.recent[a.action_id]={digest:miHash_(MINewsletter.canonical(a)),date:a.effective_session};});s.lastIssueDate=r.source.value.issue_date; s.lastReceipt={status:'repair_complete',issue:r.source.value.issue_id,mode:r.mode,filled:r.rows.length,orders:r.rows.map(x=>x.order)};miSave_(s);miProps_().setProperty('MI_ARMED','false');miRemoveTriggers_(['continueRun']); return {status:'repair_complete',note:'Actual fills reconciled. Trading is paused. Use Trading controls to preview and deliberately restart ordinary newsletter updates.'}; } function miRepairRun_(activity){return miLock_(()=>{ const c=miConfig_(),s=miLoad_(),r=s.repair,p=miProps_();if(p.getProperty('MI_ARMED')!=='true')return {status:'paused_no_orders'}; try{ miCanTrade_(c);miCheckBinding_(s,c);miAssert_(r&&r.status==='running'&&r.fingerprint===miFingerprint_(c),'Repair settings changed'); miRepairObserve_(c,s); for(const row of r.rows)if(row.attempted)miAssert_(!['rejected','canceled','expired','replaced','suspended'].includes(row.order.status),'Order '+row.order.status+'; reconcile known fills before another plan'); r.observations=(r.observations||0)+1;miAssert_(r.observations<=80,'Repair reconciliation limit reached; review actual fills');miSave_(s); if(r.rows.every(x=>x.complete)){miAssert_(!miOpenOrders_(c).length,'Orders remain open');return miRepairFinish_(s);} // One outstanding order at a time. Exits must fill before later entries. if(r.rows.some(x=>x.attempted&&!x.complete)){miResumeAt_(Date.now()+60000);return {status:'repair_waiting_for_fill'};} const row=r.rows.find(x=>!x.attempted);miAssert_(row,'Review unfinished repair');miRapidFresh_(r.source);miAssert_(miApi_(c,'/v2/clock').is_open,'Market closed'); miAssert_(miRapidSourceHash_(miRapidSource_(c))===r.sourceHash,'Newsletter changed; reconcile and preview a new plan'); const account=miAccount_(c),positions=miApi_(c,'/v2/positions');miAssert_(!miOpenOrders_(c).length,'Open orders require review');MIProRepair.same(positions,s.owned); const action={symbol:row.sourceSymbol,action:row.actionName,effective_session:r.source.snapshot.effective_session};miAsset_(c,action);const q=miQuote_(c,row.symbol),cost=Number(row.payload.qty)*Number(q.ap)*(row.actionName==='SHORT'?1.03:1); miAssert_(Number.isFinite(cost)&&cost>0,'Invalid order estimate'); if(row.reduce){const held=s.owned[row.symbol];miAssert_(held&&held.side===row.positionSide&&held.entry===row.entry&&Number(held.qty)+1e-8>=Number(row.payload.qty),'Exit no longer matches owned quantity');} else{ const gap=typeof miEntryGap_==='function'?miEntryGap_(c,action,r.source.snapshot.source_session):{skip:false};miAssert_(!gap.skip,'Entry price-gap check requires review'); miAssert_(cost<=row.estimateDollars*1.01+.01&&cost<=c.maxOrder,'Price or order size moved beyond preview'); const equity=Number(account.equity),gross=positions.reduce((a,x)=>a+Math.abs(Number(x.market_value)),0),long=positions.reduce((a,x)=>a+Math.max(0,Number(x.market_value)),0); miAssert_(gross+cost<=equity*c.gross&&Number(account.buying_power)>=cost,'Gross exposure or buying power limit'); miAssert_(row.targetQty*Number(q.ap)<=equity*c.entry,'Position limit'); if(row.actionName==='BUY')miAssert_(long+cost<=Math.min(equity-c.cashBuffer,r.capitalDollars),'Funded long allocation limit'); if(c.maxSession!==undefined)s.sessionEntryBudget={session:r.source.snapshot.effective_session,cents:miCheckSessionBudget_(c,s,r.source.snapshot.effective_session,Math.ceil(cost*100))}; } if(row.payload.side==='buy')miAssert_(Number(account.cash)-c.cashBuffer>=cost,'Cash unavailable; review before another order'); miCanTrade_(c);row.attempted=true;miSave_(s); const o=miApi_(c,'/v2/orders','post',row.payload);MIProRepair.applyFill(s.owned,row,o);row.order=miViewOrder_(o);row.complete=o.status==='filled';miSave_(s); if(activity){activity.issue=r.source.value.issue_id;activity.accountSuffix=String(account.account_number).slice(-4);activity.orders.push({symbol:row.symbol,action:row.actionName,status:o.status});} miResumeAt_(Date.now()+60000);return {status:'repair_reconciling',filled:r.rows.filter(x=>x.complete).length,total:r.rows.length}; }catch(e){if(r){r.status='needs_review';r.reason=String(e.message);miSave_(s);}p.setProperty('MI_ARMED','false');miRemoveTriggers_(['continueRun']);if(activity)activity.paused=true;miReport_({status:'repair_needs_review',reason:String(e.message)});throw e;} });} function miProRepairStatus(){const s=miLoad_(),r=s.repair;return r?{status:r.status,reason:r.reason||'',filled:r.rows.filter(x=>x.complete).length,total:r.rows.length,note:'Check broker orders before another plan. Pausing does not cancel accepted orders.'}:{status:s.active?'ordinary_run_unfinished':'no_repair_in_progress',note:s.active?'Pause and reconcile the unfinished run.':'Choose a preview. No account changes occur when checking.'};} function miProRepairReconcile(form){return miLock_(()=>{ const c=miConfig_(),s=miLoad_();miRepairPaused_(c);miCheckBinding_(s,c);miAccount_(c);miAssert_(form&&form.confirm===true,'Confirm reconciling actual broker fills'); if(s.repair&&['running','needs_review'].includes(s.repair.status)){ miRepairObserve_(c,s);const r=s.repair;miAssert_(!miOpenOrders_(c).length,'Orders still open; wait for their outcome'); miAssert_(r.rows.filter(x=>x.attempted).every(x=>['filled','rejected','canceled','expired'].includes(x.order.status)),'An order outcome is not final'); if(r.rows.every(x=>x.complete))return miRepairFinish_(s); s.repairReceipts=s.repairReceipts||[];s.repairReceipts.push({id:r.id,sourceHash:r.sourceHash,status:'ended_after_reconciliation',mode:r.mode,source:r.source,at:new Date().toISOString(),rows:r.rows});r.status='reconciled_incomplete';delete s.repairPreview;miSave_(s); return {status:'reconciled_incomplete',note:'Actual fills retained. Unsubmitted remainders were not sent. Preview a new current plan; trading remains paused.'}; } miAssert_(s.active,'No unfinished ordinary run to reconcile');const a=s.active,owned=JSON.parse(JSON.stringify(s.owned)),observed=[]; for(const row of a.rows){ if(!row.attempted&&!row.applied)continue; miAssert_(row.payload.client_order_id,'Attempted order has no identity');const o=miApi_(c,'/v2/orders:by_client_order_id?client_order_id='+encodeURIComponent(row.payload.client_order_id),'get',null,true);miAssert_(o,'Uncertain order outcome; do not retry');miAssert_(['filled','rejected','canceled','expired'].includes(o.status),'Wait for the broker order to finish or review it in Alpaca'); const copy=JSON.parse(JSON.stringify(row));if(row.applied)copy.appliedQty=Number(o.filled_qty);MIProRepair.applyFill(owned,copy,o);observed.push({action:row.action,payload:row.payload,order:miViewOrder_(o),appliedQty:Number(o.filled_qty)}); } miAssert_(!miOpenOrders_(c).length,'Open orders require review');MIProRepair.same(miApi_(c,'/v2/positions'),owned); s.repairReceipts=s.repairReceipts||[];s.repairReceipts.push({status:'ordinary_run_reconciled',issue:a.source.value.issue_id,at:new Date().toISOString(),observed,selection:a.selection,sourceDigest:a.source.digest,unsubmitted:a.rows.filter(x=>!x.attempted&&!x.applied).map(x=>x.action)});s.owned=owned; observed.forEach(x=>{s.recent[x.action.action_id]={digest:miHash_(MINewsletter.canonical(x.action)),date:x.action.effective_session};}); s.issues[a.source.value.issue_id]={digest:a.source.digest,date:a.source.value.issue_date,reconciledIncomplete:true};s.lastReceipt={status:'ordinary_run_reconciled',issue:a.source.value.issue_id,orders:observed.map(x=>x.order)};s.active=null;delete s.repairPreview;miSave_(s);miRemoveTriggers_(['continueRun']); return {status:'ordinary_run_reconciled',note:'Actual broker fills recorded. Old unsubmitted actions were not replayed. Preview a current repair or restart ordinary updates; trading remains paused.'}; });} function openProRepair(){SpreadsheetApp.getUi().showModalDialog(HtmlService.createHtmlOutput(MI_REPAIR_HTML).setWidth(720).setHeight(650),'Pro check & repair');} const MI_REPAIR_HTML="

Pro check & repair

Pause trading first. Check actual fills, then preview a one-time change using the amount you assigned to Pro.

Checking places no orders.

\n

Repair keeps quantities for existing model episodes. Match can add to or trim them. Both require a current eligible portfolio snapshot and may be blocked by account limits or unavailable holdings.

\n
Unfinished or rejected orders?

Wait for open orders to finish, or review them directly in Alpaca. Then reconcile actual fills here. This preserves filled quantities and retires unsubmitted remainders; it does not submit, cancel or retry orders. An uncertain outcome remains blocked.

Repair ends paused. Preview and Start ordinary updates when ready. A partial or blocked match is never called fully synchronized. Keep your original Sheet and order journal.

\n";