LibraryOpen sourceOther

PositionKit

Position sizing by risk, ATR stops, margin and liquidation estimates, Grid Bot levels and price rounding for your own scripts.

Copy and edit
PositionKitLiveBinance data
Loading chart…

Position Kit gathers the calculations that come before every order: how large the position should be, where the stop goes, how much margin the position needs, where a leveraged position would be liquidated and how a grid is laid out. Import it once, and every indicator or strategy you write uses the same tested formulas.

How it works

Position size follows from risk, not the other way round. You decide what share of the account you are prepared to lose if the stop is hit; the distance between the entry and the stop then sets the size. A wide stop gives a small position, a tight stop a larger one, and the amount at risk stays the same.

Stops can be placed by volatility. atrStop measures the average true range (ATR) of recent bars and keeps the stop a set multiple of it away from the close, so the stop allows more room in an active market and less in a quiet one.

For futures, two figures matter before an order is sent: the initial margin, which is the position value divided by the leverage, and the liquidation price, where the remaining margin no longer covers the maintenance margin. Position Kit estimates both. With a maintenance margin rate of zero, the liquidation estimate is the same one the strategy tester uses.

gridLevels returns the same levels as Grid Bot. Both ends of the range are included; arithmetic levels are an equal price step apart, and geometric levels an equal percentage apart.

Reading the chart

The library draws a small demonstration on its own chart, so that each part can be seen on real prices. Hover over a line below to see it on the chart.

  • Green step line: a long stop two ATRs below the close, using a 14-bar ATR.
  • Red step line: a short stop two ATRs above the close.
  • Amber dashed line: the estimated liquidation price of a long position opened at each close with 10 times leverage and a 0.5% maintenance margin rate. It runs about 9.5% below price.
  • Blue dotted lines: nine geometric grid levels across the high-low range of the last 150 bars.

Functions

sizeByRisk(equity, riskPct, entry, stop)
float
The size in units of the base asset that loses riskPct percent of equity if the stop is hit. Returns na when the entry and the stop are equal.
atrStop(side, mult, len)
float
A stop mult ATRs below the close for side 1 (long), or above it for side -1 (short).
liquidationPrice(side, entry, leverage, mmrPct)
float
The estimated liquidation price of an isolated position. Returns na when the leverage is 1 or lower.
marginNeeded(qty, price, leverage)
float
The initial margin in the quote currency: size × price ÷ leverage.
gridLevels(lower, upper, count, mode)
array
The grid prices from the lowest to the highest level, both ends included. An empty array when the range is not valid.
roundToTick(price, tick)
float
The price rounded to the nearest multiple of the price tick.
roundToStep(qty, step)
float
The quantity rounded down to the quantity step, so that an order never exceeds the size it was given.
planFor(equity, riskPct, entry, stop, rr)
Plan
A plan with the target set rr times the stop distance away from the entry and the size filled in.
Plan
type
The entry, stop, target, qty and riskAmount of one position.
GridMode
enum
Arithmetic or Geometric.

Using it

Copy the import line from this page and give the library a short name. The example below sizes a long position so that a two-ATR stop risks 1% of a 10,000 account, and plots the margin the position would need at 5 times leverage:

indicator("Risk Sizing Example", overlay = true)
import MarkudaDev/PositionKit/1 as pk

stopPrice = pk.atrStop(1, 2, 14)
plan = pk.planFor(10000, 1, close, stopPrice, 2)
plot(plan.stop, "Stop", "#fb5b6b")
plot(plan.target, "Target", "#33d69f")
plot(pk.marginNeeded(plan.qty, close, 5), "Margin at 5x")

Grid levels are read the same way, as an array:

levels = pk.gridLevels(60000, 70000, 11, pk.GridMode.Arithmetic)
plot(arrayGet(levels, 5), "Middle grid level")
ExampleWith 10,000 USDT of equity, 1% risk, an entry at 80,000 and a stop at 78,400, sizeByRisk returns 0.0625 BTC. At 5 times leverage, that position needs 1,000 USDT of margin, and a long from the same entry at 10 times leverage would be liquidated near 72,400 with a 0.5% maintenance margin rate.

