longPositionsAtOrBelowDigitizedPrice(double openingPrice) {
return filter(openPositions, p -> p.isLong() && p.digitizedOpeningPrice() <= openingPrice);
}
final PriceCells priceCells(){ return cells(); }
PriceCells cells() {
return digitizer == null ? null : digitizer.cells;
}
String formatPriceX(double price) {
if (isNaN(price)) return "-";
String s = formatPrice(price);
if (cells() == null) return s;
double num = cells().priceToCellNumber(price);
return s + " (C" + formatDouble2(num) + ")";
}
final void currentPrice(double price){ price(price); }
abstract void price(double price);
boolean inCooldown() {
if (cooldownMinutes <= 0) return false;
if (nempty(openPositions)) return true;
var lastClosed = last(closedPositions);
if (lastClosed == null) return false;
var minutes = toMinutes(currentTime()-lastClosed.closingTime);
return minutes < cooldownMinutes;
}
void assureCanOpen(Position p) {
if (cooldownMinutes > 0) {
if (nempty(openPositions))
throw fail("Already have an open position");
var lastClosed = last(closedPositions);
if (lastClosed != null) {
var minutes = toMinutes(currentTime()-lastClosed.closingTime);
if (minutes < cooldownMinutes)
throw fail("Last position closed " + formatMinutes(fromMinutes(minutes)) + " ago, cooldown is " + cooldownMinutes);
}
}
}
P openPosition(P p, int direction) { return openPosition(p, direction, null); }
P openPosition(P p, int direction, Object openReason) {
try {
assureCanOpen(p);
p.openReason(openReason);
var price = digitizedPrice();
var realPrice = currentPrice();
logVars("openPosition", "realPrice", realPrice, "price", price, "digitizer", digitizer);
if ((isNaN(price) || price == 0) && digitizer != null) {
price = digitizer.digitizeIndividually(currentPrice());
print("digitized individually: " + price);
}
p.openingPrice(realPrice);
p.direction(direction);
p.digitizedOpeningPrice(price);
// Calculate quantity (cryptoAmount) from margin
// unless cryptoAmount is already set
if (p.cryptoAmount == 0)
p.cryptoAmount = p.marginToUse/realPrice*leverage;
// Round cryptoAmount to the allowed increments
p.cryptoAmount = roundTo(cryptoStep, p.cryptoAmount);
// Clamp to minimum/maximum order
p.cryptoAmount = clamp(p.cryptoAmount, minCrypto, maxCrypto);
log(renderVars("openPosition", "marginPerPosition", marginPerPosition, "realPrice", realPrice, "leverage", leverage, "cryptoAmount" , p.cryptoAmount, "cryptoStep", cryptoStep));
p.open();
//print("Opening " + p);
//printPositions();
p.openOnMarket();
return p;
} catch (Throwable e) { log(e);
throw rethrow(e); }
}
List status() {
double mulProf = multiplicativeProfit();
return llNonNulls(
empty(comment) ? null : "Comment: " + comment,
"Profit: " + marginCoin + " " + plusMinusFix(formatMarginPrice(coinProfit())),
"Realized profit: " + marginCoin + " " + formatMarginProfit(realizedCoinProfit) + " from " + n2(closedPositions, "closed position")
+ " (" + formatMarginProfit(realizedCoinWins) + " from " + n2(realizedWins, "win")
+ ", " + formatMarginProfit(realizedCoinLosses) + " from " + n2(realizedLosses, "loss", "losses") + ")",
"Unrealized profit: " + marginCoin + " " + formatMarginProfit(unrealizedCoinProfit()) + " in " + n2(openPositions, "open position"),
isNaN(mulProf) ? null : "Multiplicative profit: " + formatProfit(mulProf) + "%",
//baseToString(),
!primed() ? null : "Primed",
!started() ? null : "Started. current price: " + formatPriceX(currentPrice)
+ (isNaN(digitizedPrice()) ? "" : ", digitized: " + formatPriceX(digitizedPrice())),
(riskPerTrade == 0 ? "" : "Risk per trade: " + formatDouble1(riskPerTrade) + "%. ")
+ "Position size: " + marginCoin + " " + formatPrice(marginPerPosition) + "x" + formatDouble1(leverage) + " = " + marginCoin + " " + formatPrice(positionSize()),
!usingCells() ? null : "Cell size: " + formatCellSize(cellSize),
spaceCombine("Step " + n2(stepCount), renderStepSince()),
//"Debt: " + marginCoin + " " + formatMarginProfit(debt()) + " (max seen: " + formatMarginProfit(maxDebt) + ")",
"Investment used: " + marginCoin + " " + formatMarginPrice(maxInvestment()),
strategyJuicer == null ? null : "Strategy juicer: " + strategyJuicer);
}
String renderStepSince() {
if (stepSince == 0) return "";
return "since " + (active()
? formatHoursMinutesColonSeconds(currentTime()-stepSince)
: formatLocalDateWithSeconds(stepSince));
}
List fullStatus() {
return listCombine(
tradingAccount,
status(),
"",
n2(openPositions, "open position") + ":",
reversed(openPositions),
"",
n2(closedPositions, "closed position")
+ " (" + (showClosedPositionsBackwards ? "latest first" : "oldest first") + "):",
showClosedPositionsBackwards ? reversed(closedPositions) : closedPositions);
}
void feed(PricePoint pricePoint) {
if (!active()) return;
setTime(pricePoint.timestamp);
price(pricePoint.price);
}
void feed(TickerSequence ts) {
if (!active()) return;
if (ts == null) return;
for (var pricePoint : ts.pricePoints())
feed(pricePoint);
}
public int compareTo(G22TradingStrategy s) {
return s == null ? 1 : cmp(coinProfit(), s.coinProfit());
}
// Returns closed positions
List closeAllPositions() { return closeAllPositions("User close"); }
List closeAllPositions(Object reason) {
var positions = openPositions();
closePositions(positions, reason);
return (List) positions;
}
void closeMyself() {
closedItself(currentTime());
closeAllPositionsAndDeactivate();
}
void closeAllPositionsAndDeactivate() {
deactivate();
closeAllPositions();
}
void deactivate() {
market(null);
if (!active) return;
active(false);
deactivated(currentTime());
log("Strategy deactivated.");
}
final void reset_G22TradingStrategy(){ reset(); }
void reset() {
resetFields(this, fieldsToReset());
change();
}
final G22TradingStrategy emptyClone_G22TradingStrategy(){ return emptyClone(); }
G22TradingStrategy emptyClone() {
var clone = shallowCloneToUnlistedConcept(this);
clone.reset();
return clone;
}
List allPositions() {
return concatLists(openPositions, closedPositions);
}
List sortedPositions() {
var allPositions = allPositions();
return sortedByCalculatedField(allPositions, __7 -> __7.openingTime());
}
boolean positionsAreNonOverlapping() {
for (var __0: overlappingPairs(sortedPositions()))
{ var a = pairA(__0); var b = pairB(__0); if (b.openingTime() < a.closingTime())
return false; }
return true;
}
// Profit when applying all positions (somewhat theoretical because you
// might go below platform limits)
// Also only works when positions are linear
double multiplicativeProfit() {
if (!positionsAreNonOverlapping()) return Double.NaN;
double profit = 1;
for (var p : sortedPositions())
profit *= 1+p.profit()/100;
return (profit-1)*100;
}
boolean haveBackData() { return backDataHoursWanted == 0 | backDataFed; }
boolean didRealTrades() {
return any(allPositions(), p -> p.openedOnMarket() || p.closedOnMarket());
}
String formatCellSize(double cellSize) {
return formatPercentage(cellSize, 3);
}
String areaDesc() {
if (eq(area, "Candidates")) return "Candidate";
return nempty(area) ? area : archived ? "Archived" : "";
}
final G22TradingStrategy currentTime(long time){ return setTime(time); }
G22TradingStrategy setTime(long time) {
int age = ifloor(ageInHours());
long lastMod = mod(currentTime()-startTime, hoursToMS(1));
currentTime = () -> time;
if (ifloor(ageInHours()) > age)
log("Hourly profit log: " + formatMarginProfit(coinProfit()));
return this;
}
double ageInHours() { return startTime == 0 ? 0 : msToHours(currentTime()-startTime); }
// only use near start of strategy, untested otherwise
G22TradingStrategy changeCellSize(double newCellSize) {
double oldCellSize = cellSize();
if (oldCellSize == newCellSize) return this;
cellSize(newCellSize);
if (digitizer != null)
digitizer.swapPriceCells(makePriceCells(priceCells().basePrice()));
log("Changed cell size from " + oldCellSize + " to " + newCellSize);
return this;
}
boolean hasClosedItself() { return closedItself != 0; }
public double juiceValue() { return coinProfit(); }
// drift is our cumulative delta (=sum of all signed position
// quantities)
double drift() {
double drift = 0;
for (var p : openPositions())
drift += p.cryptoAmount()*p.direction();
return drift;
}
String formatCryptoAmount(double amount) {
return formatDouble3(amount);
}
Position openShort() { return openPosition(-1); }
Position openLong() { return openPosition(1); }
Position openPosition(int direction) { return openPosition(direction, null); }
Position openPosition(int direction, Object openReason) {
Position p = new Position();
p.marginToUse = marginToUseForNewPosition();
return openPosition(p, direction, openReason);
}
// Open or close positions until the drift (delta) is
// equal to targetDrift (or as close as the platform's
// restrictions allow).
// Returns the list of positions opened or closed
// (Function is in dev.)
List