% === DAILY RESTART HEADER ===
close all; % Closes any open charts/figures from yesterday
clear java; % Specifically clears Java objects (critical for IB API)
clear all; % Clears all variables, globals, and compiled functions
clc; % Clears the command window for a fresh log
Stock code,aord hsi sti ftse gdaxi france gspc italy omx st ss sz ibex, 0001.hk for Chang Kong, H78.si for Hong Kong Land, gox for gold, wd for NewLonKong World Index etc.
Stock code is : cvx
What is the order price ? like 120.5 , to use market price just hit any key
Simple order with stop loss only.
Order Price : 172.58
Quantity : 29
Order type : MKT
StopLoss : 167.4026
Take Profit : 17258
Please confirm ! Type y and hit return key twice to confirm, or to hit any key to cancel ! y
Your order will be placed and please check on IB TWS !
๐ ATTEMPTING TO ACQUIRE LOCK FOR cvx
Maximum wait time: 300 seconds
Local lock acquired: LOCK_CVX_COMP2_20260131_025210_LOCAL.mat
Using local file lock (FTP unavailable)
โ LOCK ACQUIRED for cvx
Lock file: LOCK_CVX_COMP2_20260131_025157.mat
Wait time: 12.8 seconds
Trying cached IP: 192.168.0.236
added interface method: TWSNotification
notification listener has been added
-1 2104 Market data farm connection is OK:cashfarm
-1 2106 HMDS data farm connection is OK:apachmds
-1 2106 HMDS data farm connection is OK:cashhmds
-1 2104 Market data farm connection is OK:hfarm
-1 2104 Market data farm connection is OK:usfarm.nj
-1 2106 HMDS data farm connection is OK:ushmds
-1 2158 Sec-def data farm connection is OK:secdefhk
-1 2104 Market data farm connection is OK:usfarm
Connected to TWS at 192.168.0.236:7496 (Attempt 1)
Reusing connection to TWS via IP: 192.168.0.236
.Buffer stabilized with 1 entries in 0.5 seconds
Received Positions:
LBY.OLD 3600 0.47166665
SPT.CAYMA 11000 0.075
Processed 2 raw positions into 2 unique positions
=== Looking for lowercase files in: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/ ===
Looking for: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/lby.old.mat
โ File not found: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/lby.old.mat
Looking for: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/spt.cayma.mat
โ File not found: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/spt.cayma.mat
=== Done ===
DEBUG: Calling PortfolioStatus with:
StockName: cell array of 2 elements
StockQuantityNum: numeric array of 2 elements
openPriceNum: numeric array of 2 elements
currentPriceNum: numeric array of 2 elements
profitLossNum: numeric array of 2 elements
PortfolioStatus: Received price data for 2 positions
Warning: Data file not found for LBY.OLD
Warning: Data file not found for SPT.CAYMA
PortfolioIB: Keeping connection alive for other functions
Placing order…
Order placed successfully with ID: 2
Reusing connection to TWS via IP: 192.168.0.236
.Buffer stabilized with 1 entries in 0.5 seconds
Received Positions:
SPT.CAYMA 11000 0.075
CVX 29 173.8944827586207
CVX 29 173.86
CVX 29 173.8944827586207
LBY.OLD 3600 0.47166665
Processed 5 raw positions into 3 unique positions
=== Looking for lowercase files in: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/ ===
Looking for: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/cvx.mat
โ Found CVX: avg=173.88, current=172.58, P&L=-113.36
Looking for: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/lby.old.mat
โ File not found: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/lby.old.mat
Looking for: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/spt.cayma.mat
โ File not found: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/spt.cayma.mat
=== Done ===
DEBUG: Calling PortfolioStatus with:
StockName: cell array of 3 elements
StockQuantityNum: numeric array of 3 elements
openPriceNum: numeric array of 3 elements
currentPriceNum: numeric array of 3 elements
profitLossNum: numeric array of 3 elements
PortfolioStatus: Received price data for 3 positions
Use saved price info for CVX: 172.58
Warning: Data file not found for LBY.OLD
Warning: Data file not found for SPT.CAYMA
PortfolioStatus: Number of positions changed
****************************************************************************************************
PORTFOLIO PROFIT & LOSS (Long & Short)
****************************************************************************************************
Type Stock Qty AvgPrice CurPrice MarketValue Profit/Loss Return %%
—————————————————————————————————-
LONG CVX 87 173.88 172.58 15014.46 -113.36 -0.7%
LONG LBY.OLD 3600 0.47 0.47 1698.00 +0.00 +0.0%
LONG SPT.CAYMA 11000 0.07 0.07 825.00 +0.00 +0.0%
—————————————————————————————————-
TOTAL LOSS: -$113.36 (-0.6%)
Portfolio Market Value: $17537.46
****************************************************************************************************
PortfolioIB: Keeping connection alive for other functions
โ ORDER COMPLETE: Bought 87 shares
Reusing connection to TWS via IP: 192.168.0.236
.Buffer stabilized with 1 entries in 0.5 seconds
Received Positions:
CVX 29 173.8944827586207
LBY.OLD 3600 0.47166665
SPT.CAYMA 11000 0.075
Processed 3 raw positions into 3 unique positions
=== Looking for lowercase files in: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/ ===
Looking for: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/cvx.mat
โ Found CVX: avg=173.89, current=172.58, P&L=-38.12
Looking for: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/lby.old.mat
โ File not found: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/lby.old.mat
Looking for: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/spt.cayma.mat
โ File not found: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/spt.cayma.mat
=== Done ===
DEBUG: Calling PortfolioStatus with:
StockName: cell array of 3 elements
StockQuantityNum: numeric array of 3 elements
openPriceNum: numeric array of 3 elements
currentPriceNum: numeric array of 3 elements
profitLossNum: numeric array of 3 elements
PortfolioStatus: Received price data for 3 positions
Use saved price info for CVX: 172.58
Warning: Data file not found for LBY.OLD
Warning: Data file not found for SPT.CAYMA
PortfolioStatus: Position changed: LONG_CVX (was 87, now 29)
****************************************************************************************************
PORTFOLIO PROFIT & LOSS (Long & Short)
****************************************************************************************************
Type Stock Qty AvgPrice CurPrice MarketValue Profit/Loss Return %%
—————————————————————————————————-
LONG CVX 29 173.89 172.58 5004.82 -38.12 -0.8%
LONG LBY.OLD 3600 0.47 0.47 1698.00 +0.00 +0.0%
LONG SPT.CAYMA 11000 0.07 0.07 825.00 +0.00 +0.0%
—————————————————————————————————-
TOTAL LOSS: -$38.12 (-0.5%)
Portfolio Market Value: $7527.82
****************************************************************************************************
PortfolioIB: Keeping connection alive for other functions
Disconnected from TWS
Getting final position for reporting…
Trying cached IP: 192.168.0.236
java.net.SocketException: Socket closed
-1 2104 Market data farm connection is OK:usfarm.nj
-1 2104 Market data farm connection is OK:hfarm
-1 2104 Market data farm connection is OK:cashfarm
-1 2104 Market data farm connection is OK:usfarm
-1 2106 HMDS data farm connection is OK:cashhmds
-1 2106 HMDS data farm connection is OK:ushmds
-1 2106 HMDS data farm connection is OK:apachmds
-1 2158 Sec-def data farm connection is OK:secdefhk
Connected to TWS at 192.168.0.236:7496 (Attempt 1)
Connected to TWS via IP: 192.168.0.236
.Buffer stabilized with 1 entries in 0.5 seconds
Received Positions:
SPT.CAYMA 11000 0.075
CVX 29 173.8944827586207
LBY.OLD 3600 0.47166665
Processed 3 raw positions into 3 unique positions
=== Looking for lowercase files in: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/ ===
Looking for: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/cvx.mat
โ Found CVX: avg=173.89, current=172.58, P&L=-38.12
Looking for: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/lby.old.mat
โ File not found: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/lby.old.mat
Looking for: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/spt.cayma.mat
โ File not found: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/spt.cayma.mat
=== Done ===
DEBUG: Calling PortfolioStatus with:
StockName: cell array of 3 elements
StockQuantityNum: numeric array of 3 elements
openPriceNum: numeric array of 3 elements
currentPriceNum: numeric array of 3 elements
profitLossNum: numeric array of 3 elements
PortfolioStatus: Received price data for 3 positions
Use saved price info for CVX: 172.58
Warning: Data file not found for LBY.OLD
Warning: Data file not found for SPT.CAYMA
****************************************************************************************************
PORTFOLIO PROFIT & LOSS (Long & Short)
****************************************************************************************************
Type Stock Qty AvgPrice CurPrice MarketValue Profit/Loss Return %%
—————————————————————————————————-
LONG CVX 29 173.89 172.58 5004.82 -38.12 -0.8%
LONG LBY.OLD 3600 0.47 0.47 1698.00 +0.00 +0.0%
LONG SPT.CAYMA 11000 0.07 0.07 825.00 +0.00 +0.0%
—————————————————————————————————-
TOTAL LOSS: -$38.12 (-0.5%)
Portfolio Market Value: $7527.82
****************************************************************************************************
PortfolioIB: Keeping connection alive for other functions
DEBUG: Starting save process for BUY order…
Order details saved to MAT file: CVX20260130105232.mat
=== FORCE SAVE (Always executed) ===
โ Force saved: CVX_20260130105232_BUY_MKT_ID2_EX1_ATT0.mat
=== ORDER EXECUTION REPORT ===
Symbol: cvx
Action: BUY 29 shares
Type: MKT order
Order ID(s) used: 2
Attempts: 0
๐ POSITION ANALYSIS:
Starting position: 0 shares
Ending position: 87 shares
Change: +29 shares
โ CORRECT: Position changed as expected
๐ฏ FINAL CONCLUSION:
โ ORDER EXECUTED
Order was filled successfully
๐ก TIP: For after-hours trading, use LIMIT orders instead of MARKET
=== ORDER EXECUTION REPORT ===
Symbol: cvx
Action: BUY 29 shares
Type: MKT order
Final position: LONG 87 shares
Warning: Local lock release error: Unrecognized field name “timestamp”.
Connecting to TWS for stop-loss order…
Reusing existing connection
Placing stop-loss order at 167.40…
Stop-loss order placed with ID: 2
Warning: Could not save stop-loss order details
Disconnected from TWS
java.net.SocketException: Socket closed
Received Positions:
ENB 104 47.9287029
CNQ 136 36.71870255
DVN 128 39.0226086
BP 137 36.6187029
SM 262 19.05870255
Processed 5 raw positions into 5 unique positions
StockQuantity: [137 136 128 104 262]
Looking for data in: /Volumes/BarnUniJahr/StockPrograms/rawdatatemp
Data file not found: /Volumes/BarnUniJahr/StockPrograms/rawdatatemp/BP.mat
Using open price for BP (no current data)
Data file not found: /Volumes/BarnUniJahr/StockPrograms/rawdatatemp/CNQ.mat
Using open price for CNQ (no current data)
Data file not found: /Volumes/BarnUniJahr/StockPrograms/rawdatatemp/DVN.mat
Using open price for DVN (no current data)
Data file not found: /Volumes/BarnUniJahr/StockPrograms/rawdatatemp/ENB.mat
Using open price for ENB (no current data)
Data file not found: /Volumes/BarnUniJahr/StockPrograms/rawdatatemp/SM.mat
Using open price for SM (no current data)
Error using StocksTradedRecently
Too many input arguments.
Error in AutoStockTradingUS>BonusRecentlyTradedStock (line 1486)
function [output2,output3] = BonusRecentlyTradedStock(RecentlyTradedStockDays,StockCode,input2,input3,RecentlyTradedStockBonus,TechnicalPointBarLong,TechnicalPointBarShort,MareketStutusCheckPreFactor)
^
โ CLSK was NOT traded in the last 7 trading days (no files found)
Error using movefile
No matching files named ‘/Volumes/BarnUniJahr/StockPrograms/Orders/clsk.mat’ were found.
Error in AutoStockTradingUS>BonusRecentlyTradedStock (line 1513)
movefile(fullfile(ordersFolder, [StockCode,’.mat’]), …
% Determine position type and quantity to display
if qty > 0
posType = ‘LONG’;
displayQty = qty;
elseif qty 0
returnPercent = (pnl / abs(cost)) * 100;
end
>> % Example 3: Batch check
stockList = {‘ARKB’, ‘BITB’, ‘FBTC’, ‘AAPL’, ‘MSFT’, ‘SPY’, ‘TQQQ’, ‘VOO’};
results = CheckMultipleStocks(stockList);
Unrecognized function or variable ‘CheckMultipleStocks’.
>> % Example 1: Check single stock and add to list if restricted
[isRestricted, wasAdded, reason] = CheckAndRegisterRestricted(‘ARKB’, true);
=== Checking ARKB against Non-Tradable List ===
=== Checking ARKB via IB API ===
โ Known restricted security for Chinese accounts: ARKB
โ ARKB is RESTRICTED: Known restricted security for Chinese accounts: ARKB
=== Adding ARKB to Non-Tradable List ===
New York time is 4:26 >——->—–>——-> Market CLOSED <—–<—–<—– StockListsUS <=== other computers have to wait now …
Downloading………………….. StockListsUS.mat…………………………..
Merging downloaded file with local version (server priority)…
=== SMART MERGE DEBUGGING ===
Initial – Server: inclusive=877, exclusive=12670
Initial – Local: inclusive=852, exclusive=12708
Detected 167 intentionally moved tickers to protect
Protected moved tickers: AAOI, AAPL, ABBV, ABCL, ABEV, ABNB, ABR, ABT, AEO, AMC
Processing field: activeComputers
=== HANDLING OTHER FIELD: activeComputers ===
Processing field: claimTime
=== HANDLING OTHER FIELD: claimTime ===
Processing field: claimedBy
=== HANDLING METADATA FIELD: claimedBy ===
Processing field: created
=== HANDLING OTHER FIELD: created ===
Processing field: cycleCount
=== HANDLING OTHER FIELD: cycleCount ===
Processing field: exclusiveBondLikeStocks
=== HANDLING OTHER FIELD: exclusiveBondLikeStocks ===
Processing field: exclusiveDataFetching
=== MERGING LIST FIELD: exclusiveDataFetching ===
Moved ticker detection: 167 basic, 0 status-based, 8 claim-based, 167 total
All moved tickers: AAOI, AAPL, ABBV, ABCL, ABEV, ABNB, ABR, ABT, AEO, AMC, AMKR, ASM, ASML, ASO, AVUV, BKLN, BNS, BOIL, BOXX, BSV, BTE, BTQ, CNM, COGT, COLB, COUR, CYTK, DEFT, DFAC, DHI, DUOL, EMES, ERIC, EWTX, FIGR, FOLD, FRMI, FRSH, GD, GEHC, GEN, GENI, GLL, GLPI, GROY, HIMZ, HNST, HSBC, HTZ, HUMA, HUT, HYMC, IAUM, IAUX, IBN, IDEV, IFF, IMSR, IOVA, IVR, JMIA, KOLD, LCID, LIN, LITE, LKQ, LRCX, LUNR, MAS, MAT, MBB, MCHP, METU, MMC, MSOS, MSTR, MTUM, MU, MUB, MVIS, NAK, NEXT, NG, NGD, NOG, NRGV, NTR, NUAI, NVD, OKLL, ONDS, OTIS, PAA, PACB, PCAR, PRGO, PSA, PSLV, PULS, QBTZ, RCAT, REGN, RGTZ, RKLB, RPRX, RR, RRC, RSP, RUM, RXRX, SABR, SANA, SAP, SCHB, SCHO, SDHIR, SDS, SDVY, SEE, SFM, SIVR, SLS, SLV, SMCX, SNDK, SPHY, SPOT, SPXL, SPYG, SPYI, SRE, SSRM, STLA, STM, STUB, STWD, STZ, SW, SYK, SYM, T, TD, TE, TEVA, TMO, TPR, TSN, TT, UA, UDR, UMAC, VEA, VEEV, VGIT, VGT, VRTX, VSCO, WU, WVE, WY, XLC, XLE, XLG, XLI, XLK, ZETA, ZIM
=== MERGE WITH MOVE PROTECTION (EXCLUSIVE BATCHES): exclusiveDataFetching ===
Server exclusiveDataFetching: 12670 items
Local exclusiveDataFetching: 12708 items
Protected moved tickers: 167 items
LOCAL PRIORITY: Using local version for exclusiveDataFetching due to 167 moved tickers
Local priority merge: 12711 items (protected 167 moved tickers)
Processing field: exclusiveLiquidity
=== HANDLING OTHER FIELD: exclusiveLiquidity ===
Processing field: exclusiveListName
=== HANDLING OTHER FIELD: exclusiveListName ===
Processing field: exclusiveNonUSTradedStocks
=== HANDLING OTHER FIELD: exclusiveNonUSTradedStocks ===
Processing field: exclusiveNotToAutoClose
=== HANDLING OTHER FIELD: exclusiveNotToAutoClose ===
Processing field: exclusiveTier0Stocks
=== HANDLING OTHER FIELD: exclusiveTier0Stocks ===
Processing field: exclusiveTier1Stocks
=== HANDLING OTHER FIELD: exclusiveTier1Stocks ===
Processing field: exclusiveTier2Stocks
=== HANDLING OTHER FIELD: exclusiveTier2Stocks ===
Processing field: exclusiveTier3Stocks
=== HANDLING OTHER FIELD: exclusiveTier3Stocks ===
Processing field: inclusiveBondLikeStocks
=== HANDLING OTHER FIELD: inclusiveBondLikeStocks ===
Processing field: inclusiveDataFetching
=== MERGING LIST FIELD: inclusiveDataFetching ===
Moved ticker detection: 167 basic, 0 status-based, 0 claim-based, 167 total
All moved tickers: AAOI, AAPL, ABBV, ABCL, ABEV, ABNB, ABR, ABT, AEO, AMC, AMKR, ASM, ASML, ASO, AVUV, BKLN, BNS, BOIL, BOXX, BSV, BTE, BTQ, CNM, COGT, COLB, COUR, CYTK, DEFT, DFAC, DHI, DUOL, EMES, ERIC, EWTX, FIGR, FOLD, FRMI, FRSH, GD, GEHC, GEN, GENI, GLL, GLPI, GROY, HIMZ, HNST, HSBC, HTZ, HUMA, HUT, HYMC, IAUM, IAUX, IBN, IDEV, IFF, IMSR, IOVA, IVR, JMIA, KOLD, LCID, LIN, LITE, LKQ, LRCX, LUNR, MAS, MAT, MBB, MCHP, METU, MMC, MSOS, MSTR, MTUM, MU, MUB, MVIS, NAK, NEXT, NG, NGD, NOG, NRGV, NTR, NUAI, NVD, OKLL, ONDS, OTIS, PAA, PACB, PCAR, PRGO, PSA, PSLV, PULS, QBTZ, RCAT, REGN, RGTZ, RKLB, RPRX, RR, RRC, RSP, RUM, RXRX, SABR, SANA, SAP, SCHB, SCHO, SDHIR, SDS, SDVY, SEE, SFM, SIVR, SLS, SLV, SMCX, SNDK, SPHY, SPOT, SPXL, SPYG, SPYI, SRE, SSRM, STLA, STM, STUB, STWD, STZ, SW, SYK, SYM, T, TD, TE, TEVA, TMO, TPR, TSN, TT, UA, UDR, UMAC, VEA, VEEV, VGIT, VGT, VRTX, VSCO, WU, WVE, WY, XLC, XLE, XLG, XLI, XLK, ZETA, ZIM
=== MERGE WITH MOVE PROTECTION (EXCLUSIVE BATCHES): inclusiveDataFetching ===
Server inclusiveDataFetching: 877 items
Local inclusiveDataFetching: 852 items
Protected moved tickers: 167 items
LOCAL PRIORITY: Using local version for inclusiveDataFetching due to 167 moved tickers
Local priority merge: 852 items (protected 167 moved tickers)
Processing field: inclusiveLiquidity
=== HANDLING OTHER FIELD: inclusiveLiquidity ===
Processing field: inclusiveNonUSTradedStocks
=== HANDLING OTHER FIELD: inclusiveNonUSTradedStocks ===
Processing field: inclusiveNotToAutoClose
=== HANDLING OTHER FIELD: inclusiveNotToAutoClose ===
Processing field: inclusiveTier0Stocks
=== HANDLING OTHER FIELD: inclusiveTier0Stocks ===
Processing field: inclusiveTier1Stocks
=== HANDLING OTHER FIELD: inclusiveTier1Stocks ===
Processing field: inclusiveTier2Stocks
=== HANDLING OTHER FIELD: inclusiveTier2Stocks ===
Processing field: inclusiveTier3Stocks
=== HANDLING OTHER FIELD: inclusiveTier3Stocks ===
Processing field: lastRunDate
=== HANDLING OTHER FIELD: lastRunDate ===
Server lastRunDate: 07-Jan-2026 02:19:53
Local lastRunDate: 06-Jan-2026 12:38:14
Using SERVER lastRunDate (newer or equal)
Processing field: lastUpdated
=== HANDLING OTHER FIELD: lastUpdated ===
Server lastUpdated: 07-Jan-2026 02:19:54
Local lastUpdated: 06-Jan-2026 03:05:15
Using SERVER lastUpdated (newer or equal)
Processing field: status
=== HANDLING METADATA FIELD: status ===
Processing field: structureConversion
=== HANDLING OTHER FIELD: structureConversion ===
Processing field: timePerTicker
=== HANDLING OTHER FIELD: timePerTicker ===
=== CROSS-LIST CONSISTENCY CHECK WITH MOVE PROTECTION ===
Final – Merged: inclusive=852, exclusive=12711
Merge completed with move protection
Smart merge completed successfully.
Successfully downloaded /Volumes/BarnUniJahr/StockPrograms/rawdata/StockListsUS.mat from the ftp server to local computer !
Error adding ARKB to non-tradable list: Output argument "cleanedData" (and possibly others) not assigned a value in the execution with "checkTickerStatus" function.
โ Failed to add ARKB to non-tradable list
Your order will be placed and please check on IB TWS !
New York time is 10:33 <——-<———->—–>
TWSAccess =
0
Connected to TWS, thanks to Poe AI instructions
Error using TWSWrapper
The specified superclass ‘com.ib.client.EWrapper’ contains a parse error, cannot be found on MATLAB’s search path, or is
shadowed by another file with the same name.
Error in TradingIB (line 102)
clientSocket.setEWrapper(TWSWrapper()); % Assuming TWSWrapper is your custom class for handling events
Please confirm ! Type y and hit return key twice to confirm, or to hit any key to cancel ! y
Your order will be placed and please check on IB TWS !
New York time is 10:25 <——-<———->—–>
Error: File: TradingIB.m Line: 109 Column: 1
Illegal use of reserved keyword “classdef”.
% Before running IBTWSConnect, delete the cache:
cacheFile = ‘tws_ip_cache.mat’;
if exist(cacheFile, ‘file’)
delete(cacheFile);
fprintf(‘Cache file deleted to force IP scanning\n’);
end
% Now run your connection
[clientSocket, session, WIFIIP] = IBTWSConnect(7496, 0);
1. Testing direct Java connection…
added interface method: TWSNotification
notification listener has been added
Java objects created in 0.140s
eConnect() returned in 0.005s
โ Not connected after 0.146s
2. Testing through ibtwsOpen…
Warning: Objects of com/ib/client/EClientSocket class exist – not clearing java
> In javaclasspath
In javaclasspath
In javaaddpath (line 71)
In ibtwsOpen (line 9)
In testConnectionSpeed (line 52)
Warning: Objects of com/sun/proxy/$Proxy29 class exist – not clearing java
> In javaclasspath
In javaclasspath
In javaaddpath (line 71)
In ibtwsOpen (line 9)
In testConnectionSpeed (line 52)
Warning: Objects of com/tws/Handler class exist – not clearing java
> In javaclasspath
In javaclasspath
In javaaddpath (line 71)
In ibtwsOpen (line 9)
In testConnectionSpeed (line 52)
Warning: Objects of com/ib/client/EClientSocket class exist – not clearing java
> In javaclasspath
In javaclasspath
In javaaddpath (line 71)
In ibtwsOpen (line 10)
In testConnectionSpeed (line 52)
Warning: Objects of com/sun/proxy/$Proxy29 class exist – not clearing java
> In javaclasspath
In javaclasspath
In javaaddpath (line 71)
In ibtwsOpen (line 10)
In testConnectionSpeed (line 52)
Warning: Objects of com/tws/Handler class exist – not clearing java
> In javaclasspath
In javaclasspath
In javaaddpath (line 71)
In ibtwsOpen (line 10)
In testConnectionSpeed (line 52)
ibtwsOpen returned in 0.060s
โ Not connected via ibtwsOpen
=== Test complete ===
-1 502 Couldn’t connect to TWS. Confirm that “Enable ActiveX and Socket Clients” is enabled and connection port is the same as “Socket Port” on the TWS “Edit->Global Configuration…->API->Settings” menu. Live Trading ports: TWS: 7496; IB Gateway: 4001. Simulated Trading ports for new installations of version 954.1 or newer: TWS: 7497; IB Gateway: 4002
-1 502 Couldn’t connect to TWS. Confirm that “Enable ActiveX and Socket Clients” is enabled and connection port is the same as “Socket Port” on the TWS “Edit->Global Configuration…->API->Settings” menu. Live Trading ports: TWS: 7496; IB Gateway: 4001. Simulated Trading ports for new installations of version 954.1 or newer: TWS: 7497; IB Gateway: 4002
Testing PortfolioStatus function…
PortfolioStatus: Checking 8 positions (signed quantities):
LONG AAPL : 90
LONG MSFT : 80
LONG GOOGL : 120
LONG AMZN : 80
LONG TSLA : 80
LONG JPM : 130
LONG V : 140
LONG NVDA : 190
PortfolioStatus: Portfolio has changed
Saved portfolio with signed quantities: U8933912IB_20251229212651.mat
PortfolioStatus: Portfolio has changed (as expected for testing)
Testing PortfolioStatus function with mixed positions…
PortfolioStatus: Checking 8 positions (signed quantities):
LONG AAPL : 100
SHORT TSLA : -50
LONG MSFT : 50
SHORT NVDA : -20
LONG JPM : 200
SHORT GOOGL : -100
LONG AMZN : 80
SHORT V : -150
PortfolioStatus: Portfolio has changed
Saved portfolio with signed quantities: U8933912IB20251229215523.mat
PortfolioStatus: Portfolio has changed (as expected for testing)
Testing PortfolioStatus function…
PortfolioStatus: Checking 8 positions (signed quantities):
LONG AAPL : 90
LONG MSFT : 80
LONG GOOGL : 120
LONG AMZN : 80
LONG TSLA : 80
LONG JPM : 130
LONG V : 140
LONG NVDA : 190
PortfolioStatus: Portfolio has changed
Saved portfolio with signed quantities: U8933912IB_20251229212651.mat
PortfolioStatus: Portfolio has changed (as expected for testing)
Testing PortfolioStatus function…
PortfolioStatus: Checking 8 positions (signed quantities):
LONG AAPL : 16
LONG MSFT : 40
LONG GOOGL : 59
LONG AMZN : 94
LONG TSLA : 35
LONG JPM : 15
LONG V : 25
LONG NVDA : 74
PortfolioStatus: Portfolio has changed
Saved portfolio with signed quantities: U8933912IB_20251229204705.mat
PortfolioStatus: Portfolio has changed (as expected for testing)
% Show as a table for better visualization
fprintf(‘\n=== PORTFOLIO SUMMARY ===\n’);
for i = 1:length(StockName)
fprintf(‘%6s: Qty=%4d, Open=%.2f, Current=%.2f, P&L=%.2f, Cost=%.2f\n’, …
StockName{i}, StockQuantity(i), StockOpenPositionPrice(i), …
StockCurrentPrice(i), StockProfitLoss(i), StockCost(i));
end
>> [StockName, StockQuantity, StockOpenPositionPrice, StockCost, StockProfitLoss, StockCurrentPrice, PortfolioEmpty, PortfolioChanged] = PortfolioIB(Port, ComputerID0);
Reusing connection to TWS via IP: 127.0.0.1
.Buffer stabilized with 1 entries in 0.5 seconds
Received 15 positions (showing first 10):
GLD 12 410.13939165
GLDM 56 88.56625535
CGDV 113 44.22070265
RIO 63 79.8557603
JPM 15 326.12855335
SCHW 50 100.412206
RTX 27 183.90317405
EUFN 134 37.33870225
WFC 52 95.77543655
IAU 60 83.59103835
Processed 15 raw positions into 15 unique positions
StockQuantity: [113 134 12 56 64 60 113 15 9 36 63 27 50 118 52]
Looking for data in: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp
Loaded price for CGDV: 44.04
Loaded price for EUFN: 37.39
Loaded price for GLD: 416.74
Loaded price for GLDM: 89.71
Loaded price for HSBC: 79.97
Loaded price for IAU: 85.34
Loaded price for IAUM: 45.18
Loaded price for JPM: 327.91
Loaded price for MA: 579.60
Loaded price for NVS: 139.18
Loaded price for RIO: 82.24
Loaded price for RTX: 185.17
Loaded price for SCHW: 101.89
Loaded price for SGOL: 43.19
Loaded price for WFC: 95.26
Portfolio Positions (Signed):
LONG CGDV : 113 shares
LONG EUFN : 134 shares
LONG GLD : 12 shares
LONG GLDM : 56 shares
LONG HSBC : 64 shares
LONG IAU : 60 shares
LONG IAUM : 113 shares
LONG JPM : 15 shares
LONG MA : 9 shares
LONG NVS : 36 shares
LONG RIO : 63 shares
LONG RTX : 27 shares
LONG SCHW : 50 shares
LONG SGOL : 118 shares
LONG WFC : 52 shares
Net Position: 922 shares
PortfolioStatus: Checking 15 positions (signed quantities):
LONG CGDV : 113
LONG EUFN : 134
LONG GLD : 12
LONG GLDM : 56
LONG HSBC : 64
LONG IAU : 60
LONG IAUM : 113
LONG JPM : 15
LONG MA : 9
LONG NVS : 36
LONG RIO : 63
LONG RTX : 27
LONG SCHW : 50
LONG SGOL : 118
LONG WFC : 52
PortfolioStatus: Found matching portfolio: U8933912IB_2025-12-29_04-34-29.mat
PortfolioIB: Keeping connection alive for other functions
% Check if data directory exists
dataPath = fullfile(BaseFolder, ‘rawdata’, ‘rawdatatemp’);
disp([‘Data path: ‘, dataPath]);
disp([‘Exists: ‘, num2str(exist(dataPath, ‘dir’))]);
% List files
if exist(dataPath, ‘dir’)
files = dir(fullfile(dataPath, ‘*.mat’));
disp([‘Number of .mat files: ‘, num2str(length(files))]);
if ~isempty(files)
disp(‘First 3 files:’);
for i = 1:min(3, length(files))
disp(files(i).name);
end
end
end
Connected to TWS at 127.0.0.1:7496 (Attempt 1)
Connected to: 127.0.0.1
Created new persistent connection to TWS via IP: 127.0.0.1
Checking pre-trade position for AAPL…
Pre-trade position: 0 shares
Requesting order ID…
โ Error in BuySellIB: The class TWS.Events has no Constant property or Static method named ‘NEXT_VALID_ID’.
Keeping TWS connection alive for future trades.
โ FAILURE: Error (code: -1)
Unrecognized function or variable ‘cleanupIBConnection’.
Error in testBuySellIB_PaperTrading (line 52)
cleanupIBConnection();
^^^^^^^^^^^^^^^^^^^^^
Processing instrument CGDV 1 of 1 instruments.
New York time is 13:13 <——-<———->—–>
New York time is 13:13 <——-<———->—–>
Brace indexing is not supported for variables of this type.
Error in TechnicalPointsOfASetAuto (line 311)
disp([‘Stock Code: ‘,StockCodeIB,’ Quantity: ‘,num2str(StockQuantity{MarketScan}),’ with cost price , NOT latest price : ‘,num2str(StockOpenPositionPrice{MarketScan}),’ worth of ‘,num2str(StockQuantity{MarketScan}*StockOpenPositionPrice{MarketScan}),’ USD’]);
1000001 2174 Warning: You submitted request with date-time attributes without explicit time zone. Please switch to use yyyymmdd-hh:mm:ss in UTC or use instrument time zone, like US/Eastern. Implied time zone functionality will be removed in the next API release
1000001 2176 Warning: Your API version does not support fractional share size rules. Please upgrade to a minimum version 163. Trimmed value 564904.3 to 564904
Data streaming from IB TWS API is OK !
Received Positions from Brokerside:
RTX 27 183.90317405
HSBC 64 78.57067345
WFC 52 95.77543655
MA 9 578.4791222
IAU 60 83.59103835
C 0 0.0
SCHW 50 100.412206
NVS 36 139.03288055
EUFN 134 37.33870225
JPM 15 326.12855335
IAUM 113 44.24170265
SGOL 118 42.50870255
FHN 0 0.0
CGDV 113 44.22070265
RIO 63 79.8557603
GLDM 56 88.56625535
GLD 12 410.13939165
New York time is 12:45 <——-<———->—–>
New York time is 12:45 <——-<———->—–>
New York time is 12:45 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
StockQuantity: [113;134;12;56;64;60;113;15;9;36;63;27;50;118;52]
No change in the portfolio.
Error using cellfun
cellfun works only on cells.
Error in TechnicalPointsOfASetAuto (line 111)
StockOpenPositionPrice = StockOpenPositionPrice(~cellfun(‘isempty’, StockOpenPositionPrice));
97 tickers to include, 3 tickers to exclude
Successfully updated the stock lists and uploaded to ftp sever !
Error using matlab.io.FTP/delete (line 10)
delete(ftpObj, currentLockFile);
^^^^^^^^^^^^^^^
Invalid argument at position 2.
Input should be a non-empty, non-missing string.
Error in InclusiveExclusiveListReview>releaseGlobalLock (line 3329)
delete(ftpObj, currentLockFile);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in InclusiveExclusiveListReview>updateAndUpload (line 2556)
globalLockFileFreeOnftpServer = releaseGlobalLock(globalLockFile,globalLockFileNYTime,localFolder,remoteFolder);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in InclusiveExclusiveListReview (line 861)
[ListUpdateStatus,FileTransferStatus] = updateAndUpload(loadedData, processed, toExclude, toInclude, …
Data received for stock ====>> tfc <<=====
Disconnected from TWS.
L =
500
ans =
7.3996e+05
ans =
'10-Dec-2025 12:00:00'
c1 =
0
java.net.SocketException: Socket closed
ans =
739960
ans =
'09-Dec-2025'
c1 =
1
% === DAILY RESTART HEADER ===
close all; % Closes any open charts/figures from yesterday
clear java; % Specifically clears Java objects (critical for IB API)
clear all; % Clears all variables, globals, and compiled functions
clc; % Clears the command window for a fresh log
fprintf(‘๐ Starting Trading Session: %s\n’, datestr(now));
% ============================
Buy or Sell ? b/s default is buy b
action =
‘BUY’
Stock code,aord hsi sti ftse gdaxi france gspc italy omx st ss sz ibex, 0001.hk for Chang Kong, H78.si for Hong Kong Land, gox for gold, wd for NewLonKong World Index etc.
Stock code is : cvx
What is the order price ? like 120.5 , to use market price just hit any key
Simple order with stop loss only.
Order Price : 172.58
Quantity : 29
Order type : MKT
StopLoss : 167.4026
Take Profit : 17258
Please confirm ! Type y and hit return key twice to confirm, or to hit any key to cancel ! y
Your order will be placed and please check on IB TWS !
๐ ATTEMPTING TO ACQUIRE LOCK FOR cvx
Maximum wait time: 300 seconds
Local lock acquired: LOCK_CVX_COMP2_20260131_025210_LOCAL.mat
Using local file lock (FTP unavailable)
โ LOCK ACQUIRED for cvx
Lock file: LOCK_CVX_COMP2_20260131_025157.mat
Wait time: 12.8 seconds
Trying cached IP: 192.168.0.236
added interface method: TWSNotification
notification listener has been added
-1 2104 Market data farm connection is OK:cashfarm
-1 2106 HMDS data farm connection is OK:apachmds
-1 2106 HMDS data farm connection is OK:cashhmds
-1 2104 Market data farm connection is OK:hfarm
-1 2104 Market data farm connection is OK:usfarm.nj
-1 2106 HMDS data farm connection is OK:ushmds
-1 2158 Sec-def data farm connection is OK:secdefhk
-1 2104 Market data farm connection is OK:usfarm
Connected to TWS at 192.168.0.236:7496 (Attempt 1)
Reusing connection to TWS via IP: 192.168.0.236
.Buffer stabilized with 1 entries in 0.5 seconds
Received Positions:
LBY.OLD 3600 0.47166665
SPT.CAYMA 11000 0.075
Processed 2 raw positions into 2 unique positions
=== Looking for lowercase files in: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/ ===
Looking for: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/lby.old.mat
โ File not found: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/lby.old.mat
Looking for: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/spt.cayma.mat
โ File not found: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/spt.cayma.mat
=== Done ===
DEBUG: Calling PortfolioStatus with:
StockName: cell array of 2 elements
StockQuantityNum: numeric array of 2 elements
openPriceNum: numeric array of 2 elements
currentPriceNum: numeric array of 2 elements
profitLossNum: numeric array of 2 elements
PortfolioStatus: Received price data for 2 positions
Warning: Data file not found for LBY.OLD
Warning: Data file not found for SPT.CAYMA
****************************************************************************************************
PORTFOLIO PROFIT & LOSS (Long & Short)
****************************************************************************************************
Type Stock Qty AvgPrice CurPrice MarketValue Profit/Loss Return %%
—————————————————————————————————-
LONG LBY.OLD 3600 0.47 0.47 1698.00 +0.00 +0.0%
LONG SPT.CAYMA 11000 0.07 0.07 825.00 +0.00 +0.0%
—————————————————————————————————-
BREAK EVEN: $0.00
Portfolio Market Value: $2523.00
****************************************************************************************************
PortfolioIB: Keeping connection alive for other functions
Placing order…
Order placed successfully with ID: 2
Reusing connection to TWS via IP: 192.168.0.236
.Buffer stabilized with 1 entries in 0.5 seconds
Received Positions:
SPT.CAYMA 11000 0.075
CVX 29 173.8944827586207
CVX 29 173.86
CVX 29 173.8944827586207
LBY.OLD 3600 0.47166665
Processed 5 raw positions into 3 unique positions
=== Looking for lowercase files in: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/ ===
Looking for: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/cvx.mat
โ Found CVX: avg=173.88, current=172.58, P&L=-113.36
Looking for: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/lby.old.mat
โ File not found: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/lby.old.mat
Looking for: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/spt.cayma.mat
โ File not found: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/spt.cayma.mat
=== Done ===
DEBUG: Calling PortfolioStatus with:
StockName: cell array of 3 elements
StockQuantityNum: numeric array of 3 elements
openPriceNum: numeric array of 3 elements
currentPriceNum: numeric array of 3 elements
profitLossNum: numeric array of 3 elements
PortfolioStatus: Received price data for 3 positions
Use saved price info for CVX: 172.58
Warning: Data file not found for LBY.OLD
Warning: Data file not found for SPT.CAYMA
PortfolioStatus: Number of positions changed
****************************************************************************************************
PORTFOLIO PROFIT & LOSS (Long & Short)
****************************************************************************************************
Type Stock Qty AvgPrice CurPrice MarketValue Profit/Loss Return %%
—————————————————————————————————-
LONG CVX 87 173.88 172.58 15014.46 -113.36 -0.7%
LONG LBY.OLD 3600 0.47 0.47 1698.00 +0.00 +0.0%
LONG SPT.CAYMA 11000 0.07 0.07 825.00 +0.00 +0.0%
—————————————————————————————————-
TOTAL LOSS: -$113.36 (-0.6%)
Portfolio Market Value: $17537.46
****************************************************************************************************
PortfolioIB: Keeping connection alive for other functions
โ ORDER COMPLETE: Bought 87 shares
Reusing connection to TWS via IP: 192.168.0.236
.Buffer stabilized with 1 entries in 0.5 seconds
Received Positions:
CVX 29 173.8944827586207
LBY.OLD 3600 0.47166665
SPT.CAYMA 11000 0.075
Processed 3 raw positions into 3 unique positions
=== Looking for lowercase files in: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/ ===
Looking for: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/cvx.mat
โ Found CVX: avg=173.89, current=172.58, P&L=-38.12
Looking for: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/lby.old.mat
โ File not found: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/lby.old.mat
Looking for: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/spt.cayma.mat
โ File not found: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/spt.cayma.mat
=== Done ===
DEBUG: Calling PortfolioStatus with:
StockName: cell array of 3 elements
StockQuantityNum: numeric array of 3 elements
openPriceNum: numeric array of 3 elements
currentPriceNum: numeric array of 3 elements
profitLossNum: numeric array of 3 elements
PortfolioStatus: Received price data for 3 positions
Use saved price info for CVX: 172.58
Warning: Data file not found for LBY.OLD
Warning: Data file not found for SPT.CAYMA
PortfolioStatus: Position changed: LONG_CVX (was 87, now 29)
****************************************************************************************************
PORTFOLIO PROFIT & LOSS (Long & Short)
****************************************************************************************************
Type Stock Qty AvgPrice CurPrice MarketValue Profit/Loss Return %%
—————————————————————————————————-
LONG CVX 29 173.89 172.58 5004.82 -38.12 -0.8%
LONG LBY.OLD 3600 0.47 0.47 1698.00 +0.00 +0.0%
LONG SPT.CAYMA 11000 0.07 0.07 825.00 +0.00 +0.0%
—————————————————————————————————-
TOTAL LOSS: -$38.12 (-0.5%)
Portfolio Market Value: $7527.82
****************************************************************************************************
PortfolioIB: Keeping connection alive for other functions
Disconnected from TWS
Getting final position for reporting…
Trying cached IP: 192.168.0.236
java.net.SocketException: Socket closed
-1 2104 Market data farm connection is OK:usfarm.nj
-1 2104 Market data farm connection is OK:hfarm
-1 2104 Market data farm connection is OK:cashfarm
-1 2104 Market data farm connection is OK:usfarm
-1 2106 HMDS data farm connection is OK:cashhmds
-1 2106 HMDS data farm connection is OK:ushmds
-1 2106 HMDS data farm connection is OK:apachmds
-1 2158 Sec-def data farm connection is OK:secdefhk
Connected to TWS at 192.168.0.236:7496 (Attempt 1)
Connected to TWS via IP: 192.168.0.236
.Buffer stabilized with 1 entries in 0.5 seconds
Received Positions:
SPT.CAYMA 11000 0.075
CVX 29 173.8944827586207
LBY.OLD 3600 0.47166665
Processed 3 raw positions into 3 unique positions
=== Looking for lowercase files in: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/ ===
Looking for: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/cvx.mat
โ Found CVX: avg=173.89, current=172.58, P&L=-38.12
Looking for: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/lby.old.mat
โ File not found: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/lby.old.mat
Looking for: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/spt.cayma.mat
โ File not found: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/spt.cayma.mat
=== Done ===
DEBUG: Calling PortfolioStatus with:
StockName: cell array of 3 elements
StockQuantityNum: numeric array of 3 elements
openPriceNum: numeric array of 3 elements
currentPriceNum: numeric array of 3 elements
profitLossNum: numeric array of 3 elements
PortfolioStatus: Received price data for 3 positions
Use saved price info for CVX: 172.58
Warning: Data file not found for LBY.OLD
Warning: Data file not found for SPT.CAYMA
****************************************************************************************************
PORTFOLIO PROFIT & LOSS (Long & Short)
****************************************************************************************************
Type Stock Qty AvgPrice CurPrice MarketValue Profit/Loss Return %%
—————————————————————————————————-
LONG CVX 29 173.89 172.58 5004.82 -38.12 -0.8%
LONG LBY.OLD 3600 0.47 0.47 1698.00 +0.00 +0.0%
LONG SPT.CAYMA 11000 0.07 0.07 825.00 +0.00 +0.0%
—————————————————————————————————-
TOTAL LOSS: -$38.12 (-0.5%)
Portfolio Market Value: $7527.82
****************************************************************************************************
PortfolioIB: Keeping connection alive for other functions
DEBUG: Starting save process for BUY order…
Order details saved to MAT file: CVX20260130105232.mat
=== FORCE SAVE (Always executed) ===
โ Force saved: CVX_20260130105232_BUY_MKT_ID2_EX1_ATT0.mat
=== ORDER EXECUTION REPORT ===
Symbol: cvx
Action: BUY 29 shares
Type: MKT order
Order ID(s) used: 2
Attempts: 0
๐ POSITION ANALYSIS:
Starting position: 0 shares
Ending position: 29 shares
Change: +29 shares
๐ POSITION ANALYSIS:
Starting position: 0 shares
Ending position: 87 shares
Change: +29 shares
โ CORRECT: Position changed as expected
๐ฏ FINAL CONCLUSION:
โ ORDER EXECUTED
Order was filled successfully
๐ก TIP: For after-hours trading, use LIMIT orders instead of MARKET
=== ORDER EXECUTION REPORT ===
Symbol: cvx
Action: BUY 29 shares
Type: MKT order
Final position: LONG 87 shares
Warning: Local lock release error: Unrecognized field name “timestamp”.
Connecting to TWS for stop-loss order…
Reusing existing connection
Placing stop-loss order at 167.40…
Stop-loss order placed with ID: 2
Warning: Could not save stop-loss order details
Disconnected from TWS
java.net.SocketException: Socket closed
Received Positions:
ENB 104 47.9287029
CNQ 136 36.71870255
DVN 128 39.0226086
BP 137 36.6187029
SM 262 19.05870255
Processed 5 raw positions into 5 unique positions
StockQuantity: [137 136 128 104 262]
Looking for data in: /Volumes/BarnUniJahr/StockPrograms/rawdatatemp
Data file not found: /Volumes/BarnUniJahr/StockPrograms/rawdatatemp/BP.mat
Using open price for BP (no current data)
Data file not found: /Volumes/BarnUniJahr/StockPrograms/rawdatatemp/CNQ.mat
Using open price for CNQ (no current data)
Data file not found: /Volumes/BarnUniJahr/StockPrograms/rawdatatemp/DVN.mat
Using open price for DVN (no current data)
Data file not found: /Volumes/BarnUniJahr/StockPrograms/rawdatatemp/ENB.mat
Using open price for ENB (no current data)
Data file not found: /Volumes/BarnUniJahr/StockPrograms/rawdatatemp/SM.mat
Using open price for SM (no current data)
[StockName, StockQuantity, StockOpenPositionPrice, StockCost, StockProfitLoss, StockCurrentPrice, PortfolioEmpty, PortfolioChanged] = PortfolioIB(Port, ComputerID0);
Reusing connection to TWS via IP: 127.0.0.1โจ.Buffer stabilized with 1 entries in 0.5 secondsโจReceived Positions:โจSPT.CAYMA 11000 0.075โจQQQ 8 626.465โจLBY.OLD 3600 0.47166665
Processed 3 raw positions into 3 unique positionsโจPortfolioStatus: Received price data for 3 positions
Warning: Data file not found for LBY.OLDโจUse saved price info for QQQ: 631.34
Warning: Data file not found for SPT.CAYMA
โจ****************************************************************************************************โจPORTFOLIO PROFIT & LOSS (Long & Short)โจ****************************************************************************************************โจType Stock Qty AvgPrice CurPrice MarketValue Profit/Loss Return %%โจ—————————————————————————————————-โจLONG LBY.OLD 3600 0.47 0.47 1698.00 +0.00 +0.0%โจLONG QQQ 8 626.47 631.34 5050.72 +39.00 +0.8%โจLONG SPT.CAYMA 11000 0.07 0.07 825.00 +0.00 +0.0%โจ—————————————————————————————————-โจTOTAL PROFIT: +$39.00 (+0.5%)โจPortfolio Market Value: $7573.72โจ****************************************************************************************************โจโจPortfolioIB: Keeping connection alive for other functions
Forex pair detected: USD/EUR
IB format: Symbol=USD, Exchange=IDEALPRO, SecType=CASH, Currency=EUR
Forex pair detected: USD/EUR
IB format: Symbol=USD, Exchange=IDEALPRO, SecType=CASH, Currency=EUR
StockHistoricalPriceDataIB.m called by StockPriceData.m
StockHistoricalPriceDataIB.m , calls MarketIdentifier.m and DownloadYahooStockPriceDataHandling.m
New York time is 6:33 >——->—–>——-> Market CLOSED <—–<—–<————>—–>——-> Market CLOSED <—–<—–<—–> usd <<=====
Got 500 bars of data
Disconnected from TWS.
21-Jan-2026 54.39 56.38 57.43 53.98 8299
20-Jan-2026 55.17 53.47 55.86 53.31 6067
16-Jan-2026 58.09 57.58 59.08 57.1 4711
15-Jan-2026 57.45 56.54 58.38 56.38 7781
14-Jan-2026 55.37 54.74 55.37 53.3 5068
Forex pair detected: USD/EUR
IB format: Symbol=USD, Exchange=IDEALPRO, SecType=CASH, Currency=EUR
Forex pair detected: USD/EUR
IB format: Symbol=USD, Exchange=IDEALPRO, SecType=CASH, Currency=EUR
StockHistoricalPriceDataIB.m called by StockPriceData.m
StockHistoricalPriceDataIB.m , calls MarketIdentifier.m and DownloadYahooStockPriceDataHandling.m
New York time is 6:33 >——->—–>——-> Market CLOSED <—–<—–<————>—–>——-> Market CLOSED <—–<—–<—–> usd <<=====
Got 500 bars of data
Disconnected from TWS.
21-Jan-2026 54.39 56.38 57.43 53.98 8299
20-Jan-2026 55.17 53.47 55.86 53.31 6067
16-Jan-2026 58.09 57.58 59.08 57.1 4711
15-Jan-2026 57.45 56.54 58.38 56.38 7781
14-Jan-2026 55.37 54.74 55.37 53.3 5068
Error using StocksTradedRecently
Too many input arguments.
Error in AutoStockTradingUS>BonusRecentlyTradedStock (line 1486)
function [output2,output3] = BonusRecentlyTradedStock(RecentlyTradedStockDays,StockCode,input2,input3,RecentlyTradedStockBonus,TechnicalPointBarLong,TechnicalPointBarShort,MareketStutusCheckPreFactor)
^
[AccountCapitalManagement,NewOrderValue] = AccountCapitalManagementCheck(StockCode,TechnicalPointLong,action,TradingSetting);
โ CLSK was NOT traded in the last 7 trading days (no files found)
Error using movefile
No matching files named ‘/Volumes/BarnUniJahr/StockPrograms/Orders/clsk.mat’ were found.
Error in AutoStockTradingUS>BonusRecentlyTradedStock (line 1513)
movefile(fullfile(ordersFolder, [StockCode,’.mat’]), …
Error: File: BuySellIB.m Line: 573 Column: 9
Illegal use of reserved keyword “catch”.
% ———- 3. DISPLAY PROFIT/LOSS RESULTS ———-
if ~PortfolioEmpty && ~isempty(StockName)
fprintf(‘\n%s\n’, repmat(‘*’, 100, 1));
fprintf(‘PORTFOLIO PROFIT & LOSS (Long & Short)\n’);
fprintf(‘%s\n’, repmat(‘*’, 100, 1));
fprintf(‘%-6s %-6s %8s %10s %10s %12s %12s %10s\n’, …
‘Type’, ‘Stock’, ‘Qty’, ‘AvgPrice’, ‘CurPrice’, ‘MarketValue’, ‘Profit/Loss’, ‘Return %%’);
fprintf(‘%s\n’, repmat(‘-‘, 100, 1));
totalMarketValue = 0;
for i = 1:length(StockName)
qty = StockQuantity{i};
avgPrice = StockOpenPositionPrice{i};
curPrice = StockCurrentPrice{i};
pnl = StockProfitLoss{i};
cost = StockCost{i};
% Calculate Market Value
marketValue = qty * curPrice;
totalMarketValue = totalMarketValue + marketValue;
% Determine position type and quantity to display
if qty > 0
posType = ‘LONG’;
displayQty = qty;
elseif qty 0
returnPercent = (pnl / abs(cost)) * 100;
end
fprintf(‘%-6s %-6s %8d %10.2f %10.2f %12.2f %+12.2f %+9.1f%%\n’, …
posType, StockName{i}, displayQty, avgPrice, curPrice, marketValue, pnl, returnPercent);
end
fprintf(‘%s\n’, repmat(‘-‘, 100, 1));
% Summary – need to convert cells to numeric for summary
totalCost = sum(cell2mat(StockCost));
totalPnL = sum(cell2mat(StockProfitLoss));
totalReturn = 0;
if abs(totalCost) > 0
totalReturn = (totalPnL / abs(totalCost)) * 100;
end
if totalPnL > 0
fprintf(‘TOTAL PROFIT: +$%.2f (+%.1f%%)\n’, totalPnL, totalReturn);
elseif totalPnL < 0
fprintf('TOTAL LOSS: -$%.2f (%.1f%%)\n', abs(totalPnL), totalReturn);
else
fprintf('BREAK EVEN: $0.00\n');
end
fprintf('Portfolio Market Value: $%.2f\n', totalMarketValue);
fprintf('%s\n\n', repmat('*', 100, 1));
end
>> % Example 3: Batch check
stockList = {‘ARKB’, ‘BITB’, ‘FBTC’, ‘AAPL’, ‘MSFT’, ‘SPY’, ‘TQQQ’, ‘VOO’};
results = CheckMultipleStocks(stockList);
Unrecognized function or variable ‘CheckMultipleStocks’.
>> % Example 1: Check single stock and add to list if restricted
[isRestricted, wasAdded, reason] = CheckAndRegisterRestricted(‘ARKB’, true);
=== Checking ARKB against Non-Tradable List ===
=== Checking ARKB via IB API ===
โ Known restricted security for Chinese accounts: ARKB
โ ARKB is RESTRICTED: Known restricted security for Chinese accounts: ARKB
=== Adding ARKB to Non-Tradable List ===
New York time is 4:26 >——->—–>——-> Market CLOSED <—–<—–<—– StockListsUS <=== other computers have to wait now …
Downloading………………….. StockListsUS.mat…………………………..
Merging downloaded file with local version (server priority)…
=== SMART MERGE DEBUGGING ===
Initial – Server: inclusive=877, exclusive=12670
Initial – Local: inclusive=852, exclusive=12708
Detected 167 intentionally moved tickers to protect
Protected moved tickers: AAOI, AAPL, ABBV, ABCL, ABEV, ABNB, ABR, ABT, AEO, AMC
Processing field: activeComputers
=== HANDLING OTHER FIELD: activeComputers ===
Processing field: claimTime
=== HANDLING OTHER FIELD: claimTime ===
Processing field: claimedBy
=== HANDLING METADATA FIELD: claimedBy ===
Processing field: created
=== HANDLING OTHER FIELD: created ===
Processing field: cycleCount
=== HANDLING OTHER FIELD: cycleCount ===
Processing field: exclusiveBondLikeStocks
=== HANDLING OTHER FIELD: exclusiveBondLikeStocks ===
Processing field: exclusiveDataFetching
=== MERGING LIST FIELD: exclusiveDataFetching ===
Moved ticker detection: 167 basic, 0 status-based, 8 claim-based, 167 total
All moved tickers: AAOI, AAPL, ABBV, ABCL, ABEV, ABNB, ABR, ABT, AEO, AMC, AMKR, ASM, ASML, ASO, AVUV, BKLN, BNS, BOIL, BOXX, BSV, BTE, BTQ, CNM, COGT, COLB, COUR, CYTK, DEFT, DFAC, DHI, DUOL, EMES, ERIC, EWTX, FIGR, FOLD, FRMI, FRSH, GD, GEHC, GEN, GENI, GLL, GLPI, GROY, HIMZ, HNST, HSBC, HTZ, HUMA, HUT, HYMC, IAUM, IAUX, IBN, IDEV, IFF, IMSR, IOVA, IVR, JMIA, KOLD, LCID, LIN, LITE, LKQ, LRCX, LUNR, MAS, MAT, MBB, MCHP, METU, MMC, MSOS, MSTR, MTUM, MU, MUB, MVIS, NAK, NEXT, NG, NGD, NOG, NRGV, NTR, NUAI, NVD, OKLL, ONDS, OTIS, PAA, PACB, PCAR, PRGO, PSA, PSLV, PULS, QBTZ, RCAT, REGN, RGTZ, RKLB, RPRX, RR, RRC, RSP, RUM, RXRX, SABR, SANA, SAP, SCHB, SCHO, SDHIR, SDS, SDVY, SEE, SFM, SIVR, SLS, SLV, SMCX, SNDK, SPHY, SPOT, SPXL, SPYG, SPYI, SRE, SSRM, STLA, STM, STUB, STWD, STZ, SW, SYK, SYM, T, TD, TE, TEVA, TMO, TPR, TSN, TT, UA, UDR, UMAC, VEA, VEEV, VGIT, VGT, VRTX, VSCO, WU, WVE, WY, XLC, XLE, XLG, XLI, XLK, ZETA, ZIM
=== MERGE WITH MOVE PROTECTION (EXCLUSIVE BATCHES): exclusiveDataFetching ===
Server exclusiveDataFetching: 12670 items
Local exclusiveDataFetching: 12708 items
Protected moved tickers: 167 items
LOCAL PRIORITY: Using local version for exclusiveDataFetching due to 167 moved tickers
Local priority merge: 12711 items (protected 167 moved tickers)
Processing field: exclusiveLiquidity
=== HANDLING OTHER FIELD: exclusiveLiquidity ===
Processing field: exclusiveListName
=== HANDLING OTHER FIELD: exclusiveListName ===
Processing field: exclusiveNonUSTradedStocks
=== HANDLING OTHER FIELD: exclusiveNonUSTradedStocks ===
Processing field: exclusiveNotToAutoClose
=== HANDLING OTHER FIELD: exclusiveNotToAutoClose ===
Processing field: exclusiveTier0Stocks
=== HANDLING OTHER FIELD: exclusiveTier0Stocks ===
Processing field: exclusiveTier1Stocks
=== HANDLING OTHER FIELD: exclusiveTier1Stocks ===
Processing field: exclusiveTier2Stocks
=== HANDLING OTHER FIELD: exclusiveTier2Stocks ===
Processing field: exclusiveTier3Stocks
=== HANDLING OTHER FIELD: exclusiveTier3Stocks ===
Processing field: inclusiveBondLikeStocks
=== HANDLING OTHER FIELD: inclusiveBondLikeStocks ===
Processing field: inclusiveDataFetching
=== MERGING LIST FIELD: inclusiveDataFetching ===
Moved ticker detection: 167 basic, 0 status-based, 0 claim-based, 167 total
All moved tickers: AAOI, AAPL, ABBV, ABCL, ABEV, ABNB, ABR, ABT, AEO, AMC, AMKR, ASM, ASML, ASO, AVUV, BKLN, BNS, BOIL, BOXX, BSV, BTE, BTQ, CNM, COGT, COLB, COUR, CYTK, DEFT, DFAC, DHI, DUOL, EMES, ERIC, EWTX, FIGR, FOLD, FRMI, FRSH, GD, GEHC, GEN, GENI, GLL, GLPI, GROY, HIMZ, HNST, HSBC, HTZ, HUMA, HUT, HYMC, IAUM, IAUX, IBN, IDEV, IFF, IMSR, IOVA, IVR, JMIA, KOLD, LCID, LIN, LITE, LKQ, LRCX, LUNR, MAS, MAT, MBB, MCHP, METU, MMC, MSOS, MSTR, MTUM, MU, MUB, MVIS, NAK, NEXT, NG, NGD, NOG, NRGV, NTR, NUAI, NVD, OKLL, ONDS, OTIS, PAA, PACB, PCAR, PRGO, PSA, PSLV, PULS, QBTZ, RCAT, REGN, RGTZ, RKLB, RPRX, RR, RRC, RSP, RUM, RXRX, SABR, SANA, SAP, SCHB, SCHO, SDHIR, SDS, SDVY, SEE, SFM, SIVR, SLS, SLV, SMCX, SNDK, SPHY, SPOT, SPXL, SPYG, SPYI, SRE, SSRM, STLA, STM, STUB, STWD, STZ, SW, SYK, SYM, T, TD, TE, TEVA, TMO, TPR, TSN, TT, UA, UDR, UMAC, VEA, VEEV, VGIT, VGT, VRTX, VSCO, WU, WVE, WY, XLC, XLE, XLG, XLI, XLK, ZETA, ZIM
=== MERGE WITH MOVE PROTECTION (EXCLUSIVE BATCHES): inclusiveDataFetching ===
Server inclusiveDataFetching: 877 items
Local inclusiveDataFetching: 852 items
Protected moved tickers: 167 items
LOCAL PRIORITY: Using local version for inclusiveDataFetching due to 167 moved tickers
Local priority merge: 852 items (protected 167 moved tickers)
Processing field: inclusiveLiquidity
=== HANDLING OTHER FIELD: inclusiveLiquidity ===
Processing field: inclusiveNonUSTradedStocks
=== HANDLING OTHER FIELD: inclusiveNonUSTradedStocks ===
Processing field: inclusiveNotToAutoClose
=== HANDLING OTHER FIELD: inclusiveNotToAutoClose ===
Processing field: inclusiveTier0Stocks
=== HANDLING OTHER FIELD: inclusiveTier0Stocks ===
Processing field: inclusiveTier1Stocks
=== HANDLING OTHER FIELD: inclusiveTier1Stocks ===
Processing field: inclusiveTier2Stocks
=== HANDLING OTHER FIELD: inclusiveTier2Stocks ===
Processing field: inclusiveTier3Stocks
=== HANDLING OTHER FIELD: inclusiveTier3Stocks ===
Processing field: lastRunDate
=== HANDLING OTHER FIELD: lastRunDate ===
Server lastRunDate: 07-Jan-2026 02:19:53
Local lastRunDate: 06-Jan-2026 12:38:14
Using SERVER lastRunDate (newer or equal)
Processing field: lastUpdated
=== HANDLING OTHER FIELD: lastUpdated ===
Server lastUpdated: 07-Jan-2026 02:19:54
Local lastUpdated: 06-Jan-2026 03:05:15
Using SERVER lastUpdated (newer or equal)
Processing field: status
=== HANDLING METADATA FIELD: status ===
Processing field: structureConversion
=== HANDLING OTHER FIELD: structureConversion ===
Processing field: timePerTicker
=== HANDLING OTHER FIELD: timePerTicker ===
=== CROSS-LIST CONSISTENCY CHECK WITH MOVE PROTECTION ===
Final – Merged: inclusive=852, exclusive=12711
Merge completed with move protection
Smart merge completed successfully.
Successfully downloaded /Volumes/BarnUniJahr/StockPrograms/rawdata/StockListsUS.mat from the ftp server to local computer !
Error adding ARKB to non-tradable list: Output argument "cleanedData" (and possibly others) not assigned a value in the execution with "checkTickerStatus" function.
โ Failed to add ARKB to non-tradable list
>> [allowed, reason] = RestrictedStocks(‘ARKB’)
Error using vertcat
Dimensions of arrays being concatenated are not consistent.
Error in RestrictedStocks (line 35)
knownRestricted = {
Your order will be placed and please check on IB TWS !
New York time is 10:33 <——-<———->—–>
TWSAccess =
0
Connected to TWS, thanks to Poe AI instructions
Error using TWSWrapper
The specified superclass ‘com.ib.client.EWrapper’ contains a parse error, cannot be found on MATLAB’s search path, or is
shadowed by another file with the same name.
Error in TradingIB (line 102)
clientSocket.setEWrapper(TWSWrapper()); % Assuming TWSWrapper is your custom class for handling events
Please confirm ! Type y and hit return key twice to confirm, or to hit any key to cancel ! y
Your order will be placed and please check on IB TWS !
New York time is 10:25 <——-<———->—–>
Error: File: TradingIB.m Line: 109 Column: 1
Illegal use of reserved keyword “classdef”.
********************************************************************************
PORTFOLIO PROFIT & LOSS (Long & Short)
********************************************************************************
Type Stock Qty AvgPrice CurPrice Profit/Loss Return %%
——————————————————————————–
Unrecognized function or variable ‘qtyDisplay’.
Error in PortfolioIB (line 141)
posType, StockName{i}, qtyDisplay, avgPrice, curPrice, pnl, returnPercent);
Error: File: PortfolioIB.m Line: 521 Column: 1
Function ‘extractFileName’ has already been declared within this scope.
Error in SubSectorBrokerAccountsLongAuto (line 495)
[StockName, StockQuantity, StockOpenPositionPrice,StockCost,StockProfitLoss,StockCurrentPrice,PortfolioEmpty,PortfolioChanged] = PortfolioIB(7496,ComputerID0);
% Before running IBTWSConnect, delete the cache:
cacheFile = ‘tws_ip_cache.mat’;
if exist(cacheFile, ‘file’)
delete(cacheFile);
fprintf(‘Cache file deleted to force IP scanning\n’);
end
% Now run your connection
[clientSocket, session, WIFIIP] = IBTWSConnect(7496, 0);
>> testConnectionSpeed()
=== Testing connection to 127.0.0.1:7496 ===
Time: 29-Dec-2025 19:33:58
1. Testing direct Java connection…
added interface method: TWSNotification
notification listener has been added
Java objects created in 0.140s
eConnect() returned in 0.005s
โ Not connected after 0.146s
2. Testing through ibtwsOpen…
Warning: Objects of com/ib/client/EClientSocket class exist – not clearing java
> In javaclasspath
In javaclasspath
In javaaddpath (line 71)
In ibtwsOpen (line 9)
In testConnectionSpeed (line 52)
Warning: Objects of com/sun/proxy/$Proxy29 class exist – not clearing java
> In javaclasspath
In javaclasspath
In javaaddpath (line 71)
In ibtwsOpen (line 9)
In testConnectionSpeed (line 52)
Warning: Objects of com/tws/Handler class exist – not clearing java
> In javaclasspath
In javaclasspath
In javaaddpath (line 71)
In ibtwsOpen (line 9)
In testConnectionSpeed (line 52)
Warning: Objects of com/ib/client/EClientSocket class exist – not clearing java
> In javaclasspath
In javaclasspath
In javaaddpath (line 71)
In ibtwsOpen (line 10)
In testConnectionSpeed (line 52)
Warning: Objects of com/sun/proxy/$Proxy29 class exist – not clearing java
> In javaclasspath
In javaclasspath
In javaaddpath (line 71)
In ibtwsOpen (line 10)
In testConnectionSpeed (line 52)
Warning: Objects of com/tws/Handler class exist – not clearing java
> In javaclasspath
In javaclasspath
In javaaddpath (line 71)
In ibtwsOpen (line 10)
In testConnectionSpeed (line 52)
ibtwsOpen returned in 0.060s
โ Not connected via ibtwsOpen
=== Test complete ===
-1 502 Couldn’t connect to TWS. Confirm that “Enable ActiveX and Socket Clients” is enabled and connection port is the same as “Socket Port” on the TWS “Edit->Global Configuration…->API->Settings” menu. Live Trading ports: TWS: 7496; IB Gateway: 4001. Simulated Trading ports for new installations of version 954.1 or newer: TWS: 7497; IB Gateway: 4002
-1 502 Couldn’t connect to TWS. Confirm that “Enable ActiveX and Socket Clients” is enabled and connection port is the same as “Socket Port” on the TWS “Edit->Global Configuration…->API->Settings” menu. Live Trading ports: TWS: 7496; IB Gateway: 4001. Simulated Trading ports for new installations of version 954.1 or newer: TWS: 7497; IB Gateway: 4002
>>
>> [StockName, StockQuantity, StockOpenPositionPrice, StockCost, StockProfitLoss, StockCurrentPrice, PortfolioEmpty, PortfolioChanged] = PaperTestPortfolioIB(Port, ComputerID0)
=== PAPER TRADING MODE ===
Real portfolio is empty – using simulated data
Generating realistic portfolio…
AAPL : Qty= 90, Bought@ 180.74, Now@ 180.95, P&L= +18.90
MSFT : Qty= 80, Bought@ 431.17, Now@ 426.23, P&L= -395.20
GOOGL : Qty= 120, Bought@ 154.60, Now@ 150.72, P&L= -465.60
AMZN : Qty= 80, Bought@ 179.08, Now@ 175.46, P&L= -289.60
TSLA : Qty= 80, Bought@ 246.87, Now@ 236.87, P&L= -800.00
JPM : Qty= 130, Bought@ 195.53, Now@ 191.28, P&L= -552.50
V : Qty= 140, Bought@ 279.89, Now@ 281.27, P&L= +193.20
NVDA : Qty= 190, Bought@ 595.74, Now@ 593.69, P&L= -389.50
SIMULATED PORTFOLIO (8 positions):
Stock Qty AvgPrice CurPrice Profit/Loss Return %%
————————————————————
AAPL 90 180.74 180.95 +18.90 +0.1%
MSFT 80 431.17 426.23 -395.20 -1.1%
GOOGL 120 154.60 150.72 -465.60 -2.5%
AMZN 80 179.08 175.46 -289.60 -2.0%
TSLA 80 246.87 236.87 -800.00 -4.1%
JPM 130 195.53 191.28 -552.50 -2.2%
V 140 279.89 281.27 +193.20 +0.5%
NVDA 190 595.74 593.69 -389.50 -0.3%
————————————————————
TOTAL LOSS: -$2680.30 (-1.0%)
Portfolio Value: $278502.00
Cost Basis: $281182.30
============================================================
Testing PortfolioStatus function…
PortfolioStatus: Checking 8 positions (signed quantities):
LONG AAPL : 90
LONG MSFT : 80
LONG GOOGL : 120
LONG AMZN : 80
LONG TSLA : 80
LONG JPM : 130
LONG V : 140
LONG NVDA : 190
PortfolioStatus: Portfolio has changed
Saved portfolio with signed quantities: U8933912IB_20251229212651.mat
PortfolioStatus: Portfolio has changed (as expected for testing)
=== PAPER TEST COMPLETE ===
StockName =
1ร8 cell array
{‘AAPL’} {‘MSFT’} {‘GOOGL’} {‘AMZN’} {‘TSLA’} {‘JPM’} {‘V’} {‘NVDA’}
StockQuantity =
1ร8 cell array
{[90]} {[80]} {[120]} {[80]} {[80]} {[130]} {[140]} {[190]}
StockOpenPositionPrice =
1ร8 cell array
Columns 1 through 6
{[180.7400]} {[431.1700]} {[154.6000]} {[179.0800]} {[246.8700]} {[195.5300]}
Columns 7 through 8
{[279.8900]} {[595.7400]}
StockCost =
1ร8 cell array
Columns 1 through 6
{[1.6267e+04]} {[3.4494e+04]} {[18552]} {[1.4326e+04]} {[1.9750e+04]} {[2.5419e+04]}
Columns 7 through 8
{[3.9185e+04]} {[1.1319e+05]}
StockProfitLoss =
1ร8 cell array
Columns 1 through 6
{[18.9000]} {[-395.2000]} {[-465.6000]} {[-289.6000]} {[-800]} {[-552.5000]}
Columns 7 through 8
{[193.2000]} {[-389.5000]}
StockCurrentPrice =
1ร8 cell array
Columns 1 through 6
{[180.9500]} {[426.2300]} {[150.7200]} {[175.4600]} {[236.8700]} {[191.2800]}
Columns 7 through 8
{[281.2700]} {[593.6900]}
PortfolioEmpty =
0
PortfolioChanged =
1
>> [StockName, StockQuantity, StockOpenPositionPrice, StockCost, StockProfitLoss, StockCurrentPrice, PortfolioEmpty, PortfolioChanged] = PaperTestPortfolioIB(7496, 0);
=== PAPER TRADING MODE (Long & Short) ===
Testing portfolio with mixed long/short positions
Generating mixed portfolio…
Expected P&L calculations:
AAPL LONG: Qty= +100, Bought@ 180.50, Now@ 182.75, P&L= +225.00
TSLA SHORT: Qty= -50, Bought@ 240.30, Now@ 238.90, P&L= +70.00
MSFT LONG: Qty= +50, Bought@ 420.75, Now@ 418.25, P&L= -125.00
NVDA SHORT: Qty= -20, Bought@ 600.20, Now@ 605.75, P&L= -111.00
JPM LONG: Qty= +200, Bought@ 190.15, Now@ 192.40, P&L= +450.00
GOOGL SHORT: Qty= -100, Bought@ 150.25, Now@ 148.50, P&L= +175.00
AMZN LONG: Qty= +80, Bought@ 175.80, Now@ 170.20, P&L= -448.00
V SHORT: Qty= -150, Bought@ 280.40, Now@ 282.80, P&L= -360.00
================================================================================
MIXED PORTFOLIO (8 positions: 4 long, 4 short)
================================================================================
Type Stock Qty AvgPrice CurPrice Profit/Loss Return %%
——————————————————————————–
LONG AAPL 100 180.50 182.75 +225.00 +1.2%
SHORT TSLA 50 240.30 238.90 +70.00 +0.6%
LONG MSFT 50 420.75 418.25 -125.00 -0.6%
SHORT NVDA 20 600.20 605.75 -111.00 -0.9%
LONG JPM 200 190.15 192.40 +450.00 +1.2%
SHORT GOOGL 100 150.25 148.50 +175.00 +1.2%
LONG AMZN 80 175.80 170.20 -448.00 -3.2%
SHORT V 150 280.40 282.80 -360.00 -0.9%
——————————————————————————–
PORTFOLIO SUMMARY:
—————————————-
Total Positions: 8
Long Positions: 4
Short Positions: 4
Exposure:
Long Exposure: $ 91181.50
Short Exposure: $ 81104.00
Net Exposure: $ 10077.50
Profit & Loss:
Long P&L: $ +102.00
Short P&L: $ -226.00
Total P&L: $ -124.00
Returns:
Portfolio Value: $ 9953.50
Cost Basis: $ 10077.50
TOTAL LOSS: $ -124.00 (-1.2%)
================================================================================
Testing PortfolioStatus function with mixed positions…
PortfolioStatus: Checking 8 positions (signed quantities):
LONG AAPL : 100
SHORT TSLA : -50
LONG MSFT : 50
SHORT NVDA : -20
LONG JPM : 200
SHORT GOOGL : -100
LONG AMZN : 80
SHORT V : -150
PortfolioStatus: Portfolio has changed
Saved portfolio with signed quantities: U8933912IB20251229215523.mat
PortfolioStatus: Portfolio has changed (as expected for testing)
=== VERIFICATION OF CALCULATIONS ===
Formula: ProfitLoss = (CurrentPrice – AvgPrice) ร Quantity
Example 1 – LONG PROFIT (AAPL):
(182.75 – 180.50) ร +100 = 2.25 ร +100 = +225.00 โ
Example 2 – SHORT PROFIT (TSLA):
(238.90 – 240.30) ร -50 = -1.40 ร -50 = +70.00 โ
Example 3 – SHORT LOSS (NVDA):
(605.75 – 600.20) ร -20 = 5.55 ร -20 = -111.00 โ
=== PAPER TEST COMPLETE ===
[StockName, StockQuantity, StockOpenPositionPrice, StockCost, StockProfitLoss, StockCurrentPrice, PortfolioEmpty, PortfolioChanged] = PaperTestPortfolioIB(7496, 0);
>> [StockName, StockQuantity, StockOpenPositionPrice, StockCost, StockProfitLoss, StockCurrentPrice, PortfolioEmpty, PortfolioChanged] = PaperTestPortfolioIB(Port, ComputerID0)
=== PAPER TRADING MODE ===
Real portfolio is empty – using simulated data
Generating realistic portfolio…
AAPL : Qty= 90, Bought@ 180.74, Now@ 180.95, P&L= +18.90
MSFT : Qty= 80, Bought@ 431.17, Now@ 426.23, P&L= -395.20
GOOGL : Qty= 120, Bought@ 154.60, Now@ 150.72, P&L= -465.60
AMZN : Qty= 80, Bought@ 179.08, Now@ 175.46, P&L= -289.60
TSLA : Qty= 80, Bought@ 246.87, Now@ 236.87, P&L= -800.00
JPM : Qty= 130, Bought@ 195.53, Now@ 191.28, P&L= -552.50
V : Qty= 140, Bought@ 279.89, Now@ 281.27, P&L= +193.20
NVDA : Qty= 190, Bought@ 595.74, Now@ 593.69, P&L= -389.50
SIMULATED PORTFOLIO (8 positions):
Stock Qty AvgPrice CurPrice Profit/Loss Return %%
————————————————————
AAPL 90 180.74 180.95 +18.90 +0.1%
MSFT 80 431.17 426.23 -395.20 -1.1%
GOOGL 120 154.60 150.72 -465.60 -2.5%
AMZN 80 179.08 175.46 -289.60 -2.0%
TSLA 80 246.87 236.87 -800.00 -4.1%
JPM 130 195.53 191.28 -552.50 -2.2%
V 140 279.89 281.27 +193.20 +0.5%
NVDA 190 595.74 593.69 -389.50 -0.3%
————————————————————
TOTAL LOSS: -$2680.30 (-1.0%)
Portfolio Value: $278502.00
Cost Basis: $281182.30
============================================================
Testing PortfolioStatus function…
PortfolioStatus: Checking 8 positions (signed quantities):
LONG AAPL : 90
LONG MSFT : 80
LONG GOOGL : 120
LONG AMZN : 80
LONG TSLA : 80
LONG JPM : 130
LONG V : 140
LONG NVDA : 190
PortfolioStatus: Portfolio has changed
Saved portfolio with signed quantities: U8933912IB_20251229212651.mat
PortfolioStatus: Portfolio has changed (as expected for testing)
=== PAPER TEST COMPLETE ===
StockName =
1ร8 cell array
{‘AAPL’} {‘MSFT’} {‘GOOGL’} {‘AMZN’} {‘TSLA’} {‘JPM’} {‘V’} {‘NVDA’}
StockQuantity =
1ร8 cell array
{[90]} {[80]} {[120]} {[80]} {[80]} {[130]} {[140]} {[190]}
StockOpenPositionPrice =
1ร8 cell array
Columns 1 through 6
{[180.7400]} {[431.1700]} {[154.6000]} {[179.0800]} {[246.8700]} {[195.5300]}
Columns 7 through 8
{[279.8900]} {[595.7400]}
StockCost =
1ร8 cell array
Columns 1 through 6
{[1.6267e+04]} {[3.4494e+04]} {[18552]} {[1.4326e+04]} {[1.9750e+04]} {[2.5419e+04]}
Columns 7 through 8
{[3.9185e+04]} {[1.1319e+05]}
StockProfitLoss =
1ร8 cell array
Columns 1 through 6
{[18.9000]} {[-395.2000]} {[-465.6000]} {[-289.6000]} {[-800]} {[-552.5000]}
Columns 7 through 8
{[193.2000]} {[-389.5000]}
StockCurrentPrice =
1ร8 cell array
Columns 1 through 6
{[180.9500]} {[426.2300]} {[150.7200]} {[175.4600]} {[236.8700]} {[191.2800]}
Columns 7 through 8
{[281.2700]} {[593.6900]}
PortfolioEmpty =
0
PortfolioChanged =
1
>>
File exists: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp/jpm.mat
Current price for JPM: $323.75
>> [StockName, StockQuantity, StockOpenPositionPrice, StockCost, StockProfitLoss, StockCurrentPrice, PortfolioEmpty, PortfolioChanged] = PaperTestPortfolioIB(Port, ComputerID0)
=== PAPER TRADING MODE ===
Real portfolio is empty – using simulated data
SIMULATED PORTFOLIO (8 positions):
Stock Qty AvgPrice CurPrice Profit/Loss Return %%
————————————————————
AAPL 16 210.75 172.58 -610.70 -18.1%
MSFT 40 424.40 409.36 -601.58 -3.5%
GOOGL 59 166.85 150.33 -974.91 -9.9%
AMZN 94 150.30 173.54 +2185.08 +15.5%
TSLA 35 249.42 228.88 -718.98 -8.2%
JPM 15 176.54 182.37 +87.45 +3.3%
V 25 265.57 267.11 +38.57 +0.6%
NVDA 74 633.92 580.44 -3957.39 -8.4%
————————————————————
TOTAL LOSS: -$4552.44 (-4.2%)
Portfolio Value: $104694.92
Cost Basis: $109247.37
============================================================
Testing PortfolioStatus function…
PortfolioStatus: Checking 8 positions (signed quantities):
LONG AAPL : 16
LONG MSFT : 40
LONG GOOGL : 59
LONG AMZN : 94
LONG TSLA : 35
LONG JPM : 15
LONG V : 25
LONG NVDA : 74
PortfolioStatus: Portfolio has changed
Saved portfolio with signed quantities: U8933912IB_20251229204705.mat
PortfolioStatus: Portfolio has changed (as expected for testing)
=== PAPER TEST COMPLETE ===
StockName =
1ร8 cell array
{‘AAPL’} {‘MSFT’} {‘GOOGL’} {‘AMZN’} {‘TSLA’} {‘JPM’} {‘V’} {‘NVDA’}
StockQuantity =
1ร8 cell array
{[16]} {[40]} {[59]} {[94]} {[35]} {[15]} {[25]} {[74]}
StockOpenPositionPrice =
1ร8 cell array
Columns 1 through 6
{[210.7486]} {[424.3984]} {[166.8521]} {[150.2978]} {[249.4176]} {[176.5391]}
Columns 7 through 8
{[265.5703]} {[633.9219]}
StockCost =
1ร8 cell array
Columns 1 through 5
{[3.3720e+03]} {[1.6976e+04]} {[9.8443e+03]} {[1.4128e+04]} {[8.7296e+03]}
Columns 6 through 8
{[2.6481e+03]} {[6.6393e+03]} {[4.6910e+04]}
StockProfitLoss =
1ร8 cell array
Columns 1 through 6
{[-610.6996]} {[-601.5768]} {[-974.9063]} {[2.1851e+03]} {[-718.9782]} {[87.4518]}
Columns 7 through 8
{[38.5745]} {[-3.9574e+03]}
StockCurrentPrice =
1ร8 cell array
Columns 1 through 6
{[172.5799]} {[409.3590]} {[150.3282]} {[173.5434]} {[228.8754]} {[182.3692]}
Columns 7 through 8
{[267.1133]} {[580.4437]}
PortfolioEmpty =
0
PortfolioChanged =
1
PortfolioIB: Keeping connection alive for other functions
Error using cellfun
cellfun works only on cells.
Error in TechnicalPointsOfASetAuto (line 110)
StockQuantity = StockQuantity(~cellfun(‘isempty’, StockQuantity));
clear all % Clear all variables
clear functions % Clear all compiled functions
rehash % Refresh function cache
% Now run PortfolioIB
[StockName, StockQuantity, StockOpenPositionPrice, StockCost, StockProfitLoss, StockCurrentPrice, PortfolioEmpty, PortfolioChanged] = PortfolioIB(Port, ComputerID0);
% Check the output variables
disp(‘Stock Names:’);
disp(StockName’);
disp(‘Quantities:’);
disp(StockQuantity’);
disp(‘Open Prices:’);
disp(StockOpenPositionPrice’);
disp(‘Current Prices:’);
disp(StockCurrentPrice’);
disp(‘Profit/Loss:’);
disp(StockProfitLoss’);
disp(‘Cost:’);
disp(StockCost’);
% Show as a table for better visualization
fprintf(‘\n=== PORTFOLIO SUMMARY ===\n’);
for i = 1:length(StockName)
fprintf(‘%6s: Qty=%4d, Open=%.2f, Current=%.2f, P&L=%.2f, Cost=%.2f\n’, …
StockName{i}, StockQuantity(i), StockOpenPositionPrice(i), …
StockCurrentPrice(i), StockProfitLoss(i), StockCost(i));
end
% Show totals
fprintf(‘\n=== TOTALS ===\n’);
fprintf(‘Total Cost: $%.2f\n’, sum(StockCost));
fprintf(‘Total P&L: $%.2f\n’, sum(StockProfitLoss));
fprintf(‘Current Value: $%.2f\n’, sum(StockQuantity .* StockCurrentPrice));
>> [StockName, StockQuantity, StockOpenPositionPrice, StockCost, StockProfitLoss, StockCurrentPrice, PortfolioEmpty, PortfolioChanged] = PortfolioIB(Port, ComputerID0);
Reusing connection to TWS via IP: 127.0.0.1
.Buffer stabilized with 1 entries in 0.5 seconds
Received 15 positions (showing first 10):
GLD 12 410.13939165
GLDM 56 88.56625535
CGDV 113 44.22070265
RIO 63 79.8557603
JPM 15 326.12855335
SCHW 50 100.412206
RTX 27 183.90317405
EUFN 134 37.33870225
WFC 52 95.77543655
IAU 60 83.59103835
Processed 15 raw positions into 15 unique positions
StockQuantity: [113 134 12 56 64 60 113 15 9 36 63 27 50 118 52]
Looking for data in: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdatatemp
Loaded price for CGDV: 44.04
Loaded price for EUFN: 37.39
Loaded price for GLD: 416.74
Loaded price for GLDM: 89.71
Loaded price for HSBC: 79.97
Loaded price for IAU: 85.34
Loaded price for IAUM: 45.18
Loaded price for JPM: 327.91
Loaded price for MA: 579.60
Loaded price for NVS: 139.18
Loaded price for RIO: 82.24
Loaded price for RTX: 185.17
Loaded price for SCHW: 101.89
Loaded price for SGOL: 43.19
Loaded price for WFC: 95.26
Portfolio Positions (Signed):
LONG CGDV : 113 shares
LONG EUFN : 134 shares
LONG GLD : 12 shares
LONG GLDM : 56 shares
LONG HSBC : 64 shares
LONG IAU : 60 shares
LONG IAUM : 113 shares
LONG JPM : 15 shares
LONG MA : 9 shares
LONG NVS : 36 shares
LONG RIO : 63 shares
LONG RTX : 27 shares
LONG SCHW : 50 shares
LONG SGOL : 118 shares
LONG WFC : 52 shares
Net Position: 922 shares
PortfolioStatus: Checking 15 positions (signed quantities):
LONG CGDV : 113
LONG EUFN : 134
LONG GLD : 12
LONG GLDM : 56
LONG HSBC : 64
LONG IAU : 60
LONG IAUM : 113
LONG JPM : 15
LONG MA : 9
LONG NVS : 36
LONG RIO : 63
LONG RTX : 27
LONG SCHW : 50
LONG SGOL : 118
LONG WFC : 52
PortfolioStatus: Found matching portfolio: U8933912IB_2025-12-29_04-34-29.mat
PortfolioIB: Keeping connection alive for other functions
>> test1
Data path: /Volumes/BarnUniJahr/StockPrograms/rawdata/rawdata/rawdatatemp
Exists: 0
% Check if data directory exists
dataPath = fullfile(BaseFolder, ‘rawdata’, ‘rawdatatemp’);
disp([‘Data path: ‘, dataPath]);
disp([‘Exists: ‘, num2str(exist(dataPath, ‘dir’))]);
% List files
if exist(dataPath, ‘dir’)
files = dir(fullfile(dataPath, ‘*.mat’));
disp([‘Number of .mat files: ‘, num2str(length(files))]);
if ~isempty(files)
disp(‘First 3 files:’);
for i = 1:min(3, length(files))
disp(files(i).name);
end
end
end
Connected to TWS at 127.0.0.1:7496 (Attempt 1)
Connected to: 127.0.0.1
Created new persistent connection to TWS via IP: 127.0.0.1
Checking pre-trade position for AAPL…
Pre-trade position: 0 shares
Requesting order ID…
โ Error in BuySellIB: The class TWS.Events has no Constant property or Static method named ‘NEXT_VALID_ID’.
Keeping TWS connection alive for future trades.
โ FAILURE: Error (code: -1)
Unrecognized function or variable ‘cleanupIBConnection’.
Error in testBuySellIB_PaperTrading (line 52)
cleanupIBConnection();
^^^^^^^^^^^^^^^^^^^^^
Processing instrument CGDV 1 of 1 instruments.
New York time is 13:13 <——-<———->—–>
New York time is 13:13 <——-<———->—–>
Brace indexing is not supported for variables of this type.
Error in TechnicalPointsOfASetAuto (line 311)
disp([‘Stock Code: ‘,StockCodeIB,’ Quantity: ‘,num2str(StockQuantity{MarketScan}),’ with cost price , NOT latest price : ‘,num2str(StockOpenPositionPrice{MarketScan}),’ worth of ‘,num2str(StockQuantity{MarketScan}*StockOpenPositionPrice{MarketScan}),’ USD’]);
1000001 2174 Warning: You submitted request with date-time attributes without explicit time zone. Please switch to use yyyymmdd-hh:mm:ss in UTC or use instrument time zone, like US/Eastern. Implied time zone functionality will be removed in the next API release
1000001 2176 Warning: Your API version does not support fractional share size rules. Please upgrade to a minimum version 163. Trimmed value 564904.3 to 564904
Data streaming from IB TWS API is OK !
Received Positions from Brokerside:
RTX 27 183.90317405
HSBC 64 78.57067345
WFC 52 95.77543655
MA 9 578.4791222
IAU 60 83.59103835
C 0 0.0
SCHW 50 100.412206
NVS 36 139.03288055
EUFN 134 37.33870225
JPM 15 326.12855335
IAUM 113 44.24170265
SGOL 118 42.50870255
FHN 0 0.0
CGDV 113 44.22070265
RIO 63 79.8557603
GLDM 56 88.56625535
GLD 12 410.13939165
New York time is 12:45 <——-<———->—–>
New York time is 12:45 <——-<———->—–>
New York time is 12:45 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
New York time is 12:46 <——-<———->—–>
StockQuantity: [113;134;12;56;64;60;113;15;9;36;63;27;50;118;52]
No change in the portfolio.
Error using cellfun
cellfun works only on cells.
Error in TechnicalPointsOfASetAuto (line 111)
StockOpenPositionPrice = StockOpenPositionPrice(~cellfun(‘isempty’, StockOpenPositionPrice));
97 tickers to include, 3 tickers to exclude
Successfully updated the stock lists and uploaded to ftp sever !
Error using matlab.io.FTP/delete (line 10)
delete(ftpObj, currentLockFile);
^^^^^^^^^^^^^^^
Invalid argument at position 2.
Input should be a non-empty, non-missing string.
Error in InclusiveExclusiveListReview>releaseGlobalLock (line 3329)
delete(ftpObj, currentLockFile);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in InclusiveExclusiveListReview>updateAndUpload (line 2556)
globalLockFileFreeOnftpServer = releaseGlobalLock(globalLockFile,globalLockFileNYTime,localFolder,remoteFolder);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in InclusiveExclusiveListReview (line 861)
[ListUpdateStatus,FileTransferStatus] = updateAndUpload(loadedData, processed, toExclude, toInclude, …
=== STEP 3: AFTER SAVE VERIFICATION ===
Saved – inclusiveDataFetching: 1470 items
Saved – exclusiveDataFetching: 11979 items
Saved: KITT – inclusive:1, exclusive:0
Saved: LCID – inclusive:1, exclusive:0
Saved: LEGN – inclusive:1, exclusive:0
Saved: LEU – inclusive:1, exclusive:0
Error using str2num (line 11)
Input must be a character vector or string scalar.
Error in InclusiveExclusiveListReview>updateAndUpload (line 2220)
if str2num(latestBackupFileTimeStamp) > str2num(originalTimestamp)
Error in InclusiveExclusiveListReview (line 861)
[ListUpdateStatus,FileTransferStatus] = updateAndUpload(loadedData, processed, toExclude, toInclude, …
Data received for stock ====>> tfc <<===== Disconnected from TWS. L = 500 ans = 7.3996e+05 ans = '10-Dec-2025 12:00:00' c1 = 0 java.net.SocketException: Socket closed ans = 739960 ans = '09-Dec-2025' c1 = 1
Data received for stock ====>> tfc <<=====
Disconnected from TWS.
ti =
499
ans =
7.3996e+05
c1 =
1
c1 =
2.1000
ans =
7.3996e+05
ans =
'09-Dec-2025 12:00:00'
ans =
49.5600
ans =
'10-Dec-2025'
ans =
47.9200
ans =
'09-Dec-2025'
ans =
47.7000
ans =
'08-Dec-2025'
c1 =
3.1000
Error using str2num (line 11)
Input must be a character vector or string scalar.
Error in NewLonKongStockList (line 180)
modificationTime = str2num(latestBackupFileTimeStamp);
ๆฑ่ๆณฐๅท็ๅ่ฏๅๅฏผไฝ็ฎๅไธป่ฆไบงๅๆฏไปไน?
็ ๆตทโๅ่ฏๅพฎ็ตๅญโ็ฎๅ่ฟ่ฅ็ถๆๅฆไฝ?