Limits and points to note

  • The liquidation price is an estimate. Exchanges use tiered maintenance margin rates, charge fees and funding, and in cross margin also count other open positions. The figure shown by the exchange always takes precedence.
  • sizeByRisk measures the loss at the stop price only. Fees, slippage and gaps past the stop can make the actual loss larger than the amount planned.
  • Sizes are in units of the base asset (BTC for BTCUSDT). Round them with roundToStep before using them in an order, and check the minimum order size of the symbol.
  • A wider stop does not make a trade safer; it only makes the position smaller for the same risk.
  • Margin and liquidation figures assume an isolated position with a single entry.
  • Leverage multiplies losses as well as gains. Please size positions so that a liquidation can never take more than you are prepared to lose.

Position Kit, her emirden önce yapılan hesapları bir araya getirir: pozisyonun ne büyüklükte olacağı, zarar-durdurun nereye konacağı, pozisyonun ne kadar teminat gerektirdiği, kaldıraçlı bir pozisyonun hangi fiyatta tasfiye olacağı ve bir gridin nasıl kurulacağı. Kitaplığı bir kez içe aktardığınızda yazdığınız her gösterge ve strateji aynı, sınanmış formülleri kullanır.

Nasıl çalışır

Pozisyon büyüklüğü riskten çıkar, tersinden değil. Zarar-durdur çalışırsa hesabın hangi payını kaybetmeyi kabul ettiğinize siz karar verirsiniz; giriş ile zarar-durdur arasındaki mesafe de büyüklüğü belirler. Geniş zarar-durdur küçük, dar zarar-durdur daha büyük pozisyon verir; riske giren tutar aynı kalır.

Zarar-durdur oynaklığa göre de konabilir. atrStop son barların ortalama gerçek aralığını (ATR) ölçer ve zarar-durduru kapanıştan bunun belirli bir katı kadar uzakta tutar. Böylece hareketli piyasada daha geniş, sakin piyasada daha dar bir pay bırakılır.

Vadelide emir gönderilmeden önce iki rakam önemlidir: pozisyon değerinin kaldıraca bölünmesiyle bulunan başlangıç teminatı ve kalan teminatın bakım teminatını artık karşılamadığı tasfiye fiyatı. Position Kit ikisini de tahmin eder. Bakım teminatı oranı sıfır verildiğinde tasfiye tahmini, strateji sınamasının kullandığı hesapla aynıdır.

gridLevels, Grid Bot ile aynı kademeleri verir. Aralığın iki ucu da dahildir; aritmetik kademeler eşit fiyat adımıyla, geometrik kademeler eşit yüzde adımıyla dizilir.

Grafiği okuma

Kitaplık kendi grafiğinde küçük bir gösterim çizer; böylece her parça gerçek fiyatlar üzerinde görülebilir. Aşağıdaki bir çizginin üzerine geldiğinizde grafikte öne çıkar.

  • Yeşil basamaklı çizgi: kapanışın iki ATR altındaki long zarar-durduru (14 barlık ATR).
  • Kırmızı basamaklı çizgi: kapanışın iki ATR üstündeki short zarar-durduru.
  • Amber kesikli çizgi: her kapanışta 10 kat kaldıraç ve %0,5 bakım teminatı oranıyla açılan long pozisyonun tahmini tasfiye fiyatı. Fiyatın yaklaşık %9,5 altında ilerler.
  • Mavi noktalı çizgiler: son 150 barın en yüksek ve en düşük fiyatı arasındaki dokuz geometrik grid kademesi.

İşlevler

sizeByRisk(equity, riskPct, entry, stop)
float
Zarar-durdur çalışırsa sermayenin riskPct yüzdesini kaybettiren, ana varlık cinsinden büyüklük. Giriş ile zarar-durdur eşitse na döner.
atrStop(side, mult, len)
float
side 1 (long) için kapanışın mult ATR altında, side -1 (short) için üstünde bir zarar-durdur.
liquidationPrice(side, entry, leverage, mmrPct)
float
Ayrık (isolated) pozisyonun tahmini tasfiye fiyatı. Kaldıraç 1 ya da altındaysa na döner.
marginNeeded(qty, price, leverage)
float
Karşı para birimi cinsinden başlangıç teminatı: büyüklük × fiyat ÷ kaldıraç.
gridLevels(lower, upper, count, mode)
array
En alttan en üste grid fiyatları, iki uç dahil. Aralık geçersizse boş dizi.
roundToTick(price, tick)
float
Fiyatı, fiyat adımının en yakın katına yuvarlar.
roundToStep(qty, step)
float
Miktarı miktar adımına aşağı yuvarlar; böylece emir verilen büyüklüğü hiçbir zaman aşmaz.
planFor(equity, riskPct, entry, stop, rr)
Plan
Kâr-al seviyesi girişten zarar-durdur mesafesinin rr katı uzağa konmuş ve büyüklüğü hesaplanmış bir plan.
Plan
type
Bir pozisyonun entry, stop, target, qty ve riskAmount alanları.
GridMode
enum
Arithmetic ya da Geometric.

Kullanımı

Bu sayfadaki içe aktarma satırını kopyalayın ve kitaplığa kısa bir ad verin. Aşağıdaki örnek, iki ATR'lik zarar-durdurun 10.000'lik hesabın %1'ini riske attığı long pozisyonu boyutlar ve bu pozisyonun 5 kat kaldıraçta gerektireceği teminatı çizer:

indicator("Risk Sizing Example", overlay = true)
import MarkudaDev/PositionKit/1 as pk

stopPrice = pk.atrStop(1, 2, 14)
plan = pk.planFor(10000, 1, close, stopPrice, 2)
plot(plan.stop, "Stop", "#fb5b6b")
plot(plan.target, "Target", "#33d69f")
plot(pk.marginNeeded(plan.qty, close, 5), "Margin at 5x")

Grid kademeleri de aynı biçimde, dizi olarak okunur:

levels = pk.gridLevels(60000, 70000, 11, pk.GridMode.Arithmetic)
plot(arrayGet(levels, 5), "Middle grid level")
Örnek10.000 USDT sermaye, %1 risk, 80.000'den giriş ve 78.400'de zarar-durdur için sizeByRisk 0,0625 BTC verir. Bu pozisyon 5 kat kaldıraçta 1.000 USDT teminat gerektirir; aynı girişten 10 kat kaldıraçla açılan long ise %0,5 bakım teminatı oranıyla 72.400 civarında tasfiye olur.

Sınırlar ve dikkat edilecekler

  • Tasfiye fiyatı bir tahmindir. Borsalar kademeli bakım teminatı oranları kullanır, komisyon ve funding alır, çapraz teminatta diğer açık pozisyonları da hesaba katar. Her zaman borsanın gösterdiği rakam esastır.
  • sizeByRisk yalnız zarar-durdur fiyatındaki kaybı ölçer. Komisyon, kayma ve zarar-durdurun ötesine açılan fiyat boşlukları gerçek kaybı planlanan tutardan büyük yapabilir.
  • Büyüklükler ana varlık cinsindendir (BTCUSDT için BTC). Emirde kullanmadan önce roundToStep ile yuvarlayın ve sembolün en küçük emir büyüklüğünü kontrol edin.
  • Daha geniş bir zarar-durdur işlemi daha güvenli yapmaz; aynı risk için yalnız pozisyonu küçültür.
  • Teminat ve tasfiye rakamları tek girişli, ayrık bir pozisyon varsayar.
  • Kaldıraç kazancı olduğu kadar kaybı da büyütür. Pozisyonlarınızı, bir tasfiyenin kaybetmeyi kabul ettiğinizden fazlasını alamayacağı büyüklükte tutmanızı rica ederiz.

Exports

Once the line is at the top of your code, you can reach the exported definitions through the alias.

Usage
import MarkudaDev/PositionKit/1 as positionKit
type PlanType

A trade plan: the prices and the size of one position.

Fields
entry
float
The entry price.
stop
float
The stop price.
target
float
The target price.
qty
float
The position size in units of the base asset.
riskAmount
float
The amount lost if the stop is hit, before fees and slippage.
enum GridModeEnum

How the grid levels are spaced.

Members
Arithmetic
Geometric
sizeByRisk(float equity, float riskPct, float entry, float stop)Function

Returns the position size that loses a set share of equity if the stop is hit.

Parameters
equity
float
The account value in the quote currency.
riskPct
float
The share of equity to risk, in percent (1 means 1%).
entry
float
The entry price.
stop
float
The stop price.

ReturnsThe size in units of the base asset, or na when the entry and the stop are equal.

atrStop(int side, float mult, int len)Function

Returns a stop price set a multiple of the average true range away from the close.

Parameters
side
int
1 for a long position (stop below the close), -1 for a short position (stop above the close).
mult
float
How many average true ranges away the stop is placed.
len
int
The average true range length in bars.

ReturnsThe stop price on the current bar.

liquidationPrice(int side, float entry, float leverage, float mmrPct)Function

Returns the estimated liquidation price of an isolated futures position.

Parameters
side
int
1 for a long position, -1 for a short position.
entry
float
The entry price.
leverage
float
The leverage, for example 5 for 5x.
mmrPct
float
The maintenance margin rate in percent (0.5 means 0.5%).

ReturnsThe estimated liquidation price, or na at 1x leverage and below.

marginNeeded(float qty, float price, float leverage)Function

Returns the margin needed to open a position.

Parameters
qty
float
The position size in units of the base asset.
price
float
The entry price.
leverage
float
The leverage, for example 5 for 5x.

ReturnsThe initial margin in the quote currency, or na when the leverage is not positive.

gridLevels(float lower, float upper, int count, GridMode mode)Function

Returns the price levels of a grid between two prices, both ends included.

Parameters
lower
float
The lowest level.
upper
float
The highest level.
count
int
The number of levels, at least 2.
mode
GridMode
GridMode.Arithmetic for equal price steps, GridMode.Geometric for equal percentage steps.

ReturnsAn array of prices from the lowest to the highest level, or an empty array when the range is not valid.

roundToTick(float price, float tick)Function

Rounds a price to the nearest multiple of the price tick.

Parameters
price
float
The price to round.
tick
float
The price tick of the symbol, for example 0.1.

ReturnsThe rounded price, or the price unchanged when the tick is not positive.

roundToStep(float qty, float step)Function

Rounds a quantity down to a multiple of the quantity step, so the order never exceeds the size it was given.

Parameters
qty
float
The quantity to round.
step
float
The quantity step of the symbol, for example 0.001.

ReturnsThe rounded quantity, or the quantity unchanged when the step is not positive.

planFor(float equity, float riskPct, float entry, float stop, float rr)Function

Builds a trade plan from an entry, a stop and a reward-to-risk ratio.

Parameters
equity
float
The account value in the quote currency.
riskPct
float
The share of equity to risk, in percent.
entry
float
The entry price.
stop
float
The stop price; below the entry for a long plan, above it for a short plan.
rr
float
The target distance as a multiple of the stop distance.

ReturnsA Plan with the target and the size filled in.

PositionKit115 linesVersion 1View full code
library("PositionKit", overlay = true) //@type A trade plan: the prices and the size of one position.//@field entry The entry price.//@field stop The stop price.//@field target The target price.//@field qty The position size in units of the base asset.//@field riskAmount The amount lost if the stop is hit, before fees and slippage.export type Plan {    float entry = 0    float stop = 0    float target = 0    float qty = 0    float riskAmount = 0